在MongoDB中过滤嵌入式阵列 [英] Filtering an embedded array in MongoDB

查看:48
本文介绍了在MongoDB中过滤嵌入式阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Mongodb文档,其中包含一个深深嵌入在文档内部的数组。在我的一项操作中,我想返回整个文档,但过滤掉与该条件不匹配的数组元素。

I have a Mongodb document that contains an an array that is deeply imbedded inside the document. 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},
     ...
   ]
}

因此,在此示例中,我需要整个文档,但我只想将车辆数组具有将列出的属性设置为 true 的对象。

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.

解决方案

理想情况下,我正在寻找使用mongo查询(例如`$ unwind,$ elemMatch等的解决方案... ),但我也使用猫鼬,所以使用猫鼬的解决方案就可以。

Ideally, I'm looking for a solution using mongo's queries (e.g. `$unwind, $elemMatch, etc...) but I'm also using mongoose so solution that uses Mongoose is OK.

推荐答案

您可以使用如下聚合框架:

You could use aggregation framework like this:

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

这篇关于在MongoDB中过滤嵌入式阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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