MongoEngine – Dynamic Schema


MongoEngine – Dynamic Schema



”;


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

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

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

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

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.

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.

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *