假设我有这些文件:
{ "_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 :(得分:2)
您可以尝试以下聚合。
db.collection.aggregate({$unwind:"$colors"},{$group: { _id:"$colors",count:{$sum:1} }})
查询将$unwind
数组。来自文档
从输入文档解构数组字段以输出a 每个元素的文档。
$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" }
使用$group
计算颜色时,下一步是color
$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)))));