我正在关注java中的mongo db聚合,示例显示了下面的管道。我要做的是添加一个名为的附加字段department
,其中包含部门值(因此在这种情况下,该字段将具有相同的值。我尝试在with_id
中添加另一个字段,但这不起作用。groupFields
new BasicDBObject("department",$department)
// 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 );
输出为
{"_id" : "Human Resources" , "average" : 74.91735537190083} ,
{"_id" : "Sales" , "average" : 72.30275229357798} ,
{"_id" : "Engineering" , "average" : 74.1}