spring 两个日期之间的Spring Data MongoDB日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12308756/
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
Spring Data MongoDB Date between two Dates
提问by sics
i'm using Spring Data for MongoDB and got the following classes
我正在使用 Spring Data for MongoDB 并获得以下类
class A {
List<B> b;
}
class B {
Date startDate;
Date endDate;
}
when i save an object of A it gets persisted like
当我保存 A 的对象时,它会像
{
"_id" : "DQDVDE000VFP8E39",
"b" : [
{
"startDate" : ISODate("2009-10-05T22:00:00Z"),
"endDate" : ISODate("2009-10-29T23:00:00Z")
},
{
"startDate" : ISODate("2009-11-01T23:00:00Z"),
"endDate" : ISODate("2009-12-30T23:00:00Z")
}
]
}
Now i want to query the db for documents matching entries in b where a given date is between startDate and endDate.
现在我想在数据库中查询与 b 中的条目匹配的文档,其中给定的日期在 startDate 和 endDate 之间。
Query query = new Query(Criteria.where("b").elemMatch(
Criteria.where("startDate").gte(date)
.and("endDate").lte(date)
);
Which results in the following mongo query:
这导致以下 mongo 查询:
{
"b": {
"$elemMatch": {
"startDate" : { "$gte" : { "$date" : "2009-11-03T23:00:00.000Z"}},
"endDate" : { "$lte" : { "$date" : "2009-11-03T23:00:00.000Z"}}
}
}
}
but returns no resulting documents. Does anybody know what i'm doing wrong? I don't get it...
但不返回结果文件。有谁知道我做错了什么?我不明白...
Thank you very much in advance!!
非常感谢您提前!
回答by JohnnyHK
If you want to find docs where dateis between the startDateand endDateof a barray element then you need to reverse your gteand ltecalls:
如果你想找到的文档,其中date是间startDate和endDate一个的b数组元素,那么你需要扭转你gte和lte来电:
Query query = new Query(Criteria.where("b").elemMatch(
Criteria.where("startDate").lte(date)
.and("endDate").gte(date)
);
回答by Simon Liu
{"created_at":{$gt:ISODate("2013-04-30T00:00:00Z"),$lt:ISODate("2013-04-30T23:59:59Z")}}

