我正在使用java mongodb驱动程序执行聚合操作,我按照文档中的示例(粘贴在下面)。据此,应隐藏_id
字段。但是,根据我对自己的代码以及此示例的输出的经验,即使将投影值设置为0(它可以从mongo shell运行),_id
字段也不会隐藏。有谁知道这是mongodb java驱动程序中的错误吗?或者我做错了什么?
// 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 );
答案 0 :(得分:2)
最后得到的_id字段来自$group
运算符。如果要将其重命名为部门,请将另一个$project
添加到管道的末尾,并将_id转换为部门。