MongoEngine – Document Class

MongoEngine – Document Class

MongoEngine is termed as ODM (Object Document Mapper). MongoEngine defines a Document class. This is a base class whose inherited class is used to define structure and properties of collection of documents stored in MongoDB database. Each object of this subclass forms Document in Collection in database.
Attributes in this Document subclass are objects of various Field classes. Following is an example of a typical Document class −

from enum import unique
from mongoengine import connect
from mongoengine import connect
from mongoengine import StringField, IntField, Document, DecimalField
connect('mydata', host='mongodb://localhost/mydata')
class Books(Document):
book_id = IntField(unique=True, required=True)
book_name = StringField(max_length=50)
book_price = DecimalField()
def _init__(self, book_id, book_name, book_price):
self.book_id = book_id
self.book_name = book_name
self.book_price = book_price

This appears similar to a model class in SQLAlchemy ORM. By default, name of Collection in database is the name of Python class with its name converted to lowercase. However, a different name of collection can be specified in meta attribute of Document class.

meta={collection': 'books_collection'}

Now declare object of this class and call save() method to store the document in a database.

b1 = Books(book_id=1001, book_name='let us C', book_price=360)

this will produce following output in user collection:

"book_name":"let us C",
Connecting to MongoDB Database (Prev Lesson)
(Next Lesson) MongoEngine – Add/Delete Document
', { 'anonymize_ip': true });