Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python, mongoengine - do like/regex search

I know I can do a glob-type search on mongodb:

db.person.find({ name: /*.bob.*/ })

or

db.person.find({ name: { $regex: '*.bob.*' }})

How do I do this with mongoengine without using a raw query (which is apparently the only way based on my searches)?

I've blindly tried several variations like:

Person.objects(name='/.*bob.*/')
Person.objects(name='/\.*bob\.*/')
Person.objects(name='.*bob.*')
Person.objects(name='\\.*bob\\.*')

etc, to no avail...

like image 989
lps Avatar asked Aug 22 '16 23:08

lps


People also ask

Which is better PyMongo or MongoEngine?

Both PyMongo and MongoEngine can be used to access data from a MongoDB database. However, they work in very different ways and offer different features. PyMongo is the MongoDB recommended library. It makes it easy to use MongoDB documents and maps directly to the familiar MongoDB Query Language.

What is the difference between PyMongo and MongoEngine?

PyMongo is the low-level driver wrapping the MongoDB API into Python and delivering JSON in and out. MongoEngine or other layers like MongoKit map your MongoDB-based data to objects similar to native Python database drivers + SQLAlchemy as ORM. Ok.

How do I search for a regular expression in MongoDB?

MongoDB also provides functionality of regular expression for string pattern matching using the $regex operator. MongoDB uses PCRE (Perl Compatible Regular Expression) as regular expression language. Unlike text search, we do not need to do any configuration or command to use regular expressions.

How do I delete MongoEngine?

To delete a document, call the delete() method. Note that this will only work if the document exists in the database and has a valid id .


1 Answers

It looks like you can do it this way:

import re

regex = re.compile('.*bob.*')
Person.objects(name=regex)
like image 187
lps Avatar answered Oct 20 '22 16:10

lps