Mongoengine 简明教程

MongoEngine - Dynamic Schema

MongoDB 数据库的优点之一是支持动态架构。若要创建支持动态架构的类,可从 DynamicDocument 基类进行子类化。以下是具有动态架构的 Student 类−

One of the advantages of MongoDB database is that it supports dynamic schema. To create a class that supports dynamic schema, subclass it from DynamicDocument base class. Following is the Student class with dynamic schema −

>>> class student(DynamicDocument):
... name=StringField()

第一步是要先添加 Document 。

The first step is to add first Document as before.

>>> s1=student()
>>> s1.name="Tara"
>>> connect('mydb')
>>> s1.save()

现在另一个属性添加到第二个文档中并保存。

Now add another attribute to second document and save.

>>> s2=student()
>>> setattr(s2,'age',20)
>>> s2.name='Lara'
>>> s2.save()

在数据库中,学生集合将显示两个具有动态架构的文档。

In the database, student collection will show two documents with dynamic schema.

dynamic schema

文档类的元字典可以通过指定 max_documents 和 max_size 使用限幅集合。

The meta dictionary of document class can use a Capped Collection by specifying max_documents and max_size.

max_documents − 集合中允许存储的最大文档数。

max_documents − The maximum number of documents that is allowed to be stored in the collection.

max_size − 集合的最大大小(以字节为单位)。max_size 由 MongoDB 在内部以及 mongoengine 在之前舍入为 256 的下一个倍数。

max_size − The maximum size of the collection in bytes. max_size is rounded up to the next multiple of 256 by MongoDB internally and mongoengine before.

如果没有指定 max_size 但指定了 max_documents ,则 max_size 的默认值为 10485760 字节(10MB)。

If max_size is not specified and max_documents is, max_size defaults to 10485760 bytes (10MB).

文档类的其他参数如下所列 −

Other parameters of Document class are listed below −

objects

A QuerySet object that is created lazily on access.

cascade_save()

Recursively save any references and generic references on the document.

clean()

Hook for doing document level data cleaning before validation is run.

create_index()

Creates the given indexes if required.

drop_collection()

Drops the entire collection associated with this Document type from the database.

from_json()

Converts json data to a Document instance.

modify()

Perform an atomic update of the document in the database and reload the document object using updated version.

pk

Get the primary key.

save()

Save the Document to the database. If the document already exists, it will be updated, otherwise it will be created. Returns the saved object instance.

delete()

Delete current document from database.

insert()

Performs bulk insert operation.