python - PyMongo 使用元数据排序

标签 python mongodb pymongo mongodb-query

我想知道如何将以下 mongodb 查询转换为 pymongo 语法

db.articles.find(
   { $text: { $search: "cake" } },
   { score: { $meta: "textScore" } }
).sort( { score: { $meta: "textScore" } } ).limit(3)

我试过这个:

results = \
    mongo.db.products.find({ '$text': { '$search': 'cake' } }, { 'score': { '$meta': 'textScore' } }) \
        .sort({ 'score': { '$meta': 'textScore' } }) \
        .limit(3)

但是我在排序时遇到了以下错误:

raise TypeError("second item in each key pair must be 1, -1, "
TypeError: second item in each key pair must be 1, -1, '2d', 'geoHaystack', or another valid MongoDB index specifier.

谁能帮帮我? 提前致谢

最佳答案

我认为解决方案在这里:https://github.com/mongodb/mongo-python-driver/blob/master/pymongo/cursor.py#L658 .使用"new"功能'$text'为新方法添加(键,方向)列表:

    Beginning with MongoDB version 2.6, text search results can be
    sorted by relevance::

        cursor = db.test.find(
            {'$text': {'$search': 'some words'}},
            {'score': {'$meta': 'textScore'}})

        # Sort by 'score' field.
        cursor.sort([('score', {'$meta': 'textScore'})]) #<<<< HERE

关于python - PyMongo 使用元数据排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23689635/

相关文章:

Python:如何显示对话框窗口并同时工作

python - 如何在默认 Django 身份验证登录 View 中使用自定义装饰器

mongodb - Golang/mgo : How can I ask MongoDB to use current time in a field?

ruby-on-rails - Mongoid 中具有 Belongs_to 关联的嵌入文档

python - 我收到 mastodon/mastodon.py 的 invalid_grant 错误。我该怎么做 Oauth2 呢?

Python - 创建egg文件描述和长描述有什么用

javascript - 如何使用 promise 链接 Mongoose 查询?

python - 如何将自定义类型添加到 dill 的 pickleable 类型

python - 无效的URI方案: mongodb+srv , Mongodb错误

python-3.x - 名称解析暂时失败,mongo-sec :27017