python - Pymongo Regex $所有多个搜索词

标签 python regex mongodb pymongo

我想搜索 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}})

或者list comprehension :

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/

相关文章:

python - 从列表python的单个列表中删除子列表

javascript - 条件正则表达式javascript

javascript - 上传的文件如果文件名带括号()则不上传

java - 匹配java中的任何utf8非空白字符?

ruby-on-rails-3 - mongodb CPU占用率高

node.js - Mongoose - 无法创建带有子模型的模型

mongodb - MongoDB协助推荐

python - sklearn 矩阵分解示例

python - 从python中的字符串中删除特殊字符

python - 如何实现maxpool : taking a maximum on sliding window on image or tensor