Good morning everyone,
I would like to write a pymongo snippet to query from a database all documents having a specific field value within a given list (so also a value which is a subset of any element in the given list).
Within python, I would have two lists and I would like to find all elements from list one which are contained in at least one element from list two. Eg:
list1 = ['abc', 'bob', 'joe_123']
list2 = ['abc', 'joe', 'mike']
for string in list2:
print( string, any([ string in xxx for xxx in list1 ]) )
which gives the correct result:
abc True
joe True
mike False
How could I get the same from pymongo? I tried the "$in" operator, but the result is not complete.
from pymongo import MongoClient
from pprint import pprint
client = MongoClient('mongodb://localhost:27017')
db = client['test_query']
my_coll = db['test_collection']
list1 = ['abc', 'bob', 'joe_123']
list2 = ['abc', 'joe', 'mike']
for string in list2:
my_coll.insert_one({'string' : string})
cursor = my_coll.find({'string' : { '$in' : list1} })
which misses the case in joe < joe_123
pprint([c for c in cursor])
[{'_id': ObjectId('5f60ce9b682ff1bf4dcafb94'), 'string': 'abc'}]
Could anyone give me a hint on this?
More generally, what is the syntax to incorporate a python comprehension list into a pymongo query?
Thank you so much
Marco
$in
in mongodb does not match on a partial string.
To do this you must use $regex
, eg
for string in list1:
my_coll.insert_one({'string' : string})
query = {'$regex': '|'.join(list2)}
cursor = my_coll.find({'string' : query})
pprint([c for c in cursor])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.