首页 > 解决方案 > 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).

标签: mongodbflaskpymongomongoengine

解决方案


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')
print(db)

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

推荐阅读