3

I want to do a regex mongodb query using pymongo.

cond = {'date':'/.*2011-8-11.*/'}
coll.find(cond).count() return 0;

but I do this query directly on Mongodb return 25; Is there any problem in my query?

2
  • 1
    Note that this is not really a fuzzy query ... it's an exact matching, instead. A fuzzy search would have been to be able to set up a minimal acceptable proximity (or maximal distance) of any kind, for example as with the ~ operator in solr (term~ or term~0.75 ...). AFAIK it's not possible neither with regex nor mongoDB, unfortunately. Commented Jul 26, 2012 at 10:39
  • Is it possible to edit the question with "regex search" instead of "fuzzy search"? That's what the question is actually about. Commented Oct 18, 2018 at 0:45

1 Answer 1

6

To search with regular expressions from pymongo, you need to use a python regular expression object, not a string with slashes. For your query above, the pymongo syntax would be:

import re
# assume connection is set up, and db
# is a pymongo.database.Database instance
date_re = re.compile(r'2011-8-11')
db.collection.find({'date': date_re})

Also note that you don't need the . character (either in the pymongo syntax or the mongo shell syntax), unless you anchor your regular expression using ^ or $.

Sign up to request clarification or add additional context in comments.

2 Comments

Alternatively you can avoid the overhead of creating a regex object by doing db.collection.find({'date': {'$regex': '2011-8-11'}}).
What is the advantage of this answer versus what @TkTech wrote (which worked for me nicely)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.