3

我想使用我的數組字段第0個值在使用Mongo aggregate $ 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", 
    } 
]} 

這個查詢將返回我的對手,但是當我檢查它不匹配。我不明白爲什麼會發生這種情況,並且當我從查詢中刪除第0部分時返回空白數組。 像這樣:

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

saleCategoryId也含有categoriesKey的陣列的陣列字段。

請幫忙。

回答

3

因爲你localField是一個數組,你需要查找之前的$unwind階段添加到您的管道或使用$arrayElemAt$project管道一步得到數組中的實際元素。

下面是兩個例子,其中一個使用了$arrayElemAt操作者:

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

和此它使用$unwind在施加$lookup管道之前先平坦化類別陣列:

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

謝謝。它真的很有幫助 –

相關問題