【问题标题】:How can we count the number of items in arraylist from different documents in mongodb java?我们如何计算来自mongodb java中不同文档的arraylist中的项目数?
【发布时间】:2017-06-27 17:13:04
【问题描述】:

假设我有这些文件:

{ "_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");

【问题讨论】:

  • 对于版本 db.collection.aggregate({$unwind:"$colors"},{$group: { _id:"$colors",count:{$sum:1} }})
  • 我用的是3.2版本,但是我是mongodb新手,能不能给我一个更清楚的解释@Veeram

标签: java sql mongodb search count


【解决方案1】:

你可以试试下面的聚合。

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

【讨论】:

  • 感谢您的解释。我实际上确实了解聚合在 mongodb 中的工作原理。我无法适应 java 语法。
  • Np。有什么问题?你能展示你的java代码吗?
  • 我不确定在哪里可以放置 $unwind 和 $unwind。我正在调查stackoverflow.com/questions/31643109/…,但仍然没有任何线索
  • 它迫使我切换到这个并导致错误 table.aggregate((List extends DBObject>) Arrays.asList(Aggregates.unwind("$colors"), Aggregates.group(" $colors", Accumulators.sum("colors", 1))));
  • aggregate 返回 AggregateIterable,这只是光标的包装。您可以使用它来映射数据。
猜你喜欢
  • 2017-11-19
  • 1970-01-01
  • 1970-01-01
  • 2012-02-17
  • 1970-01-01
  • 2018-01-18
  • 2015-11-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多