MongoDB: Find Subdocument in Array Matching Parameters

后端 未结 2 1842
自闭症患者
自闭症患者 2020-12-02 14:46

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:



        
相关标签:
2条回答
  • 2020-12-02 14:47

    You want to use $elemMatch.

    db.foo.findOne({ data: { $elemMatch : {
      start: { $lte: 5 },
      end: { $gte: 5 }
      }}
    })
    
    0 讨论(0)
  • 2020-12-02 15:11

    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);
    
    0 讨论(0)
提交回复
热议问题