我想搜索 MongoDB,以便只获得所有 x 在某些配置中一起在键中找到的结果。
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,就可以了。
cursor = db.collection.find({"key": {"$all": [re.compile("Firstsomething"),
re.compile("Secondsomething"),
re.compile("Thirdsomething"),
re.compile("Fourthsomething")]}})
我做错了什么?
最佳答案
您正在 for 循环中构建一个字符串,而不是 re.compile
对象列表。你想要:
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
构建列表:
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}})
关于python - Pymongo Regex $所有多个搜索词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25126255/