Reputation: 557
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:
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
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