mongodb命令方式:
db.myexcel.aggregate([
{
"$group": {
"_id": null,
"totalFormalNumber": {
"$sum": {
"$toDouble": "$FormalNumber"
}
},
"count": {
"$sum": 1
}
}
}
])
结果:
{
"_id": null,
"count": 1,
"totalAmount": 1000
}
java方式:主要做的就是将字符串字段$FormalNumber转化为double可做计算new Document("$toDouble","$FormalNumber")
Document sub_group = new Document();
sub_group.put("_id","$SID"); //分组字段
sub_group.put("totalFormalNumber",new Document("$avg",new Document("$toDouble","$FormalNumber"))); //平均值
Bson groupBson = new Document("$group",sub_group);
List<Document> documents = context.mongoAggregate(MongoDBConst.EXCELDB, MongoDBConst.EXCELTABLE, groupBson);