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:
You want to use $elemMatch.
db.foo.findOne({ data: { $elemMatch : {
start: { $lte: 5 },
end: { $gte: 5 }
}}
})
Came across this post thinking of cheating the code which wasn't there ;) So thought of sharing the code snippet in Java
using spring-data-mongodb
Mongo mongo = new Mongo("localhost", 27017);
MongoTemplate mongoTemplate = new MongoTemplate(mongo, "db");
Query query = new Query();
query.addCriteria(Criteria.where("data").elemMatch(
Criteria.where("start").lte(5)
.andOperator(Criteria.where("end").gte(5))));
Foo foo = mongoTemplate.findOne(query, Foo.class);