开发者

how to do regex search in Mongodb using pymongo?

开发者 https://www.devze.com 2023-03-27 01:47 出处:网络
I want to do a regex mongodb query using pymongo. cond = {\'date\':\'/.*2011-8-11.*/\'} coll.find(cond).count() return 0;

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 $.

0

精彩评论

暂无评论...
验证码 换一张
取 消