Mongoengine 简明教程
MongoEngine - Document Class
MongoEngine 被称为 ODM(@(s0))。MongoEngine 定义了 Document 类。这是一个基类,其继承的类用于定义存储在 MongoDB 数据库中的一系列文档的结构和属性。此子类的每个对象形成数据库中 Collection 中的 Document。
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.
此 Document 子类中的属性是由各种 Field 类的对象组成的。以下是一个典型的 Document 类的示例 −
Attributes in this Document subclass are objects of various Field classes. Following is an example of a typical Document class −
from mongoengine import *
class Student(Document):
studentid = StringField(required=True)
name = StringField(max_length=50)
age = IntField()
def _init__(self, id, name, age):
self.studentid=id,
self.name=name
self.age=age
这类似于 SQLAlchemy ORM 中的模型类。默认情况下,数据库中 Collection 的名称是 Python 类名,采用小写字母。然而,可在 Document 类的 meta 属性中指定不同的集合名称。
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': 'student_collection'}
现在,声明此类的对象并调用 save() 方法以将文档存储在数据库中。
Now declare object of this class and call save() method to store the document in a database.
s1=Student('A001', 'Tara', 20)
s1.save()