我有以下查询:
db.listener.aggregate(
[
{ "$match" : { "location.countryName" : "Italy" } },
{ "$project" : { "location" : "$location"} },
{ "$group" : { "_id" : { "country": "$location.countryName", "city": "$location.cityName" }, "count" : { "$sum" : 1 }, "co-ords" : { "$addToSet" : { "lat" : "$location.latitude", "long" : "$location.longitude" } } } },
{ "$group" : { "_id" : "$_id.country", "cities" : { "$push" : { "city" : "$_id.city", "count" : "$count", "co-ords" : "$co-ords" } } } },
{ "$sort" : { "_id" : 1 } },
]
以下是截断后的结果:
给出以下结果:
{
"result" : [
{
"_id" : "Italy",
"cities" : [
{
"city" : "Seriate",
"count" : 1,
"co-ords" : [
{
"lat" : "45.6833",
"long" : "9.7167"
}
]
},
{
"city" : "Milan",
"count" : 3,
"co-ords" : [
{
"lat" : "45.4612",
"long" : "9.1878"
},
{
"lat" : "45.4667",
"long" : "9.2"
}
]
},
正如您在米兰城市的示例中所看到的,总城市数量为3,但经度/纬度集的数量是两个。这意味着其中一个更精确的位置有两个实例,另一个位置只有一个。 现在我需要修改我的查询以反映每个纬度/经度的实例数以及总计数。 它可能看起来像这样:
{
"city" : "Milan",
"count" : 3,
"co-ords" : [
{
"lat" : "45.4612",
"long" : "9.1878",
"total" : 2
},
{
"lat" : "45.4667",
"long" : "9.2",
"total" : 1
}
]
},
我已尝试了几种方法来实现这个目标,但结果并不如我所愿,或者 MongoDB 报错了。 有人知道最好的方法吗?
谢谢大家,
Nick.