gpt4 book ai didi

python - PyMongo 使用元数据排序

转载 作者:可可西里 更新时间:2023-11-01 09:59:11 26 4
gpt4 key购买 nike

我想知道如何将以下 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com