pythonpymongotornado-motor

PyMongo full text search of items in a list


I am looking to do a text search using PyMongo for some items that are embedded within a list. My database is structured as follows: {_id:"148319665188372481" }, "tags": ['#123456', '#789012'}

I want to search my database specifically for the phrase "123456" but because the items are embedded in a list... I'm not quite sure how to do that.

Here is my current code:

        accounts.create_index([('tags', pymongo.TEXT)])
        async for something in accounts.find({"$text": {"$search": "123456"}}):
            print('Entered loop')
            print(something)

Solution

  • You've created your text index on the tags field, but your data is in the items field.

    You can only create one text index, per collection, but you can add multiple fields if needed; this example creates an index on both tags and items fields:

    import pymongo
    
    db = pymongo.MongoClient()['mydatabase']
    db.accounts.create_index([('tags', pymongo.TEXT), ('items', pymongo.TEXT)])
    db.accounts.insert_one({"items": ['apple', 'orange', 'peach']})
    
    for something in db.accounts.find({"$text": {"$search": 'apple'}}):
        print(something)
    

    result:

    {'_id': ObjectId('5e3f03992a4d2cf213983fe3'), 'items': ['apple', 'orange', 'peach']}