0

I want to do sum aggregation of a salary which is stored as String in document. I dont want to convert the string value to int in database itself. Something like below in mongoDB using java driver.

SELECT sum(CAST(amount AS UNSIGNED)) FROM tbl1

I tried to cast in acumulator as follows but its giving zero as output.

 accumulator = Accumulators.sum("value",  $toInt: "$"+field);

I can do it in native mongodb query but I want to do it in java driver.

1 Answer 1

0
List<Bson> pipeline = Arrays.asList(group(new BsonNull(), sum("total", eq("$toInt", "$value"))));
AggregateIterable<Document> result = collection.aggregate​(pipeline);

The static imports are from the com.mongodb.client.model package.

Optionally, since you are accumulating money, you can consider $toDecimal or $toDouble instead of $toInt.

Sign up to request clarification or add additional context in comments.

9 Comments

where is eq method present. Its not int com.mongodb.client.model?
The com.mongodb.client.model.Filters class. eq is a static method. Also, Aggregates.group and Accumulators.sum.
Does eq mean "equal" here? Why could it apply $toDecimal to a field?
@can. In this case it means (I think), that the $toInt operator is applied to the documentproperty value and assigned to the field total. The definition of Filters.eq. says: "Note that this doesn't actually generate a $eq operator, as the query language doesn't require it."
_Why could it apply $toDecimal to a field? _ Because sometimes the source value (a number in a string type field) can have decimal values (e.g., "12.59") - so you can use the $toDecimal to sum, and get the result as the same data type. Note that MongoDB supports 4 types of number fields - int, long, double and NunberDecimal. And the default for a number type is a double or an int (depends upon the version of MongoDB and the size of the number).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.