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

后端 未结 3 1931
臣服心动
臣服心动 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条回答
  •  余生分开走
    2021-02-13 13:56

    When you have many, many fields in the sub-document and occasionally it is updated with new fields, then projection is not a viable option. Fortunately, since 3.4, MongoDB has a new operator called $replaceRoot.

    All you have to do is add a new stage at the end of your pipeline.

    db.getCollection('sample').aggregate([
        {
            $replaceRoot: {newRoot: "$command"}
        },
        {
            $project: {score: 0 } //exclude score field
        }
    ])
    

    This would give you the desired output.

    Note that in case of aggregation (especially after a $group stage) the 'command' document could be an array and could contain multiple documents. In this case you need to $unwind the array first to be able to use $replaceRoot.

提交回复
热议问题