The docs says I can perform a $lookup without the ‘from’ field and passing an array to $documents stage inside a pipeline. But I’m getting an error trying that: “MongoServerError: missing ‘from’ option to $lookup stage specification”.
Is that really supported?
My use case is I have to perform an aggregation in one collection using $graphLookup to build an array with the document ancestors. That is in one collection called ‘inventoryCategories’
Now I need to get this data and do a $lookup in the “inventory’ collection to add that information in each document.
The solution I imagined was to perform the first aggregation on ‘inventoryCategories’” save the data on a array, and use this array in the second aggregation in the ‘inventory’ collection. That makes sense?
InventoryCategory:
[{
_id: {
"$oid": "641c81364e238225b6362cfb"
},
parent: {
"$oid": "641cd6eb5d09817ea0222ecc"
},
name: "Towable",
...other fields
}]
Array after first aggregation
[{
{
"_id": {
"$oid": "641c81364e238225b6362cfb"
},
"inventoryCategory": "Towable",
"ancestors": [
"Boom Lifts",
"Material Handling"
]
},
}]
Inventory:
[{
{
"_id": {
"$oid": "6425b1f0f7c12b4f67bdbd51"
},
"inventoryCategoryId": {
"$oid": "641c81364e238225b6362cfb"
},
...other fields
}]
Desired output (Materialized View - Inventory)
[{
{
"_id": {
"$oid": "6425b1f0f7c12b4f67bdbd51"
},
"inventoryCategoryId": {
"$oid": "641c81364e238225b6362cfb"
},
"inventoryCategory": "Towable",
"ancestors": [
"Boom Lifts",
"Material Handling"
]
}]
Aggregations:
const pipeline = [
{
$graphLookup: {
from: 'inventoryCategories',
startWith: '$parent',
connectFromField: 'parent',
connectToField: '_id',
depthField: 'order',
as: 'ancestor',
},
},
{
$unwind: '$ancestor',
},
{
$sort: {
_id: 1,
'ancestor.order': 1,
},
},
{
$group: {
_id: '$_id',
name: { $first: '$name' },
parent: { $first: '$parent' },
ancestor: { $push: '$ancestor' },
},
},
{
$project: {
inventoryCategory: '$name',
ancestors: '$ancestor.name',
},
},
];
const categoriesWithAncestors = await categories.aggregate(pipeline).toArray();
const inventoryPipeline = [
{
$lookup: {
localField: 'inventoryCategoryId',
foreignField: '_id',
as: 'category',
pipeline: [
{
$documents: [...categoriesWithAncestors],
},
],
},
},
{
$set: {
inventoryCategory: { $arrayElemAt: ['$category.name', 0] },
},
},
{
$unset: 'category',
},
{
$limit: 5,
},
{
$merge: {
into: 'inventoryWithCategory',
whenMatched: 'replace',
whenNotMatched: 'insert',
},
},
];