Can I easily return all of the fields of a subdocument as fields in the top level document using the aggregation framework?

后端 未结 3 1444
栀梦
栀梦 2021-01-02 04:33

I have a document similar to the following, from which I want to return the sub-fields of the current top level field as the top level fields in every document of the result

3条回答
  •  情歌与酒
    2021-01-02 04:54

    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:

    // { field1: { a: 1, b: 2, c: 3 }, field2: { d: 4, e: 5 } }
    // { field1: { a: 6, b: 7 }, field2: { d: 8 } }
    db.collection.aggregate({ $replaceWith: "$field1" })
    // { a: 1, b: 2, c: 3 }
    // { a: 6, b: 7 }
    

提交回复
热议问题