2017-02-09 55 views
0

假設我有這些文件:我們如何計算mongodb java中不同文檔中arraylist的項目數量?

{ "_id" : 1, "item" : "ABC1", "description" : "product 1", colors: [ "blue", "black", "red" ] } 
{ "_id" : 2, "item" : "ABC2", "description" : "product 2", colors: [ "blue", "purple" ] } 
{ "_id" : 3, "item" : "XYZ1", "description" : "product 3", colors: [ "red", "yellow"] } 

結果我想是

blue : 2 
red : 2 
black : 1 
purple : 1 
yellow : 1 

這可能使用MongoDB的執行或者我需要得到顏色數組中的Java後手動執行?提示或任何幫助將非常有用。

這是我如何得到數據庫和集合

MongoClient mongoClient = new MongoClient("localhost", 27017); 
MongoCollection<Document> collection = mongoClient.getDatabase("tweets") 
      .getCollection("tweet"); 
+0

適用版本<= 3.2可以使用'db.collection.aggregate({$展開: 「$顏色」},{$組:{_id: 「$顏色」,計數:{$ sum:1}}}) ' – Veeram

+0

我使用的是3.2版本,但我是mongodb的新手,能否給我一個更清晰的解釋@Veeram –

回答

2

你可以試試下面的聚集。

db.collection.aggregate({$unwind:"$colors"},{$group: { _id:"$colors",count:{$sum:1} }}) 

該查詢將$unwind該數組。來自文檔

解構輸入文檔中的數組字段以輸出每個元素的 文檔。

$unwind階段後的響應。

{ "_id" : 1, "item" : "ABC1", "description" : "product 1", "colors" : "blue" } 
{ "_id" : 1, "item" : "ABC1", "description" : "product 1", "colors" : "black" } 
{ "_id" : 1, "item" : "ABC1", "description" : "product 1", "colors" : "red" } 
{ "_id" : 2, "item" : "ABC2", "description" : "product 2", "colors" : "blue" } 
{ "_id" : 2, "item" : "ABC2", "description" : "product 2", "colors" : "purple" } 
{ "_id" : 3, "item" : "XYZ1", "description" : "product 3", "colors" : "red" } 
{ "_id" : 3, "item" : "XYZ1", "description" : "product 3", "colors" : "yellow" } 

下一步是$groupcolor的數據,而使用$sum計數的顏色

最終輸出

{ "_id" : "yellow", "count" : 1 } 
{ "_id" : "blue", "count" : 2 } 
{ "_id" : "black", "count" : 1 } 
{ "_id" : "red", "count" : 2 } 
{ "_id" : "purple", "count" : 1 } 

的Java更新:

3.x版

collection.aggregate(Arrays.asList(Aggregates.unwind("$colors"), Aggregates.group("$colors", Accumulators.sum("count", 1)))); 

2.x的版

collection.aggregate(Arrays.asList(new BasicDBObject("$unwind", "$colors"), new BasicDBObject("$group", new BasicDBObject("_id","$colors").append("count",new BasicDBObject("$sum", 1))))); 
+0

感謝您的解釋。我確實明白在MongoDB中聚合是如何工作的。我無法適應java語法。 –

+0

Np。有什麼麻煩?你能顯示你的java代碼嗎? – Veeram

+0

我不知道我可以放置$ unwind和$ unwind。 我正在調查http://stackoverflow.com/questions/31643109/mongodb-aggregation-with-java-driver,但仍然沒有線索 –