使用聚合$ $ of $ sum

时间:2016-10-30 21:29:29

标签: mongodb mongodb-query aggregation-framework

我正在尝试使用$ sum计算每个州的总数。然后,仅使用$ lt。

显示小于100的状态

每笔总和的工作总数:

 db.zipcode.aggregate([{$group:{_id:"$state", count_of_cities:{$sum:1}}}])

尝试显示小于100的总和:

 db.zipcode.aggregate([{$group:{_id:"$state"}, less_than:{$cond:{if:{$lt:[$sum:1,100]}}}}])

样品采集:

 { "_id" : "01001", "city" : "AGAWAM", "loc" : [ -72.622739, 42.070206 ], "pop" : 15338, "state" : "MA" }
 { "_id" : "05042", "city" : "RYEGATE", "loc" : [ -72.072669, 44.193453 ], "pop" : 328, "state" : "VT" }
 { "_id" : "05043", "city" : "EAST THETFORD", "loc" : [ -72.19668, 43.825757 ], "pop" : 657, "state" : "VT" }
 { "_id" : "08052", "city" : "MAPLE SHADE", "loc" : [ -74.99464399999999, 39.951085 ], "pop" : 19365, "state" : "NJ" }

整个馆藏可在MongoDB官方网站上找到:http://media.mongodb.org/zips.json

1 个答案:

答案 0 :(得分:2)

您可以执行:

  • 1 $group用于将城市汇总为count_of_cities
  • 1 $match来过滤您的金额值

查询是:

db.zipcode.aggregate([{
    $group: { _id: "$state", count_of_cities: { $sum: 1 } }
}, {
    $match: {
        count_of_cities: { $lt: 100 }
    }
}])