在PyMongo中查找子字符串 [英] Find substrings in PyMongo

查看:103
本文介绍了在PyMongo中查找子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用PyMongo在MongoDB的字段中查找子字符串.

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})

但是,如果我尝试在Python中将值/cat|Dog/i作为字符串传递,则无法正常工作.

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

是否可以在 PyMongo 中复制查询?

Is there a way to replicate the query in PyMongo?

注意:/cat|Dog/i是另一个集合中字段的值.它的形式为猫狗".基本上,我想将一个字段中的子字符串与另一个字段中的子字符串匹配.

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.

推荐答案

您需要使用

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}})

这篇关于在PyMongo中查找子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆