I have a data structure where I have a deeply nested array of objects, which then contain an array of ids. I want to do a lookup of those ids against another table, and substitute the full objects in place in this aggregation.
My attempted pipeline looks like this:
db.orders.aggregate([
{
"$match": {
"_id": 1
}
},
{
"$lookup": {
"from": "inventory",
"localField": "items.things",
"foreignField": "sku",
"as": "items.things"
}
}
])
The problem is that this only matches against the first object in the items
array, and it overwrites other fields within the items
scope, leaving just the things property, with the lookup of the first array.
Setup can be found here: Mongo playground
Sample output:
[
{
"_id": 1,
"items": {
"things": [
{
"_id": 1,
"description": "product 1",
"instock": 120,
"sku": "almonds"
},
{
"_id": 3,
"description": "product 3",
"instock": 60,
"sku": "cashews"
}
]
},
"price": 12,
"quantity": 2
}
]
With the following sample input (from orders)
"orders": [
{
"_id": 1,
"items": [
{
"name": "first",
"things": [
"almonds"
]
},
{
"name": "second",
"things": [
"cashews",
"almonds"
]
}
],
"price": 12,
"quantity": 2
},
{
"_id": 2,
"item": [
"pecans",
"cashews"
],
"price": 20,
"quantity": 1
},
{
"_id": 3
}
],