我正在使用java mongodb驱动程序执行聚合操作,并且我遵循文档中的示例(粘贴在下面)。据此,_id
字段应该被隐藏。然而,根据我自己的代码以及本例的输出经验,即使将投影值设置为0(它在mongo shell中工作),_id
字段也不会隐藏。有人知道这是mongodb java驱动程序中的一个bug吗?还是我做错了什么?
// 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字段来自$group
操作符。如果您想将其重命名回department,请在管道的末尾添加另一个$project
并将_id转换为department。