PyMongo $regex across all text fields and subfields

Viewed 130

I have a rather convoluted Mongo collection and I'm trying to implement detailed matching criteria. I have already created a text index across all fields as follows:

db.create_index([("$**", "text")], name='allTextFields')

I am using this for some straightforward search terms in PyMongo (e.g., "immigration") as follows:

db.find({'$text': {'$search': "immigration"}

However, there are certain terms I need to match that are generic enough as to require regex-type specifications. For instance, I want match all occurrences of "ice" without finding "police" and a variety of other exclusion terms.

Ideally, I could create a regex that would search all fields and subfields (see example below), but I can't figure out how to implement this in PyMongo (or Mongo for that matter).

db.find({all_fields_and_subfields: {'$regex': '^ice\s*', '$options': 'i'}

Does anyone know how to do so?

1 Answers

One way of doing this is to add another field to the documents which contains a concatenation of all the fields you want to search, and $regex on that.

Note that unless your regexes are anchored to the beginning of input, they won't be using indexes (so you'll be doing collection scans).

I am surprised that a full text query for "ice" finds "police", surely that's a bug somewhere.

You may also consider Atlas search instead of full-text search, which is more powerful but proprietary to Atlas.

Related