node.js - mongodb聚合查找函数中的对象id数组匹配
问题描述
我有一个产品 ID 数组,我想在查找函数中使用该数组来查找产品,但在 $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
}
聚合功能:
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',
}}
推荐阅读
- r - 从 R 中的 GoogleSheets 清除列表列表
- javascript - 这种流畅的 D3 方法调用是如何实现的?
- json - 使用页面令牌(android studio)获取 youtube 频道的所有视频
- r - R 使用 group_by 并汇总 7 个变量,但只得到一个结果?
- python - 如何使用熊猫在excel输出文件中合并具有相同内容的多个列
- c++ - A* 寻路算法中的育儿?
- sql - 如何在不使用滞后的情况下在偏移量旁边显示一列值
- python - 使用 optuna LightGBMTunerCV 作为 optuna 进一步搜索的起点
- javascript - “非”运算符在这个函数中是如何工作的?
- c# - 在 uwp 中使用来自 Analog Discovery 的 .dll