MongoDB:根据一个字段的频率对另一个字段进行排序
我有一个JSON对象,如下所示:MongoDB:根据一个字段的频率对另一个字段进行排序,mongodb,mongodb-query,aggregation-framework,Mongodb,Mongodb Query,Aggregation Framework,我有一个JSON对象,如下所示: { _id: Object(...), address: {...}, borough: “Brooklyn”, (other values can be: Bronx, Manhattan, Staten Island, Queens) cuisine: “American”, (other values can be: Italian, Indian, Chinese, etc) grade: “A”, sco
{
_id: Object(...),
address: {...},
borough: “Brooklyn”, (other values can be: Bronx, Manhattan, Staten Island, Queens)
cuisine: “American”, (other values can be: Italian, Indian, Chinese, etc)
grade: “A”,
score: “9”
{
我希望能够根据每个行政区的“美国”菜系数量对每个行政区进行排名,并按降序预测该行政区和该行政区的美国菜系数量。如果可能的话,我希望能够使用db.collection.aggregate
实现这一点
示例输出:
[{borough: "Brooklyn", count: 9312}, {borough: "Bronx", count: 8763}, {borough: "Queens", count: 5461}...]
我能想出的唯一办法是手动查找五个行政区中每个行政区的美国美食数量,然后使用这些信息。但我希望在一个问题上做到这一点。我熟悉基本的Mongo查询,但我真的很难理解。任何帮助都将不胜感激 演示-
用于按行政区分组,并使用
并重塑您的数据
db.collection.aggregate([
{ $group: { _id: "$borough", count: { $sum: 1 } } },
{ $project: { _id: 0, borough: "$_id", count: 1 } }
])
这与@Tushar的答案类似,只是我不得不做额外的过滤以去除缺失的行政区,用$match
只查看美国菜,用$sort
按降序排列
db.restaurants.aggregate([
{$match: {cuisine: "American", borough: {$ne: "Missing"}}},
{$group: {_id: "$borough", count: {$sum: 1}}},
{$sort: {count: -1}},
{$project: {_id: 0, borough: "$_id", count: 1}}
])
这是有帮助的,但它计算了每个行政区所有菜系的数量,而不仅仅是“美国”菜系。我还需要按降序列出,并删除一个可能丢失的borough字段,该字段的值为“missing”