-->

MongoDB - Project only the matching element in an

2019-02-26 20:41发布

问题:

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:

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"}}
])