mongodbmongodb-queryaggregate-functionsmgo

How to return Mongodb Aggregate pipeline docs to ONE document?


I know this has got to be simple, but for the life of me I can't seem to generate the correct final stage in my pipeline to get this working. Here are the documents output from a stage that I have in a mongo query:

{ "_id" : ObjectId("61435ceb233ce0118c1d93ec") }
{ "_id" : ObjectId("61435cf29598d31c17f0d839") }
{ "_id" : ObjectId("611e5cf953396d78985d222f") }
{ "_id" : ObjectId("61435cf773b8b06c848af83e") }
{ "_id" : ObjectId("61435cfd7ac204efa857e7ce") }
{ "_id" : ObjectId("611e5cf953396d78985d2237") }

I would like to get these documents into ONE single document with an array as such:

{ 
   "_id" : [
      ObjectId("61435ceb233ce0118c1d93ec"),
      ObjectId("61435cf29598d31c17f0d839"),
      ObjectId("611e5cf953396d78985d222f"),
      ObjectId("61435cf773b8b06c848af83e"),
      ObjectId("61435cfd7ac204efa857e7ce"),
      ObjectId("611e5cf953396d78985d2237")
   ]
}

My last stage in the pipeline is simply:

{
   $group:{_id:"$uniqueIds"}
}

I've tried everything from $push to $mergeObjects, but no matter what I do, it keeps returning the original 6 documents in some shape or form instead of ONE document. Any advice would be greatly appreciated! Thanks in advance.


Solution

  • Test code here

    Query

    db.collection.aggregate([
      {
        "$group": {
          "_id": null,
          "ids": {
            "$push": "$_id"
          }
        }
      },
      {
        "$unset": "_id"
      }
    ])