Home > Software design >  Mongodb: promote sub-document to the top level
Mongodb: promote sub-document to the top level

Time:10-22

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

CodePudding user response:

Query

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

Test code here

db.collection.update({},
[{"$replaceRoot": 
   {"newRoot": 
     {"$mergeObjects": 
       ["$$ROOT", {"$arrayElemAt": ["$subDocument", 0]}]}}},
 {"$unset": ["subDocument"]}])
  • Related