简体   繁体   English

pymongo中的字段中的子字符串或正则表达式匹配列表

[英]List of substring or regex match in a field in pymongo

i have a document 我有一个文件

{title: 'India is my country'}


i need to find and return this document when any elements in list contain in title field 当列表中的任何元素包含在标题字段中时,我需要查找并返回此文档

list = ["when","is","and"]

How can i return this in pymongo find() 我如何在pymongo find()中返回此值

You will have to generate a regular expression containing all the items in the list ( that should do good if the list is not large). 您将必须生成一个包含列表中所有项目的正则表达式(如果列表不大的话,这样做会很好)。 But if the list is large, you shall query for each item seperately. 但是,如果列表很大,则应分别查询每个项目。 Regex would be used in both the cases. 在两种情况下都将使用正则表达式。

import re
term_list = ["when","is","and"]
regexp = re.compile(r"|".join(term_list), re.IGNORECASE)
db.my_collection.find_one({"title": regexp })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM