2

I'd like know how can I use multiply inside sum static method, in a AggregationPipeline with group by the same field using Morphia in Java.

Something like this, in Morphia:

   new BasicDBObject("totalSales",
                new BasicDBObject("$sum",
                        new BasicDBObject("$multiply",
                                new String[]{"$value", "$amount"})));

Is very similar at this question: Calculated group-by fields in MongoDB

Thanks in advance.

Community
  • 1
  • 1
Jnmgr
  • 169
  • 1
  • 13

1 Answers1

2

In your aggregation framework, create a projection pipeline first that does the arithmetic calculations then use the new field in your group pipeline, something like this:

Iterator<Foo> aggregate = datastore.createAggregation(Foo.class)
       .project(projection("_id").suppress(),
           projection("field1", "_id"),
           projection("field2"), projection("field3"),
           projection("sales", multiply(projection("value"), projection("amount"))))
      .group("field3", grouping("totalSales", sum("sales")));
chridam
  • 100,957
  • 23
  • 236
  • 235