How can I combine $regex with $in in PyMongo?
I want to search for either /*.heavy.*/
or /*.metal.*/
.
I tried in python without success:
db.col.find({'music_description' : { '$in' : [ {'$regex':'/*.heavy.*/'} ]} })
The equivalent in Mongo shell is:
db.inventory.find( { music_description: { $in: [ /heavy/, /metal/ ] } } )
Definition. $regex. Provides regular expression capabilities for pattern matching strings in queries. MongoDB uses Perl compatible regular expressions (i.e. "PCRE" ) version 8.42 with UTF-8 support.
The most basic type of query that can be performed in MongoDB is find_one() . This method returns a single document matching a query (or None if there are no matches).
The find_One() method of pymongo is used to retrieve a single document based on your query, in case of no matches this method returns nothing and if you doesn't use any query it returns the first document of the collection.
Use python regular expressions.
import re
db.col.find({'music_description': {'$in': [ re.compile('.*heavy.*'), re.compile('.*metal.*')]}})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With