mongodb 带条件的聚合多重查找

mongodb aggregation multiple lookup with conditions

我有 3 个collection。

db.a.insert([
  { "_id" : ObjectId("5b56989172ebcb11105e8f41"), "db_type":b, "number" : 1},
  { "_id" : ObjectId("5b56989172ebcb11105e8f42"), "db_type":c, "number" : 2},
])

db.b.insert([
  { "_id" : ObjectId("5b56989172ebcb11105e8f43"), "number" : 1, "value" : "111"},
])

db.c.insert([
  { "_id" : ObjectId("5b56989172ebcb11105e8f44"), "number" : 2, "value" : "222"},
])

我想进行查找查询,根据 db_type 从每个 collection 获取值。

遇到这种情况怎么办?

结果:

{ "_id" : ObjectId("5b56989172ebcb11105e8f41"), "db_type" : b, "number" : 1, "value" : "111"}
{ "_id" : ObjectId("5b56989172ebcb11105e8f42"), "db_type" : c, "number" : 2, "value" : "222"}

部分堵塞...

db.getCollection('a').aggregate([
    {
        "$lookup":{
            "from":         "b" or "c", // I want to give condition here.
            "localField":   "number",
            "foreignField": "number",
            "as":           "result"
        }
    },
])

对于您的案例,因为您只有 2 个案例 bc 可供查找。您可以简单地进行 2 次单独的查找并使用 $setUnion 将结果组合在一起。

db.a.aggregate([
  {
    "$lookup": {
      "from": "b",
      "let": {
        db_type: "$db_type",
        number: "$number"
      },
      "pipeline": [
        {
          $match: {
            $expr: {
              $and: [
                {
                  $eq: [
                    "$$db_type",
                    "b"
                  ]
                },
                {
                  $eq: [
                    "$$number",
                    "$number"
                  ]
                }
              ]
            }
          }
        }
      ],
      "as": "bLookup"
    }
  },
  {
    "$lookup": {
      "from": "c",
      "let": {
        db_type: "$db_type",
        number: "$number"
      },
      "pipeline": [
        {
          $match: {
            $expr: {
              $and: [
                {
                  $eq: [
                    "$$db_type",
                    "c"
                  ]
                },
                {
                  $eq: [
                    "$$number",
                    "$number"
                  ]
                }
              ]
            }
          }
        }
      ],
      "as": "cLookup"
    }
  },
  {
    "$addFields": {
      "allLookup": {
        "$setUnion": [
          "$bLookup",
          "$cLookup"
        ]
      }
    }
  }
])

这里是Mongo playground供您参考。