Aggregate in MongoDB with Java

67 views
Skip to first unread message

m p

unread,
Nov 27, 2016, 6:36:37 AM11/27/16
to mongodb-user
Hi, I am trying to implement aggregate function but I am getting this error: 

Command failed with error 16410: 'FieldPath field names may not start with '$'.'


Here is what I have implemented:

groupFields = new BasicDBObject("_id", 0); 
        groupFields.put("count",new BasicDBObject("$sum",1)); 
        groupFields.put("_id", "$RetailerZip"); 
        group = new BasicDBObject("$group", groupFields); 
        sort = new BasicDBObject(); 
        projectFields = new BasicDBObject(); 
        
        projectFields.put("value", "$_id"); 
        projectFields.put("ReviewValue","$count"); 
        project = new BasicDBObject("$project", projectFields); 
        sort.put("ReviewValue",-1); 
        orderby=new BasicDBObject("$sort",sort); 
        limit=new BasicDBObject("$limit",5); 
        
         List<DBObject> pipeline = Arrays.asList(group, project, orderby, limit);
        AggregationOutput output = mongo.myReviews.aggregate(pipeline); //Error occurs on this line. 

Mongodb version I am using is 3.2.11. and mongo-java-driver jar file version is 3.0.4

Wan Bachtiar

unread,
Nov 27, 2016, 10:04:06 PM11/27/16
to mongodb-user

Mongodb version I am using is 3.2.11. and mongo-java-driver jar file version is 3.0.4

Hi Mittal,

I’m not entirely sure why you would be getting the error message. Although I can see a couple of improvements that could be made:

  • The use of Document class instead of BasicDBObject for MongoDB Java Driver v3.0+
  • There’s a duplicate of _id entry in your $group that could be removed.

See below example:

Document groupFields = new Document("_id", "$RetailerZip").append("count", new Document("$sum", 1));
Document group = new Document("$group", groupFields); 

Document projectFields = new Document("value", "$_id").append("ReviewValue", "$count");
Document project = new Document("$project", projectFields); 

Document orderby= new Document("$sort", new Document("ReviewValue", -1)); 
Document limit= new Document("$limit",5); 

List<Document> pipeline = asList(group, project, orderby, limit);
AggregateIterable<Document> output = db.getCollection("myReviews").aggregate(pipeline);

If you are still seeing the same error message, could you please provide:

  • Example documents in your myReviews collection.
  • The variable types of groupField, group
  • The equivalent of the aggregation pipeline in mongo shell

Regards,

Wan.

Reply all
Reply to author
Forward
0 new messages