MongoDB:在数组匹配参数中查找子文档

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11823296/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 12:47:10  来源:igfitidea点击:

MongoDB: Find Subdocument in Array Matching Parameters

mongodb

提问by Matt Weir

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:

在 MongoDB 中,我想根据满足某些参数的子文档的值来查找文档。具体来说,我有一个结构如下的文档:

{
  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

如果数据子文档的开始时间小于 5 并且同一子文档的结束时间大于 5,我如何告诉 MongoDB 仅返回我的文档?目前,如果我这样做

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?

它将始终返回我的文档,因为 5 大于 0 且小于 18。如果 5(或任何值)大于 0 且小于 2 或大于 15 且小于 18,我如何告诉 MongoDB 仅返回我的文档?

回答by Thilo

You want to use $elemMatch.

你想使用$elemMatch

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

回答by Arpit Aggarwal

Came across this post thinking of cheating the code which wasn't there ;) So thought of sharing the code snippet in Javausing spring-data-mongodb

看到这篇文章想欺骗不存在的代码 ;) 所以想到在Java使用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);