How to flatten a subdocument into root level in MongoDB?

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

    We can do this with $replaceWith an alias for $replaceRoot and the $mergeObjects operator.

    let pipeline = [
       {
          "$replaceWith": {
             "$mergeObjects": [ { "a": "$a" }, "$subdoc" ]
          }
       }
    ];
    

    or

    let pipeline = [
        {
            "$replaceRoot": {
                "newRoot": {
                    "$mergeObjects": [{ "a": "$a" }, "$subdoc" ]
                }
            }
        }
    ];
    
    db.collection.aggregate(pipeline)
    

提交回复
热议问题