问题
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