3

Using a MongoDB aggregate query, how do I convert an array of documents to a single document. The array can have N number of documents.

Before

"loop" : [
    {
        "field1" : "1"
    }, 
    {
        "field2" : "2", 
        "field3" : "3", 
    }, 
    {
        "field4" : "4", 
    }, 
    {
        "field5" : "5", 
        "field6" : "6"
    }
]

After

"loop" : {
    "field1" : "1",
    "field2" : "2", 
    "field3" : "3", 
    "field4" : "4", 
    "field5" : "5", 
    "field6" : "6"
}
Matthew
  • 2,871
  • 5
  • 34
  • 59

2 Answers2

4

You can use below aggregation in 3.6 and above.

db.colname.aggregate(
 [{"$project":{
    "loop":{
      "$reduce":{
        "input":"$loop",
        "initialValue":{},
        "in":{"$mergeObjects":["$$value","$$this"]
        }
      }
    }
 }}]
)
s7vr
  • 73,656
  • 11
  • 106
  • 127
3

Based on Veeram's answer above using $mergeObjects, here's a more concise query using $project.

Query

db.loop.aggregate(
    [{
        "$project": {
            "loop": { $mergeObjects: "$loop" }
        }
    }]
)    

Result

{ 
    "loop" : {
        "field1" : "1", 
        "field2" : "2", 
        "field3" : "3", 
        "field4" : "4", 
        "field5" : "5", 
        "field6" : "6"
    }
}
Matthew
  • 2,871
  • 5
  • 34
  • 59