I have a Mongo collection as such:
db.items.find({}):
[{
"_id": {
"$oid": "64e929386a2bff904d86118a"
},
"name": "Copies",
"legacy_id": 181
},
{
"_id": {
"$oid": "64e929386a2bff904d86118b"
},
"name": "Temp",
"legacy_id": 182
},
{
"_id": {
"$oid": "64e929386a2bff904d86118c"
},
"name": "Test",
"legacy_id": 183
}]
Is there a way to combine the data to have a single document that contains the key/value pairs of the "_id": "legacy_id"
of the returned query results? A result like below would work fine for me. I know I can do this after the fact through some code but I’m wondering if there is a way to do this in the aggregate pipeline. Here’s the end result that I would like to achieve:
[{
"64e929386a2bff904d86118a": 181,
"64e929386a2bff904d86118b": 182,
"64e929386a2bff904d86118c": 183,
}]
2
Answers
Perform unconditional
$group
to$push
all k-v tuples of records into an array first. Then use$arrayToObject
to convert the array into object.Mongo Playground
you can use
$arrayToObject
and using$replaceRoot
you can make it roottest it here: mongo playgroung