在Mongoose中汇总结果

我在澳大利亚有800多家不同的酒吧,俱乐部和餐厅的数据库。

我想为我的网站build立一个链接列表,统计不同郊区和主要类别的不同场地的数量。

喜欢这个:

餐厅,鲍恩山(15)
餐厅,Dawes Point(6)
悉尼俱乐部(138)

我可以通过首先获得所有的场地来做到这一点。 然后运行一个Venue.distinct('details.location.suburb')来获得所有独特的郊区。

从这里我可以运行后续的查询来计算该特定郊区和类别的场馆数量。

这将是很多电话。 还有更好的方法吗?

Mongo汇总框架可以在这里帮助吗? 在单个查询中这似乎是不可能的。

这是场地模型:

{ "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的美化解决scheme:

 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); }); } 

您可以使用以下聚合操作获得非常有用且易于转换的输出。

  • 根据国家,类别,州,城市和郊区对logging进行分组。
  • 获取每组中logging的数量。
  • 从组的第一条logging中获取组的types。
  • 计划必要的领域。

码:

 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" }