您的位置:首页 > 数据库 > Mongodb

mongodb在aggregate中怎么统计总数

2015-09-17 18:03 537 查看
[size=medium]在aggregate只能通过$group中的$sum来进行统计,如果sales表中有下面数据:[/size]

{ "_id" : { "month" : 3, "day" : 15, "year" : 2014 }, "totalPrice" : 50, "averageQuantity" : 10, "count" : 1 }
{ "_id" : { "month" : 4, "day" : 4, "year" : 2014 }, "totalPrice" : 200, "averageQuantity" : 15, "count" : 2 }
{ "_id" : { "month" : 3, "day" : 1, "year" : 2014 }, "totalPrice" : 40, "averageQuantity" : 1.5, "count" : 2 }

[size=medium]如果要得到count总记录数该怎么做呢?
我们可以通过:[/size]

db.sales.aggregate(
[
{
$group : {
_id : null,
totalPrice: { $sum: { $multiply: [ "$price", "$quantity" ] } },
averageQuantity: { $avg: "$quantity" },
count: { $sum: 1 }
}
}
]
)

[size=medium]即可得到,id:null这个非常关键
得到如下结果[/size]:

{ "_id" : null, "totalPrice" : 290, "averageQuantity" : 8.6, "count" : 5 }

[size=medium]java代码可以通过如下[/size]

DBObject count = new BasicDBObject("$sum",1);
DBObject groupFileds = new BasicDBObject("_id", null);
groupFileds.put("count", count);
DBObject group = new BasicDBObject("$group", groupFileds);
AggregationOutput output = collection.aggregate(Arrays.asList(group));
List<DBObject> dbObjects = (List<DBObject>) output.results();
int count = (int) dbObjects.get(0).get("count");


这里干嘛不直接用mongodb的count,这是因为如果在这个统计中如果有根据地理空间距离查找的要求,那么就不满足要求了,所以改用aggregate进行统计是个不错的选择
阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: