1

我有一个典型的 Web 应用程序,我正在尝试从 mongodb 集合中生成构面。目前这是通过使用 Java 驱动程序 (v2.10.1) 的聚合框架来完成的。除了包含子数组的文档之外,构面已正确生成,例如我有以下 json 文档:

  1. {name: polo, fueltypes:[benzin, lpg], color: black}
  2. {name: golf, fueltypes:[benzin, cng], color: blue}
  3. {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);
4

1 回答 1

0

按数组“fueltypes”分组为您提供数组的出现次数。

要单独计算它的元素,您必须使用 $unwind 运算符,如下所示:

// create unwind
BasicDBObject unwind = new BasicDBObject();
unwind.put("$unwind", "$" + str);

并将其包含在 $group 运算符之前。或者,仅当 str 为“fueltypes”时,您才可以调用 $unwind。

有关展开的更多信息,请参阅http://docs.mongodb.org/manual/reference/aggregation/

于 2013-04-01T19:18:37.857 回答