Yoga
Yoga

Reputation: 293

MongoDB aggregate query to java code

I am trying to convert mongoDB query to Javacode, but it is returning proper values in mongo, but when running in java code it is not returning proper values for count (it is returning proper machineID, errorID but count as null, instead count should return number of records).

Mongo driver name

mongo-java-driver-3.3.0.jar

MongoDB query

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

Returning values

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

Upvotes: 0

Views: 2057

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151190

It helps if you try to keep the same sort of structure to see in JSON format examples:

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

Upvotes: 3

Related Questions