Home > database >  Opposite of $replaceRoot in MongoDB aggregation
Opposite of $replaceRoot in MongoDB aggregation

Time:11-10

Aggregation stage $replaceRoot can be used to move a subdocument to the root level. For instance move the address subdocument in here to the root:

{ "name": "John Doe", "address": { "city": "Prague", "zip": "15000" } }
 ->
  { "city": "Prague", "zip": "15000" }

I need to do the exact opposite. That is, take the root document and move it to a subdocument. So take the root document and encapsulate it:

{ "name": "John Doe", "address": { "city": "Prague", "zip": "15000" } }
 ->
  { "person": { "name": "John Doe", "address": { "city": "Prague", "zip": "15000" } } }

Does there exist an aggregation stage/operation with which this could be achieved? Or maybe can I hack the $replaceRoot itself to do this?

CodePudding user response:

db.collection.aggregate([
  {
    "$project": {
      "person": "$$ROOT"
    }
  }
])

It'll also include your ObjectId, but you could add specific fields if you'd prefer

  • Related