MongoDB - Project only the matching element in an

2019-02-26 19:59发布

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'}  

         ]
}

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

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

or so: {type: 'dog', name: 'Steve'}

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).

1条回答
老娘就宠你
2楼-- · 2019-02-26 20:33

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

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

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"}}
])
查看更多
登录 后发表回答