MongoDB
MongoDB is a NoSQL, document-oriented database that stores
data in a flexible, JSON-like format called BSON (Binary JSON).
Unlike traditional SQL databases (like MySQL or PostgreSQL),
MongoDB does not use tables and rows, but instead uses
collections and documents.
Why Use MongoDB?
Schema-less: No need to define strict schemas—documents can
vary.
Scalable: Built to handle large amounts of unstructured data
across multiple machines.
Flexible: Great for hierarchical/nested data like arrays and sub-
documents.
Powerful Queries: Supports filtering, projections, aggregations,
and indexing.
High Performance: Designed for speed and scalability.
MongoDB’s structure:
MongoDB uses a document-oriented data model that is highly
flexible and scalable.
1. Database
A database is the top-level container in MongoDB.
Each database holds a set of collections.
MongoDB can host multiple databases.
Example: use myDatabase
2. Collection
A collection is like a table in relational databases.
It stores documents.
Collections do not enforce a schema, meaning documents can
have different fields.
Example: db.students
3. Document
A document is the basic unit of data in MongoDB.
It’s stored in BSON format (Binary JSON), but appears like
JSON.
Documents are schema-less and can have nested fields (arrays,
sub-documents).
2
MongoDB: Creating Databases and Collections Using the Shell
MongoDB is a NoSQL document database that stores data in
flexible, JSON-like documents. It doesn’t require a fixed schema,
making it ideal for dynamic and rapidly changing data.
1. Starting the MongoDB Shell
To begin working with MongoDB, you need to start the MongoDB
shell.
Bash-mongosh on command prompt
This connects your terminal to the MongoDB server.
You can now run MongoDB commands interactively.
2. Creating or Switching a Database
MongoDB does not require you to create a database explicitly.
Instead, you switch to a database using:
use myDatabase
If 'myDatabase' exists, MongoDB switches to it.
If it does not exist, MongoDB will prepare to create it. However,
the database is only actually created after a document is
inserted.
To check which database you're currently using:
db
This command returns the name of the currently selected
database.
To list all existing databases:
show dbs
Note: Newly created databases won’t appear in 'show dbs' until
at least one document is inserted into them.
3
3. Creating Collections
A collection in MongoDB is similar to a table in relational
databases, but without a rigid schema.
Method 1: Automatic Collection Creation (Recommended for
Simplicity)
You can create a collection automatically by inserting a
document into it:
db.students.insertOne({ name: "Ravi", age: 21, course: "CS"
})
If the 'students' collection does not exist, it will be created.
The document will be inserted as the first entry in that collection.
Method 2: Manual Collection Creation (Advanced Use)
You can explicitly create a collection using:
db.createCollection("students")
This method is useful when:
- You want to pre-define options (e.g., capped collections)
- You want to apply validation rules or storage settings during
creation.
4. Viewing Collections
To list all collections in the current database:
show collections
Or:
db.getCollectionNames()
4
These commands return the names of all existing collections
under the currently selected database.
5. Deleting Collections
To remove a collection and all its documents:
db.collectionName.drop()
Example:
db.students.drop()
This command permanently deletes the 'students' collection and
its data.
Note:
o Collections Are Schema-less by Default
o You can store documents with different fields inside the
same collection. This flexibility is one of MongoDB’s key
strengths.
o A Database Doesn’t Truly Exist Until It Has Data
o Just switching with 'use myDB' doesn’t create the database
until a collection is populated.
o Use 'createCollection()' Only When You Need Special
Options, such as:
- Capped collections (fixed-size, auto-deleting old
entries)
- Validation rules
- Storage engines or specific indexes
5
MongoDB: Inserting Documents into a Collection
1. Connecting to the Database
To work with a specific database, switch to it using:
use myDatabase
Replace 'myDatabase' with your actual database name.
2. Inserting a Single Document using insert()
You can insert a single document into a collection like this:
db.users.insert({
name: "Ali",
age: 30,
email: "
[email protected]"
});
- If the 'users' collection does not exist, it will be created
automatically.
- MongoDB auto-generates a unique '_id' field for each
document if not manually specified.
3. Inserting Multiple Documents using insert()
To insert an array of documents in one go:
db.users.insert([
{ name: "Aisha", age: 25 },
{ name: "Bilal", age: 28 }
]);
- This method is efficient for batch insertions.
- Each document will be inserted with a unique '_id'.
4. Using insertOne() for Single Insert
This is the modern and recommended way to insert a single
document:
6
db.users.insertOne({ name: "Zara", age: 22 });
- Returns a confirmation object containing:
- Acknowledgement of insertion
- The auto-generated '_id'
5. Using insertMany() for Bulk Insert
To insert multiple documents at once using insertMany():
db.users.insertMany([
{ name: "Omar", age: 35 },
{ name: "Sara", age: 29 }
]);
- Returns a bulk result object containing:
- Status of insertion
- An array of inserted '_id' values
Note:
- Use the method that best fits your use case:
- insertOne() → For inserting a single document
- insertMany() → For inserting multiple documents
- insert() → Legacy method; flexible but less preferred in modern
code
- MongoDB will auto-generate '_id' fields unless explicitly provided.
- If the collection doesn’t exist, it will be created automatically when
inserting a document.
7
MongoDB: Core Data Types Guide
This guide covers core MongoDB data types using examples in the
mongo shell (mongosh).
1. BSON & Data Types Overview
o MongoDB stores data in BSON (Binary JSON), a binary-
encoded serialization of JSON-like documents.
o Each field stores its type information (e.g., String, Number,
Boolean) along with the name and value.
2. String
Strings are used to store text values. Example:
db.products.insertOne({ name: "Laptop", category:
"Electronics" })
Strings are used frequently in queries, filtering, and sorting.
3. Number (int, double, decimal)
o MongoDB distinguishes between integers, floating points,
and high-precision decimals:
o - NumberInt() → 32-bit integer
- NumberDouble() → 64-bit floating-point
- NumberDecimal() → 128-bit decimal
o Use the correct type for arithmetic operations and
precision-sensitive fields.
4. Boolean
Boolean values represent true/false. Example:
db.tasks.insertOne({ title: "Cleanup", done: false })
8
5. Date
Dates are stored using ISODate(). Useful for timestamps and
queries using date filters.
What is ISODate()?
ISODate() is a helper function in the MongoDB shell that creates a
date object in ISO 8601 format (e.g., 2025-06-11T13:45:00Z).
It is stored as a BSON Date type, which internally represents the
number of milliseconds since the Unix epoch (1970-01-
01T00:00:00Z).
MongoDB stores all dates in UTC format.
When displaying or querying, the Mongo shell may adjust times to the
local timezone.
To avoid timezone issues, always format your ISO strings with the Z
suffix or use UTC methods in your application.
Creating Dates
There are multiple ways to create date values in MongoDB shell:
o Current date and time
new Date()
o ISODate with a specific time
ISODate("2024-12-25T00:00:00Z")
o Using JavaScript Date constructor (less precise than ISODate)
new Date("December 25, 2024")
9
6. Null
A field with a null value is different from a missing field. Example
query:
db.users.find({ middleName: null })
7. Array
Arrays store lists of values inside a document. Example:
db.orders.insertOne({ items: ["pen", "notebook", "eraser"] })
MongoDB supports queries on array elements.
8. Embedded Documents
Documents can contain other nested documents. Example:
db.contacts.insertOne({ name: "Sara", address: { city:
"Karachi", zip: 75500 } })
Access nested fields using dot notation (e.g., address.city).
9. ObjectId
By default, MongoDB assigns a 12-byte ObjectId to the _id field
of each document.
Structure includes timestamp, machine id, process id, and
counter.
Example query: db.posts.find({ _id: ObjectId("...") })
10. Other Special Types
- BinData() → Binary data
10
- Timestamp() → Internal replication timestamp
- MinKey and MaxKey → Special scalars used in range queries
Key Takeaways
- MongoDB supports a wide range of data types: text, numbers,
booleans, dates, arrays, nested documents, and more.
- Correct data types impact storage, querying, indexing, and
schema design.
- Use type wrappers when necessary: NumberInt(), ISODate(),
ObjectId(), etc.
- Understanding data types helps in writing efficient and
accurate MongoDB queries.
JSON Schema Validation in MongoDB
🔹 Definition
JSON Schema Validation is a feature in MongoDB that allows
you to enforce rules on the structure and content of documents
inserted or updated in a collection. It uses a JSON Schema–like
syntax to define:
Required fields
Data types (bsonType)
Value constraints (like min/max, patterns, etc.)
11
Why is JSON Schema Validation Important?
Benefit Description
Ensures every document follows the
✅ Data Consistency
expected structure.
Prevents accidental insertion of invalid,
✅ Error Prevention
incomplete, or malformed data.
✅ Improves Data Makes it easier to maintain clean,
Quality queryable datasets.
✅ Supports Backend Avoids relying only on application-side
Validation checks.
Offers detailed field-level constraints for
✅ Custom Rules
business logic enforcement.
How to Use JSON Schema Validation:
MongoDB supports schema validation via the validator option in
collection creation or with the collMod command for existing
collections.
1. While Creating a New Collection
db.createCollection("Students", {
validator: {
$jsonSchema: {
bsonType: "object",
title:”Student Object validation”
required: ["name", "age", "course"],
properties: {
name: {
bsonType: "string",
12
description: "must be a string and is required"
},
age: {
bsonType: "int",
minimum: 0,
maximum: 120,
description: "must be an integer in [0, 120]"
},
couse: {
bsonType: "string",
enum:[“BCA”,”Btech”,”MCA”]
description: "can only be BCA or Btech or MCA"
}
}
}
},
validationLevel: "moderate", // optional
validationAction: "error" // optional
})
validator: validator object defines rules the documents in this
collection must follow.
$jsonSchema: $jsonSchema is a keyword that tells MongoDB to
interpret the validator using schema definitions.
bsonType: bsonType is a keyword used in MongoDB's JSON
Schema validation to specify the data type of a field in a
document. MongoDB stores data in BSON (Binary JSON)
13
format internally, so bsonType refers to BSON-native data
types, not just plain JSON types.
required: Any document missing even one of these fields will be
rejected.
properties: Begins the detailed definition for each field.
If Collection is Already Created
Use the collMod command to modify an existing collection and add
schema validation:
db.runCommand({
collMod: "yourCollection",
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "age", "email"],
properties: {
name: { bsonType: "string" },
age: { bsonType: "int", minimum: 0, maximum: 120 },
email: { bsonType: "string", pattern: "^.+@.+$" }
}
}
},
validationLevel: "strict",
validationAction: "error"
})
Update & Replace Documents in MongoDB:
14
updateOne():
Updates only the first document that matches the filter condition.
Useful when you are sure there's only one match, or you want to
modify just one.
Syntax-db.collection.updateOne(
{ filter },
{ updateOperation }
);
Example-db.students.updateOne(
{ name: "Ali" },
{ $set: { age: 23 } }
);
updateMany():
Updates all documents that match the given filter.
Useful when a change must be applied across multiple records.
Syntax-db.collection.updateMany(
{ filter },
{ updateOperation }
);
Example-db.students.updateMany(
{ enrolled: true },
{ $set: { active: false } }
);
Update Operators
$set
15
Adds a new field or updates an existing one.
Example: { $set: { age: 25 } }
$unset
Removes a field from the document.
Example: { $unset: { age: "" } }
$inc
Increments or decrements a numeric field.
Example: { $inc: { views: 1 } } or { $inc: { quantity: -1 } }
$rename
Renames a field.
Example: { $rename: { oldName: "newName" } }
$min / $max
$min: updates the field only if the specified value is less than the
current value.
$max: updates only if the value is greater.
Example: { $min: { score: 50 } }
16