java - MongoDB聚合查询转java代码

标签 java mongodb aggregation-framework

我正在尝试将mongoDB查询转换为Javacode,但它在mongo中返回正确的值,但是当在java代码中运行时,它没有返回正确的计数值(它返回正确的machineID、errorID,但计数为null,而是count 应返回记录数)。

Mongo 驱动程序名称

mongo-java-driver-3.3.0.jar

MongoDB 查询

 db.getCollection('collectionName').aggregate([
    {"$match" : {"machineID": {"$in": ["1","10"]} , "errorID" : "error5"}},
    {"$group" : {_id : {machineID : "$machineID", errorID : "$errorID"}, count : {$sum  : 1} } },
    {$project : {machineID : "$_id.machineID", errorID : "$_id.errorID", count : "$count", _id : 0}}
])

Java 代码:

AggregateIterable<Document> resultset =dbCollection.aggregate(Arrays.asList(
                new Document("$group", new Document("_id", new BasicDBObject("machineID", "$machineID").append("errorID","$errorID").append("count", new BasicDBObject("$sum",1)))),
                new Document("$project", new Document("machineID", "$_id.machineID").append("errorID", "$_id.errorID").append("count", "$count").append("_id", 0))));

返回值

machine ID -> 100
errorID  -> error3
count  -> null

最佳答案

如果您尝试保持与 JSON 格式示例相同的结构,这会有所帮助:

AggregateIterable<Document> resultset =dbCollection.aggregate(Arrays.asList(
  new Document("$match",
    new Document("machineID", new Document("$in", Arrays.asList("1","10")))
      .append("errorID", "error5")
  ),

  new Document("$group", 
    new Document("_id", 
      new Document("machineID", "$machineID").append("errorID","$errorID")
    ).append("count", new Document("$sum",1))
  ),

  new Document("$project", 
    new Document("machineID", "$_id.machineID")
      .append("errorID", "$_id.errorID")
      .append("count", "$count")
      .append("_id", 0)
  )
));

关于java - MongoDB聚合查询转java代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44513423/

相关文章:

mongodb - 在嵌套数组中查找第一个符合条件的元素

MongoDB: '$redact' 结果仅匹配嵌入对象

java - 在 Java 中将对象和原始数据作为参数传递有什么区别?

java - 数字图像处理中是否有任何标准算法将输入 RGB 图像划分为所需大小的子图像(示例 8x8)

javascript - 如果我链接 .sort(), Mongoose 查询会失败

python-3.x - 无法使用类对象中的ssh隧道建立与远程mongoDB服务器的连接

javascript - 按字段的一部分进行分组/计数

java - Hibernate 从控制台记录异常

java - 如何使用 JDBC 在一个事务中执行 2 个更新查询

node.js - Mongoose 聚合返回不需要的空数组