2

给定以下数据集:

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

4

1 回答 1

3
> db.z.aggregate({ $unwind:'$codes'}, 
                 { $group : {_id:'$_id', count:{$sum:1}}}, 
                 { $sort :{ count: 1}})
于 2013-01-29T00:20:41.203 回答