0

I am facing always the same thing when I would like to query macting subdocuments of an array.

Lets think I have a collection like below:

{ 
  "_id" : 1, 
  "value" : 5, 
  "array" :[ {"name" : "John", "born" : ISODate("1980-04-17T13:11:54Z"),  "hasACar" : false}, 
             {"name" : "Alice", "born" : ISODate("1985-04-17T13:11:54Z"), "hasACar" : false},
             {"name" : "Jordan", "born" : ISODate("1980-05-19T104:11:54Z"), "hasACar" : true} ] 
}

{
  "_id" : 2, 
  "value" : 3, 
  "array" :[ {"name" : "Neil", "born" : ISODate("1985-11-14T16:11:54Z"), "hasACar" : false}, 
             {"name" : "Marin", "born" : ISODate("1987-08-17T13:15:00Z"), "hasACar" : false}] 
}

{ 
  "_id" : 3, 
  "value" : 7, 
  "array" :[ {"name" : "Micheal", "born" : ISODate("1975-04-17T13:11:54Z"), "hasACar" : false},
             {"name" : "Lisa", "born" : ISODate("1985-04-17T13:11:54Z"), "hasACar" : true}, 
             {"name" : "Pascal", "born" : ISODate("1965-05-19T104:11:54Z"), "hasACar" : false} ] 
}

{
  "_id" : 4, 
  "value" : 1,
  "array": [ {"name" : "Dave", "born" : ISODate("1980-04-17T13:11:54Z"), "hasACar" : true}, 
             {"name" : "Paul", "born" : ISODate("1985-04-17T13:11:54Z"), "hasACar" : false}, 
             {"name"  :"Chuck", "born" : ISODate("1980-05-19T104:11:54Z"), "hasACar" : true} ]
}

I would like to retrieve all documents with only matching subdocuments. The criteria is born after 1979 and hasACar is false, which means omit people who has a var, and born before 1979, then return documents.

I could make this mathing with Aggregation framework but I am curious about is there another way to make it without using aggregationor mapreduce.

I tried to used $elemMatch operator in projection case when querying but it returns documents with only first matching subdocument.

Any help or advice appreciated.

Thx.

C.Kaya
  • 21
  • 1
  • 4
  • Can you edit your question to improve the formatting of your example docs? – JohnnyHK Sep 18 '14 at 21:43
  • Much better now, thanks! You're going to need to use the aggregation framework for what you're looking to do. Here's the most canonical set of answers on the topic: http://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection – JohnnyHK Sep 18 '14 at 22:31
  • In fact I can do what I want with aggregation framework as I mentioned above. But I would like to learn is there a way just using this with default find method and operator of mongoDB itself. Is aggregaton(map-reduce) only the way to reach my point ? – C.Kaya Sep 18 '14 at 22:40
  • The aggregation framework is the only way. MongoDB find queries don't match multiple elements of an array field. – wdberkeley Sep 19 '14 at 15:06

0 Answers0