Skip to content
Velloreth
Technology 5 min read

MongoDB Basics: Documents, Collections and Queries

MongoDB stores a document, not a row. Learn the collection, the query, the index, the aggregation, and the schema design.

By

The model

SQLMongoDB
A tablea collection
A rowa document
A columna field
A joinan embed or a lookup
A primary key_id

A document is a JSON-like object.

{
  "_id": "abc123",
  "title": "Hello",
  "tags": ["a", "b"],
  "author": { "name": "Alice", "id": "u1" },
  "createdAt": "2026-10-26T10:00:00Z"
}

The query

db.posts.find({ tags: "a" });
db.posts.findOne({ _id: "abc123" });
db.posts.find({ "author.name": "Alice" });
db.posts.find({ createdAt: { $gte: new Date("2026-01-01") } });

The operators:

OperatorMeaning
$eqequal
$gt, $ltgreater, less
$inin a list
$existsthe field exists
$regexa pattern
$and, $ora logical combination

A dot path reaches a nested field.

The write

db.posts.insertOne({ title: "Hello" });
db.posts.updateOne({ _id: "abc" }, { $set: { title: "Hi" } });
db.posts.updateOne({ _id: "abc" }, { $push: { tags: "c" } });
db.posts.deleteOne({ _id: "abc" });

$set updates a field.

$push appends to an array.

$inc increments a number.

An upsert inserts if the document does not exist.

db.posts.updateOne({ _id: "abc" }, { $set: { title: "Hi" } }, { upsert: true });

The index

db.posts.createIndex({ createdAt: -1 });
db.posts.createIndex({ tags: 1, createdAt: -1 });
db.posts.createIndex({ title: "text" });

An index is required for a query to be fast.

Without an index, the query scans every document.

A compound index covers a query with several fields, and the field order matters.

A text index supports a full-text search.

explain() shows whether an index was used.

db.posts.find({ tags: "a" }).explain("executionStats");

The aggregation

db.posts.aggregate([
  { $match: { published: true } },
  { $group: { _id: "$author.id", count: { $sum: 1 } } },
  { $sort: { count: -1 } },
  { $limit: 10 },
]);

A sequence of stages, each taking the output of the previous.

StagePurpose
$matchfilter
$groupaggregate
$sortorder
$projectselect the fields
$lookupa join
$unwindexpand an array
$limitcap the count

$match first is the rule, because it reduces the documents the later stages process.

The schema design

Embed when the data is read together and is bounded.

{
  "orderId": "o1",
  "lines": [
    { "sku": "a", "qty": 2 },
    { "sku": "b", "qty": 1 }
  ]
}

Reference when the data is large, shared, or changes independently.

{
  "postId": "p1",
  "authorId": "u1"
}

The rule: the data read together is stored together.

A document has a 16 MB limit, so an unbounded array is a problem.

The replica set

One primary and several secondaries.

A write goes to the primary and is replicated.

A read can go to a secondary, which may be slightly stale.

A failover promotes a secondary if the primary fails.

A write concern decides how many replicas must acknowledge.

db.posts.insertOne(doc, { writeConcern: { w: "majority" } });

The schema validation

db.createCollection("posts", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["title"],
      properties: { title: { bsonType: "string" } },
    },
  },
});

The database does not enforce a schema by default.

A validation rule adds a constraint.

The application must enforce the rest, because a flexible schema is a risk for a typo.

The write path

A write in MongoDB is not a single operation, and knowing the path explains the durability options. The driver sends the write to the primary, which applies it to the in-memory view and appends it to the oplog, the operation log that the secondaries tail. The secondaries apply the oplog entry and acknowledge, and the write concern decides how many acknowledgements the primary waits for before it reports success. A write concern of one acknowledges as soon as the primary has it, which is fast and loses the write if the primary fails before the replication. A write concern of majority waits for a majority of the replicas, which is slower and survives a failover. The journal is a separate durability layer: a write is in memory until it is journaled, and a journaled write survives a restart of the primary. The two settings are independent, and a critical write usually wants both a majority write concern and a journaled write.

The read preference

A read can go to the primary or to a secondary, and the choice is a trade-off between freshness and load. A primary read is always current, and it puts the read load on the primary, which is also handling the writes. A secondary read spreads the load and may return a slightly stale value, because the secondary applies the oplog asynchronously. The read preference options are primary, primaryPreferred, secondary, secondaryPreferred and nearest. The common pattern is a primary read for a value the user just wrote, because a secondary read after a write can return the old value, and a secondary read for an analytics query that tolerates a small lag. A read concern of majority on a secondary gives a consistent snapshot at the cost of a slower read.

Common mistakes

No index. A full scan.

A compound index in the wrong order. It is not used.

An unbounded array. The 16 MB limit.

A reference where an embed would do. An extra query.

An embed where a reference would do. A duplicated value.

No schema validation. A typo is stored.

A $match after a $group. A wasted stage.

A read from a secondary for a fresh value. A stale read.

A write concern of 1 for a critical write. A possible loss.

No connection pool. A connection per request.

A quotable summary

MongoDB stores a document, which is a JSON-like object with a flexible set of fields, in a collection. Embed the data that is read together and is bounded, and reference the data that is large, shared or changes independently, because the rule is that the data read together is stored together. An index is required for a query to be fast, the aggregation pipeline transforms the documents in stages, and the database does not enforce a schema by default, so the application must.

For the related topics, see database-indexes-explained and caching-strategies-guide. For the broader context, database-sharding-basics and eventual-consistency-guide.

Frequently asked questions

What is a document in MongoDB?
A JSON-like object with a flexible set of fields, stored in a collection. It can contain a nested object and an array, so a related value can be embedded rather than stored in another table. Each document has an _id field, which is unique in the collection.
When should I embed a document and when should I reference it?
Embed when the related data is read with the parent and is bounded, such as the lines of an order. Reference when the related data is large, is shared, or changes independently, such as the author of a post. The rule is that the data read together is stored together.
What is the aggregation pipeline?
A sequence of stages that transform the documents, such as match, group, sort and project. Each stage takes the output of the previous one, so the pipeline is a series of transformations. It is the equivalent of a SQL query with a group by.
Does MongoDB need an index?
Yes, for a query to be fast. Without an index, the query scans every document in the collection, which is slow as the collection grows. An index on the queried field makes the lookup efficient, and a compound index covers a query with several fields.
Is MongoDB schemaless?
It is schema-flexible rather than schemaless. The database does not enforce a schema by default, so the application must, and a schema validation rule can be added to the collection. A flexible schema is a benefit for an evolving shape and a risk for a typo.
What is a replica set?
A group of MongoDB servers that hold the same data, with one primary and several secondaries. A write goes to the primary and is replicated, and a read can go to a secondary. It provides a failover, because a secondary is promoted if the primary fails.