In MongoDB, the concept of embedded documents allows you to nest one document within another. This is useful when you have a document that contains a set of related data that you don’t want to store separately.
MongoEngine, a Python Object-Document Mapper (ODM), provides support for working with embedded documents. With MongoEngine, you can define EmbeddedDocument classes that can be used to organize and structure your data within MongoDB.
Defining an EmbeddedDocument
To define an embedded document with MongoEngine, you need to create a class that subclasses mongoengine.EmbeddedDocument
. Below is an example of how to create an embedded document class representing a user’s address:
import mongoengine
class Address(mongoengine.EmbeddedDocument):
street = mongoengine.StringField()
city = mongoengine.StringField()
state = mongoengine.StringField()
zip_code = mongoengine.StringField()
In this example, the Address
class is defined as an embedded document by subclassing mongoengine.EmbeddedDocument
. The class has fields such as street
, city
, state
, and zip_code
which represent different properties of an address.
Using Embedded Documents
Once you have defined an embedded document, you can use it within another document by declaring it as a field with the EmbeddedDocumentField
type. In the example below, we define a User
document that has an embedded Address
:
import mongoengine
class User(mongoengine.Document):
name = mongoengine.StringField()
address = mongoengine.EmbeddedDocumentField(Address)
The User
class defines a name
field of type StringField
and an address
field of type EmbeddedDocumentField
that references the Address
embedded document.
Accessing Embedded Document Fields
To access the fields of an embedded document, you can use dot notation on the field within the parent document. In the example below, we create a User
instance and access its embedded Address
fields:
user = User()
user.name = "John Doe"
user.address = Address(street="123 Main St", city="New York", state="NY", zip_code="10001")
print(user.name)
print(user.address.street)
print(user.address.city)
print(user.address.state)
print(user.address.zip_code)
In this example, we create a User
instance, set its name
field, and initialize the address
field with an Address
instance. We then print out the different fields of the embedded Address
document using dot notation.
Conclusion
MongoEngine’s support for embedded documents allows you to create more complex and structured data models within MongoDB. By defining embedded document classes and using them within your main documents, you can organize related data and improve the efficiency of your queries.