I have two collections, one with orders and one with items
Orders:
{
_id: "123456",
name: "John Doe",
items: [
{
item: "7890",
count: 4
},
{
item: "6543",
count: 4
},
]
}
Items:
{
_id: "7890",
name: "item1"
},
{
_id: "6543",
name: "item2"
}
Ideally, I would like whenever an order is pulled up, the items will populate with the count requested; as shown below
{
_id: "123456",
name: "John Doe",
items: [
{
item: "7890",
name: "item1",
count: 4
},
{
item: "6543",
name: "item2",
count: 4
},
]
}
Currently, I have tried the following lookup in the Orders collection;
{
"$lookup": {
"from": "items",
"localField": "items.item",
"foreignField": "_id",
"as": "items"
}
}
However, that lookup completely overrides the ‘count’ field in the order and gives me this;
{
_id: "123456",
name: "John Doe",
items: [
{
item: "7890",
name: "item1"
},
{
item: "6543",
name: "item2"
},
]
}
Is there a way to expand the ‘item’ object in the ‘order.items’ array without it overriding the ‘count’ field?, I would think it could be something done with $mergeObjects, but I am not experienced enough with the aggregation pipeline to understand how it works,
Thank you for the advice ahead of time.