BasicDBObjectの制限により、2番目の「$ and」を追加することはできません
問題
以下は、SpringデータとMongodbを使用して、日付範囲内のデータを検索する関数です。
public ListfindByIpAndDate(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)
)
);
同じフィールドに複数の条件がある場合、「コンマ」を使用してそれらを結合します。