I have this console query:
db.testcol.find({ $expr: { $lte: [ { $toDouble: "$someField" }, 5 ] } })
I want to write it programmatically using Criteria so I can do the following:
mongoTemplate.find(new Query(criteria), MyClass.class)
I tried:
Criteria criteria = Criteria.where("someField").lte(5)
But I don't really know where I can put the $toDouble
part.
Thanks in advance!
You need to call Criteria.expr() method:
MongoExpression expr = ComparisonOperators.Lte
.valueOf(ConvertOperators.ToDouble.toDouble("$someField"))
.lessThanEqualToValue(5);
Criteria criteria = Criteria.expr(expr);
mongoTemplate.find(Query.query(criteria), MyClass.class);
Alternative solution: Not all MongoDB queries are easily done in the "Spring way". You may run the query operator JSON this way:
collection.find(query) == collection.aggregate([{"$match": query}])
Aggregation agg = Aggregation.newAggregation(ctx -> new Document("$match",
Document.parse("{ $expr: { $lte: [ { $toDouble: '$someField' }, 5 ] } }")));
mongoTemplate.aggregate(agg, MyClass.class, MyClass.class).getMappedResults();