java操作mongodb根據關鍵字分組統計個數
阿新 • • 發佈:2019-01-11
部分需求需要在mongodb的集合中按照關鍵字分組並統計出個數,如:一個集合裡是所有公司的資訊,然後在前端頁面中需要展示公司的分佈情況,這時就需要後端對公司所在的城市分組求和,然後給出每個城市中公司的數量。這個操作就需要mongodb的聚合函數了(aggregate);
舉個例子,集合中有公司的city關鍵字,我們需要對city分組,然後求和。
聚合命令:
db.getCollection('company_profile').aggregate( [{ "$group" : { "_id" : "$city", "value" : { "$sum" : 1 } } }] )
顯然,這個格式並不是很好用,因為資料需要弄到echars的地圖上,需要換成name:成都市,value:50的形式。
換格式,在後面加條命令:{ "$project" : { "_id" : 0, "name" : "$_id", "value" : "$value" } }
意思就是說:name欄位的值就是上面查詢出來的_id,value就是上面的value,_id則不需要。
命令如下:
db.getCollection('company_profile').aggregate( [{ "$group" : { "_id" : "$city", "value" : { "$sum" : 1 } } }, { "$project" : { "_id" : 0, "name" : "$_id", "value" : "$value" } }] )
查詢結果:
java程式碼:
package org.kelab.enterprise.dao; import com.mongodb.*; import com.mongodb.client.AggregateIterable; import com.mongodb.client.MongoCursor; import com.mongodb.client.MongoDatabase; import org.bson.Document; import org.bson.conversions.Bson; import org.cn.wzy.util.PropertiesUtil; import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { MongoClientOptions options = MongoClientOptions.builder() .connectionsPerHost(PropertiesUtil.IntegerValue("mongo.connectionsPerHost")) .maxWaitTime(PropertiesUtil.IntegerValue("mongo.maxWaitTime")) .socketTimeout(PropertiesUtil.IntegerValue("mongo.socketTimeout")) .maxConnectionLifeTime(PropertiesUtil.IntegerValue("mongo.maxConnectionLifeTime")) .connectTimeout(PropertiesUtil.IntegerValue("mongo.connectTimeout")) .serverSelectionTimeout(PropertiesUtil.IntegerValue("mongo.serverSelectionTimeout")) .localThreshold(PropertiesUtil.IntegerValue("mongo.localThreshold")) .build(); ServerAddress serverAddress = new ServerAddress(PropertiesUtil.StringValue("mongo.host"), PropertiesUtil.IntegerValue("mongo.port")); List<ServerAddress> addrs = new ArrayList<>(); addrs.add(serverAddress); MongoCredential credential = MongoCredential.createScramSha1Credential( PropertiesUtil.StringValue("mongo.user") , PropertiesUtil.StringValue("mongo.connect") , PropertiesUtil.StringValue("mongo.pwd").toCharArray()); MongoClient mongoClient = new MongoClient(addrs, credential, options); MongoDatabase mongo = mongoClient.getDatabase(PropertiesUtil.StringValue("mongo.db")); List<Bson> list = new ArrayList<>(); BasicDBObject _id = new BasicDBObject("_id", "$city"); _id.append("value", new BasicDBObject("$sum", 1)); BasicDBObject group = new BasicDBObject("$group", _id); list.add(group); BasicDBObject result = new BasicDBObject(); result.append("_id", 0); result.append("name", "$_id"); result.append("value", "$value"); BasicDBObject project = new BasicDBObject("$project", result); list.add(project); System.out.println(list); AggregateIterable<Document> iterable = mongo.getCollection("company_profile").aggregate(list); MongoCursor<Document> set = iterable.iterator(); while (set.hasNext()) { Document map = set.next(); System.out.println(map); } } }