Can I use $project to return a field as the top level document in a mongo aggregation query?

后端 未结 2 1892
既然无缘
既然无缘 2020-12-29 06:17

I have a document similar to the following, where I want to return a field of the current top level documents as the top level document itself in the results array:

2条回答
  •  借酒劲吻你
    2020-12-29 07:01

    • Starting Mongo 3.4, the $replaceRoot aggregation operator can be used to replace a document by another (in our case by a sub-document):

      // { field1: { content: { a: 1, b: 2 } }, field2: { othercontent: {} } }
      // { field1: { content: { c: 1, d: 2 } }, field2: { othercontent: {} } }
      db.collection.aggregate({ $replaceRoot: { newRoot: "$field1" } })
      // { content: { a: 1, b: 2 } }
      // { content: { c: 1, d: 2 } }
      
    • Starting Mongo 4.2, the $replaceWith operator can also be used:

      db.collection.aggregate({ $replaceWith: "$field1" })
      

提交回复
热议问题