Search code examples
javamongodbgroupingprojection

mongodb (java) including id field by name


I'm following the mongo db aggregation in java, and the example shows the pipeline below. What I'm trying to do is add an additional field named department that contains the department value (so in this case it would have the same value is the _id field. I tried adding another field in the groupFields with new BasicDBObject("department",$department), but that didn't work.

// create our pipeline operations, first with the $match
DBObject match = new BasicDBObject("$match", new BasicDBObject("type", "airfare") );

// build the $projection operation
DBObject fields = new BasicDBObject("department", 1);
fields.put("amount", 1);
fields.put("_id", 0);
DBObject project = new BasicDBObject("$project", fields );

// Now the $group operation
DBObject groupFields = new BasicDBObject( "_id", "$department");
groupFields.put("average", new BasicDBObject( "$avg", "$amount"));
DBObject group = new BasicDBObject("$group", groupFields);

// run aggregation
AggregationOutput output = collection.aggregate( match, project, group );

With an output of

{"_id" : "Human Resources" , "average" : 74.91735537190083} , 
{"_id" : "Sales" , "average" : 72.30275229357798} ,
{"_id" : "Engineering" , "average" : 74.1}

Solution

  • Try to switch the order:

    AggregationOutput output = collection.aggregate( match, group, project);
    

    Or you can add another project after group. If you are using $project before $group, it just passes values into group operator, not directly to output.