groupby不会返回任何内容

时间:2014-11-21 23:58:40

标签: mongodb-query

我是mongodb的新手,我有以下数据库:

/* 0 */
 {
    "_id" : ObjectId("546fca4bbadc0f7939048d76"),
     "name" : "ali",
     "time" : "20141105230000",
     "entity" : [ 
      1, 
      3, 
      4
   ],
"count" : 10
}

 /* 1 */
   {
        "_id" : ObjectId("546fca91badc8a4a144cfd8e"),
        "name" : "ali",
        "time" : "20141105231200",
       "entity" : [ 
      1, 
      3
    ],
     "count" : 10
     }

现在我想按姓名分组并返回计数总和:

我有以下代码,但它没有返回任何内容:

 DBCollection coll=db.getCollection("test");
     DBObject groupFields = new BasicDBObject( "_id", "$name");
      DBCursor  cur=coll.find(groupFields);
      while(cur.hasNext()){
          System.out.println(cur.next());

任何人都可以帮助我如何正确地做到这一点吗?

1 个答案:

答案 0 :(得分:2)

您需要将$sum函数传递到$group阶段才能获得每个组的计数总和。而且您不能简单地触发查找查询。您需要执行聚合操作才能获得结果。

  DBObject groupFields = new BasicDBObject( "_id", "$name");
  groupFields.put("sum", new BasicDBObject( "$sum", "$count"));
  DBObject group = new BasicDBObject("$group", groupFields);

  List<DBObject> pipeline = Arrays.asList(group);
  AggregationOutput output = coll.aggregate(pipeline);

  for (DBObject result : output.results()) {
        System.out.println(result);
    }

我请求您浏览文档以获取更多信息,尝试直到您找不到解决方案然后在stackoverflow上询问它。这就是你将如何改进。这只是一个建议。 :http://docs.mongodb.org/ecosystem/tutorial/use-aggregation-framework-with-java-driver/