我有一个典型的 Web 应用程序,我正在尝试从 mongodb 集合中生成构面。目前这是通过使用 Java 驱动程序 (v2.10.1) 的聚合框架来完成的。除了包含子数组的文档之外,构面已正确生成,例如我有以下 json 文档:
{name: polo, fueltypes:[benzin, lpg], color: black}
{name: golf, fueltypes:[benzin, cng], color: blue}
{name: a4, fueltypes:[diesel], color: blue}
返回的结果集为:
姓名:
{_id: polo, count: 1}
{_id: golf, count: 1}
{_id: a4, count: 1}
颜色:
{_id: black, count: 1}
{_id: blue, count: 2}
燃料类型:
{_id: [benzin,lpg,cng,diesel], count: 3}
Fueltypes 字段的聚合结果包含所有数组字段。
然而,期望的结果应该是:
燃料类型:
{_id: benzin, count: 2}
{_id: lpg, count: 1}
{_id: diesel, count: 1}
{_id: cng, count: 1}
和相应的java代码:
String str = "name" ; //or fueltypes, color
// create match
BasicDBObject match = new BasicDBObject();
match.put("$match", new BasicDBObject());
// build the $projection operation
DBObject fields = new BasicDBObject();
// fields.put("count", 1);
DBObject project = new BasicDBObject();
// Now the $group operation
DBObject groupFields = new BasicDBObject();
DBObject unwindFields = new BasicDBObject();
// build the $projection operation
fields.put(str, 1);
project.put("$project", fields);
// Now the $group operation
groupFields.put("_id", "$" + str);
// performing sum and storing it in the count attribute
groupFields.put("count", new BasicDBObject("$sum", 1));
DBObject group = new BasicDBObject("$group", groupFields);
AggregationOutput output = serviceCollection.aggregate(match, project, group);