Back to Interview PrepGet interview ready with AILearn each topic the way interviewers ask it, then answer like you would in the interview.
Course progress0/12 chapters · 0%

Chapter 2 of 13

~11 min

Documents & Collections

Documents are the basic unit of data in MongoDB, and collections are the containers that hold them. Understanding how the _id field works and how flexible schemas play out in practice is essential before writing any real query.

Anatomy of a Document

A document is an ordered set of key-value pairs, similar to a JavaScript object. Values can be strings, numbers, booleans, dates, arrays, nested sub-documents, or null. Because a document can nest other documents and arrays inside it, a single document can represent what would be several joined rows in a relational schema - a customer with an embedded array of addresses, for example.

Field names are case-sensitive, cannot contain a null character, and by convention avoid starting with "$" or containing "." (both have special meaning to the query language). Document size is capped at 16MB, which matters if you are tempted to embed unbounded amounts of data into a single document.

Collections vs. Tables

A collection groups documents that are conceptually similar - a "users" collection, an "orders" collection - but MongoDB does not enforce that every document in a collection has the same fields or types unless you add schema validation yourself. This is often summarized as MongoDB having a "flexible" or "dynamic" schema, in contrast to a relational table's fixed column definitions.

Collections are created implicitly the first time you insert into them, and MongoDB creates the containing database implicitly too, the first time you write to a collection inside it - there is no CREATE TABLE step required to get going.

queries.js
db.users.insertMany([
  { name: "Ada", email: "ada@example.com" },
  { name: "Grace", email: "grace@example.com", phone: "555-0101" },
  { name: "Alan", nickname: "Al", roles: ["admin", "editor"] }
])

// All three live happily in the same "users" collection,
// even though their field sets differ.
A collection with intentionally varied document shapes

The _id Field

Every document must have a unique "_id" field that serves as its primary key within the collection. If you do not supply one on insert, MongoDB automatically generates an ObjectId - a 12-byte value encoding a timestamp, a random machine/process identifier, and an incrementing counter, which makes it unique across a distributed system without any central coordination.

You can also supply your own "_id" (a string, a number, anything comparable) if it makes sense for your domain - for example using an email address as "_id" for a users collection to get uniqueness enforcement for free. Once set, "_id" is immutable; you cannot update it on an existing document.

queries.js
db.users.insertOne({ name: "Ada Lovelace" })
// _id is auto-assigned, e.g. ObjectId("64f1c2a5e4b0a1b2c3d4e5f6")

db.users.insertOne({ _id: "ada@example.com", name: "Ada Lovelace" })
// _id is the string you supplied; inserting another document
// with the same _id will throw a duplicate key error
Auto-generated vs. custom _id

Flexible Schema Is a Tool, Not a Free Pass

The absence of an enforced schema does not mean you should design without one - it means schema enforcement moves from the database to your application (or to MongoDB's optional schema validation rules). Most real applications still have an implicit schema in mind for each collection; MongoDB just does not stop you from violating it accidentally, so disciplined application code and, ideally, validation rules matter more than they would in a relational system.

Coding challenge

Insert three documents into a "books" collection where each book has a title and author, but only some books have an optional "rating" field, then query the collection for all documents that do have a "rating" field using $exists.

// Write your solution here

Answer every question below to mark this chapter as complete.

Quiz Yourself

Score: 0/4

1. What happens if you insert a document without an "_id" field?

2. Can two documents in the same collection have different sets of fields?

3. What is an ObjectId primarily designed to guarantee?

4. Can you change the value of a document's "_id" field after it has been inserted?

You're viewing a free lesson. Sign up free to track your progress and unlock the full course.Sign up freeSign in