vbatista
vbatista

Reputation: 359

Spring data mongo not binding some parameters

I have a spring mongo repository with the following method

@Query(value = "{storeId: ?0, code: ?1, $or: [ { campaignId: ?2}, {campaignId: ''}, {campaignId: null}], $or: [ {$and: [ {'effectiveDate.from': { $lte: ?3}}, {'effectiveDate.to': { $gte: ?3}} ]}, {$and: [ {'effectiveDate.from': { $lte: ?4}}, {'effectiveDate.to': { $gte: ?4}} ]}]}")
List<GiftCard> findByGiftCardExisting(
        String storeId, String code, String campaignId, LocalDateTime from, LocalDateTime to);

The query has been tested using mongo's console. However, when running the application, I get a JSONParseException. After some digging, I have noted that parameter $2 was not bound as expected.

{storeId: "L_STORE", code: "TESTE1", $or: [ { campaignId: ?2}, {campaignId: ''}, {campaignId: null}], $or: [ {$and: [ {'effectiveDate.from': { $lte: { "$date" : "2017-04-03T03:00:00.000Z"}}}, {'effectiveDate.to': { $gte: { "$date" : "2017-04-03T03:00:00.000Z"}}} ]}, {$and: [ {'effectiveDate.from': { $lte: { "$date" : "2017-04-03T03:00:00.000Z"}}}, {'effectiveDate.to': { $gte: { "$date" : "2017-04-03T03:00:00.000Z"}}} ]}]}

The remaining parameters are working as expected. Can someone please point what's wrong?

Upvotes: 1

Views: 957

Answers (1)

s7vr
s7vr

Reputation: 75984

You have couple of problems with your query.

You are missing the parenthesis around the $or operator and the other one is you have to use explicit $and when you use specify multiple expression with same ($or) operator.

https://docs.mongodb.com/manual/reference/operator/query/and/#and-queries-with-multiple-expressions-specifying-the-same-operator

Try

@Query(value = "{storeId: ?0, code: ?1, $and:[{$or: [ { campaignId: ?2}, {campaignId: ''}, {campaignId: null}]}, {$or: [ {$and: [ {'effectiveDate.from': { $lte: ?3}}, {'effectiveDate.to': { $gte: ?3}} ]}, {$and: [ {'effectiveDate.from': { $lte: ?4}}, {'effectiveDate.to': { $gte: ?4}} ]}]}]}")
List<GiftCard> findByGiftCardExisting(
    String storeId, String code, String campaignId, LocalDateTime from, LocalDateTime to);

Upvotes: 2

Related Questions