$ avg没有返回平均值

时间:2013-03-25 15:50:49

标签: java mongodb average jongo

这是我的代码:

//Build the query
        //match only records in cluster 1
        DBObject match = new BasicDBObject("$match", new BasicDBObject("clusterId",_id));
        //the projected result must be : clusterId, squeezePlay, weakShowdown, playsWithFriends
        DBObject projectFields = new BasicDBObject("clusterId",1);
        projectFields.put("squeezePlay", 1);
        projectFields.put("weakShowdown", 1);
        projectFields.put("playsWithFriends", 1);
        DBObject project = new BasicDBObject("$project", projectFields);        
        //the groupfields are the average of each category grouped by clusterId
        DBObject groupFields = new BasicDBObject("_id",new BasicDBObject("clusterId","$clusterId"));
        groupFields.put("squeezePlay", new BasicDBObject("$avg","$squeezePlay"));
        groupFields.put("weakShowdown", new BasicDBObject("$avg","$weakShowdown"));
        groupFields.put("playsWithFriends", new BasicDBObject("$avg","$playsWithFriends"));
        DBObject group = new BasicDBObject("$group", groupFields);


        AggregationOutput output = coll.aggregate( match, project, group);

数据库中的玩家如下:

        Player p1 = new Player();
        p1.SetClusterID(1);
        p1.SetId("Player 1");
        p1.SetNumberOfPlays(21);
        p1.SetPlaysWithFriends(22);
        p1.SetSqueezePlay(23);
        p1.SetWeakShowdown(24);

        Player p2 = new Player();
        p1.SetClusterID(1);
        p2.SetId("Player 2");
        p2.SetNumberOfPlays(11);
        p2.SetPlaysWithFriends(12);
        p2.SetSqueezePlay(13);
        p2.SetWeakShowdown(14);

输出应为:(17.0,18.0,19.0) 但我得到:"Averages are: 23.0 22.0 24.0"这对我来说更像是Max(或者也许只是玩家1的结果)......我不知道。

1 个答案:

答案 0 :(得分:1)

错误错误:

在实例化播放器p2后,您应该说p2.setClusterId(1)