[英]Object id array matching in lookup function of mongodb aggregation
我有一個產品 ID 數組,我想在查找 function 中使用該數組來查找產品,但在 $in 中出現錯誤。
購物車架構:
{
"_id": "5ec7b6d484649a451f836102",
"date": "2020-05-22T11:26:07.570Z",
"checkout": false,
"products": [
{
"_id": "5ec7b6d484649a451f836103",
"product_id": "5ec7b1b184649a451f8360f8",
"quantity": 1
}
],
"total_price": 150,
"total_quantity": 1,
"user_id": "5ec793d437b834429648657d",
"price_with_discount": 148.5,
"total_discount": 1.5,
"__v": 0
}
聚合 Function:
const checkouts = await Cart.aggregate([
{
$match: {
user_id, checkout: true
}
},
{
$group: {
_id: '$_id',
product_list: {
$first: '$products.product_id'
}
}
},
{
$lookup: {
from: 'products',
let: { list: "$product_list" },
pipeline: [
{
$match: {
_id: {
$in: "$$list"
}
}
}
],
as: 'cart_products',
}
}
]);
得到 $in 需要數組的錯誤。
為了在查找中使用$$variable
,您必須將它包裝在$expr表達式中。
在您描述的示例中, $in
是不必要的,您可以使用簡單的查找形式,它可能可以使用索引:
{$lookup: {
from: 'products',
localFields: "product_list",
foreignField: "_id",
as: 'cart_products',
}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.