使用aggregate进行分组时,多个分组条件,如下
原生sql:
db.test.aggregate(
{
$group:{
_id:{name:'$name',pro:'$pro},
total:{$sum:'$num'}
}
},
{
$project:{
total:1
}
}
)
在java中对应如下:
//按照subjname和province进行分组
DBObject groupFields = new BasicDBObject("_id", new BasicDBObject("subjname", "$subjects.name").append("province", "$province"));
//继续添加sum,avg等其他operation
groupFields.put("AvgScore", new BasicDBObject("$avg", "$subjects.scores"));