0

I have an entity class where I have a value as the salary. Datatype of salary is bigdecimal. Now I want to perform one query on this entity where I have 2 values, fromSalary and toSalary. I want all the employees with salary > fromSalary and salary < toSalary. I am using mongodb as datastore and using mongotemplate criteria query for this operation.

Salary is in Bigdeciaml, fromSalary and toSalary are in Double.

I tried 2 ways.

Criteria.where(Salary).gte(new BigDecimal(fromSalary)).lte(new BigDecimal(toSalary))) ; Criteria.where(Salary).gte(fromSalary).lte(toSalary)) ;

When I perform these operation, I get empty response in both the cases even though I have data in this range in my database.

How to perform range operation on bigdecimal?

1 Answers1

0

The underlying problem is Spring Data MongoDB converts BigDecimal values to String by default, so your salary field is actually being stored as String in MongoDB.

You can modify the default conversion with @Field annotation like this:

@Field(targetType = FieldType.DECIMAL128)
private BigDecimal salary;

This way the salary field's value will be stored as MongoDB's native Decimal128 type, and the queries in your question will work as you expect.

You can check the relevant answer from Christoph Strobl here.

Turzo
  • 490
  • 1
  • 5
  • 14