How to flatten a subdocument into root level in MongoDB?

后端 未结 6 1006
一个人的身影
一个人的身影 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:20

    You can use $replaceRoot with a $addFields stage as follows:

    db.collection.aggregate([
        { "$addFields": { "subdoc.a": "$a" } },
        { "$replaceRoot": { "newRoot": "$subdoc" }  }
    ])
    

提交回复
热议问题