Aggregate/project sub-document as top-level document in mongo

后端 未结 3 1928
臣服心动
臣服心动 2021-02-13 13:36

After a few aggregation steps (pipeline steps) in one of my collections, I\'m ending up with the following result:

{
    \"_id\" : ObjectId(\"574e7722bffe901713d         


        
3条回答
  •  -上瘾入骨i
    2021-02-13 14:07

    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.

提交回复
热议问题