我在澳大利亚有一个拥有800多家不同酒吧,俱乐部和餐馆的数据库。
我想为我的网站建立一个链接列表,计算不同郊区和主要类别的不同场地数量。
像这样:
Restaurants, Bowen Hills (15)
Restaurants, Dawes Point (6)
Clubs, Sydney (138)
我可以通过首先获得所有场地来做到这一点。然后运行Venue.distinct('details.location.suburb')以获得所有独特的郊区。
从这里,我可以运行后续查询,以获得该特定郊区和类别中场地数量的计数。
虽然会有很多电话。必须有更好的方法吗?
Mongo聚合框架能否在这里提供帮助? 在单个查询中似乎无法做到这一点。
以下是Venue模型:
{
"name" : "Johnny's Bar & Grill",
"meta" : {
"category" : {
"all" : [
"restaurant",
"bar"
],
"primary" : "restaurant"
}
},
"details" : {
"location" : {
"streetNumber" : "180",
"streetName" : "abbotsford road",
"suburb" : "bowen hills",
"city" : "brisbane",
"postcode" : "4006",
"state" : "qld",
"country" : "australia"
},
"contact" : {
"phone" : [
"(07) 5555 5555"
]
}
}
}
}
这是我最终使用的BatScream的美化解决方案:
Venue.aggregate([
{
$group: {
_id: {
primary: '$meta.category.primary',
suburb: '$details.location.suburb',
country: '$details.location.country',
state: '$details.location.state',
city: '$details.location.city'
},
count: {
$sum: 1
},
type: {
$first: '$meta.category.primary'
}
}
},
{
$sort: {
count: -1
}
},
{
$limit: 50
},
// Reshapes each document in the stream, such as by adding new fields or removing existing fields. For each input document, outputs one document.
{
$project: {
_id: 0,
type : '$type',
location : '$_id.suburb',
count: 1
}
}
],
function(err, res){
next(err, res);
});
}
答案 0 :(得分:1)
使用以下聚合操作,您可以获得非常有用且易于转换的输出。
代码:
db.collection.aggregate([
{$group:{"_id":{"primary":"$meta.category.primary",
"suburb":"$details.location.suburb",
"country":"$details.location.country",
"state":"$details.location.state",
"city":"$details.location.city"},
"count":{$sum:1},
"type":{$first:"$meta.category.primary"}}},
{$sort:{"count":-1}},
{$project:{"_id":0,
"type":"$type",
"location":"$_id.suburb",
"count":1}}
])
样本o / p:
{ "count" : 1, "type" : "restaurant", "location" : "bowen hills" }