Morphia - 聚合管道计算字段

Morphia - AggregationPipeline Calculated fields

我想知道如何在 AggregationPipeline 中使用 multiply inside sum 静态方法,在 Java.

中使用 Morphia 按同一字段分组

像这样的东西,在 Morphia 中:

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

在这个问题上非常相似:Calculated group-by fields in MongoDB

提前致谢。

在您的 aggregation framework, create a projection pipeline first that does the arithmetic calculations then use the new field in your group 管道中,如下所示:

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")));