[JAVA-2627] Accumulators not working properly Created: 09/Oct/17  Updated: 27/Oct/23  Resolved: 10/Oct/17

Status: Closed
Project: Java Driver
Component/s: BSON
Affects Version/s: 3.5.0, 3.6.0
Fix Version/s: None

Type: Bug Priority: Major - P3
Reporter: ALESSANDRO PENDINELLI Assignee: Ross Lawley
Resolution: Works as Designed Votes: 0
Labels: accumulator, aggregate
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Windows 8.1 - IDE Eclipse Java - Java 8 - MongoDB 3.4.9



 Description   

Accumulators dosn't work as they should, they just replace the value given instead to process it.

Example:

Document document = new Document("firstname", "Pedro")
.append("lastname", "Doe")
.append("age", 14)
.append("country", "Tanzania")
.append("index", 1);

collection.insertOne(document);

List<Bson> query= asList(Aggregates.match(Filters.eq("firstname", "Pedro")),Aggregates.group("$_id", Accumulators.avg("age", 100), Accumulators.sum("index", 100)));
AggregateIterable<Document> resuls t= collection.aggregate(query);
for(Document d : results)

{ System.out.println(d.toJson()); }

-Result:
{ "_id" :

{ "$oid" : "59dbb669dfbc63214831e70c" }

, "age" : 100.0, "index" : 100 }

-expected:
{ "_id" :

{ "$oid" : "59dbb669dfbc63214831e70c" }

, "age" : 57.0, "index" : 101}



 Comments   
Comment by Ross Lawley [ 10/Oct/17 ]

No problems pendy01,

All the best,

Ross

Comment by ALESSANDRO PENDINELLI [ 09/Oct/17 ]

I'm sorry to posted this as bug now i do understand the proper way to use it.

Thank you very much for the answer.

Comment by Ross Lawley [ 09/Oct/17 ]

Hi pendy01,

Thanks for the ticket. I think theres a misunderstanding as to how the the $avg and $sum accumulators work. Take Accumulators.age:

Accumulators.age(fieldName, expression)

The fieldName, is the outputted field name - essentially the projected field name. The expression can relate to a number of different expressions types. However, here you probably want to use a field path.

In the following example, the age field is averaged and projected out into an averageAge field.:

Accumulators.avg("averageAge","$age")

The sum accumulator works in the same fashion.

I hope that helps,

Ross

Generated at Thu Feb 08 08:57:41 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.