MongoDB: Find Subdocument in Array Matching Parame

2019-01-10 17:19发布

问题:

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?

回答1:

You want to use $elemMatch.

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


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


标签: mongodb