数据集可在http://docs.mongodb.org/manual/tutorial/aggregation-zip-code-data-set/
中找到现在,我正在尝试实施以下功能“按州恢复平均城市人口”:
db.zips.aggregate( { $group :
{ _id : { state : "$state", city : "$city" },
pop : { $sum : "$pop" } } },
{ $group :
{ _id : "$_id.state",
avgCityPop : { $avg : "$pop" } } } )
输出: { “结果”:[ { “_id”:“RI”, “avgCityPop”:18933.28301886793 }
请帮助我JAVA,谢谢
答案 0 :(得分:0)
试试这个:
// First $group operation
DBObject compoundId = new BasicDBObject( "state", "$state");
compoundId.append("city", "$city")
DBObject groupFields1 = new BasicDBObject( "_id", compoundId );
groupFields1.put("pop", new BasicDBObject( "$sum", "$pop"));
DBObject group1 = new BasicDBObject("$group", groupFields1);
// Second $group operation
DBObject groupFields2 = new BasicDBObject( "_id", "$_id.state");
groupFields2.put("avgCityPop", new BasicDBObject( "$avg", "$pop"));
DBObject group2 = new BasicDBObject("$group", groupFields2);
// Run aggregation
AggregationOutput output = collection.aggregate( group1, group2 );