Introduction to MongoDB
Understand what MongoDB is, why document databases exist, how MongoDB differs from relational databases, how documents and collections work, and where MongoDB fits into modern application architectures.
What Is MongoDB?
MongoDB is a document-oriented database management system designed to store, retrieve, and manipulate application data using flexible, BSON-based documents.
Instead of organizing application data exclusively into tables and rows, MongoDB organizes it into collections and documents. A document represents a structured record containing fields and values. Those values can include strings, numbers, dates, arrays, nested documents, and other BSON-supported types.
MongoDB is commonly used in web applications, content platforms, e-commerce systems, event-driven applications, analytics pipelines, and services that need flexible data models.
Example: A user document
{
"_id": "user-1001",
"name": "Arun Kumar",
"email": "arun@example.com",
"age": 28,
"skills": ["JavaScript", "React", "Node.js"],
"address": {
"city": "Bengaluru",
"country": "India"
},
"isActive": true
}
This single document represents a user, including the user's skills and address. The address is a nested document, while the skills field is an array.
The important point is that MongoDB can represent a related group of values in one document without requiring every value to live in a separate table.
What MongoDB does not mean
MongoDB is not simply a database without tables. It is a database with its own query language, data types, indexes, transaction capabilities, consistency guarantees, storage engine, replication mechanisms, and distributed-system architecture.
It also does not mean that data modeling is unnecessary. Poor document design can create expensive queries, oversized documents, update anomalies, or difficult scaling problems.
Where MongoDB fits
Consider a learning platform. A course may have a title, description, difficulty, tags, and an array of introductory metadata. MongoDB can represent these related values naturally in one document. Other data, such as user progress, enrollments, and audit events, may be stored in separate collections because they have different access patterns and growth characteristics.
- Database type:
Document-oriented NoSQL database - Document representation:
BSON - Primary organizational units:
Databases, collections, and documents
Logical container for collectionsGroup of documentsStructured BSON recordNamed value within a documentWhen learning MongoDB, focus on the shape of your data and how your application reads and writes it. Those two factors strongly influence effective document design.
- MongoDB is a document-oriented database.
- MongoDB documents are represented using BSON.
- Documents can contain nested objects and arrays.
- Collections group documents.
- Flexible document structures do not eliminate the need for deliberate schema design.
Which statement best describes MongoDB?
Why MongoDB Was Developed
Modern applications often manage data that changes rapidly as product features evolve. Traditional relational databases remain excellent choices for many workloads, but relational modeling can become cumbersome when application data contains deeply nested structures or highly variable attributes.
MongoDB's document model provides a way to store related information together while allowing documents in a collection to have different structures.
Problem 1: Frequently changing application structures
Imagine an online learning application that initially stores courses with a title and description. Later, the product adds difficulty, tags, prerequisites, instructors, and structured learning objectives.
In a relational database, these changes may require altering tables or introducing related tables, depending on the design. In MongoDB, new fields can be introduced into documents without requiring a collection-wide table alteration.
However, flexibility does not mean that every document should have an unrelated structure. Applications often benefit from a consistent document contract, validation rules, and migration practices.
Problem 2: Nested application data
A user profile might contain an address, preferences, and notification settings. If these values are usually retrieved together, embedding them in a user document can reduce the need for multiple queries or joins.
{
"name": "Meera",
"preferences": {
"theme": "dark",
"emailNotifications": true
},
"address": {
"city": "Chennai",
"postalCode": "600001"
}
}
Problem 3: Different access patterns
A product catalog, a time-series event stream, and a user profile do not necessarily need the same data model. MongoDB offers different modeling techniques, indexes, aggregation stages, and deployment options that can support these different workloads.
Trade-offs still exist
MongoDB does not automatically outperform relational databases. Query patterns, indexes, data size, write contention, consistency requirements, schema design, and operational configuration determine actual performance.
A relational database may be preferable when an application relies heavily on relational constraints, complex joins, or an existing relational ecosystem. MongoDB can be a strong fit when document-oriented data and the required access patterns align with its model.
- MongoDB addresses use cases involving flexible, nested application data.
- A flexible schema can simplify some application changes but does not remove the need for validation.
- Embedding related information can reduce additional reads when the information is accessed together.
- Database selection should be based on requirements rather than popularity.
Why might a developer choose MongoDB for a user profile containing preferences and an address?
Understanding NoSQL Databases
NoSQL is a broad category of database technologies that do not rely exclusively on the traditional relational table model. The term does not mean that these systems cannot perform queries, use schemas, or support transactions.
Common NoSQL categories include:
- Document databases: Store structured documents. MongoDB is an example.
- Key-value databases: Store values addressed by keys. Redis is a common example.
- Wide-column databases: Organize data using column families and are designed for particular distributed workloads. Apache Cassandra is an example.
- Graph databases: Represent entities and relationships as nodes and edges. Neo4j is an example.
These categories overlap in some capabilities, but they differ in their data models, query approaches, consistency characteristics, and typical access patterns.
Relational databases versus document databases
Relational databases organize data into tables with defined columns and relationships. Document databases organize data into documents and collections.
For example, an online store may represent a customer and their addresses in separate relational tables. A MongoDB implementation might embed a small set of addresses within a customer document if they are generally accessed together.
Neither representation is automatically better. The appropriate model depends on the expected queries, update frequency, cardinality, integrity requirements, and growth patterns.
SQL and MongoDB query syntax
MongoDB uses a document-oriented query interface rather than SQL as its primary query language.
A relational query might look like this:
SELECT name, age
FROM users
WHERE age >= 25;
The equivalent MongoDB query is:
db.users.find(
{ age: { $gte: 25 } },
{ _id: 0, name: 1, age: 1 }
);
The filter selects users whose age is at least 25. The projection returns only the name and age fields while excluding _id.
MongoDB also provides aggregation pipelines for grouping, transforming, joining, and analyzing data. The aggregation framework will be covered in depth in a later chapter.
Tables and relationshipsDocuments and collectionsKeys and valuesNodes and edges- NoSQL describes multiple database models rather than a single technology.
- MongoDB belongs to the document-database category.
- Relational and document databases both support querying and can support transactions.
- MongoDB queries use document-shaped filters and projections.
- Choose a database according to the data model and workload.
Which database category does MongoDB primarily belong to?
MongoDB Data Hierarchy: Deployment, Database, Collection, and Document
MongoDB data is organized hierarchically. Understanding this hierarchy is essential before learning queries, indexes, permissions, backups, or deployment architecture.
flowchart TD
A[MongoDB Deployment] --> B[Database: learning]
B --> C[Collection: users]
B --> D[Collection: courses]
C --> E[Document: user 1001]
C --> F[Document: user 1002]
D --> G[Document: course 2001]
Deployment
A deployment is the running MongoDB environment you connect to. It might be a standalone server, a replica set, a sharded cluster, or a managed service such as MongoDB Atlas.
Database
A database contains collections and related database-level configuration. An application may use separate databases for development, testing, and production.
For example:
learning_devlearning_testlearning_prod
These are illustrative names. Separate databases alone do not guarantee security or isolation; deployment permissions and configuration also matter.
Collection
A collection groups documents, commonly around an entity or workload such as users, courses, orders, or auditEvents.
Collections may have indexes and validation rules. Documents within a collection can have different fields, although applications often enforce a common structure.
Document
A document consists of fields and their values. A document's _id field uniquely identifies it within its collection.
Example:
{
_id: ObjectId("65a000000000000000000001"),
title: "MongoDB Fundamentals",
difficulty: "beginner",
durationMinutes: 180,
tags: ["database", "backend"],
instructor: {
name: "Kavitha",
experienceYears: 6
}
}
The document contains scalar values, an array, and an embedded document. The _id value is an ObjectId in this example.
Important naming detail
Collection names such as users and courses are conventions, not special keywords. You can choose names appropriate to your application, while avoiding confusing or reserved system namespaces.
MongoDB also creates some collections and internal structures for its own purposes. Application developers generally work with their own collections and the supported administrative interfaces.
- A deployment can contain multiple databases.
- A database can contain multiple collections.
- A collection contains documents.
- Documents contain fields and values, including arrays and embedded documents.
- The
_idfield uniquely identifies a document within its collection.
Which hierarchy correctly represents the primary MongoDB data organization?
Understanding Documents, Fields, Arrays, and Embedded Documents
MongoDB's document model is one of its most important concepts. A document is similar to a structured record, but its values can include complex nested structures.
Consider this course document:
{
_id: ObjectId("65a000000000000000000010"),
slug: "mongodb-fundamentals",
title: "MongoDB Fundamentals",
published: true,
price: 499,
tags: ["mongodb", "database", "backend"],
instructor: {
name: "Kavitha",
country: "India"
},
createdAt: ISODate("2026-01-10T10:00:00Z")
}
Scalar fields
Fields such as title, published, and price contain scalar values: a string, Boolean, and number respectively.
Arrays
The tags field is an array. Arrays can contain strings, numbers, documents, or other supported values.
For example:
{
title: "Advanced Aggregation",
prerequisites: [
"mongodb-fundamentals",
"mongodb-querying"
]
}
Arrays are useful when a document naturally owns a bounded list of related values. Unbounded arrays need special care because documents have a maximum BSON size and large arrays can make updates and queries expensive.
Embedded documents
The instructor field contains another document. Nested values can be queried using dot notation:
db.courses.find({ "instructor.country": "India" });
The dot in instructor.country identifies a nested field path. It is not a literal field name separator in the stored structure.
BSON types
MongoDB uses BSON, a binary-encoded serialization format based on a JSON-like document model. BSON supports additional types and distinctions that ordinary JSON does not represent directly, including ObjectId, Date, Decimal128, binary data, and several integer types.
For instance, an actual BSON Date is different from a string that merely looks like a date. That distinction matters when filtering by date ranges, sorting chronologically, and calculating date differences.
{
createdAt: ISODate("2026-10-22T09:30:00Z"),
expiresAt: null,
version: NumberInt(3)
}
This example uses MongoDB shell notation to illustrate BSON values. ISODate() and NumberInt() are shell helpers, not JSON syntax.
Documents have a size limit
MongoDB BSON documents have a maximum size of 16 MiB. This limit affects document design, especially when embedding large arrays, storing binary data, or accumulating historical events in a single document.
The solution is not always to split every nested value into its own collection. Instead, model documents around access patterns, relationships, cardinality, and expected growth.
db.courses.insertOne({
slug: "mongodb-fundamentals",
title: "MongoDB Fundamentals",
published: true,
tags: ["mongodb", "database"],
instructor: {
name: "Kavitha",
country: "India"
},
createdAt: new Date("2026-10-22T09:30:00Z")
});
db.courses.find(
{ "instructor.country": "India" },
{ _id: 0, title: 1, "instructor.name": 1, tags: 1 }
);courses collection. MongoDB generates an _id if one is not supplied. The second operation filters by a nested field and projects only the course title, instructor name, and tags. The date is created as a BSON Date using JavaScript's Date object. Run this in mongosh after connecting to your MongoDB deployment and selecting a database.- Documents can contain scalar fields, arrays, and nested documents.
- Dot notation addresses nested fields in queries.
- BSON supports types beyond standard JSON.
- A BSON Date is not equivalent to a date-formatted string.
- MongoDB documents have a 16 MiB maximum BSON size.
Which query filters documents whose nested instructor country is India?
Flexible Schema: Benefits, Limitations, and Validation
MongoDB collections can contain documents with different fields and structures. This is commonly called a flexible schema.
For example, a collection might contain these documents:
{ name: "Arun", age: 28 }
{ name: "Meera", email: "meera@example.com", skills: ["React"] }
{ name: "Ravi", age: 32, department: "Engineering" }
MongoDB can store all three documents in the same collection. A query that expects age will not match every document, and an application that assumes email always exists must account for documents where it is absent.
Flexible does not mean structureless
A production application typically defines a logical schema even if the database does not require every field to exist in every document.
For example, a user record may require:
nameto be a string.emailto be a string.createdAtto be a date.isActiveto be a Boolean.
Without appropriate validation, one service might store age as a number while another stores it as a string. These inconsistent types can make filters, sorting, aggregation, and application code harder to reason about.
MongoDB schema validation
MongoDB supports collection-level validation using JSON Schema rules and other supported validation expressions.
db.createCollection("validatedUsers", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "email", "createdAt"],
properties: {
name: {
bsonType: "string",
minLength: 1
},
email: {
bsonType: "string",
minLength: 3
},
createdAt: {
bsonType: "date"
},
age: {
bsonType: ["int", "long", "double", "decimal"],
minimum: 0
}
}
}
},
validationLevel: "strict",
validationAction: "error"
});
This creates a collection that requires name, email, and createdAt, with the specified types and constraints. The age field is optional but, if present, must use an accepted numeric BSON type and be nonnegative.
validationLevel: "strict" applies validation to inserts and updates under the configured rules. validationAction: "error" rejects operations that produce invalid documents.
Schema evolution
As an application grows, you may need to change its document structure. A safe migration can involve adding new fields, temporarily supporting old and new shapes, backfilling existing documents, updating application code, and eventually removing deprecated fields.
Do not assume that changing a Mongoose schema automatically migrates every document already stored in MongoDB. Application-level schemas and database-level validation are separate mechanisms.
A flexible schema allows different document structures, but it does not guarantee that the stored data follows your application's intended contract. Use application validation, MongoDB schema validation, and migrations where appropriate.
db.schemaDemo.insertMany([
{ name: "Arun", age: 28 },
{ name: "Meera", age: "29" },
{ name: "Ravi" }
]);
// Matches numeric age values of at least 25.
db.schemaDemo.find({ age: { $gte: 25 } });
// Find documents where age is missing.
db.schemaDemo.find({ age: { $exists: false } });
// Find documents where age is stored as a string.
db.schemaDemo.find({ age: { $type: "string" } });"29" as the number 29. $exists: false finds documents without the field, and $type: "string" identifies documents whose age field has the string BSON type. These differences illustrate why flexible schemas should be paired with deliberate validation and migration practices.- Documents in a collection can have different fields.
- Missing fields and fields with inconsistent types can cause application bugs.
- MongoDB supports collection-level JSON Schema validation.
- Strict validation can reject writes that violate configured rules.
- Changing an application schema does not automatically migrate existing database documents.
What happens when a collection has strict schema validation with validationAction set to error and a write violates the rules?
Real-World MongoDB Use Cases
MongoDB can support many application architectures, but the best design depends on the workload. The following examples demonstrate how the document model can fit real systems.
1. E-commerce product catalog
Products often have category-specific attributes. A laptop may have RAM and processor details, while a shirt may have size and material.
{
sku: "LAPTOP-001",
name: "Developer Laptop",
category: "electronics",
attributes: {
ramGB: 32,
storageGB: 1024,
processor: "Example CPU"
}
}
Another document can use a different set of attributes:
{
sku: "SHIRT-001",
name: "Cotton Shirt",
category: "clothing",
attributes: {
material: "cotton",
sizes: ["M", "L", "XL"]
}
}
This structure accommodates product-specific attributes. Frequently filtered attributes may still require carefully selected indexes or a more standardized model.
2. Learning platform
A course document can store its title, tags, difficulty, and other metadata. Enrollments and user progress may deserve separate collections because the number of enrollments can grow independently of the course document.
3. Content management system
Articles can contain structured metadata, author references, publication status, and arrays of tags. An embedded structure may be useful when the article is typically read as one unit.
4. Event and activity tracking
Applications can store events with a timestamp, event type, user identifier, and contextual metadata. Event collections need deliberate retention, indexing, and growth strategies. MongoDB also has specialized time-series collection support for suitable workloads.
5. Inventory management
Products and stock movements have different lifecycles. A product document may represent current product information, while inventory movements are stored separately to preserve a growing history of changes.
6. Logging and operational analytics
MongoDB can store structured application events and support queries or aggregation over them. However, ingestion rates, retention, cardinality, and analytical requirements should be evaluated before selecting it for large-scale observability workloads.
When MongoDB may not be the best fit
MongoDB is not automatically the ideal database for every application. Consider alternatives or a polyglot architecture when:
- The workload depends heavily on relational joins and relational constraints.
- A specialized graph, search, analytical, or time-series system better matches the main access pattern.
- The team already has strong operational capabilities around another database.
- The application's consistency and transaction requirements favor a different architecture.
A production database decision should consider data modeling, performance testing, availability, security, backup and recovery, cost, and operational expertise.
- MongoDB can store products with different attributes in a shared catalog.
- Collections should be designed around entity relationships, access patterns, and growth.
- Event data requires retention and indexing strategies.
- MongoDB is useful for many workloads but is not universally the best database.
- Production architecture should account for security, reliability, and operational cost.
An application stores a growing history of inventory movements. Which design is generally more appropriate than adding every movement to one ever-growing product array?
MongoDB Installation and Ways to Practice
You can learn MongoDB using a local installation, a managed cloud deployment, or a containerized environment. The right option depends on whether you want to focus on queries, local development, or deployment operations.
Option 1: MongoDB Atlas
MongoDB Atlas is MongoDB's managed database service. It provides hosted deployments and management features so you can practice without administering a database server yourself.
Create a deployment, configure an appropriate database user, allow the required network access, and obtain a connection string. Follow the current official instructions for your chosen environment.
Security note: avoid allowing unrestricted network access for production deployments. Use appropriate network restrictions, least-privilege database users, and secure secret storage.
Option 2: Local MongoDB installation
A local installation is useful for learning mongosh, creating databases and collections, running queries, and inspecting database behavior without depending on a remote service.
Install a MongoDB Community Server version supported by your operating system, and install or use a compatible MongoDB Shell (mongosh). Start the server and connect with the shell.
mongosh "mongodb://127.0.0.1:27017"
This command assumes a local MongoDB server is running on the default port and does not require authentication. If your local setup uses authentication or a different port, adjust the connection command accordingly.
Option 3: Docker
Docker can provide a repeatable development environment. The following command starts a local MongoDB container with a named persistent volume and credentials for local development:
docker volume create mongodb-course-data
docker run -d \
--name mongodb-course \
-p 127.0.0.1:27017:27017 \
-e MONGO_INITDB_ROOT_USERNAME=courseadmin \
-e MONGO_INITDB_ROOT_PASSWORD=local-dev-password-change-me \
-v mongodb-course-data:/data/db \
mongo:8.0
The command binds MongoDB to the local loopback interface rather than exposing it on every network interface. The example password is for a disposable local learning environment only; use a unique secret if adapting the command, and never use the example credentials in production.
The official image initializes the root user when it creates a fresh database directory. Changing the environment variables later does not automatically rotate an existing user's password.
Connect to this container with:
mongosh "mongodb://courseadmin:local-dev-password-change-me@127.0.0.1:27017/admin?authSource=admin"
Which option should you choose?
For a beginner, MongoDB Atlas is convenient if you prefer not to manage the server, while a local installation or Docker is useful for hands-on control. You can follow the course with any supported environment that provides mongosh and a MongoDB server.
Managed cloud deploymentLocal database installationContainerized developmentMongoDB command-line shellUse one working MongoDB environment for the course exercises. Keep a separate practice database, and avoid experimenting with destructive commands against production data.
- MongoDB Atlas provides a managed deployment.
- Local MongoDB installations provide direct control over the server.
- Docker can provide a repeatable development environment.
mongoshis the interactive shell used in this course.- Use least-privilege access and secure credentials outside disposable local environments.
Which tool is designed to provide an interactive command-line shell for MongoDB?
Connecting to MongoDB and Exploring the Shell
After setting up a database environment, learn how to connect and inspect the deployment before writing application queries.
Connecting to a local server
mongosh "mongodb://127.0.0.1:27017"
If the connection succeeds, the shell connects to the local MongoDB server. If it fails, check whether the server is running, whether the port is correct, and whether authentication or network restrictions apply.
Connecting to a managed deployment
A MongoDB Atlas connection string commonly has a form similar to:
mongodb+srv://<username>:<password>@<cluster-host>/<database>?retryWrites=true&w=majority
This is a template, not a working connection string. Replace the placeholders with the values from your deployment and encode special characters in credentials as required by the connection-string format. Avoid committing credentials to source control.
Select a database
use learning
The shell switches its current database context to learning. The database may not be physically created until data is written or a collection is explicitly created.
Inspect the current database
db
The shell displays the current database name.
List collections
db.getCollectionNames()
This returns the names of collections in the current database that are visible to the connected user.
Insert your first document
db.courseDemo.insertOne({
title: "MongoDB Fundamentals",
level: "beginner",
published: true
});
This creates a collection if necessary and inserts a document. If you omit _id, MongoDB generates one.
Read the document
db.courseDemo.find();
The shell returns documents matching the query. With no filter, the query matches every document in the collection.
Understand the db variable
In mongosh, db represents the current database. Expressions such as db.users.find() access a collection through that database context.
The db variable is a shell interface, not a global database object that exists in every programming language. In Node.js, you interact with MongoDB through a driver or an object-document mapper such as Mongoose.
use learning
db.courseDemo.insertMany([
{
title: "MongoDB Fundamentals",
level: "beginner",
published: true
},
{
title: "MongoDB Querying",
level: "intermediate",
published: false
}
]);
// Display all course documents.
db.courseDemo.find();
// Display only published courses.
db.courseDemo.find({ published: true });
// Count the documents matching a filter.
db.courseDemo.countDocuments({ published: true });learning database, inserts two documents, reads the collection, filters published courses, and counts matching documents. The shell's use command is a shell helper. The database is persisted when data is written or a collection is created. countDocuments() counts documents matching the specified filter.- Use
mongoshto connect to a MongoDB deployment. - The
useshell command changes the current database context. - MongoDB can create a collection when the first document is inserted.
find()reads documents and accepts a filter.countDocuments()counts documents matching a filter.
What does `db.courseDemo.find({ published: true })` do?
Practical Lab: Build Your First Learning Database
This lab combines the concepts from the chapter into a small learning-platform dataset. Run the commands in mongosh against a development database.
Step 1: Select the practice database
use mongodb_course_lab
Step 2: Insert sample courses
db.courses.insertMany([
{
slug: "mongodb-basics",
title: "MongoDB Basics",
category: "database",
level: "beginner",
durationMinutes: 120,
published: true,
tags: ["mongodb", "nosql", "backend"],
instructor: {
name: "Kavitha",
country: "India"
},
createdAt: ISODate("2026-10-01T09:00:00Z")
},
{
slug: "mongodb-querying",
title: "MongoDB Querying in Depth",
category: "database",
level: "intermediate",
durationMinutes: 240,
published: true,
tags: ["mongodb", "queries", "backend"],
instructor: {
name: "Arun",
country: "India"
},
createdAt: ISODate("2026-10-05T09:00:00Z")
},
{
slug: "react-foundations",
title: "React Foundations",
category: "frontend",
level: "beginner",
durationMinutes: 180,
published: false,
tags: ["react", "javascript", "frontend"],
instructor: {
name: "Meera",
country: "India"
},
createdAt: ISODate("2026-10-08T09:00:00Z")
},
{
slug: "mongodb-data-modeling",
title: "MongoDB Data Modeling",
category: "database",
level: "advanced",
durationMinutes: 360,
published: true,
tags: ["mongodb", "schema-design", "architecture"],
instructor: {
name: "Kavitha",
country: "India"
},
createdAt: ISODate("2026-10-12T09:00:00Z")
}
]);
Step 3: Inspect the inserted records
db.courses.find();
Observe the _id values generated by MongoDB. Inspect the arrays, nested instructor documents, dates, and scalar fields.
Step 4: Filter by category
db.courses.find({ category: "database" });
This query returns the database courses. It does not require every document in the collection to belong to that category.
Step 5: Query a nested field
db.courses.find({ "instructor.name": "Kavitha" });
The query uses dot notation to select courses taught by Kavitha.
Step 6: Filter by multiple conditions
db.courses.find({
category: "database",
published: true
});
Multiple fields in a standard query filter are combined using logical AND. A document must satisfy both conditions to match.
Step 7: Return selected fields
db.courses.find(
{ published: true },
{ _id: 0, title: 1, level: 1, durationMinutes: 1 }
);
The first argument specifies which documents to match. The second argument specifies which fields to return. This projection excludes _id and includes the three requested fields.
Step 8: Count published courses
db.courses.countDocuments({ published: true });
With the supplied data, this should return 3.
Step 9: Inspect a date range
db.courses.find({
createdAt: {
$gte: ISODate("2026-10-05T00:00:00Z"),
$lt: ISODate("2026-10-13T00:00:00Z")
}
});
This query uses an inclusive lower bound and an exclusive upper bound. It returns documents created on or after October 5 and before October 13, 2026, according to the stored UTC dates.
Step 10: Clean up when finished
If this is a disposable practice database and you want to remove the lab collection, run:
db.courses.drop();
This deletes the collection and its documents. Do not run destructive commands against a production collection.
Lab challenges
- Find every course whose level is
beginner. - Find published courses taught by Arun.
- Return only
slugandtitlefor frontend courses. - Count all courses in the
databasecategory. - Find courses whose tags contain
backend. - Find courses created after October 5, 2026.
- Explain why
instructor.nameis a nested field path rather than a separate top-level field. - Describe one reason you might keep enrollments in a separate collection rather than embedding an unbounded enrollment history inside each course.
// 1. Beginner courses
db.courses.find({ level: "beginner" });
// 2. Published courses taught by Arun
db.courses.find({
published: true,
"instructor.name": "Arun"
});
// 3. Slug and title for frontend courses
db.courses.find(
{ category: "frontend" },
{ _id: 0, slug: 1, title: 1 }
);
// 4. Count database courses
db.courses.countDocuments({ category: "database" });
// 5. Courses whose tags contain backend
db.courses.find({ tags: "backend" });
// 6. Courses created after October 5, 2026
db.courses.find({
createdAt: { $gt: ISODate("2026-10-05T00:00:00Z") }
});{ tags: "backend" } matches documents whose tags array contains that value. The date example uses a BSON Date boundary rather than comparing strings.- A single collection can contain documents with nested fields and arrays.
- Multiple ordinary filter fields are combined using AND.
- Projection controls which fields are returned.
- Array fields can be queried by matching an element.
- BSON Date values support chronological range filtering.
- Destructive collection operations should be restricted to appropriate development environments.
Given the lab dataset, how many courses match `{ category: "database", published: true }`?