Home > Enterprise >  Get total of field of Mongodb collection in Java
Get total of field of Mongodb collection in Java

Time:10-18

I can find the answer (think?) for plain Mongodb querying, but nothing for Java for this particular use case...

I have a collection that is typed to the following object:

public class TestObj {
    ObjectId id;
    long value = 0;
    // etc
}

I would like the sum of the value field across all objects held in the collection. How can I do this?

My current hangup is no matter wat I do, the aggregate method from the collection returns the type TestObj, and not a more generic object with the answer I seek. I have tried project, but didn't seem to have any effect.

Current code:

    public long getTotalValue(){
        Object returned = this.getCollection().aggregate(
            List.of(
                Aggregates.group(null, Accumulators.sum("$value", 1))
            )
        );
        //TODO:: get sum
        return 0L;
    }

CodePudding user response:

If you want to count how many collections have the value field you can use count in aggregation.

But if you want the sum of the values that the value field has in your collections you can calculate it like this with mongoDb aggregation

Arrays.asList(new Document("$group", 
   new Document("_id", 
   new BsonNull())
        .append("value", 
   new Document("$sum", "$value"))))

value is the name of your field in the collection

  • Related