Java mongodb - 找到平均值

时间:2015-05-20 18:28:25

标签: java mongodb

哎呀,让我们开始吧。想象一下,我们有下一个mongo系列:

{
 "city": "TWENTYNINE PALMS", 
 "loc": [-116.06041, 34.237969], 
 "pop":   11412, 
 "state": "CA", 
 "_id": "92278"
}

{
"city": "NEW CUYAMA", 
"loc": [-74.823806, 34.996709], 
"pop": 80, 
"state": "CA", 
"_id": "93254"
}

{
"city": "WATERBURY", 
"loc": [-72.996268, 41.550328], 
"pop": 25128, 
"state": "CT", 
"_id": "06705"
}

请注意,loc数组是[纬度,经度]

我想获得使用java mongo驱动程序" pop"海拔高度为-75,-70的城市的平均值。

所以,使用SQL我知道查询是:

SELECT avg(pop)
WHERE loc.altitude > -75 AND lloc.altitude < -70

我在mongodb非常棒,这是我目前的代码:

    BasicDBObject doc = new BasicDBObject("loc.0", new BasicDBObject("$gte",
            -75).append("$lte", -70));

    DBCursor cursor = collection.find(doc);

前面的代码返回高度beetwen(-75,-70),的所有文件,但我不知道如何获得平均值,使用mongo驱动程序,我知道我可以使用迭代结果的java。即可。

谢谢

1 个答案:

答案 0 :(得分:0)

aggregation framework 与以下聚合管道(Mongo shell实施)一起使用:

db.collection.aggregate([
    {
        "$match": {
            "loc.0": { "$gte": -75 },
            "loc.1": { "$lte": 70 }
        }        
    },
    {
        "$group": {
            "_id": 0,
            "average": {
                "$avg": "$pop"
            }
        }
    }
])

通过上面的示例,这将输出到控制台:

/* 1 */
{
    "result" : [ 
        {
            "_id" : 0,
            "average" : 12604
        }
    ],
    "ok" : 1
}

使用Java,可以按如下方式实现:

DBObject match = new BasicDBObject();
match.put("loc.0", new BasicDBObject("$gte", -75));
match.put("loc.1", new BasicDBObject("$lte", 70));

DBObject groupFields = new BasicDBObject( "_id", 0);
groupFields.put("average", new BasicDBObject( "$avg", "$pop"));
DBObject group = new BasicDBObject("$group", groupFields);

AggregationOutput output = collection.aggregate( match, group );