O'Reilly logo

MongoDB and Python by Niall O'Higgins

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 3. Common MongoDB and Python Patterns

After some time working with MongoDB and Python to solve different problems, various patterns and best practices begin to emerge. Just as with any programming language and database system, there are established approaches for modeling data along with known methods for answering queries as quickly and efficiently as possible.

While there are myriad sources of such knowledge for traditional RDBM systems like MySQL, there are far fewer resources available for MongoDB. This chapter is an attempt to address this.

A Uniquely Document-Oriented Pattern: Embedding

While the ability of MongoDB documents to contain sub-documents has been mentioned previously in this book, it has not been explored in detail. In fact, embedding is an extremely important modeling technique when working with MongoDB and can have important performance and scalability implications. In particular, embedding can be used to solve many data modeling problems usually solved by a join in traditional RDBMS. Furthermore, embedding is perhaps more intuitive and easier to understand than a join.

What exactly is meant by embedding? In Python terms, when the value of a key in a dictionary is yet another dictionary, we say that you are embedding the latter in the former. For example:

my_document = {
    "name":"foo document",
    "data":{"name":"bar document"}
}

Here, “data” is a sub-document embedded in the top-level document “my_document”.

Embedding sub-documents can be a useful, natural technique ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required