pmajcher
pmajcher

Reputation: 557

'If' statement in mongodb query

Let's assume I have collection in mongodb with a few documents:

{aField: 1},
{aField: 4},
{aField: 5}

I'm trying to write a MongoRepository (from Spring Data) method

@Query(...)
List<DomainObject> find(String aParam)

with following requirements:

  1. If parameter 'aParam' is lower than SOME_VALUE (let's say 4) -> select all documents that have field 'aField' lower than 'aParam'
  2. Else get all documents with 'aField' greater than SOME_VALUE.

Is it doable in one query? Or do I need to prepare two separate queries and chose a proper one in (Java) code?

I'm trying to do something like this:

@Query"{$or: [
{aField: {$lte: ?0}, 4: {$gt: ?0}}}, 
{aField: {$gt: 4}, 4: {$lte: ?0}}
]}"

or

@Query"{$or: [
{$and: [{aField: {$lte: ?0}}, {4: {$gt: ?0}}]},
{$and: [{aField: {$gt: 4}},  {4: {$lte: ?0}}]} 
]}"

Both queries are valid but don't work. Corner cases are not important here (gt vs gte and so on). I'm looking for a general solution in that case.

I will be grateful for help.

Upvotes: 1

Views: 5934

Answers (1)

Clement Amarnath
Clement Amarnath

Reputation: 5466

You are looking for a dynamic condition, pseudo code of your scenario

if aParam <= 4
   db.collection.find({aField:{$lte:aParam}})
else 
   db.collection.find({aField:{$gte:aParam}})

this cannot be done as of now in a single query, you have to wait for Mongo version 3.3.5 and currently available official version is 3.2.10, Please see https://jira.mongodb.org/browse/SERVER-10689

So please do this logic in the java layer itself.

Hope it Helps!

Upvotes: 1

Related Questions