How to flatten a subdocument into root level in MongoDB?

后端 未结 6 1009
一个人的身影
一个人的身影 2020-12-01 13:53

For example, if I have a document like this

{
  a: 1,
  subdoc: {
          b: 2,
          c: 3
          }
}

How can I convert it into a

6条回答
  •  天涯浪人
    2020-12-01 14:32

    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 the $replaceRoot mentioned by @chridam.

    We can thus first include within the sub-document the root field to keep using the $set operator (also introduced in Mongo 4.2 as an alias for $addFields) and then replace the whole document by the sub-document using $replaceWith:

    // { a: 1, subdoc: { b: 2, c: 3 } }
    db.collection.aggregate([
      { $set: { "subdoc.a": "$a" } },
      { $replaceWith: "$subdoc" }
    ])
    // { b: 2, c: 3, a: 1 }
    

提交回复
热议问题