简体   繁体   English

mongo 管道 $lookup 中的 $in/$eq 不起作用

[英]$in/$eq in mongo pipeline $lookup is not working

I've a collection details with array of string values on quotes_id like the following我在quotes_id上有一个包含字符串值数组的集合details ,如下所示

{
    "quantity": 2000,
    "quotes_id": ["SQ-CPQ10037"],
    "status": "processed",
    "logs": [""],
    "product_id": "5ff5cf3dc1ceb9144901da81"
}

And my quotes collection还有我的quotes

{
    "_id":"SQ-CPQ10037",
    "product_id":"5ff5cf3dc1ceb9144901da81",
    ...more fields here
}

Now, I'm trying to access this collection from another collection named quotes using lookup pipeline like the following现在,我正在尝试使用查找管道从另一个名为quotes的集合中访问此集合,如下所示

$lookup: {
     from: "details",
     "let": { "product_id": "$quotes.product_id", "quotes_id": "$quotes._id"},
     pipeline: [
     { 
         $match: { 
            $expr: { 
               $and: [
                 { $in: [ "$quotes_id",  ["$$quotes_id"] ] },
                 { $eq: [ "$product_id",  "$$product_id" ] },
               ]
            }
         }
     }],      
     as: "product.productquotes",
},

This is returning empty collection.这是返回空集合。 However, if I comment the line但是,如果我评论该行

{ $in: [ "$quotes_id",  ["$$quotes_id"] ] },

then it is returning me the record.然后它把记录还给我。 I also tried with simple $eq for the quotes_id but with same result.我还尝试使用简单的$eq作为quotes_id ,但结果相同。 But if I run the query directly like但是如果我直接运行查询

{$and: [{"product_id": ObjectId('5ff5cf3dc1ceb9144901da81')}, {"quotes_id": "SQ-CPQ10037"}]}

on mongo compass, I receive the record without any issue.在 mongo 指南针上,我收到了没有任何问题的记录。

You have done almost correct.你做的几乎是正确的。 But wrongly wrote the $in args.但是错误地写了$in参数。 Second arg of in should be an array. in 的第二个参数应该是一个数组。

{
  $in: [
    "$$quotes_id",
    "$quotes_id"
  ]
}

So the lookup likes所以查找喜欢

db.quotes.aggregate([
  {
    $lookup: {
      from: "details",
      "let": { "product_id": "$product_id", "quotes_id": "$_id" },
      pipeline: [
        {
          $match: {
            $expr: {
              $and: [
                {  $in: [ "$$quotes_id", "$quotes_id" ] },
                {  $eq: [ "$product_id", "$$product_id" ] }                
              ]
            }
          }
        }
      ],
      as: "product.productquotes"      
    }
  }
])

Working Mongo playground工作蒙戈游乐场

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

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