MongoDB-仅投影数组中匹配的元素 [英] MongoDB - Project only the matching element in an array

查看:213
本文介绍了MongoDB-仅投影数组中匹配的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从Mongo文档的数组中获取具有以下结构的元素:

How could I get one element from array from Mongo document with following structure:

{
 array : [ 
           {type: 'cat', name: 'George'}
           {type: 'cat', name: 'Mary'} 
           {type: 'dog', name: 'Steve'} 
           {type: 'dog', name: 'Anna'}  

         ]
}

例如,我需要获得史蒂夫(Steve),在这种情况下,结果必须看起来像这样:

For example I need to get Steve, in this case result must looks so:

{
 array : [ 
           {type: 'dog', name: 'Steve'}
 ] 
}

左右:{type: 'dog', name: 'Steve'}

我知道如何在发布时进行创建,但是我需要在整个数组可用的客户端上进行创建,我可以使用forEach从数组中返回该值,但是我正在寻找更优雅的方式(使用Mongo查询). /p>

I know how make it while publishing but I need to make it on client side where whole array is available, I could return this value from array using forEach, but I'm searching more elegant way (using Mongo query).

推荐答案

使用位置运算符( $ )以仅投影第一个匹配的子文档.

Use the positional operator($) to project only the first matching sub document.

db.t.find({"array":{"type":"dog", "name":"Steve"}},{"array.$":1})

使用meteor,您将不得不坚持聚合,因为positional运算符不起作用:

Using meteor, you would have to stick to aggregation, since the positional operator does not work:

db.t.aggregate([
{$match:{"array.type":"dog","array.name":"Steve"}},
{$unwind:"$array"},
{$match:{"array.type":"dog","array.name":"Steve"}}
])

这篇关于MongoDB-仅投影数组中匹配的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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