Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: Find Subdocument in Array Matching Parameters

Tags:

mongodb

In MongoDB I would like to find a document based on the values of a subdocument meeting certain parameters. Specifically I have a document structured like this:

{   name: "test",   data: [{     name: "test1",     start: 0,     end: 2   },   {     name: "test2",     start: 15     end: 18   }] } 

How can I tell MongoDB to only return my document if the start time for a data subdocument is less than 5 and the end time for the same subdocument is greater than 5? Currently, if I do

db.foo.findOne({   'data.start': { $lte: 5 },   'data.end': { $gte: 5 } }) 

it will return my document always because 5 is greater than 0 and less than 18. How can I tell MongoDB to only return my document if 5 (or whatever value) is greater than 0 and less than 2 OR greater than 15 and less than 18?

like image 868
Matt Weir Avatar asked Aug 06 '12 06:08

Matt Weir


People also ask

How do I filter an array in subdocument with MongoDB?

MongoDB 3.2 Update Does this solution utilises the indexes, inside the array elements (if the array element is a document in itself) ? Suppose there is an index on some path in the array element. Use cond: { $eq: ['$$item. a', <value> ] } to filter elements based on exact equivalent values.

How do I query an array of objects in MongoDB?

To search the array of object in MongoDB, you can use $elemMatch operator. This operator allows us to search for more than one component from an array object.

Where can I find nested documents in MongoDB?

Accessing embedded/nested documents – In MongoDB, you can access the fields of nested/embedded documents of the collection using dot notation and when you are using dot notation, then the field and the nested field must be inside the quotation marks.


1 Answers

You want to use $elemMatch.

db.foo.findOne({ data: { $elemMatch : {   start: { $lte: 5 },   end: { $gte: 5 }   }} }) 
like image 129
Thilo Avatar answered Nov 05 '22 09:11

Thilo