Reputation: 569
I am trying to merge a set of documents into a collection A
{'s': 'v1', 'id': 1}
{'s': 'v2', 'id': 2}
{'s': 'v3', 'id': 3}
{'s': 'v4', 'id': 4}
into a unique document of key value pairs as fallow.
{
'v1': 1,
'v2': 2,
'v3': 3,
'v4': 4
}
Could you suggest a way to do that using a unique MongoDB command without persisting data in another collection?
Upvotes: 4
Views: 237
Reputation: 20354
"$group"
with $addToSet
to create an array with key/value pairs from all documents$set
and $arrayToObject
to make an object from the array generated in previous stage and assign it to the result field$replaceRoot
to replace the root with the result field generated in previous stepdb.collection.aggregate([
{
"$group": {
"_id": null,
"result": {
"$addToSet": {
"k": "$s",
"v": "$id"
}
}
}
},
{
"$set": {
"result": {
"$arrayToObject": "$result"
}
}
},
{
"$replaceRoot": {
"newRoot": "$result"
}
}
])
Upvotes: 4