gpt4 book ai didi

java - 如何使用JAVA在mongoDB中实现分组功能

转载 作者:太空宇宙 更新时间:2023-11-04 14:57:32 25 4
gpt4 key购买 nike

数据集可以在 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”, “平均城市流行”:18933.28301886793 }

请帮我JAVA,谢谢

最佳答案

试试这个:

// 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 );

关于java - 如何使用JAVA在mongoDB中实现分组功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23017978/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com