简体   繁体   English

在MongoDB中过滤嵌入式阵列

[英]Filtering an embedded array in MongoDB

I have a Mongodb document that contains an an array that is deeply imbedded inside the document. 我有一个Mongodb文档,其中包含一个深深嵌入在文档内部的数组。 In one of my action, I would like to return the entire document but filter out the elements of that array that don't match that criteria. 在我的一项操作中,我想返回整个文档,但过滤掉与该条件不匹配的数组元素。

Here is some simplified data: 这是一些简化的数据:

{
   id: 123 ,
   vehicles : [
     {name: 'Mercedes', listed: true},
     {name: 'Nissan', listed: false},
     ...
   ]
}

So, in this example I want the entire document but I want the vehicles array to only have objects that have the listed property set to true . 因此,在此示例中,我需要整个文档,但我希望vehicles数组仅具有将listed属性设置为true

Solutions 解决方案

Ideally, I'm looking for a solution using mongo's queries (eg `$unwind, $elemMatch, etc...) but I'm also using mongoose so solution that uses Mongoose is OK. 理想情况下,我正在寻找使用mongo的查询的解决方案(例如$ unwind,$ elemMatch等),但我也在使用mongoose,因此使用Mongoose的解决方案就可以了。

You could use aggregation framework like this: 您可以使用如下聚合框架:

db.test312.aggregate(
    {$unwind:"$vehicles"},
    {$match:{"vehicles.name":"Nissan"}},
    {$group:{_id:"$_id",vehicles:{$push:"$vehicles"}}}
)

You can use $addToSet on the group after unwinding and matching by listed equals true. 展开并匹配列出的true之后,可以在组上使用$addToSet

Sample shell query: 示例shell查询:

db.collection.aggregate([
{
    $unwind: "$vehicles"
},
{
    $match: {
        "vehicles.listed": {
            $eq: true
        }
    }
},
{
    $group: {
        _id: "$id",
        vehicles: {
            "$addToSet": {
                name: "$vehicles.name",
                listed: "$vehicles.listed"
            }
        }
    }
},
{
    $project: {
        _id: 0,
        id: "$_id",
        vehicles: 1
    }
}
]).pretty();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM