在 mongo 聚合 $lookup 查询中使用数组第一个字段来匹配文档

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

我想使用我的数组字段第 0 个值通过 Mongo 聚合 $lookup 查询在销售文档中查找匹配项。这是我的查询:

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

结果:

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

此查询将 return 与我匹配,但当我检查时它不匹配。我不明白为什么会这样,当我从查询中删除第 0 部分时,它的 return 空白数组。 像这样:

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

saleCategoryId也是一个包含categoriesKey数组的数组字段。

请帮忙。

因为您的 localField 是一个数组,您需要添加一个 $unwind stage to your pipeline before the lookup or use the $arrayElemAt in a $project 管道步骤来获取数组中的实际元素。

这里有两个示例,其中一个使用了 $arrayElemAt 运算符:

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

以及使用 $unwind to flatten the categories array first before applying the $lookup 管道的这个:

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