database - 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
使用聚合运算符如何实现这一点?
解决方案
例外或要退回的cond
部分。不管右手边的表达式有多复杂。在您的情况下,您可以使用$swtich根据值指定过滤条件:$filter
true
false
company
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
}
}
}
}
}
}
])
推荐阅读
- json - 将带有嵌套消息的 protobuf 绑定到 Golang 结构
- javascript - 我可以在其他文件而不是 index.js 中编写 firebase 实时数据库触发器吗?
- javascript - 从 Google 自动完成设置邮政编码/ZIP
- javascript - 我在运行以下代码时遇到问题,我想打印 msg
- javascript - 检查最后一个字符是否为点 (.)
- webrtc - 如何在 WEBrtc 频道上发送图像?
- c++ - ‘AES_ctr128_encrypt’ was not declared in this scope
- php - 使用 PHP 检查所有复选框
- python - 来自胶囊网络代码的分类模块
- linux - 无法打开文件 lol.json:使用 Jq 拒绝权限?