Mongoengine is a Python Object-Document Mapper (ODM) that allows easy integration of MongoDB with Python applications. With the help of mongoengine, you can define your data models as Python classes and interact with MongoDB in a more intuitive and Pythonic way.
In mongoengine, you can define metadata for your models using the meta
attribute. This metadata provides additional settings and options for your models. Let’s take a look at some common use cases for configuring metadata in mongoengine.
Collection Name
By default, mongoengine uses the class name converted to snake case as the collection name in MongoDB. However, you can customize the collection name by setting the collection
attribute in the meta
class.
class MyModel(mongoengine.Document):
meta = {'collection': 'my_custom_collection'}
# rest of the model definition
In the above example, the MyModel
documents will be stored in the collection named “my_custom_collection” instead of the default “my_model”.
Indexes
Indexes are crucial for improving query performance in MongoDB. You can define indexes for your models using the indexes
attribute in the meta
class. The value of the indexes
attribute should be a list of dictionaries, where each dictionary represents an index specification.
class MyModel(mongoengine.Document):
meta = {
'indexes': [
{'fields': [('field1', 'asc'), ('field2', 'desc')]},
{'fields': ['field3'], 'unique': True}
]
}
# rest of the model definition
In the above example, we define two indexes for the MyModel
. The first index is a compound index on “field1” ascending and “field2” descending. The second index is a single field index on “field3” with a unique constraint.
Ordering
You can specify the default ordering of query results using the ordering
attribute in the meta
class. The value of the ordering
attribute should be a list of fields to order by.
class MyModel(mongoengine.Document):
meta = {'ordering': ['-created_at']}
# rest of the model definition
In the above example, the query results of MyModel.objects.all()
will be ordered by the “created_at” field in descending order by default.
Additional Configuration
Other than the above examples, mongoengine provides various other options that can be configured using the meta
attribute. Some common options include allow_inheritance
, db_alias
, abstract
, strict
, etc. You can refer to the mongoengine documentation for a full list of available options.
Overall, using the meta
attribute in mongoengine allows you to customize the behavior and settings of your models, providing flexibility and control over the MongoDB integration in your Python application.