mongodb java driver在聚合/投影操作中隐藏id字段

时间:2013-01-14 03:14:19

标签: java mongodb aggregation-framework

我正在使用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 );

1 个答案:

答案 0 :(得分:2)

最后得到的_id字段来自$group运算符。如果要将其重命名为部门,请将另一个$project添加到管道的末尾,并将_id转换为部门。