2

如何计算 mongoDB 和 spring 中字段的平均值。我们有 $avg() 函数供终端使用,但如何使用 mongotemplate 执行它。

例如在

 db.sales.aggregate(
    [
     {
       $group:
         {
           _id: "$item",
           avgAmount: { $avg: { $multiply: [ "$price", "$quantity" ] } },
           avgQuantity: { $avg: "$quantity" }
         }
     }
   ]
)

我们在这里计算平均值,所以我们如何使用 mongotemplate 执行它。

现在我正在使用一个函数来获得平均评分

我正在使用这样的功能..

public List getrating() {

    TypedAggregation<RatingReviewModel> agg = newAggregation(RatingReviewModel.class,

           group("hospitalid")            
            .avg("rating").as("avgrating")
    );

    AggregationResults<DBObject> result = operations.aggregate(agg, DBObject.class);
    List<DBObject> resultList = result.getMappedResults();

return resultList;
}

但是在调试时 resultList 是 Empty 所以它什么也没返回。

4

1 回答 1

2

假设您的 Sale 对象定义为:

class Sale {
    String id;
    String item;
    double price;
    int quantity;
}

使用 mongotemplate 您需要事先$project在管道中使用一个阶段来获取计算字段,这可能有点违反直觉,因为使用本机 MongoDB 聚合,所有操作都在一个$group操作管道中完成,而不是将聚合分为两个阶段,因此:

import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;

TypedAggregation<Sale> agg = newAggregation(Sale.class,
      project("quantity")
         .andExpression("price * quantity").as("totalAmount"),
      group("item")            
        .avg("totalAmount").as("avgAmount")
        .avg("quantity").as("avgQuantity")
);

AggregationResults<DBObject> result = mongoTemplate.aggregate(agg, DBObject.class);
List<DBObject> resultList = result.getMappedResults();

以上也可以使用本机Java Driver实现来实现:

ApplicationContext context = new AnnotationConfigApplicationContext(SpringMongoConfig.class);
MongoOperations operation = (MongoOperations) context.getBean("mongoTemplate");

BasicDBList pipeline = new BasicDBList();
String[] multiplier = { "$price", "$quantity" };

pipeline.add(
    new BasicDBObject("$group",
        new BasicDBObject("_id", "$item")
        .append("avgAmount", new BasicDBObject(
            "$avg", new BasicDBObject(
                "$multiply", multiplier
            )
        ))
        .append("avgQuantity", new BasicDBObject("$avg", "$quantity"))
    )
);

BasicDBObject aggregation = new BasicDBObject("aggregate", "sales")
                            .append("pipeline", pipeline);
System.out.println(aggregation);
CommandResult commandResult = operation.executeCommand(aggregation);
于 2015-03-27T12:35:41.120 回答