Combine MongoDb clients: pyMongo and MongoEngine


In my web application, I use Flask as framework and MongoDB as persistent layer. There are multiple libraries to connect to MongoDB. I am currently using the low-level lib pyMongo. However, I would like to combine it with MongoEngine for some models.

The only approach I see is to create an instance of both clients. This looks a big doggy. Is there a simpler way to combine these libraries (pyMongo, MongoEngine) such that they use the same database (with different collections).


Its currently not possible to use an existing Pymongo client to connect MongoEngine but you can do the opposite; if you connect MongoEngine, you can retrieve its underlying pymongo client or database instances.

from mongoengine import connect, get_db, Document, StringField

conn = connect()    # connects to the default "test" database on localhost:27017

print(conn)    # pymongo.MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True, read_preference=Primary())

db = get_db()  # pymongo.Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True, read_preference=Primary()), u'test')

class Person(Document):
    name = StringField()

coll = Person._get_collection()
print(coll)    # pymongo.Collection(Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True, read_preference=Primary()), u'test'), u'person')

Answered By – bagerard

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published