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

2 Answers 2

4

You can use below aggregation in 3.6 and above.

db.colname.aggregate(
 [{"$project":{
    "loop":{
      "$reduce":{
        "input":"$loop",
        "initialValue":{},
        "in":{"$mergeObjects":["$$value","$$this"]
        }
      }
    }
 }}]
)
Sign up to request clarification or add additional context in comments.

1 Comment

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

1 Comment

This also works for older MongoDb version. Specifically, I have 3.0.6.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.