Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB - Project only the matching element in an array

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

like image 659
expeerd Avatar asked Dec 20 '15 20:12

expeerd


People also ask

How do you match an array field in MongoDB?

Match an Array To specify equality condition on an array, use the query document { <field>: <value> } where <value> is the exact array to match, including the order of the elements.

How do I pull an element from an array in MongoDB?

The $pull operator removes from an existing array all instances of a value or values that match a specified condition. The $pull operator has the form: { $pull: { <field1>: <value|condition>, <field2>: <value|condition>, ... } } To specify a <field> in an embedded document or in an array, use dot notation.

How do you find documents with a matching item in an embedded array?

Use $match With $eq to Find Matching Documents in an Array in MongoDB. Use $match With $all to Find Matching Documents in an Array in MongoDB.

How do I filter elements in MongoDB?

Filter MongoDB Array Element Using $Filter Operator This operator uses three variables: input – This represents the array that we want to extract. cond – This represents the set of conditions that must be met. as – This optional field contains a name for the variable that represent each element of the input array.


1 Answers

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"}}
])
like image 146
BatScream Avatar answered Sep 27 '22 18:09

BatScream