'Mongodb: promote sub-document to the top level

I have document like this,

{
  "_id": 1,
  "attribute1":"123",
  "attribute2":"abc",
  "subDocument": [
    {
      "attribute1":"456",
      "attribute2":"xyz",
    }
  ]
}

I want to promote the first item of subDocument to the top level. Note that the item of subDocument has the same attributes as in the top level and I want to replace them. So the result will be

{
  "_id": 1,
  "attribute1":"456",
  "attribute2":"xyz",
  
}

How should I write the query? Playground https://mongoplayground.net/p/x0pzzwdi5k9



Solution 1:[1]

Query

  • get first member
  • merge it with the root, and replace the root
  • same names will be replaced from the first member

PlayMongo

update({},
[{"$replaceRoot": 
   {"newRoot": 
     {"$mergeObjects": 
       ["$$ROOT", {"$arrayElemAt": ["$subDocument", 0]}]}}},
 {"$unset": ["subDocument"]}])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1