Reputation: 551
I've got the following query:
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 } },
]
)
which give the following results (truncated):
{
"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"
}
]
},
As you can see in the example for the city of Milan, the total city count is 3 but the number of longitude/latitude sets is two. This means that one of those more precise locations has two instances and the other has one. I now need to amend my query to reflect the number of instances per latitude/longitude as well as the overall count. It might look something like this:
{
"city" : "Milan",
"count" : 3,
"co-ords" : [
{
"lat" : "45.4612",
"long" : "9.1878",
"total" : 2
},
{
"lat" : "45.4667",
"long" : "9.2",
"total" : 1
}
]
},
I've tried a few things to achieve this but it never come out as I'd like or Mongo throws an error. Anyone know the best way to do this?
Many thanks,
Nick.
Upvotes: 4
Views: 6812
Reputation: 42352
db.listener.aggregate(
[
{ "$match" : { "location.countryName" : "Italy" } },
{ "$group" : { "_id" : { "country": "$location.countryName",
"city": "$location.cityName",
"coords": { "lat" : "$location.latitude", "long" : "$location.longitude" }
},
"count" : { "$sum" : 1 }
}
},
{ "$group" : { "_id" : { "country": "$_id.country", "city": "$_id.city" },
"coords": { "$addToSet" : { "long" : "$_id.coords.long",
"lat" : "$_id.coords.lat",
"total" : "$count"
}
},
"count" : { "$sum" : "$count" }
}
},
{ "$group" : { "_id" : "$_id.country",
"cities" : { "$push" : { "city" : "$_id.city",
"count" : "$count",
"coords" : "$coords" } } } },
{ "$sort" : { "_id" : 1 } },
]);
Sample output on your data from this:
{ "_id" : "Italy",
"cities" : [
{
"city" : "Seriate",
"count" : 1,
"coords" : [
{
"long" : "9.7167",
"lat" : "45.6833",
"total" : 1
}
]
},
{
"city" : "Milan",
"count" : 3,
"coords" : [
{
"long" : "9.1878",
"lat" : "45.4612",
"total" : 1
},
{
"long" : "9.2",
"lat" : "45.4667",
"total" : 2
}
]
}
]
}
Upvotes: 5