mongodb聚合$ redact以过滤数组元素 [英] mongodb aggregate $redact to filter array elements
问题描述
在mongodb 3.4.5中,请考虑以下简单集合 ooo
:
In mongodb 3.4.5 think below simple collection ooo
:
{ "id" : 1, "to" : [ { "id" : 2 }, { "id" : 4, "valid" : true } ] }
想要 $ redact
到
$ c>有效 不是是:
Want to $redact
to
if valid
not true:
db.ooo.aggregate([{ "$redact": {
"$cond": {
"if": { "$ne": [ "$valid", true] },
"then": "$$KEEP",
"else": "$$PRUNE"
}
}}])
结果:
{ "id" : 1, "to" : [ { "id" : 2 } ] }
但是将条件更改为if 有效
是是:
But when changed condition to if valid
is true:
db.ooo.aggregate([{ "$redact": {
"$cond": {
"if": { "$eq": [ "$valid", true] },
"then": "$$KEEP",
"else": "$$PRUNE"
}
}}])
结果为空。
推荐答案
$ redact
将整个文档从顶层移至向下,将 $ valid:true
部分不能在顶层传递(顶层没有 valid
字段),然后是 $$ ROOT
是 $$ PRUNE
d,什么也没有返回。
The $redact
walks the whole documents from top level then downwards, the "$valid": true
part cannot pass on top level (top level have no valid
field), then the $$ROOT
be $$PRUNE
d, and nothing returned.
解决方案(跳过此操作并查看下面的更新):
The solution (skip this and see below updated):
db.ooo.aggregate([{ "$redact": {
"$cond": {
"if": { $or: ["$to", {"$eq": [ "$valid", true]}] },
"then": "$$KEEP",
"else": "$$PRUNE"
}
}}])
更新:
根据@neil的评论,我更正了答案:
based on @neil's comment, I corrected the answer:
db.ooo.aggregate([{ "$redact": {
"$cond": {
"if": { $or: ["$to", {"$eq": [ "$valid", true]}] },
"then": "$$DESCEND",
"else": "$$PRUNE"
}
}}])
一个d显示的预期结果:
And the expected result shown:
{ "id" : 1, "to" : [ { "id" : 4, "valid" : true } ] }
即 { id: 2}
被修剪。
这篇关于mongodb聚合$ redact以过滤数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!