Databases, Collections and Documents

beginner
10 min

Databases, Collections and Documents

Every piece of data in MongoDB lives inside a three-level hierarchy: databases contain collections, and collections contain documents. Understanding how these levels work, and how MongoDB creates them lazily, is essential before we start inserting and querying data. In this CodeYourCraft lesson you will create your first database, add collections, and learn the rules that govern documents.

Databases: The Top Level

A MongoDB deployment can host many independent databases. Each database has its own collections and its own files on disk. Switching to a database in mongosh is done with the use command:

javascript
use shop

Here is the interesting part: this command succeeds even if the shop database does not exist yet. MongoDB creates databases lazily, meaning the database only materializes on disk when you first store data in it. If you run show dbs immediately after use shop, you will not see shop listed until a document is written.

A few database names are reserved. The admin database holds administrative commands and users, local stores replication data specific to one server, and config supports sharding metadata. Avoid using these for application data.

Collections: Groups of Documents

A collection is a named group of documents inside a database, playing a role similar to a table in SQL, but without a fixed schema. Collections are also created lazily the first time you insert into them:

javascript
use shop db.products.insertOne({ name: 'Laptop Stand', price: 1899 }) show collections // products

You can also create a collection explicitly when you need special options:

javascript
db.createCollection('logs', { capped: true, size: 1048576, // max bytes max: 5000 // max documents })

A capped collection is a fixed-size, insertion-ordered collection that overwrites its oldest entries when full, which is handy for rolling logs. Explicit creation is also how you attach schema validation rules, which we will explore in the schema design lesson.

Documents: The Records Themselves

Documents are BSON objects made of field and value pairs. Values can be strings, numbers, booleans, dates, null, arrays, or even other documents. There are a few rules worth memorizing:

  • Every document must have an _id field that is unique within its collection. If you omit it, MongoDB generates an ObjectId, a 12-byte value that encodes a timestamp, so ObjectIds sort roughly by creation time.
  • Field names are case sensitive, and a single document can be at most 16 MB.
  • Documents can nest up to 100 levels deep, though in practice you should stay far shallower.
javascript
db.products.insertOne({ name: 'Mechanical Keyboard', price: 4499, tags: ['electronics', 'accessories'], stock: { warehouse: 120, store: 8 }, addedAt: new Date() })

Flexible Does Not Mean Chaotic

Because MongoDB does not enforce a schema by default, two documents in the products collection could have completely different fields. That flexibility is a feature during prototyping, but production applications should keep documents in a collection structurally consistent, using the same field names and types for the same concepts. Your application code, and optionally MongoDB schema validation, becomes the guardian of that consistency.

Naming Conventions

Good names prevent confusion later. Use short lowercase names for databases (shop, blog). Use plural nouns for collections (users, orders, products) and camelCase for field names (createdAt, unitPrice). Avoid special characters, dots in collection names, and starting field names with a dollar sign, which is reserved for operators.

Key Takeaways

  • Databases contain collections, and collections contain documents.
  • Both databases and collections are created lazily on first write.
  • Every document has a unique _id, generated as an ObjectId if omitted.
  • Documents max out at 16 MB and can nest objects and arrays.
  • Keep collections structurally consistent even though MongoDB does not force you to.

In the next lesson we will go deeper into writes and master insertOne, insertMany, and the options that control them.

Databases, Collections and Documents - MongoDB | CodeYourCraft | CodeYourCraft