Pymongo Regex $all multiple search terms

喜你入骨 提交于 2019-12-08 04:16:24

问题


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

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

What am I doing wrong?


回答1:


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

A simple approach would be to use map to build the list:

collected = map(re.compile, input)[:-2]
db.collection.find({"key": {"$all": collected}})

Or a list comprehension:

collected = [re.compile(x) for x in input][:-2]
db.collection.find({"key": {"$all": collected}})


来源:https://stackoverflow.com/questions/25126255/pymongo-regex-all-multiple-search-terms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!