首页 > 解决方案 > MongoDB:仅在满足条件时才应用 $filter 阶段?

问题描述

我有一个看起来像这样的数据模型:

{
  "company": <company name>,
  ...,
  "subFields": [
    {
      ...,
      "division" <division name>
    },
    ...
    ]
  }
}

给定这个数据模型,我的 mongoDB 管道只需要匹配company列表中的文档,并根据自己的规则all_companies过滤公司在列表中的其他人的内容。special_companies因此,例如,对于special company #1我们只想要subFields其字段具有特定值的元素division,因此必须应用以下过滤器:

{
  "$addFields": {
    "subFields": {
       "$filter": {
         "input": "$subFields",
         "as": "subFields",
         "cond": {"$eq": ["$$subFields.division", <division of special company #1>]}
       }
     }
  }
}

$match: {"company": {"$in": all_companies}}所以在实践中,一般阶段之后应该有一种if语句。

if company == special company #1:
    then apply filter #1
if company == special company #2:
    then apply filter #2
...
else:
    just pass all the results of $match

使用聚合运算符如何实现这一点?

标签: databasemongodbmongodb-queryaggregation-frameworkpymongo

解决方案


例外或要退回的cond部分。不管右手边的表达式有多复杂。在您的情况下,您可以使用$swtich根据值指定过滤条件:$filtertruefalsecompany

db.collection.aggregate([
    {
        $addFields: {
            "subFields": {
                $filter: {
                    input: "$subFields",
                    cond: {
                        $switch: {
                            branches: [
                                { case: { $eq: [ "$company", "company 1" ] }, then: { $eq: [ "$$this.division", "div 1" ] } },
                                { case: { $eq: [ "$company", "company 2" ] }, then: { $eq: [ "$$this.division", "div 2" ] } }
                            ],
                            default: true
                        }
                    }
                }
            }
        }
    }
])

蒙戈游乐场


推荐阅读