i'm using Spring Data for MongoDB and got the following classes
我正在为MongoDB使用Spring数据,并获得了以下类。
class A {
List<B> b;
}
class B {
Date startDate;
Date endDate;
}
when i save an object of A it gets persisted like
当我保存一个对象时,它会被持久化。
{
"_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.
现在,我想查询db,查找在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!!
非常感谢!!
2 个解决方案
#1
10
If you want to find docs where date
is between the startDate
and endDate
of a b
array element then you need to reverse your gte
and lte
calls:
如果你想找到日期介于startDate和endDate b数组元素之间的文档,那么你需要反转gte和lte调用:
Query query = new Query(Criteria.where("b").elemMatch(
Criteria.where("startDate").lte(date)
.and("endDate").gte(date)
);
#2
0
{"created_at":{$gt:ISODate("2013-04-30T00:00:00Z"),$lt:ISODate("2013-04-30T23:59:59Z")}}
#1
10
If you want to find docs where date
is between the startDate
and endDate
of a b
array element then you need to reverse your gte
and lte
calls:
如果你想找到日期介于startDate和endDate b数组元素之间的文档,那么你需要反转gte和lte调用:
Query query = new Query(Criteria.where("b").elemMatch(
Criteria.where("startDate").lte(date)
.and("endDate").gte(date)
);
#2
0
{"created_at":{$gt:ISODate("2013-04-30T00:00:00Z"),$lt:ISODate("2013-04-30T23:59:59Z")}}