给定以下数据集:

{ "_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查询端实现相同的目标。

最佳答案

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

10-06 14:19