如何根据类型从集合中有条件地查找(mongo 4.4)

问题描述 投票:0回答:1

下面是一些中间管道的聚合

[
 {
    $unwind: "$destinations"
  },
  {
    $lookup: {
      from: "customers",
      localField: "destinations.sold_to_id",
      foreignField: "_id",
      as: "sold_to_ref"
    },
    
  },
]

根据上面的查询,

destinations
是一个数组,就像

[{
   type: 1,
   sold_to_id: 'xxxxx'
 },
 {
  type: 2,
  sold_to_id: 'yyyy',
 }
]

现在我想根据类型执行查找(即) 如果 type = 1,则从

customers
查找 否则从
users
查找。 注:
customers
users
是两个不同的集合

请帮我解决这个问题。

提前致谢

编辑:

我试过的解决方案

[{
    $unwind: "$destinations"
},
{
    $lookup: {
      from: "customers",
      "let": {
        type: "$destinations.type",
        destination_id: "$destinations.sold_to_id"
      },
      pipeline: [
        {
          "$match": {
            "$expr": { $and:
                       [
                         { $eq: [ "$$type", 1 ] }, // Here I need to compare the type value with 1 which is not happening
                         { $eq: [ "$_id", "$$destination_id" ] }
                       ]
                    }
          }
        }
      ],
      as: "sold_to_ref"
    },
    
  }]
javascript mongodb mongoose mongodb-query aggregation-framework
1个回答
0
投票

不可能(甚至在 SQL 中也不行)。

解决方法: 你用

LEFT JOINS
运行 2
$facet
,合并它们并压平结果。

db.collection.aggregate([
  {
    $unwind: "$destinations"
  },
  {
    $facet: {
      users: [
        {
          $match: {
            "destinations.type": 2
          }
        },
        {
          $lookup: {
            from: "users",
            localField: "destinations.sold_to_id",
            foreignField: "_id",
            as: "sold_to_ref"
          }
        }
      ],
      customers: [
        {
          $match: {
            "destinations.type": 1
          }
        },
        {
          $lookup: {
            from: "customers",
            localField: "destinations.sold_to_id",
            foreignField: "_id",
            as: "sold_to_ref"
          }
        }
      ]
    }
  },
  {
    $project: {
      merge: {
        $concatArrays: ["$users", "$customers"]
      }
    }
  },
  {
    $unwind: "$merge"
  },
  {
    $replaceWith: "$merge"
  }
])

MongoPlayground

© www.soinside.com 2019 - 2024. All rights reserved.