fungalspores
fungalspores

Reputation: 35

How I can solve this problem pymongo.errors.OperationFailure?

I'm trying to do a title search in my database, but I can't.

import pymongo

myclient = pymongo.MongoClient("mongodb+srv://LOGIN:[email protected]/info?retryWrites=true&w=majority&ssl=true&ssl_cert_reqs=CERT_NONE")
mydb = myclient["info"]
mycol = mydb["comics"]

find = mycol.find({"title": {"$search": "68"}})

for f in find:
    print(f)

But I get this error

raise OperationFailure(msg % errmsg, code, response,
pymongo.errors.OperationFailure: unknown operator: $search, full error: {'operationTime': Timestamp(1601923289, 13), 'ok': 0.0, 'errmsg': 'unknown operator: $search', 'code': 2, 'codeName': 'BadValue', '$clusterTime': {'clusterTime': Timestamp(1601923289, 13), 'signature': {'hash': b'\x82\x91\xc5\xd4r\xd6\xbf\xbc\x13i\xe5\x83b\xd2\x9eUv\xb8\x89/', 'keyId': 6869109962937729027}}}

Upvotes: 0

Views: 6314

Answers (2)

amsh
amsh

Reputation: 3377

You need to use the $text operator to make it work. Don't forget to create an index on the title field.

import pymongo
from pymongo import TEXT

myclient = pymongo.MongoClient("mongodb+srv://LOGIN:[email protected]/info?retryWrites=true&w=majority&ssl=true&ssl_cert_reqs=CERT_NONE")
mydb = myclient["info"]
mycol = mydb["comics"]

#Creating index on title
mycol.create_index([('title', TEXT)], default_language='english')

find = mycol.find({"$text": {"$search": "68"}})

for f in find:
    print(f)

This will search all the indexed fields and return the matching ones. See more details on official documentation.

Upvotes: 2

D. SM
D. SM

Reputation: 14480

$search is an aggregation pipeline operator. See https://docs.atlas.mongodb.com/reference/atlas-search/query-syntax/#query-syntax-ref for correct usage. It cannot be specified in a find query.

Upvotes: 0

Related Questions