我有一个名为“myplace”的集合,它包含以下文件 place_name、city、latitude、longitude。
文档格式
{
"_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"}}}}])
我认为这应该可行,但我目前无法在工作中实际尝试。希望对您有所帮助!
关于mongodb - 如何在使用 go 从 mongodb 获取数据时对数据进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26754794/