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

查看:19
本文介绍了使用数组源在 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天全站免登陆