Beginner MongoDB Interview Questions and Answers

๐Ÿ“‹ Table of Contents โ–พ
  1. Questions & Answers
  2. 📝 Knowledge Check

🍃 Beginner MongoDB Interview Questions

This lesson covers core MongoDB concepts every developer must know. Master documents, collections, CRUD operations, data types, basic queries, indexes, and the differences between SQL and NoSQL. These questions reflect what interviewers ask at junior and entry-level roles.

Questions & Answers

01 What is MongoDB and what type of database is it?

Core MongoDB is an open-source, document-oriented NoSQL database developed by MongoDB, Inc. Instead of storing data in rows and columns like a relational database, MongoDB stores data as BSON documents (Binary JSON) inside collections.

Key characteristics:

  • Schema-less โ€” documents in the same collection can have different fields and structures
  • Document model โ€” data is stored as JSON-like objects, making it natural for JavaScript applications
  • Horizontally scalable โ€” built-in sharding distributes data across multiple servers
  • High availability โ€” replica sets provide automatic failover
  • Rich query language โ€” supports filtering, projections, joins (lookups), aggregations, and geospatial queries

MongoDB is used for: content management systems, real-time analytics, IoT data, user profiles, product catalogues, mobile backends, and applications requiring flexible, evolving schemas.

02 What is the difference between SQL (relational) and NoSQL (MongoDB)?

Core

  • Data model: SQL uses tables with rows and columns (fixed schema); MongoDB uses collections of documents (flexible schema)
  • Schema: SQL requires a predefined schema โ€” altering it means migrations; MongoDB allows each document to have different fields
  • Joins: SQL uses JOIN across normalised tables; MongoDB embeds related data in documents or uses $lookup for references
  • Transactions: SQL has ACID transactions built in from the start; MongoDB added multi-document ACID transactions in v4.0
  • Scaling: SQL typically scales vertically (bigger server); MongoDB scales horizontally (more servers via sharding)
  • Query language: SQL uses standardised SQL; MongoDB uses a JSON-based query API

SQL โ†’ MongoDB terminology mapping: Table โ†’ Collection, Row โ†’ Document, Column โ†’ Field, Primary Key โ†’ _id, JOIN โ†’ $lookup / embedding, Index โ†’ Index.

03 What is a Document in MongoDB? What format does it use?

Core A document is the fundamental unit of data in MongoDB โ€” equivalent to a row in a relational database. Documents are stored as BSON (Binary JSON) but are displayed and worked with as JSON.

{
  "_id": ObjectId("64b2f1a3c9d4e8a1b2c3d4e5"),
  "name": "Alice Johnson",
  "age": 29,
  "email": "alice@example.com",
  "address": {
    "street": "123 Main St",
    "city": "London",
    "postcode": "EC1A 1BB"
  },
  "skills": ["JavaScript", "Node.js", "MongoDB"],
  "createdAt": ISODate("2026-01-15T09:30:00Z"),
  "isActive": true
}

BSON extends JSON with additional types:

  • ObjectId โ€” 12-byte unique identifier (default _id)
  • Date / ISODate โ€” UTC datetime
  • NumberInt, NumberLong, NumberDecimal โ€” typed numbers
  • BinData โ€” binary data (images, files)
  • Timestamp โ€” for internal MongoDB use and replication

Documents support embedded sub-documents and arrays, enabling rich, nested data structures without joins.

04 What is a Collection in MongoDB? How does it differ from a SQL table?

Core A collection is a group of MongoDB documents โ€” the equivalent of a table in a relational database. Collections are stored within a database.

Key differences from a SQL table:

  • No enforced schema โ€” different documents in the same collection can have completely different fields. A users collection can have some documents with an address field and others without.
  • No column definitions โ€” no need to define fields and their types upfront (though you can enforce a schema with validation rules)
  • Dynamic โ€” new fields can be added to documents at any time without altering the collection
// Creating a collection implicitly by inserting a document
db.users.insertOne({ name: "Alice", age: 29 });

// Explicit creation with options (capped collections, schema validation)
db.createCollection("logs", {
  capped: true,   // fixed-size, auto-deletes oldest documents
  size: 10000000  // 10MB max
})

05 What is the _id field in MongoDB?

Core Every MongoDB document must have an _id field that acts as its primary key โ€” uniquely identifying it within a collection. If you don’t provide one on insert, MongoDB automatically generates an ObjectId.

ObjectId structure (12 bytes):

  • 4 bytes โ€” Unix timestamp (seconds since epoch)
  • 5 bytes โ€” random value unique to the machine and process
  • 3 bytes โ€” incrementing counter
// Auto-generated ObjectId
{ "_id": ObjectId("64b2f1a3c9d4e8a1b2c3d4e5") }

// Custom _id (any unique value)
db.products.insertOne({ _id: "sku-12345", name: "Widget", price: 9.99 });

// Extract creation time from ObjectId
ObjectId("64b2f1a3c9d4e8a1b2c3d4e5").getTimestamp()
// ISODate("2023-07-15T10:30:11Z")

You can use any unique value as _id: a string, integer, UUID, or composite key using a sub-document. The _id field is always indexed automatically.

06 What are the basic CRUD operations in MongoDB?

CRUD CRUD stands for Create, Read, Update, Delete โ€” the four fundamental database operations.

// CREATE
db.users.insertOne({ name: "Alice", age: 29, city: "London" });
db.users.insertMany([{ name: "Bob" }, { name: "Carol" }]);

// READ
db.users.find({ city: "London" });                    // all matching
db.users.findOne({ name: "Alice" });                  // first match
db.users.find({ age: { $gte: 18 } }, { name: 1, email: 1 }); // with projection

// UPDATE
db.users.updateOne(
  { name: "Alice" },                    // filter
  { $set: { city: "Manchester" } }      // update operator
);
db.users.updateMany({ city: "London" }, { $set: { country: "UK" } });
db.users.replaceOne({ name: "Bob" }, { name: "Bob", age: 30 }); // full replace

// DELETE
db.users.deleteOne({ name: "Alice" });
db.users.deleteMany({ isActive: false });
db.users.drop();    // delete entire collection

07 What are MongoDB query operators? Explain the common ones.

Queries Query operators are special keywords prefixed with $ that enable rich filtering beyond simple equality checks.

Comparison operators:

db.products.find({ price: { $gt: 10 } });          // greater than
db.products.find({ price: { $gte: 10, $lte: 50 } }); // between 10 and 50
db.products.find({ price: { $ne: 0 } });            // not equal
db.products.find({ status: { $in: ["active", "pending"] } }); // in array
db.products.find({ status: { $nin: ["deleted"] } }); // not in array

Logical operators:

db.products.find({ $and: [{ price: { $gt: 10 } }, { stock: { $gt: 0 } }] });
db.products.find({ $or:  [{ price: { $lt: 5  } }, { category: "sale" }] });
db.products.find({ $not: [{ status: "deleted" }] });
db.products.find({ $nor: [{ price: 0 }, { stock: 0 }] });

Element operators:

db.users.find({ email: { $exists: true } });    // field exists
db.users.find({ age:   { $type: "int" } });     // field is type

08 What are update operators in MongoDB?

CRUD Update operators modify specific parts of a document without replacing it entirely.

// $set โ€” set field values
db.users.updateOne({ _id: id }, { $set: { name: "Alice", age: 30 } });

// $unset โ€” remove a field
db.users.updateOne({ _id: id }, { $unset: { tempToken: "" } });

// $inc โ€” increment/decrement a number
db.products.updateOne({ _id: id }, { $inc: { stock: -1, views: 1 } });

// $push โ€” append to an array
db.posts.updateOne({ _id: id }, { $push: { tags: "mongodb" } });

// $pull โ€” remove from an array
db.posts.updateOne({ _id: id }, { $pull: { tags: "draft" } });

// $addToSet โ€” push only if value doesn't already exist
db.users.updateOne({ _id: id }, { $addToSet: { roles: "admin" } });

// $rename โ€” rename a field
db.users.updateMany({}, { $rename: { "fname": "firstName" } });

// upsert โ€” update if exists, insert if not
db.users.updateOne(
  { email: "alice@example.com" },
  { $set: { name: "Alice" } },
  { upsert: true }
);

09 What are Indexes in MongoDB and why are they important?

Indexes An index is a data structure that stores a small portion of a collection’s data in an easy-to-traverse form. Without an index, MongoDB performs a full collection scan (COLLSCAN) โ€” reading every document. With an index, it performs an index scan (IXSCAN) โ€” reading only matching entries.

// Create a single-field index
db.users.createIndex({ email: 1 });        // 1 = ascending

// Create a compound index (multiple fields)
db.orders.createIndex({ userId: 1, createdAt: -1 }); // -1 = descending

// Unique index โ€” enforces uniqueness
db.users.createIndex({ email: 1 }, { unique: true });

// TTL index โ€” auto-delete documents after a time period
db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 });

// List all indexes on a collection
db.users.getIndexes();

// Explain a query โ€” shows whether index was used
db.users.find({ email: "alice@example.com" }).explain("executionStats");

Trade-off: Indexes speed up reads but slow down writes (every write must update the index). Create indexes for fields that appear in query filters, sort operations, and equality checks. The _id field has a default index that cannot be removed.

10 What is the difference between embedding and referencing in MongoDB?

Schema Design MongoDB offers two ways to model relationships between entities: embedding related data inside a single document, or referencing it from another collection using its _id.

Embedding (denormalised):

{
  "_id": ObjectId("..."),
  "name": "Alice",
  "addresses": [                     // embedded โ€” stored inside the user doc
    { "type": "home", "city": "London" },
    { "type": "work", "city": "Manchester" }
  ]
}

Referencing (normalised):

// users collection
{ "_id": ObjectId("user123"), "name": "Alice" }

// orders collection โ€” references the user
{ "_id": ObjectId("order456"), "userId": ObjectId("user123"), "total": 99.99 }

When to embed: Data is always accessed together, sub-documents are small, one-to-few relationship, data doesn’t change frequently. When to reference: Data is accessed independently, large sub-documents, many-to-many relationships, data is shared across multiple parent documents.

11 What is the Aggregation Pipeline in MongoDB?

Aggregation The aggregation pipeline is a framework for data processing and transformation. Documents pass through a sequence of stages, where each stage transforms the documents from the previous stage.

db.orders.aggregate([
  { $match:   { status: "completed" } },          // Stage 1: filter
  { $group:   {
      _id:     "$customerId",
      total:   { $sum: "$amount" },
      count:   { $count: {} }
  }},                                              // Stage 2: group and sum
  { $sort:    { total: -1 } },                     // Stage 3: sort by total desc
  { $limit:   10 },                                // Stage 4: top 10 customers
  { $lookup:  {                                    // Stage 5: join with customers
      from:         "customers",
      localField:   "_id",
      foreignField: "_id",
      as:           "customerInfo"
  }},
  { $project: { name: { $first: "$customerInfo.name" }, total: 1, count: 1 } }
]);

Common stages: $match (filter), $group (group and aggregate), $sort, $limit, $skip, $project (reshape), $lookup (join), $unwind (flatten arrays), $addFields, $count.

12 What is the difference between find() and aggregate() in MongoDB?

Queries

  • find() โ€” simple querying, filtering, and projection. Fast and efficient for straightforward reads. Cannot group, join, or compute derived fields. Returns a cursor of matching documents.
  • aggregate() โ€” full data transformation pipeline. Supports grouping, joining ($lookup), computed fields, array manipulation, faceted search, and statistical operations. More powerful but slightly more complex to write.
// find() โ€” filter and project
db.users.find(
  { age: { $gte: 18 } },      // filter
  { name: 1, email: 1 }       // projection
);

// aggregate() โ€” same result, but can also group, join, etc.
db.users.aggregate([
  { $match:   { age: { $gte: 18 } } },
  { $project: { name: 1, email: 1 } }
]);

Use find() when you need simple filtering and projection. Use aggregate() when you need to transform, group, calculate, join, or reshape data. The aggregation pipeline can also use indexes via $match as the first stage.

13 What is a Replica Set in MongoDB?

Replication A replica set is a group of MongoDB instances (nodes) that maintain the same dataset, providing high availability and data redundancy. A typical replica set has one primary node and two or more secondary nodes.

  • Primary node โ€” receives all write operations. Records all changes to its oplog (operations log).
  • Secondary nodes โ€” replicate data from the primary’s oplog asynchronously. Can serve read operations if configured.
  • Automatic failover โ€” if the primary fails, the remaining nodes hold an election and promote a secondary to primary within seconds. The application reconnects automatically.
  • Arbiter โ€” a lightweight member that participates in elections but stores no data. Used when you need an odd number of voters but don’t want the cost of a full replica.
// Connecting to a replica set in a connection string
mongodb://mongo1:27017,mongo2:27017,mongo3:27017/mydb?replicaSet=rs0

MongoDB Atlas manages replica sets automatically. Minimum recommended production setup: 3-node replica set for fault tolerance.

14 What is MongoDB Atlas?

Cloud MongoDB Atlas is MongoDB’s fully managed cloud database service available on AWS, Azure, and Google Cloud. It handles all operational tasks automatically.

What Atlas provides:

  • Automated deployment โ€” deploy a production-ready replica set in minutes with no server management
  • Automatic backups โ€” continuous backup with point-in-time recovery
  • Auto-scaling โ€” scale storage and compute up or down based on demand
  • Monitoring โ€” built-in performance metrics, query profiler, and alerts
  • Global clusters โ€” distribute data across regions for low-latency global access
  • Atlas Search โ€” full-text search powered by Lucene
  • Atlas Data API โ€” access MongoDB data via REST/GraphQL without a driver
  • Free tier (M0) โ€” 512MB shared cluster, suitable for learning and small projects
15 How do you sort, limit, and skip results in MongoDB?

Queries

// sort() โ€” 1 = ascending, -1 = descending
db.products.find().sort({ price: 1 });             // cheapest first
db.products.find().sort({ createdAt: -1 });        // newest first
db.products.find().sort({ category: 1, price: 1 }); // multi-field sort

// limit() โ€” return at most N documents
db.products.find().limit(10);                      // first 10

// skip() โ€” skip N documents (for pagination)
db.products.find().limit(10).skip(20);             // page 3 (0-indexed)

// Pagination pattern
const page = 2;
const pageSize = 10;
db.products.find()
  .sort({ _id: 1 })
  .skip((page - 1) * pageSize)
  .limit(pageSize);

Caution with skip(): Large skip() values are inefficient โ€” MongoDB still reads and discards all skipped documents. For high-volume pagination, use cursor-based pagination instead: store the last _id from the previous page and query { _id: { $gt: lastId } } with a limit().

16 What are the data types supported in MongoDB?

Core BSON (Binary JSON) supports a richer set of types than JSON:

  • String โ€” UTF-8 text: "hello"
  • Number โ€” Double (default), Int32, Int64, Decimal128
  • Boolean โ€” true / false
  • Array โ€” ordered list: ["a", "b", "c"]
  • Object / Document โ€” embedded sub-document: { city: "London" }
  • ObjectId โ€” 12-byte unique identifier: ObjectId("...")
  • Date โ€” milliseconds since Unix epoch: ISODate("2026-01-01T00:00:00Z")
  • Null โ€” null value or missing field
  • Regular Expression โ€” /pattern/flags
  • Binary Data โ€” for storing files, images, hashed passwords
  • Timestamp โ€” internal MongoDB type for replication
  • MinKey / MaxKey โ€” special types that compare lower/higher than all other BSON values
17 How do you query array fields in MongoDB?

Queries

// Sample documents
{ name: "Alice", skills: ["JavaScript", "Node.js", "MongoDB"] }
{ name: "Bob",   skills: ["Python", "MongoDB", "Redis"] }

// Find documents where skills CONTAINS "MongoDB"
db.users.find({ skills: "MongoDB" });

// Find where skills contains ALL specified values
db.users.find({ skills: { $all: ["MongoDB", "Node.js"] } });

// Find where ANY element matches a condition
db.users.find({ scores: { $elemMatch: { $gte: 90, $lt: 100 } } });

// Find by array length
db.users.find({ skills: { $size: 3 } });   // exactly 3 skills

// Query by array element position
db.users.find({ "skills.0": "JavaScript" }); // first element is JS

// Update a specific array element
db.users.updateOne(
  { skills: "Node.js" },
  { $set: { "skills.$": "Node" } }  // $ = positional operator
);

18 What is the mongosh shell? What are the most useful commands?

Tooling mongosh is the official interactive shell for MongoDB (replaced the older mongo shell). It provides a JavaScript REPL for running queries, admin commands, and scripts against a MongoDB instance.

# Connect to local instance
mongosh

# Connect to a specific database on a remote host
mongosh "mongodb+srv://cluster0.abcd.mongodb.net/mydb" --username admin

# Inside mongosh:
show dbs                          # list all databases
use myDatabase                    # switch to / create database
show collections                  # list collections in current db
db.users.countDocuments()         # count documents
db.users.find().pretty()          # formatted output
db.stats()                        # database stats
db.users.stats()                  # collection stats

# Database admin
db.dropDatabase()                 # delete current database
db.users.drop()                   # delete collection
db.createUser({ user: "admin", pwd: "secret", roles: ["readWrite"] })

# Run a .js script file
mongosh myScript.js

19 What is projection in MongoDB queries?

Queries Projection controls which fields are returned in query results โ€” similar to specifying columns in a SQL SELECT. Returning only needed fields reduces network bandwidth and memory usage.

// Include specific fields (1 = include)
db.users.find({}, { name: 1, email: 1 });
// Returns: { _id: ObjectId(...), name: "Alice", email: "alice@..." }
// _id is ALWAYS included unless explicitly excluded

// Exclude specific fields (0 = exclude)
db.users.find({}, { password: 0, __v: 0 });

// Exclude _id
db.users.find({}, { name: 1, email: 1, _id: 0 });

// Project a nested field
db.users.find({}, { "address.city": 1, name: 1 });

// Array slice โ€” return only first 3 elements
db.posts.find({}, { title: 1, comments: { $slice: 3 } });

// Cannot mix inclusion and exclusion (except for _id)
// This is INVALID: { name: 1, password: 0 }  โŒ

20 What is the upsert option in MongoDB?

CRUD Upsert (update + insert) is an atomic operation that updates a document if it exists, or inserts a new one if no matching document is found. Pass { upsert: true } as an option.

// If a user with email "alice@..." exists โ€” update their lastSeen
// If not โ€” create a new document with email and lastSeen
db.users.updateOne(
  { email: "alice@example.com" },          // filter
  {
    $set:         { lastSeen: new Date() },
    $setOnInsert: { createdAt: new Date(), role: "user" }  // only on insert
  },
  { upsert: true }
);

// Typical use cases:
// - Syncing external data (upsert by external ID)
// - Updating counters where the record may not exist yet
// - User session tracking

// findOneAndUpdate with upsert โ€” returns the updated/inserted document
db.stats.findOneAndUpdate(
  { page: "/home" },
  { $inc: { views: 1 } },
  { upsert: true, returnDocument: "after" }
);

21 What is schema validation in MongoDB?

Schema Design Although MongoDB is schema-less by default, you can enforce a document structure using JSON Schema validation. This catches invalid data at the database level before it is stored.

db.createCollection("users", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["name", "email", "age"],
      properties: {
        name:  { bsonType: "string",  description: "must be a string" },
        email: { bsonType: "string",  pattern: "^.+@.+\..+$" },
        age:   { bsonType: "int",     minimum: 0, maximum: 120 },
        role:  { enum: ["user", "admin", "moderator"] }
      }
    }
  },
  validationAction: "error"   // "error" (reject) or "warn" (log only)
});

// Add validation to an existing collection
db.runCommand({
  collMod: "users",
  validator: { $jsonSchema: { ... } }
});

Validation rules are enforced on inserts and updates. Use validationLevel: "moderate" to only validate new inserts and updates to documents that already meet the schema (useful during migrations).

22 How does MongoDB ensure data durability? What is the Write Concern?

Reliability Write concern specifies the level of acknowledgement MongoDB provides after a write operation โ€” controlling the trade-off between performance and data durability.

// w:1 (default) โ€” acknowledged by the primary only
db.orders.insertOne({ ... }, { writeConcern: { w: 1 } });

// w:"majority" โ€” acknowledged by majority of replica set members (safest)
db.orders.insertOne({ ... }, { writeConcern: { w: "majority", wtimeout: 5000 } });

// w:0 โ€” fire and forget (fastest, no acknowledgement)
db.logs.insertOne({ ... }, { writeConcern: { w: 0 } });

// j:true โ€” waits for write to be committed to journal (survives crash)
db.payments.insertOne({ ... }, { writeConcern: { w: 1, j: true } });

Journal โ€” MongoDB writes to an in-memory buffer and also logs operations to a journal file on disk. On restart after a crash, MongoDB replays the journal to recover data. Enable j: true for operations where data loss is unacceptable (financial transactions, order records).

📝 Knowledge Check

Test your understanding of MongoDB fundamentals with these five questions.

🧠 Quiz Question 1 of 5

What format does MongoDB use to store documents internally?





🧠 Quiz Question 2 of 5

What MongoDB update operator increments a numeric field by a given amount?





🧠 Quiz Question 3 of 5

In MongoDB, what is a Collection equivalent to in a relational database?





🧠 Quiz Question 4 of 5

What does the upsert option do in a MongoDB updateOne() call?





🧠 Quiz Question 5 of 5

What is the primary purpose of an index in MongoDB?