简体   繁体   English

Json阵列(JAVA)上的Mongodb聚合

[英]Mongodb Aggregation on Json Array (JAVA)

I have a typical web application in which I am trying to generate facets from the mongodb collection. 我有一个典型的Web应用程序,在其中尝试从mongodb集合生成构面。 This is currently being done using the aggregation framework using the Java driver (v2.10.1). 当前,这是通过使用Java驱动程序(v2.10.1)的聚合框架来完成的。 The facets are generated correctly, except for the documents containing sub-arrays, for instance I have the following json documents: 除了包含子数组的文档外,构面均已正确生成,例如,我具有以下json文档:

  1. {name: polo, fueltypes:[benzin, lpg], color: black}
  2. {name: golf, fueltypes:[benzin, cng], color: blue}
  3. {name: a4, fueltypes:[diesel], color: blue}

The returned result set is: 返回的结果集为:

name: 名称:

{_id: polo, count: 1}
{_id: golf, count: 1}
{_id: a4, count: 1}

color: 颜色:

{_id: black, count: 1}
{_id: blue, count: 2}

fueltypes: 燃料类型:

{_id: [benzin,lpg,cng,diesel], count: 3}

The aggregated result of the fueltypes field contains all the array fields. fueltypes字段的汇总结果包含所有数组字段。

However the desired result should be: 但是,理想的结果应该是:

fueltypes: 燃料类型:

{_id: benzin, count: 2}
{_id: lpg, count: 1}    
{_id: diesel, count: 1}    
{_id: cng, count: 1}    

and the corresponding java code: 和相应的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);

Grouping by the array "fueltypes" gives you the number of occurrences of the array as such. 按数组“ fueltypes”分组可为您提供数组出现的次数。

To count it's elements individually, you'll have to use the $unwind operator, like so: 要单独计算其元素,您必须使用$ unwind运算符,如下所示:

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

and include this before the $group operator. 并将其包括在$ group运算符之前。 Alternatively, you could call the $unwind only if str is "fueltypes". 或者,仅当str为“ fueltypes”时,才可以调用$ unwind。

For more information about unwind, see http://docs.mongodb.org/manual/reference/aggregation/ 有关放松的更多信息,请参见http://docs.mongodb.org/manual/reference/aggregation/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM