MyBatis - 問題集 - "Due to limitations of the BasicDBObject, you can’t add a second ‘$and’"(轉)


轉載:http://www.mkyong.com/java/due-to-limitations-of-the-basicdbobject-you-cant-add-a-second-and/

Problem

Using Spring data and Mongodb, below is a function to find data within a date range.

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);

}

It hits following error message :

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"}}}]'

Solution

Adding multiple “$and” operators on the same field “createdDate” will make Spring interprets it into a wrong mongodb query. To fix it, change the query to follow :

Query query = new Query(
    Criteria.where("ip").is(ip)
    .andOperator(
        Criteria.where("createdDate").lt(endDate),
        Criteria.where("createdDate").gte(startDate)
    )
);

For multiple criteria on the same field, uses a “comma” to combine them.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM