Matthew
Matthew

Reputation: 3071

MongoDB Convert Array of Objects to Single Object

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"
}

Upvotes: 3

Views: 3058

Answers (2)

Matthew
Matthew

Reputation: 3071

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"
    }
}

Upvotes: 3

s7vr
s7vr

Reputation: 75914

You can use below aggregation in 3.6 and above.

db.colname.aggregate(
 [{"$project":{
    "loop":{
      "$reduce":{
        "input":"$loop",
        "initialValue":{},
        "in":{"$mergeObjects":["$$value","$$this"]
        }
      }
    }
 }}]
)

Upvotes: 4

Related Questions