MongoDB:仅在满足条件的情况下才应用$ filter阶段?

时间:2020-07-29 09:00:57

标签: database mongodb mongodb-query aggregation-framework pymongo

我有一个数据模型,如下所示:

{
  "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

如何使用聚合运算符完成此操作?

1 个答案:

答案 0 :(得分:1)

将返回cond的{​​{1}}部分,但$fitertrue除外,无论右侧表达式有多复杂。您可以使用$swtich根据false值指定过滤条件:

company

Mongo Playground