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 2. Reading and Writing to MongoDB with Python

MongoDB is a document-oriented database. This is different from a relational database in two significant ways. Firstly, not all entries must adhere to the same schema. Secondly you can embed entries inside of one another. Despite these major differences, there are analogs to SQL concepts in MongoDB. A logical group of entries in a SQL database is termed a table. In MongoDB, the analogous term is a collection. A single entry in a SQL databse is termed a row. In MongoDB, the analog is a document.

Table 2-1. Comparison of SQL/RDBMS and MongoDB Concepts and Terms
ConceptSQLMongoDB

One User

One Row

One Document

All Users

Users Table

Users Collection

One Username Per User (1-to-1)

Username Column

Username Property

Many Emails Per User (1-to-many)

SQL JOIN with Emails Table

Embed relevant email doc in User Document

Many Items Owned by Many Users (many-to-many)

SQL JOIN with Items Table

Programmatically Join with Items Collection

Hence, in MongoDB, you are mostly operating on documents and collections of documents. If you are familiar with JSON, a MongoDB document is essentially a JSON document with a few extra features. From a Python perspective, it is a Python dictionary.

Consider the following example of a user document with a username, first name, surname, date of birth, email address and score:

from datetime import datetime user_doc = { "username" : "janedoe", "firstname" : "Jane", "surname" : "Doe", "dateofbirth" : datetime(1974, 4, 12), "email" : ...

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