I’m having trouble applying a $lookup
stage after a $group
stage in my aggregation pipeline. The grouping stage produces an array($push
: $$ROOT
) as output, which seems to prevent me from using the $lookup
stage afterwards.
Does anyone know how I can apply a $lookup
stage in each document provided in the array output from $group
stage? Any help or advice would be greatly appreciated. Thanks!
MongoDB Version: 4.4
Example Order Documents:
{
_id: ObjectId("64002be8a5f7df1355bc95d0"),
status: "New",
products: [
ObjectId("63183f9492a483955009c43a"),
ObjectId("63183f9492a483955009c43b")
]
}
{
_id: ObjectId("64002be8a5f7df1355bc95d1"),
status: "In_Progress",
products: [
ObjectId("63183f9492a483955009c43a"),
ObjectId("63183f9492a483955009c43c")
]
}
{
_id: ObjectId("64002be8a5f7df1355bc95d2"),
status: "Complete",
products: [
ObjectId("63183f9492a483955009c43b"),
ObjectId("63183f9492a483955009c43c")
]
}
Example Product Documents:
{
_id: ObjectId("63183f9492a483955009c43a"),
name: "Brush",
category: "Household",
price: 100
}
{
_id: ObjectId("63183f9492a483955009c43b"),
name: "Pan",
category: "Kitchen",
price: 145
}
{
_id: ObjectId("63183f9492a483955009c43c"),
name: "Bag",
category: "Household",
price: 50
}
Trying to achieve :
Sort documents → Group them by status → Limit first n documents → Apply lookup to fetch product details → return results
Desired results:
{
"New": [
{
"_id": ObjectId("64002be8a5f7df1355bc95d0"),
"products": [
{
"_id": ObjectId("63183f9492a483955009c43a"),
"name": "Brush",
"category": "Household",
"price": 100
},
{
"_id": ObjectId("63183f9492a483955009c43b"),
"name": "Pan",
"category": "Kitchen",
"price": 145
}
]
}
],
"In_Progress": [{...},{...}....],
"Complete": [{...},{...}....]
}