Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyMongo $in + $regex

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/ ] } } )
like image 772
Diolor Avatar asked Nov 08 '13 19:11

Diolor


People also ask

What is $regex in MongoDB?

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.

What does Pymongo find_One return?

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).

How do I find a document in Pymongo?

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.


1 Answers

Use python regular expressions.

import re
db.col.find({'music_description': {'$in': [ re.compile('.*heavy.*'), re.compile('.*metal.*')]}})
like image 183
user2998367 Avatar answered Nov 18 '22 18:11

user2998367