MongoDB聚合框架按数组长度排序

时间:2013-01-29 00:00:15

标签: mongodb pymongo aggregation-framework

给出以下数据集:

{ "_id" : ObjectId("510458b188ce1d16e616129b"), "codes" : [ "oxtbyr", "xstute" ], "name" : "Ciao Mambo", "permalink" : "ciaomambo", "visits" : 1 }
{ "_id" : ObjectId("510458b188ce1d16e6161296"), "codes" : [ "zpngwh", "odszfy", "vbvlgr" ], "name" : "Anthony's at Spokane Falls", "permalink" : "anthonysatspokanefalls", "visits" : 0 }

如何将此python / pymongo排序转换为可与MongoDB聚合框架一起使用的内容?我正在根据codes数组中的代码数量对结果进行排序。

z = [(x['name'], len(x['codes'])) for x in restaurants]
sorted_by_second = sorted(z, key=lambda tup: tup[1], reverse=True)
for x in sorted_by_second:
    print x[0], x[1]

这个在python中运行,我只是想知道如何在MongoDB查询结束时实现相同的目标。

1 个答案:

答案 0 :(得分:3)

> db.z.aggregate({ $unwind:'$codes'}, 
                 { $group : {_id:'$_id', count:{$sum:1}}}, 
                 { $sort :{ count: 1}})