Reputation: 1
I have a document looking like this:
{
"_id": "some_uuid",
"inv": {
"food01": "id01",
"food02": "id02",
"food03": "id03"
},
"food": {
"id01": {
"n": "apple"
},
"id02": {
"n": "banana"
},
"id03": {
"n": "pear"
}
}
}
I want to use Mongodb Aggregate to retrieve the following output.
Expected Output
{
"_id": "some_uuid",
"inv": {
"food01": "apple",
"food02": "banana",
"food03": "pear"
}
}
Can someone guide me how to do this? Thank you!
Upvotes: 0
Views: 42
Reputation: 16033
One option is using $objectToArray
to format these fields as arrays, which will allow to use $map
and $filter
to match them:
db.collection.aggregate([
{$set: {inv: {$objectToArray: "$inv"}, food: {$objectToArray: "$food"}}},
{
$project: {
inv: {$map: {
input: "$inv",
in: {
k: "$$this.k",
v: {
$filter: {
input: "$food",
as: "food",
cond: {$eq: ["$$this.v", "$$food.k"]}
}
}
}
}
}
}
},
{
$project: {
inv: {
$map: {
input: "$inv",
in: {k: "$$this.k", v: {$first: "$$this.v.v.n"}}
}
}
}
},
{$project: {inv: {$arrayToObject: "$inv"}}}
])
See how it works on the playground example
Upvotes: 1