Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
}
like image 981
Aydus-Matthew Avatar asked Sep 13 '26 07:09

Aydus-Matthew


1 Answers

You can use below aggregation in 3.6 and above.

db.colname.aggregate(
 [{"$project":{
    "loop":{
      "$reduce":{
        "input":"$loop",
        "initialValue":{},
        "in":{"$mergeObjects":["$$value","$$this"]
        }
      }
    }
 }}]
)
like image 50
s7vr Avatar answered Sep 15 '26 02:09

s7vr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!