How to call PyMongo APIs in a MongoEngine app¶
My app code is based on MongoEngine, but how can I access the raw PyMongo APIs when MongoEngine is not able to meet my needs?
Use MongoEngine Document class's _get_collection method to call PyMongo APIs¶
Internally, MongoEngine use PyMongo client to access the MongoDB server.
In a MongoEngine app, we can call a Document class's _get_collection
method to get the PyMongo collection object with which we can easily call PyMongo APIs.
Example code¶
import mongoengine as me
class User(me.Document):
name = me.StringField()
me.connect('test')
coll = User._get_collection()
print(coll.find_one())
In the code above, User._get_collection()
returns the PyMongo collection object. We can call PyMongo APIs like find_one()
with this collection object.
This article is originally created by tooli.top. Please indicate the source when reprinting : https://www.tooli.top/posts/mongoengine_pymongo
Posted on 2023-02-28
Mail to author