skip to Main Content

Suppose I have two documents in a collection:

[
  {
    "_id": 0,
    "name": "aaaa",
    "phone": 111
  },
  {
    "_id": 1,
    "name": "bbbb",
    "phone": 999
  }
]

I want to run an aggregation pipeline that will merge/wrap/combine ALL the fields into a top-level root object called lead. Without mentioning/hardcoding the field names in the query.

Expected output:

[
  {
    "lead": {
      "_id": 0,
      "name": "aaaa",
      "phone": 111
    }
  },
  {
    "lead": {
      "_id": 1,
      "name": "bbbb",
      "phone": 999
    }
  }
]

2

Answers


  1. Chosen as BEST ANSWER

    Got some help from this answer and was able to achieve it using $project:

    db.collection.aggregate([
      {
        $project: {
          lead: "$$ROOT",
          _id: false
        }
      }
    ])
    

    Playground link

    $$ROOT in MongoDB references the content of this document.


  2. Works with $replaceWith stage to replace the input documents with new outputdocuments. To get each (original) document, you need to use the $$ROOT variable.

    db.collection.aggregate([
      {
        $replaceWith: {
          "lead": "$$ROOT"
        }
      }
    ])
    

    Demo @ Mongo Playground

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search