Domanda

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

È stato utile?

Soluzione

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

Altri suggerimenti

I upgraded pymongo to the latest version, and it worked.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top