我在資料庫中有這樣的檔案。我需要itemType從他們自己的集合中獲取每個專案的資料。
{ listId: 2, itemType: 'book', itemId: 5364 },
{ listId: 2, itemType: 'car', itemId: 354 },
{ listId: 2, itemType: 'laptop', itemId: 228 }
基于 MongoDB 檔案和一些搜索,我發現我需要在查找中使用let和$expr來制作一些條件。
ListItemsModel.aggregate([
{ $match: { listId: 2 } },
{ $lookup:
{
from: 'books',
localField: 'itemId',
foreignField: '_id',
let: { "itemType": "$itemType" },
pipeline: [
{ $project: { _id: 1, title: 1 }},
{ $match: { $expr: { $eq: ["$$itemType", "book"] } }}
],
as: 'data'
}
},
{ $lookup:
{
from: 'cars',
localField: 'itemId',
foreignField: '_id',
let: { "itemType": "$itemType" },
pipeline: [
{ $project: { _id: 1, title: 1 }},
{ $match: { $expr: { $eq: ["$$itemType", "car"] } }}
],
as: 'data'
}
},
{ $lookup:
{
from: 'laptops',
localField: 'itemId',
foreignField: '_id',
let: { "itemType": "$itemType" },
pipeline: [
{ $project: { _id: 1, title: 1 }},
{ $match: { $expr: { $eq: ["$$itemType", "laptop"] } }}
],
as: 'data'
}
}
]);
問題是,結果所有資料欄位都是空的data: []。語法對我來說似乎是正確的。怎么了?
uj5u.com熱心網友回復:
任何后續重新分配欄位值都將消除任何先前的值。
因此,對于您的聚合管道,您需要為每個"$lookup" "as"欄位分配不同的值。
例如:
// ...
{ $lookup:
{
from: 'books',
// ...
as: 'booksData'
}
},
{ $lookup:
{
from: 'cars',
// ...
as: 'carsData'
}
},
{ $lookup:
{
from: 'laptops',
// ...
as: 'laptopsData'
}
},
// ...
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/530353.html
標籤:mongodb猫鼬
下一篇:MongoDB中的復雜聚合
