0

Ich schrieb dieses MongoDB Abfrage in Java:Gruppe und die Summe in Aggregation mit MongoDB Java-Treiber

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

und der Code ist

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

er den Fehler

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) 

gibt Bitte hilf mir, den Fehler herauszufinden.

+0

Ihre MongoDB Shell Abfrage und Java-Code völlig anders, sind, haben Sie verschiedene Schlüssel für Ihre Gruppe Pipeline. – chridam

Antwort

1

In Ihrem Code

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

ist analog

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

sondern was Sie brauchen, ist

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

so die erste Abfrage wird

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

während der zweite

group2.put("_id", new BasicDBObject("invoiceNo", "$_id.invoiceNo")); 
group2.put("count", new BasicDBObject("$sum", 1)); 
Verwandte Themen