0

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
0

1 Answer 1

3

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)
  )
));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.