Filter concepts by levelShowing all levels.

MongoDB · Fundamentals

MongoDB Fundamentals

The document model, its terms, and how MongoDB treats schema

  • Document, not rowJSON-like BSON, can nest objects and arrays
  • server > db > collection > documentfour nested containers
  • update ≠ replaceupdate changes fields, replace swaps the whole document
  • Flexible ≠ freeapp code or a validator still enforces structure

1.Document-oriented databases

MongoDB stores data as documents — JSON-like records that can nest objects and arrays — instead of rows in a table. Each document lives in a collection, and documents in the same collection do not have to share one fixed set of fields.

Key features

  • A document is a set of field-value pairs, stored in BSON, a binary superset of JSON
  • A collection groups related documents, the rough equivalent of a table
  • Documents can nest objects and arrays, so related data can live in one document
  • MongoDB is the reference document database — the pattern is not unique to it
  • The document model maps closely onto objects in application code

Document terms vs. their relational rough-equivalent

Document terms vs. their relational rough-equivalent
MongoDB termRelational rough-equivalentNotable difference
databasedatabaseholds collections instead of tables
collectiontabledocuments inside it need not share one fixed schema
documentrowcan nest objects and arrays, not just scalar columns
fieldcolumnnot every document in a collection must have it
embedded document(needs a second table)related data nested inline, no join needed
A document nests what a join would otherwise need

document

field-value pairs

embedded object

nested inline

array

a list, nested too

  1. document — field-value pairs
  2. embedded object — nested inline
  3. array — a list, nested too

Command

json
{
  "field": "value",
  "nested": { "field": "value" },
  "list": ["value", "value"]
}

A document is a JSON-like BSON record; a collection groups documents that do not have to share one fixed schema. Nesting replaces some joins.

2.Databases, collections, documents and fields

A server holds databases. A database holds collections. A collection holds documents. A document holds fields, and a field's value can itself be a nested document, an array, or a scalar like a string or number.

Key features

  • _id is every document's primary key, auto-generated as an ObjectId if omitted
  • An ObjectId is a 12-byte value, unique and roughly sortable by creation time
  • A field's value can be a scalar, an embedded document, or an array
  • Two documents in one collection need not share the same fields
  • BSON adds types JSON lacks — dates, binary data, distinct integer widths

Common BSON types

Common BSON types
TypeExampleNotes
string"Dune"UTF-8 text
int32 / int6442two distinct widths — see BSON and data types
double3.14the default for a JS-style decimal literal
booleantrue
dateISODate("2026-01-01")stored as milliseconds since the Unix epoch
nullnulldistinct from a missing field
objectIdObjectId("65f1...")the default type of _id
array["a", "b"]can hold mixed types
object{ "k": "v" }an embedded document
Four nested containers

server

one running mongod / cluster

database

a named group of collections

collection

a named group of documents

document

field-value pairs, BSON-typed

  1. server — one running mongod / cluster
  2. database — a named group of collections
  3. collection — a named group of documents
  4. document — field-value pairs, BSON-typed

Command

json
{
  "_id": ObjectId("..."),   // primary key, auto-generated if omitted
  "field": "scalar value",
  "nested": { "field": "value" },  // embedded document
  "list": [1, 2, 3]                // array
}

server → database → collection → document, biggest to smallest. _id is the primary key, an ObjectId by default but any unique value is allowed.

3.Document model vs. relational model

A relational row is flat and normalized, with related data split into other tables and joined at query time. A document can nest related data directly, trading that join for a single document read.

Key features

  • A relational row is flat; related data lives in another table
  • A document can nest related data, trading a join for one read
  • Relational schema is database-enforced; document schema is not, by default
  • Denormalizing trades update-in-one-place for read-in-one-place
  • It is a workload decision, not "which database is better"

Same data, two models

Same data, two models
ConcernRelationalDocument
Related dataseparate table, joined by foreign keynested inline, or referenced by _id
Schemaenforced by table definitionflexible by default, optionally validated
Typical readJOIN across tablessingle document, no join
Typical writeupdate one row, one placemay need to update inside a nested structure

Command

text
Relational: SELECT * FROM books JOIN authors ON books.author_id = authors.id
Document:   db.books.find({ title: "Dune" })  // author already inline

Relational normalizes and joins at query time; documents can nest related data and trade the join for a single read.

4.Naming conventions and flexible schemas

Database, collection and field names follow conventions MongoDB does not enforce — lowercase names, camelCase or snake_case fields. A collection is created implicitly on first insert.

Key features

  • Database and collection names are typically lowercase, e.g. shop, orders
  • Field names are conventionally camelCase or snake_case — pick one and stay consistent
  • _id, and names starting with $, are reserved or restricted
  • A collection is created implicitly on first insert if it does not exist
  • MongoDB stores whatever shape each document is given, unvalidated by default

Naming conventions in practice

Naming conventions in practice
ThingConventionExample
Databaselowercase, shortshop
Collectionlowercase, plural nounorders
FieldcamelCase or snake_case, pick onecreatedAt or created_at
Reservednames starting with $, or _id$set is an operator, not a field name

Command

text
use shop           // switches to (or creates) database "shop"
db.orders.insertOne({ status: "pending" })   // creates collection "orders" if new

Lowercase database/collection names, camelCase or snake_case fields, pick one and stay consistent. A collection is created implicitly on first insert.

5.CRUD, conceptually

Every operation on a document is one of five verbs: insert (create it), find (read it), update (change some fields), replace (swap the whole document), or delete (remove it).

Key features

  • insert creates a new document; find reads documents matching a filter
  • update changes specific fields on matching documents, leaving the rest untouched
  • replace swaps a whole document for a new one, keeping only its _id
  • delete removes documents matching a filter
  • Each verb operates on a filter — a query document naming which to act on

The five CRUD verbs

The five CRUD verbs
VerbWhat it doesMethod family (section 4)
insertcreates a new documentinsertOne(), insertMany()
findreads documents matching a filterfind(), findOne()
updatechanges specific fields, leaves the restupdateOne(), updateMany()
replaceswaps the whole document except _idreplaceOne()
deleteremoves documents matching a filterdeleteOne(), deleteMany()
The five verbs, conceptually

insert

create

find

read

update / replace

change

delete

remove

  1. insert — create
  2. find — read
  3. update / replace — change
  4. delete — remove

Command

text
db.<collection>.<verb>(<filter>, <update or nothing>)

Five verbs: insert, find, update (changes fields), replace (swaps the whole document), delete. update and replace are not the same.

6.The MongoDB shell (mongosh)

mongosh is the current official MongoDB shell — a JavaScript REPL wired to a live connection, where db refers to the current database and every command is a real JavaScript method call.

Key features

  • mongosh is the current official shell, replacing the legacy mongo shell
  • use <db> switches the current database, creating it lazily on write
  • db is the current database; db.<collection> is a collection in it
  • show dbs and show collections list what already exists
  • Shell commands are real JavaScript method calls, not a separate language

Common mongosh commands

Common mongosh commands
CommandWhat it does
use shopswitch to (or lazily create) database "shop"
show dbslist databases on the server
show collectionslist collections in the current database
db.orders.find()read every document in the orders collection
db.orders.countDocuments()count documents in a collection
exitleave the shell

Command

bash
mongosh "mongodb://localhost:27017"

mongosh is a JavaScript REPL: use switches database, db.<collection>.<method>() runs a real method call, not a separate query language.

7.Schema-flexible, not schema-free

MongoDB does not require every document in a collection to match one fixed shape — that is a capability, not a rule against structure. App code and optional validators can still enforce what a collection needs.

Key features

  • No collection requires every document to share one column set
  • Flexibility is a choice about where structure is enforced
  • Application code checking shape before a write is one layer
  • Collection validators are a second, database-level layer
  • Critical invariants usually want both layers, not just one

Where structure can be enforced

Where structure can be enforced
LayerEnforcesBypassed by
Relational table schemaevery row, alwaysnothing — the database refuses a bad row
Application codewhatever the code checksany write that skips the application, e.g. a script
MongoDB collection validatorwhatever the validator checkswrites with a validation action set to warn instead of error
Nothingnothingeverything — the collection accepts any shape
Two ways to read "no fixed schema"

Misread: schema-free

  • No structure exists anywhere
  • Any shape is fine forever
  • Nothing needs to agree

Correct: schema-flexible

  • Structure is chosen, not forced by table definitions
  • App code and/or validators still enforce it
  • Flexibility applies where the domain genuinely varies
  • Misread: schema-free
    • No structure exists anywhere
    • Any shape is fine forever
    • Nothing needs to agree
  • Correct: schema-flexible
    • Structure is chosen, not forced by table definitions
    • App code and/or validators still enforce it
    • Flexibility applies where the domain genuinely varies

Command

text
// A validator makes a chosen shape enforced, without giving up flexibility elsewhere
db.createCollection("orders", { validator: { $jsonSchema: { required: ["status"] } } })

Schema-flexible means MongoDB does not force one shape by default — app code or a validator still can, and critical data usually wants one to.

Remember

  • A document is a BSON record; a collection groups documents that need not share one fixed shape.
  • _id is the primary key — MongoDB generates an ObjectId for it if none is supplied.
  • update changes named fields and leaves the rest; replace swaps the whole document except _id.
  • Schema-flexible means structure is chosen, not that no structure exists — validators still enforce it.

Pro tip

  • find() returns a cursor, not an array — call toArray() or iterate it to actually get documents.
  • Nesting related data removes a join at read time; the trade-off is what data modeling (section 6) is about.

Next up

  • BSON and Data Types
  • Documents and Collections
  • CRUD Operations

Sources

  • MongoDB Manual — docs.mongodb.com/manual/
  • mongosh — mongodb.com/docs/mongodb-shell/
  • Checked 2026-08-20

Spotted a mistake on this page? Tell us.