41

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?

2 Answers 2

79

You want to use $elemMatch.

db.foo.findOne({ data: { $elemMatch : {
  start: { $lte: 5 },
  end: { $gte: 5 }
  }}
})
Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

can you give a code snippet like that using morphia?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.