0

我正在关注java中的mongo db聚合,示例显示了下面的管道。我要做的是添加一个名为的附加字段department,其中包含部门值(因此在这种情况下,该字段将具有相同的值。我尝试在with_id中添加另一个字段,但这不起作用。groupFieldsnew 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}
4

1 回答 1

1

尝试切换顺序:

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

或者您可以在组后添加另一个项目。如果您使用$projectbefore $group,它只是将值传递给组运算符,而不是直接传递给输出。

于 2013-01-25T05:28:50.197 回答