按人口范围创建索引

时间:2019-05-11 15:11:33

标签: mongodb mongodb-query aggregation-framework

MongoDB的新手,我正在尝试根据人口数对城市和县的人口进行分类。数据示例如下:

{ "_id" : "D", "name" : "Dar-e-salaam", "pop" : 212253 }
{ "_id" : "WF", "name" : "Westfalia", "pop" : 50257}
{ "_id" : "G", "name" : "Gabon", "pop" : 369536 }
{ "_id" : "M", "name" : "Montgomery", "pop" : 102585 }
{ "_id" : "LA", "name" : "Los Angeles", "pop" : 38562 }

我已使用此代码获取下表:

db.project.find({pop:{$gt: 0}}, {name:1})

{ "_id" : "LA", "name" : "Los Angeles" }
{ "_id" : "WF", "name" : "Westfalia" }
{ "_id" : "M", "name" : "Montgomery" }
{ "_id" : "G", "name" : "Gabon" }
{ "_id" : "D", "name" : "Dar-e-salaam" }

我想要得到的如下:

{ "_id" : "S", "Locations" : ["Los Angeles"] }
{ "_id" : "M", "Locations" : ["Westfalia"] }
{ "_id" : "L", "Locations" : ["Montgomery", "Gabon"] }
{ "_id" : "V", "Locations" : ["Dar-e-salaam"] }

1 个答案:

答案 0 :(得分:1)

您可以使用aggregation framework。首先,将$project$switch结合使用,以基于总体输出S,M,L或V的大小。然后,使用$group$push将文档按大小分组并在数组中收集位置名称。

db.project.aggregate([{
  $project: {
    name: 1, 
    size: { 
      $switch: {
        branches: [
          {
            case: { $lt : [ "$pop", 50000 ] },
            then: "S"
          },
          {
            case: { $and : [ { $gte : [ "$pop", 50000 ] },
                             { $lt : [ "$pop", 100000 ] } ] },
            then: "M"
          },
          {
            case: { $and : [ { $gte : [ "$pop", 100000 ] },
                             { $lt : [ "$pop", 200000 ] } ] },
            then: "L"
          },
          {
            case: { $gte : [ "$pop", 200000 ] },
            then: "V"
          }
        ]
      }
    }
  }
}, {
  $group: {
    _id: "$size",
    Locations: { $push : "$name" }
  }
}])