具有排序功能的pymongo中的MongoDB查询

时间:2014-02-20 08:04:14

标签: python mongodb aggregation-framework pymongo

我是MongoDB的新手,我正在尝试创建一个查询。

我有一个列表,例如:mylist = [a,b,c,d,e] 我的数据集有一个具有类似列表的键:mydatalist = [b,d,g,e]

我想创建一个查询,它将返回包含mylist中至少一个的所有数据。

我做了什么。

query = {'mydatalist': {'$in': mylist}}
selector = {'_id':1,'name':1}
mydata = collection.find(query,selector)

这是完美的工作。我唯一想要做的就是根据mydatalist中的mylist数据的数量对结果进行排序。有没有办法在查询中执行此操作,或者我必须在光标后手动执行此操作?

使用示例进行更新:

mylist = [a,b,c,d,e,f,g]

#data from collection
data1[mydatalist] = [a,b,k,l] #2 items from mylist
data2[mydatalist] = [b,c,d,e,m] #4items from mylist
data3[mydatalist] = [a,u,i] #1 item from mylist

所以,我希望将结果排序为data2 - > data1 - > DATA3

1 个答案:

答案 0 :(得分:2)

因此,您希望结果按数组选择的匹配数排序。查找并不简单,但可以使用aggregation framework

完成此操作
 db.collection.aggregate([
    // Match your selection to minimise the 
    {$match: {list: {$in: ['a','b','c','d','e','f','g']}}},

    // Projection trick, keep the original document
    {$project: {_id: {_id: "$_id", list: "$list" }, list: 1}},

    // Unwind the array
    {$unwind: "$list"},

    // Match only the elements you want
    {$match: {list: {$in: ['a','b','c','d','e','f','g']}}},

    // Sum up the count of matches
    {$group: {_id: "$_id", count: {$sum: 1}}},

    // Order by count descending
    {$sort: {count: -1 }},

    // Clean up the response, however you want
    {$project: { _id: 0, _id: "$_id._id", list: "$_id.list", count: 1 }}
])

你的文件按照你想要的顺序排列:

{
    "result" : [
        {
            "_id" : ObjectId("5305bc2dff79d25620079105"),
            "count" : 4,
            "list" : ["b","c","d","e","m"]
        },
        {
            "_id" : ObjectId("5305bbfbff79d25620079104"),
            "count" : 2,
            "list" : ["a","b","k","l"]
        },
        {
            "_id" : ObjectId("5305bc41ff79d25620079106"),
            "count" : 1,
            "list" : ["a","u","i"]
        }
    ],
    "ok" : 1
}

此外,值得一提的是,所有最新驱动程序版本中的aggregate将返回游标,就像find一样。目前这是由驱动程序模拟,但从版本2.6开始,它将真正实现。这使aggregate成为您实施的调用中find的非常有效的“交换”替换。