1
我有一個典型的Web應用程序,我試圖從mongodb集合中生成構面。目前正在使用使用Java驅動程序的聚合框架(v2.10.1)完成此操作。刻面正確生成,除了含子陣列的文件,例如我有以下JSON文檔:JSON數組上的Mongodb聚合(JAVA)
{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}
fueltypes:
{_id: [benzin,lpg,cng,diesel], count: 3}
的fueltypes字段的聚合結果包含了所有的陣列字段。
但是所期望的結果應該是:
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);