Find substrings in PyMongo

情到浓时终转凉″ 提交于 2019-12-07 01:27:36

问题


I wanted to find sub-strings within a field in MongoDB using PyMongo.

The following query works fine and is what I require:

db.collection.find({ "Animal": /cat|Dog/i})

However, if I try passing the value /cat|Dog/i as a string in Python, it doesn't work.

Is there a way to replicate the query in PyMongo?

Note: /cat|Dog/i is value of field from another collection. It is in the form 'cat Dog'. Basically, I want to match substrings in one field with substrings in another.


回答1:


You need to compile your regular expression pattern using re.compile() function into a regular expression object.

import re

pat = re.compile(r'cat|Dog', re.I)
db.collection.find({ "Animal": {'$regex': pat}})


来源:https://stackoverflow.com/questions/33919830/find-substrings-in-pymongo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!