如何过滤子文档数组? [英] How to filter array of sub-documents?

查看:48
本文介绍了如何过滤子文档数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构如下的文件:

I have a document structured like this:

{ 
"_id" : ObjectId("564d2702d4c68225cb00726f"), 
"list" : [
    {
        "a" : NumberInt(1), 
        "test" : "public"
    }, 
    {
        "a" : NumberInt(2), 
        "test" : "public"
    }, 
    {
        "a" : NumberInt(3), 
        "test" : "public"
    }, 
    {
        "a" : NumberInt(4), 
        "test" : "public"
    }, 
    {
        "a" : NumberInt(5), 
        "test" : "public"
    }
],
"other_fields": ""}

我可以为(1,5)中的子文档进行过滤吗

Can I filter subdocument for a in (1, 5)

我的预期结果如下

{
"_id" : ObjectId("564d2702d4c68225cb00726f"),
"list" : [
    {
        "a" : NumberInt(1),
        "test" : "public"
    },
    {
        "a" : NumberInt(5),
        "test" : "public"
    }
]}

我尝试使用$elemMatch,但是当我使用$in时,发生了错误.

I try to use $elemMatch, but when I use $in, an error happened.

推荐答案

从MongoDB 3.2开始,我们可以使用 $setIsSubset 运算符,以检查给定值是否在数组中.这主要是因为我们不能使用 $in $project 阶段的查询运算符.

Starting from MongoDB 3.2, we can use the $filter operator to efficiently to this. In $filter's conditional expression we need to use the $setIsSubset operator to check if a given value is in the array. This is mainly because we can't use the $in query operator in the the $project stage.

db.collection.aggregate([
    { "$project": { 
        "list": { 
            "$filter": { 
                "input": "$list", 
                "as": "lst", 
                "cond": { "$setIsSubset": [ [ "$$lst.a" ], [ 1, 5 ] ] }
            } 
        } 
    }}
])

从MongoDB 3.0.x开始,您需要使用 $setDifference 运算符.

From MongoDB 3.0.x backwards you need a different, less efficient approach using the $map operator the and the $setDifference operator.

db.collection.aggregate([
    { "$project": { 
        "list": { 
            "$setDifference": [ 
                { "$map": { 
                    "input": "$list", 
                    "as": "lst", 
                    "in": { 
                        "$cond": [
                            { "$setIsSubset": [ [ "$$lst.a" ], [ 1, 5 ] ] },
                            "$$lst",
                            false
                        ] 
                    } 
                }}, 
                [false] 
            ]
        }
    }}
])

这篇关于如何过滤子文档数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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