简体   繁体   English

Object id 数组匹配在 mongodb 聚合中查找 function

[英]Object id array matching in lookup function of mongodb aggregation

I have an array of product ids and i want to use that array in lookup function to find the products, but i am getting an error in $in.我有一个产品 ID 数组,我想在查找 function 中使用该数组来查找产品,但在 $in 中出现错误。

Cart Schema:购物车架构:

{
  "_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
}

Aggregation Function:聚合 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',

                }
            }
        ]);

Getting the error that $in needs an array.得到 $in 需要数组的错误。

In order to use $$variable in a lookup, you have to wrap it in a $expr expression.为了在查找中使用$$variable ,您必须将它包装在$expr表达式中。

In the example you describe, $in is unnecessary, and you can use the simple form of lookup, which might be able to use an index:在您描述的示例中, $in是不必要的,您可以使用简单的查找形式,它可能可以使用索引:

 {$lookup: {
            from: 'products',
            localFields: "product_list",
            foreignField: "_id",        
            as: 'cart_products',
}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM