Chapter 1 of 13
~11 minIntroduction to MongoDB
MongoDB is a document-oriented NoSQL database that stores data as flexible, JSON-like documents instead of rows in fixed tables. It is the default choice for a huge share of modern Node.js backends, so understanding what problem it solves - and what it trades away - is the first step.
What "Document-Oriented" Actually Means
A relational database stores data as rows split across many normalized tables, joined together at query time. MongoDB instead stores a whole related unit of data - a blog post with its comments, an order with its line items - as a single document, which can contain nested objects and arrays directly. There is no mandatory join to reassemble a record; the shape you read is close to the shape you naturally think in when writing application code.
This document sits inside a collection (roughly analogous to a table), and a database can hold many collections. Because documents in the same collection do not need to share an identical set of fields, the same collection can hold a document with an extra field, a missing field, or a differently-typed field, without an ALTER TABLE-style migration.
Why NoSQL, and When It Is the Wrong Choice
MongoDB trades some of the guarantees of a relational database - rigid schemas, cross-table joins enforced by foreign keys, and (traditionally) strict multi-row ACID transactions - for flexibility and horizontal scalability. That trade pays off well for workloads with evolving or heterogeneous data shapes, high write throughput, or data that is naturally hierarchical (a user profile, a product catalog, an event log).
It pays off less well when your data is deeply relational and you constantly need to query across many entities with strong consistency guarantees - a double-entry accounting ledger, for instance, still often fits a relational database better. MongoDB does support multi-document transactions (covered later), but reaching for them constantly is usually a sign the data model itself should be rethought.
BSON: The Wire and Storage Format
Documents look like JSON when you write them in the shell, but MongoDB actually stores and transmits them as BSON (Binary JSON). BSON extends JSON with additional types JSON cannot represent natively - a proper Date type, a 64-bit integer, Decimal128 for exact decimal math, and a special ObjectId type - and it is a binary format, so it can be traversed and indexed far faster than parsing text JSON on every operation.
A document as you would type it in mongosh (JSON-like), backed by BSON on disk
const doc = {
_id: ObjectId("64f1c2a5e4b0a1b2c3d4e5f6"),
name: "Ada Lovelace",
age: 30,
createdAt: ISODate("2024-01-15T10:00:00Z"),
tags: ["mathematician", "writer"],
address: {
city: "London",
country: "UK"
}
};Installing and Connecting with mongosh
mongosh is the modern MongoDB shell - a JavaScript REPL wired directly into a MongoDB connection. After installing MongoDB Community Server (or pointing at a hosted cluster like MongoDB Atlas), you connect with a connection string that specifies the host, port, and optionally credentials and a default database.
Connecting and running a first command
// Connect to a local instance
// mongosh "mongodb://localhost:27017"
// Connect to a hosted Atlas cluster
// mongosh "mongodb+srv://cluster0.abcde.mongodb.net" --username myUser
// Once connected (mongosh shell commands):
// show dbs
// use schoolDB
db.students.insertOne({ name: "Ada", age: 30 })
db.students.find()Coding Challenge
Using mongosh syntax, switch to a database called "shop", insert a single product document with a name, price, and an inStock boolean, then run a find() to confirm it was inserted.
Answer every question below to mark this chapter as complete.
Quiz Yourself
Score: 0/41. What is the closest relational-database analogy to a MongoDB "collection"?
2. What is BSON?
3. Which scenario is generally a weaker fit for MongoDB compared to a relational database?
4. What is mongosh?