PyMongo sort with metadata
mongodb, mongodb-query, pymongo, python
Solution
I think that the solution is here: https://github.com/mongodb/mongo-python-driver/blob/master/pymongo/cursor.py#L658 . To add list of (key, direction) for new approach with "new" feature '$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
Problem
I wondering how to convert the follow mongodb query to pymongo syntax ``` db.articles.find( { $text: { $search: "cake" } }, { score: { $meta: "textScore" } } ).sort( { score: { $meta: "textScore" } } ).limit(3) ``` I tried this: ``` results = \ mongo.db.products.find({ '$text': { '$search': 'cake' } }, { 'score': { '$meta': 'textScore' } }) \ .sort({ 'score': { '$meta': 'textScore' } }) \ .limit(3) ``` But I got the follow error on sort: ``` 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. ``` Anyone can help me? Thanks in advance