Use array first field in mongo aggregate $lookup query to match a document Use array first field in mongo aggregate $lookup query to match a document mongodb mongodb

Use array first field in mongo aggregate $lookup query to match a document


Because your localField is an array, you'll need to add an $unwind stage to your pipeline before the lookup or use the $arrayElemAt in a $project pipeline step to get the actual element in the array.

Here are two examples, one which uses the $arrayElemAt operator:

db.products.aggregate([     { "$match" : { "_id": ObjectId("57c6957fb190ecc02e8b456b") } },    {        "$project": {            "category": { "$arrayElemAt": [ "$categories", 0 ] }                    }    },    {        "$lookup": {            from : 'sale',            localField: 'category',             foreignField: 'saleCategoryId',             as : 'pcSales'          }    }]);

and this which uses $unwind to flatten the categories array first before applying the $lookup pipeline:

db.products.aggregate([     { "$match" : { "_id": ObjectId("57c6957fb190ecc02e8b456b") } },    { "$unwind": "$categories" },    {        "$lookup": {            from : 'sale',            localField: 'categories',             foreignField: 'saleCategoryId',             as : 'pcSales'          }    }]);