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"
}
You can use below aggregation in 3.6 and above.
db.colname.aggregate(
[{"$project":{
"loop":{
"$reduce":{
"input":"$loop",
"initialValue":{},
"in":{"$mergeObjects":["$$value","$$this"]
}
}
}
}}]
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With