问题
下面是使用Spring数据和Mongodb的功能,用于查找日期范围内的数据。
public List<RequestAudit> findByIpAndDate(String ip, Date startDate, Date endDate) {
Query query = new Query(
Criteria.where("ip").is(ip)
.andOperator(Criteria.where("createdDate").gte(startDate))
.andOperator(Criteria.where("createdDate").lt(endDate))
);
return mongoOperation.find(query, RequestAudit.class);
}
它遇到以下错误消息:
org.springframework.data.mongodb.InvalidMongoDbApiUsageException:
Due to limitations of the com.mongodb.BasicDBObject, you can't add a second '$and'
expression specified as '$and : [ { "createdDate" : { "$lt" : { "$date" : "2013-02-25T16:00:00.000Z"}}}]'.
Criteria already contains '$and : [ { "createdDate" : { "$gte" : { "$date" : "2013-02-24T16:00:00.000Z"}}}]'
解
在同一字段“ createdDate
”上添加多个“ $and
”运算符将使Spring将其解释为错误的mongodb查询。 要解决此问题,请将查询更改为:
Query query = new Query(
Criteria.where("ip").is(ip)
.andOperator(
Criteria.where("createdDate").lt(endDate),
Criteria.where("createdDate").gte(startDate)
)
);
对于同一字段上的多个条件,请使用“逗号”将其组合。
标签: mongodb spring-data
翻译自: https://mkyong.com/java/due-to-limitations-of-the-basicdbobject-you-cant-add-a-second-and/