MongoDB
 SQL >> Datenbank >  >> NoSQL >> MongoDB

PyMongo-Regex-Suche mit $all über mehrere Begriffe

Der Fehler: Ihre Schleife baut eine Zeichenkette, wo Sie eine Liste kompilierter Patterns brauchen. Sammeln Sie stattdessen die re.compile-Objekte:

collected_x = [] # Initialize an empty list for x in input: # Iterate over the input collected_x.append(re.compile(x)) # Append a compiled pattern collected_x_cut = collected_x[:-2] # Slice outside the loop cursor = db.collection.find({"key": {"$all": collected_x_cut}})

Eine map erzeugt dieselbe Liste in einer Zeile:

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

Oder eine List Comprehension – die Variante, die ich schreiben würde:

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

Unter Python 3: map liefert einen Iterator statt einer Liste, das Slicing im zweiten Beispiel bräuchte also list(...) darum – ein weiterer Grund für die Comprehension.