MongoDB: Python

Sefism.

Chapter 01

Documents and your setup

What a document database is, how MongoDB stores documents in BSON inside collections, and the cluster, shell, GUI and sample data you need before writing real queries.

Document model

Also called document database, NoSQL, JSON document, document store

What
Data stored as documents: self-contained records of field and value pairs that can hold nested objects and arrays, much like JSON. Documents in one collection do not have to share the same fields.
Why
An object in your code maps to one document, so an order with its items can be read or written in one operation instead of joining several tables.
Example
A blog post document holds its title, author name, a tags array and the first few comments, so the post page needs a single read.

Watch out

Reading "schemaless" as "no design needed": the shape of your documents still decides how fast and correct your app is.

BSON and its types

Also called binary JSON, Decimal128, ISODate, Int32, Int64, data types

What
BSON is the binary format MongoDB stores and sends documents in. It extends JSON with real types such as dates, 32 and 64-bit integers, doubles, Decimal128 and ObjectId.
Why
Types decide how values compare, sort and index. A date stored as a Date sorts by time; the same date stored as a string sorts as text.
JavaScript
db.payments.insertOne({
  amount: NumberDecimal("19.99"),
  qty: NumberInt(2),
  paidAt: new Date(),
  settled: false
})

Watch out

Storing money as a double, which cannot hold 0.10 exactly, or dates as strings, which break range queries.

Database and collection

Also called collection, database, namespace

What
A database groups collections, and a collection groups documents, roughly like a table groups rows. Both are created automatically the first time you insert into them.
Why
Knowing the hierarchy tells you where indexes, validation rules and permissions live: indexes and validation belong to a collection, users to a database.
JavaScript
show dbs
use shop                  // switch, created on first write
show collections
db.products.countDocuments()

Watch out

A typo in a collection name silently creates a new empty collection instead of raising an error.

ObjectId and _id

Also called _id, primary key, ObjectId

What
Every document has a unique _id field, its primary key. If you do not supply one, the driver generates an ObjectId: 12 bytes made of a timestamp, a random value and a counter.
Why
ObjectIds are unique without asking the server, sort roughly by creation time and carry the time they were made.
JavaScript
const id = ObjectId()
id.getTimestamp()        // when it was created
db.users.findOne({ _id: ObjectId("66f1c2a9e4b0a1b2c3d4e5f6") })

Watch out

Querying with the id as a plain string: "66f1..." never equals ObjectId("66f1..."), so nothing matches.

Atlas free cluster

Also called MongoDB Atlas, M0, free tier, cluster

What
MongoDB Atlas is the hosted MongoDB service. Its free cluster is a small three-member replica set with a storage cap of about 0.5 GB, limited throughput and no automated backups.
Why
It gives you a real replica set in the cloud in minutes, so you can practise transactions, change streams and Atlas tools without running a server.

Watch out

Leaving the free cluster idle for weeks: Atlas pauses inactive free clusters, so export anything you want to keep.

mongosh

Also called MongoDB Shell, mongo shell, CLI

What
The MongoDB Shell: a JavaScript and Node.js based terminal program that connects to a deployment and runs queries, admin commands and scripts.
Why
Servers, containers and CI jobs rarely have a GUI, and most documentation examples are written in mongosh syntax.
Shell
mongosh "mongodb+srv://cluster0.abcde.mongodb.net/shop" \
  --username ayesha
# inside the shell
db.orders.find({ status: "paid" }).limit(5)
load("seed.js")        // run a script file

Watch out

Following tutorials for the old mongo shell, which has been removed; mongosh replaced it.

MongoDB Compass

Also called Compass, GUI

What
The free official GUI for MongoDB: browse collections, edit documents, build aggregation pipelines stage by stage, view explain plans visually and open an embedded mongosh.
Why
Seeing real documents, schema samples and query plans makes the shape of your data obvious while you learn.

Watch out

Building every query by clicking and never learning the query syntax that Compass shows you.

Sample dataset

Also called sample_mflix, sample_airbnb, sample data, mongorestore

What
Ready-made databases, such as sample_mflix (films and comments) and sample_airbnb (listings), that Atlas loads into your cluster with one click.
Why
Tiny test collections hide real problems: missing fields, big arrays, slow queries and uneven data. Thousands of realistic documents show them.

Watch out

Loading the sample data into a free cluster you also use for a project, and running out of storage.

01 · Documents and your setup1 / 9