問題

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`に追加すると、Springはそれを誤ったmongodbクエリに解釈します。これを修正するには、次のようにクエリを変更します。

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

同じフィールド上の複数の基準については、それらを組み合わせるために「カンマ」を使用します。