使用管道进行聚合查找并匹配不工作 mongodb

Kri*_*ont 3 pipeline aggregate mongodb

我有这两个简单的集合:

项目:

{
    "id" : "111",
    "name" : "apple",
    "status" : "active"
}    
{
    "id" : "222",
    "name" : "banana",
    "status" : "active"
}
Run Code Online (Sandbox Code Playgroud)

存货:

{
    "item_id" : "111",
    "qty" : 3,
    "branch" : "main"
}
{
    "item_id" : "222",
    "qty" : 3
}
Run Code Online (Sandbox Code Playgroud)

现在我只想返回库存集合中存在且等于“main”且具有“status”==“active”和“branch”的项目。我有下面的代码,但它返回所有文档,第二个文档有一个空的“info”数组。

db.getCollection('items')
.aggregate([
  {$match:{$and:[
                {"status":'active'},
                {"name":{$exists:true}}
            ]
}},
{$lookup:{
    as:"info",
    from:"inventory",
    let:{fruitId:"$id"},
    pipeline:[
     {$match:{
         $and:[
            {$expr:{$eq:["$item_id","$$fruitId"]}},
            {"branch":{$eq:"main"}},
            {"branch":{$exists:true}}
         ]         
         }    
     }
    ]    
}}
])
Run Code Online (Sandbox Code Playgroud)

谁能给我一个关于如何解决这个问题的想法?

小智 7

你的代码运行得很好。我认为你只需要$match在管道的最后一个阶段。

db.items.aggregate([
  {
    $match: {
      $and: [
        { "status": "active" },
        { "name": { $exists: true } }
      ]
    }
  },
  {
    $lookup: {
      as: "info",
      from: "inventory",
      let: { fruitId: "$id" },
      pipeline: [
        {
          $match: {
            $and: [
              { $expr: { $eq: [ "$item_id", "$$fruitId" ] } },
              { "branch": { $eq: "main" } },
              { "branch": { $exists: true } }
            ]
          }
        }
      ]
    }
  },
  {
    "$match": {
      "info": { "$ne": [] }
    }
  }
])
Run Code Online (Sandbox Code Playgroud)

蒙戈游乐场