如何在使用go从mongodb获取数据时对数据进行分组



我有一个名为"myplace"的集合,它有以下文件place_name,city,latitude,经度。

文件格式

{
      "_id" : ObjectId("544a2147785b707b340ed6c7"),
      "latitude" : 12.36547,
      "longitude" : 1.235689,
      "place_name" : "some_place",
      "city" : "City1"
}
{
      "_id" : ObjectId("544a2147785b707b340ed6c7"),
      "latitude" : 12.36547,
      "longitude" : 1.235689,
      "place_name" : "some_place",
      "city" : "City3"
}
{
      "_id" : ObjectId("544a2147785b707b340ed6c7"),
      "latitude" : 12.36547,
      "longitude" : 1.235689,
      "place_name" : "some_place",
      "city" : "City1"
 }
 {
      "_id" : ObjectId("544a2147785b707b340ed6c7"),
      "latitude" : 12.36547,
      "longitude" : 1.235689,
      "place_name" : "some_place",
      "city" : "City2"
}
{
      "_id" : ObjectId("544a2147785b707b340ed6c7"),
      "latitude" : 12.36547,
      "longitude" : 1.235689,
      "place_name" : "some_place",
      "city" : "City2"
}

如何对同一城市的数据进行分组?这意味着我需要json结果的数组,第一个数组应该包含所有具有city1的数据,第二个数组应该包括所有具有city2的数据等等

在我看来,您可以在Mongo中更容易地完成这项工作。使用聚合框架。

db.yourCollection.aggregate([{$group:{_id: "$city", details:{$push: {latitude:  "$latitude",  longitude: "$longitude", place_name:"$place_name"}}}}])

我认为这应该有效,我现在不能在工作中尝试。希望它能有所帮助!

如果您使用的是mgo,一个简单的排序就可以了。在这里,我们先按城市搜索,然后按名称搜索:

query1 := collection.Find(nil).Sort("city", "place_name")

最新更新