mongodb聚合$ redact以过滤数组元素 [英] mongodb aggregate $redact to filter array elements

查看:526
本文介绍了mongodb聚合$ redact以过滤数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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 $$PRUNEd, 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆