使用多个标准与mongo 3聚合管道进行分组

时间:2016-06-08 16:23:06

标签: java mongodb

在此处找到的示例(http://mongodb.github.io/mongo-java-driver/3.2/builders/aggregation/)中,聚合分组基于"$customerId"

collection.aggregate(Arrays.asList(match(eq("author", "Dave")),
             group("$customerId", sum("totalQuantity", "$quantity"),
                                  avg("averageQuantity", "$quantity"))
             out("authors")));

如何将其他分组字段添加到汇总管道中,例如 "$systemId"

mongo-shell 中,您可以执行以下操作:

db.coll.aggregate(
  [
    {
      $group : {
        _id : {"customerId":"$customerId", "systemId":"$systemId"},
        //etc
      }
    }
  ]
)

Java 中,您可以构建一个查询:

DBObject groupFields = new BasicDBObject();
DBObject groupIdFields = new BasicDBObject();
groupIdFields.put("customerId", "$customerID");
groupIdFields.put("systemId", "$systemId");
groupFields.put( "_id", groupIdFields );

//...
//... here some more aggregate criteria
//...

final AggregationOutput output = coll.aggregate(group);

现在,这似乎是一个非常多的代码,只是为了获得多个分组标准。如何使用 mongo 3 java驱动程序中的聚合管道?

0 个答案:

没有答案