7

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

BatScream
  • 17,549
  • 4
  • 38
  • 60
expeerd
  • 83
  • 1
  • 6
  • 1
    Possible duplicate of [Retrieve only the queried element in an object array in MongoDB collection](http://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection) – styvane Dec 20 '15 at 20:52

1 Answers1

7

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"}}
])
BatScream
  • 17,549
  • 4
  • 38
  • 60
  • On server side query that looks like yours really returns array with matched elements, but on client side (minimongo) they returns whole array. – expeerd Dec 20 '15 at 20:48
  • Not sure if the issue - https://github.com/meteor/meteor/issues/153 is still open. If it is you have to iterate through all your sub documents as in - http://stackoverflow.com/questions/27951102/returning-subdocument-array-through-meteor-mongo/27953978#27953978 – BatScream Dec 20 '15 at 20:53
  • @expeerd - you may need to stick to `aggregating` the result, in `minimongo`. See my updated answer. – BatScream Dec 20 '15 at 20:59
  • Sorry about late reply. Aggregate works for me, but it has only server side implementation and is non reactive. – expeerd Dec 29 '15 at 21:40