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?
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.
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.
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.
You want to use $elemMatch.
db.foo.findOne({ data: { $elemMatch : { start: { $lte: 5 }, end: { $gte: 5 } }} })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With