使用数组源获取mongodb中的数组子集 [英] Get array subset in mongodb using an array source

查看:181
本文介绍了使用数组源获取mongodb中的数组子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有此文档的结构:

{
    Id: "id_value",
    Elements:[
                {
                    InnerId: "inner_id_value1",
                    Value: "apple"
                },
                {
                    InnerId: "inner_id_value2",
                    Value: "pear"
                },
                {
                    InnerId: "inner_id_value3",
                    Value: "banana"
                }
             ]
}

我需要做的是创建一个查询,该查询在输入中接收一个数组(例如["apple","banana","coconut"])并返回给我:

What i need to do is create a query which receives in input an array (for example ["apple","banana","coconut"] ) and returns to me:

{
    Id: "id_value",
    Elements:[
                {
                    InnerId: "inner_id_value1",
                    Value: "apple"
                },
                {
                    InnerId: "inner_id_value3",
                    Value: "banana"
                }
             ]
}

是否可以在Mongo中执行一次查询?

Is it possible do it in Mongo with a single query?

推荐答案

您只需要将数组$filter并仅保留 value 是输入数组的子集的那些子文档.请注意,这里的 value 是一个元素数组,其中element是嵌入字段value.

You simply need to $filter the array and keep only those subdocument where the value is a subset of your input array. Note that value here is one element array where element is the embedded field value.

let fruits = ["apple","banana","coconut"];

db.collection.aggregate([
    { "$project": { 
        "Element": { 
            "$filter": { 
                "input": "$Element", 
                "as": "el", 
                "cond": { 
                    "$setIsSubset": [ [ "$$el.Value" ], fruits ] 
                 }
            }
        }
    }}
])


从MongoDB 3.4 *开始,您可以在$project阶段使用$in运算符.


Starting from MongoDB 3.4* you can use the $in operator in the $project stage.

db.collection.aggregate([
    { "$project": { 
        "Element": { 
            "$filter": { 
                "input": "$Element", 
                "as": "el", 
                "cond": { 
                    "$in": [ "$$el.Value", fruits ] 
                 }
            }
        }
    }}
])

*在撰写本文时,尚未发行的MongoDB版本

这篇关于使用数组源获取mongodb中的数组子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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