0

I wrote this MongoDB query in Java:

db.collection.aggregate(
    { $group : { 
        _id : { "category" : "$category", "type" : "$type" }, 
        number : { $sum : 1 } 
    } },
    { $group : {
        _id : "$_id.category", 
        number : { $sum : 1 } 
    } } 
)

and the code is

DBObject group1 = new BasicDBObject();
group1.put("_id",  new BasicDBObject("invoiceNo", "$invoiceNo")
      .append("invoiceDate", "$invoiceDate")
      .append("count", new BasicDBObject("$sum",1)));

DBObject group2 = new BasicDBObject();
group2.put("_id", new BasicDBObject("invoiceNo", "$_id.invoiceNo")
      .append("count", new BasicDBObject("$sum",1)));

AggregationOutput output = dummyColl.aggregate(new BasicDBObject("$group", group1), 
       new BasicDBObject("$group", group2));

It gives the error

com.mongodb.CommandFailureException: { "serverUsed" : "localhost/127.0.0.1:27017" , "errmsg" : "exception: invalid operator '$sum'" , "code" : 15999 , "ok" : 0.0}
at com.mongodb.CommandResult.getException(CommandResult.java:71)
at com.mongodb.CommandResult.throwOnError(CommandResult.java:110)
at com.mongodb.DBCollection.aggregate(DBCollection.java:1308) 

Please help me to figure out the error.

1
  • Your MongoDB shell query and Java code are completely different in that you have different keys for your group pipeline. Commented Aug 9, 2016 at 9:25

1 Answer 1

1

In your code

group1.put("_id",  new BasicDBObject("invoiceNo", "$invoiceNo")
  .append("invoiceDate", "$invoiceDate")
  .append("count", new BasicDBObject("$sum",1)));

is analogue of

$group: { 
  "_id": 
    { 
      "invoiceNo": "$invoiceNo",
      "invoiceDate": "$invoiceDate", 
      "count": { "$sum", 1 } 
    } 
}

but instead what you need is

$group: { 
  "_id": { "invoiceNo": "$invoiceNo", "invoiceDate": "$invoiceDate" },
  "count": { "$sum", 1 } 
}

so the first query will be

group1.put("_id",  new BasicDBObject("invoiceNo", "$invoiceNo")
  .append("invoiceDate", "$invoiceDate");
group1.put("count", new BasicDBObject("$sum", 1));

while the second

group2.put("_id", new BasicDBObject("invoiceNo", "$_id.invoiceNo"));
group2.put("count", new BasicDBObject("$sum", 1));
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.