具有多个条件和ID的mongodb聚合查找

时间:2019-02-21 23:43:09

标签: mongodb aggregation

具有以下集合和数据

db.a.insert([
  { "_id" : ObjectId("5b56989172ebcb00105e8f41"), "items" : [{id:ObjectId("5b56989172ebcb00105e8f41"), "instock" : 120}]},
  { "_id" : ObjectId("5b56989172ebcb00105e8f42"), "items" : [{id:ObjectId("5b56989172ebcb00105e8f42"), "instock" : 120}] },
  { "_id" : ObjectId("5b56989172ebcb00105e8f43"), "items" : [{ObjectId("5b56989172ebcb00105e8f43"), "instock" : 80}] }
])

db.b.insert([
  { "_id" : ObjectId("5b56989172ebcb00105e8f41")},
  { "_id" : ObjectId("5b56989172ebcb00105e8f42")},
  { "_id" : ObjectId("5b56989172ebcb00105e8f43")},
  { "_id" : ObjectId("5b56989172ebcb00105e8f44")},
  { "_id" : ObjectId("5b56989172ebcb00105e8f45")}
])

执行类似的查询聚合

db.b.aggregate([
   {
      $lookup:
         {
           from: "b",
           let: { bId: "$_id", qty: 100 },
           pipeline: [
              { $match:
                 { $expr:
                    { $and:
                       [
                         { $eq: [ "$items.id",  "$$bId" ] },
                         { $gte: [ "$instock", "$$qty" ] }
                       ]
                    }
                 }
              }
           ],
           as: "a"
         }
    }
])

不会在预期的查找操作中带来任何结果。使用ObjectId进行比较是否有任何限制?在官方文档中没有提及任何内容,它可以像其他类型的数据类型(如字符串)一样具有魅力

1 个答案:

答案 0 :(得分:0)

我不确定这是否是mongodb中的错误,但该查询仅在首先添加$unwind阶段之后才能工作。

db.b.aggregate([
   {
      $lookup:
         {
           from: "a",
           let: { bId: "$_id", qty: 100 },
           pipeline: [
           {    
             $unwind: {
               path: "$items"
             }
           },
           { $match:
              { $expr:
                        { $and:
                            [
                                { $eq: [ "$items.id",  "$$bId" ] },
                                { $gte: [ "$items.instock",  "$$qty" ] },
                            ]
                        }
                    }
                }
           ],
           as: "a"
         }
    }
]);

注意:Join Conditions and Uncorrelated Sub-queries是在mongo 3.6中添加的