mongodb在aggregate中怎么统计总数
在aggregate只能通过$group中的$sum来进行统计,如果sales表中有下面数据:
{ "_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 }
如果要得到count总记录数该怎么做呢?
我们可以通过:
db.sales.aggregate( [ { $group : { _id : null, totalPrice: { $sum: { $multiply: [ "$price", "$quantity" ] } }, averageQuantity: { $avg: "$quantity" }, count: { $sum: 1 } } } ] )
即可得到,id:null这个非常关键
得到如下结果:
{ "_id" : null, "totalPrice" : 290, "averageQuantity" : 8.6, "count" : 5 }
java代码可以通过如下
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进行统计是个不错的选择
相关推荐
jaylong 2020-08-19
lbyd0 2020-11-17
BigYellow 2020-11-16
sushuanglei 2020-11-12
我心似明月 2020-11-09
zhushenghan 2020-11-09
sunnnyduan 2020-10-16
不要皱眉 2020-10-14
xiaohai 2020-09-29
songxiugongwang 2020-09-22
萌亖 2020-09-17
LuckyLXG 2020-09-08
sdmzhu 2020-09-01
mkhhxxttxs 2020-09-16
xiaohai 2020-09-16
newcome 2020-09-09
大秦铁骑 2020-08-19
thatway 2020-08-19