Donnie
Donnie

Reputation: 6351

Searching ID or property for match in Mongo

Goal:

I want to allow the user to search for a document by ID, or allow other text-based queries.

Code:

l_search_results = list(
    cll_sips.find(
        {
            '$or': [
                {'_id': ObjectId(s_term)},
                {'s_text': re.compile(s_term, re.IGNORECASE)},
                {'choices': re.compile(s_term, re.IGNORECASE)}
            ]
        }
    ).limit(20)
)

Error:

<Whatever you searched for> is not a valid ObjectId

Upvotes: 0

Views: 2240

Answers (1)

Cameron
Cameron

Reputation: 98886

s_term needs to be a valid object ID (or at least in the right format) when you pass it to the ObjectId constructor. Since it's sometimes not an ID, that explains why you get the exception.

Try something like this instead:

from pymongo.errors import InvalidId

or_filter = [
    {'s_text': re.compile(s_term, re.IGNORECASE)},
    {'choices': re.compile(s_term, re.IGNORECASE)}
]

try:
    id = ObjectId(s_term)
    or_filter.append({ '_id': id })
except InvalidId:
    pass

l_search_results = list(
    cll_sips.find({ '$or': or_filter }).limit(20)
)

Upvotes: 3

Related Questions