MongoDB聚合查询到java代码

时间:2017-06-13 06:02:50

标签: java mongodb aggregation-framework

我正在尝试将mongoDB查询转换为Javacode,但是它在mongo中返回正确的值,但是在java代码中运行时它没有为count返回正确的值(它返回正确的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}}
])

Javacode:

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

1 个答案:

答案 0 :(得分:3)

如果您尝试保持相同类型的结构以便在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)
  )
));