Pymongo Regex $all multiple search terms

2019-05-31 01:50发布

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条回答
Juvenile、少年°
2楼-- · 2019-05-31 02:40

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}})
查看更多
登录 后发表回答