how to do regex search in Mongodb using pymongo?
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 2开发者_Python百科5; Is there any problem in my query?
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 $
.
精彩评论