Pymongo正则表达式$所有多个搜索词 [英] Pymongo Regex $all multiple search terms
本文介绍了Pymongo正则表达式$所有多个搜索词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想搜索MongoDB,以便仅获得在某个配置中在键中同时找到所有x的结果.
I want to search MongoDB so that I get only results where all x are found in some configuration together in the key.
collected_x = ''
for x in input:
collected_x = collected_x + 're.compile("' + x + '"), '
collected_x_cut = collected_x[:-2]
cursor = db.collection.find({"key": {"$all": [collected_x_cut]}})
这不会带来预期的结果.如果我自己输入倍数x,它将起作用.
This does not bring the anticipated result. If I input the multiple x by themselves, it works.
cursor = db.collection.find({"key": {"$all": [re.compile("Firstsomething"),
re.compile("Secondsomething"),
re.compile("Thirdsomething"),
re.compile("Fourthsomething")]}})
我在做什么错了?
推荐答案
您正在for循环中构建一个字符串,而不是re.compile
对象的列表.您想要:
You are building a string in your for loop not a list of re.compile
objects. You want:
collected_x = [] # Initialize an empty list
for x in input: # Iterate over input
collected_x.append(re.compile(x)) # Append re.compile object to list
collected_x_cut = collected_x[:-2] # Slice the list outside the loop
cursor = db.collection.find({"key": {"$all": collected_x_cut}})
一种简单的方法是使用 map
进行构建列表:
A simple approach would be to use map
to build the list:
collected = map(re.compile, input)[:-2]
db.collection.find({"key": {"$all": collected}})
collected = [re.compile(x) for x in input][:-2]
db.collection.find({"key": {"$all": collected}})
这篇关于Pymongo正则表达式$所有多个搜索词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文