Skip to content

MongoDB Basics

Work with MongoDB: collections, documents, CRUD operations, and querying.

What you'll learn

  • How MongoDB stores data as BSON documents in collections
  • Inserting documents with insertOne and insertMany
  • Querying with find, filters, and projection
  • Updating documents with updateOne and operators
  • Indexing and the _id field

Concept

Documents and Collections

MongoDB stores data as documents (JSON-like objects encoded as BSON) grouped into collections. A collection is analogous to a table, and a document is analogous to a row — but documents are flexible: each document in a collection can have a different shape. Every document automatically gets an _id field (a 12-byte ObjectId by default) that serves as the primary key.

Inserting Documents

insertOne adds a single document; insertMany adds multiple. You provide the document as a JavaScript object. Fields can be strings, numbers, booleans, arrays, nested objects, dates, and more. If you do not specify _id, MongoDB generates one automatically.

Querying with find

db.collection.find(query, projection) returns matching documents. The query is an object specifying filter conditions: { status: 'active' }, { price: { $gt: 50 } }, { tags: 'red' } (matches if 'red' is in the array). Operators like $gt, $lt, $in, $regex, and $and build complex filters. The projection specifies which fields to include or exclude.

Updating Documents

updateOne and updateMany modify documents. Use update operators: $set (set a field), $inc (increment), $push (append to array), $pull (remove from array), $unset (remove a field). replaceOne replaces the entire document. Use upsert: true to insert if no match exists.

Indexing

MongoDB supports indexes on any field, including nested fields and array elements. db.collection.createIndex({ field: 1 }) creates an ascending index. Without an index, MongoDB scans every document in the collection (a "collection scan"). Indexes are essential for performance on large collections. Use db.collection.find(...).explain() to check if an index is used.

Example

              -- Insert a document
db.products.insertOne({
  name: "Wireless Keyboard",
  price: 49.99,
  category: "electronics",
  tags: ["wireless", "usb", "keyboard"],
  specs: { batteryLife: "12 months", layout: "QWERTY" },
  inStock: true
});

-- Query with filter and projection
db.products.find(
  { price: { $gt: 20 }, category: "electronics" },
  { name: 1, price: 1, _id: 0 }
).sort({ price: -1 }).limit(10);

-- Update with operators
db.products.updateOne(
  { name: "Wireless Keyboard" },
  { $set: { price: 39.99 }, $push: { tags: "sale" } }
);

-- Create an index on the price field
db.products.createIndex({ price: 1 });
db.products.createIndex({ category: 1, price: -1 });
            

Four MongoDB operations: insert a document with nested data, query with filter and projection, update with $set and $push, and create single and compound indexes.

Try it

  • JSON Formatter

    Format MongoDB documents and query results as JSON.

  • JSON Path

    Query nested document fields with JSONPath expressions.

Common mistakes

The mistake

Not creating indexes on frequently queried fields

The fix

Without an index, MongoDB scans every document. Create indexes on fields used in find filters, sort, and join ($lookup). Use explain() to verify.

The mistake

Using MongoDB for highly relational data with many joins

The fix

MongoDB's $lookup join is limited and slow compared to SQL joins. If your data is highly relational with many connections, a relational database is likely a better fit.

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Build real projects

Apply what you learned by building guided projects with starter code and solutions.

View projects

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors