1

Hello i run this command in my shell:

db.getCollection('unaProva').aggregate( [ { 
$group : { _id : "$groupValue" ,total:{$sum:"$weight"}} }, { 
$project : { _id:0,groupValue : "$_id" , total : "$total" ,     
remainder: { $mod: [ "$total", "$_id" ] } } }] )

I works but i need that it works in my Java code and I don't know how can I convert it.

1 Answer 1

1

I can't check this code because I don't have the collection, but it should be something like this:

BasicDBList modArgs = new BasicDBList();
modArgs.add("$total");
modArgs.add("$_id");
coll.aggregate(asList(
    group("$groupValue", sum("total", "$weight")),
    project(fields(computed("groupValue", "$_id"),
        include("total"), excludeId(), 
        computed("remainder", new BasicDBObject("$mod", modArgs))))
));

Note that I'm using a bunch of static imports:

import static com.mongodb.client.model.Accumulators.sum;
import static com.mongodb.client.model.Aggregates.group;
import static com.mongodb.client.model.Aggregates.project;
import static com.mongodb.client.model.Projections.computed;
import static com.mongodb.client.model.Projections.excludeId;
import static com.mongodb.client.model.Projections.fields;
import static com.mongodb.client.model.Projections.include;
Sign up to request clarification or add additional context in comments.

Comments

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.