After a few aggregation steps (pipeline steps) in one of my collections, I\'m ending up with the following result:
{
\"_id\" : ObjectId(\"574e7722bffe901713d
Starting Mongo 4.2
, the $replaceWith aggregation operator can be used to replace a document by another (in our case by a sub-document) as syntaxic sugar for $replaceRoot
.
// { "eventname": "Ball Passed", "command": { "_id": "57e...", "name": "Run", "strike": 15, "score": true, "duration": 123 } }
// { "eventname": "Ball Passed", "command": { "_id": "573...", "name": "Run", "strike": 12, "score": false, "duration": 597 } }
db.collection.aggregate([
{ $replaceWith: "$command" }, // replaces the document by the content of "command"
{ $unset: ["score"] } // drops the "score" field
])
// { "_id" : "57e...", "name" : "Run", "strike" : 15, "duration" : 123 }
// { "_id" : "573...", "name" : "Run", "strike" : 12, "duration" : 597 }
Also note the $unset aggregation operator also introduced in Mongo 4.2
, as an alternative syntax for $project
when used to only drop fields.