6

I want to use my array field 0th value to find a match in sale document using Mongo aggregate $lookup query. Here is my query:

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

Result :

{
"_id" : ObjectId("57c6957fb190ecc02e8b456b"),   
"categories" : [
    "57c54f0db190ec430d8b4571"
],  
"pcSales" : [
    {
        "_id" : ObjectId("57c7df5f30fb6eacb3810d1b"),                       
        "Title" : "Latest Arrivals",
    }
]}

This query will return me a match but when i check it not a match. I don't get why is this happening, And when i removed 0th part from query its return blank array. Like this:

{
    "_id" : ObjectId("57c6957fb190ecc02e8b456b"),   
    "categories" : [
        "57c54f0db190ec430d8b4571"
    ],  
    "pcSales" : []
}

saleCategoryId is also a array field which contain array of categoriesKey.

Please help.

1 Answer 1

11

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'  
        }
    }
]);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.