Create/Use a Database
use myDatabase
🔹 1. db
Returns the name of the currently selected (connected) database.
db
Example Output:
myDatabase
If you haven’t switched to any, it will default to test.
🔹 2. show dbs
Displays all the databases available in your MongoDB server.
show dbs
Example Output:
admin 0.000GB
config 0.000GB
local 0.000GB
myDatabase 0.001GB
Note: A database only shows here after at least one collection and one document is
added.
🔹 3. db.dropDatabase()
Deletes the current/selected database permanently.
use myDatabase // switch to the database first
db.dropDatabase()
Example Output:
{ "ok" : 1 }
Create a collection
db.createCollection("users")
Output:
{ ok: 1 }
What is CRUD?
CRUD is the set of four basic operations you can perform on a database:
C – Create: Add new data (insert a document)
R – Read: View or retrieve data (query documents)
U – Update: Change existing data (modify documents)
D – Delete: Remove data (delete documents)
In MongoDB, data is stored in:
Database → Collection → Documents (JSON-like objects)
Step 1: Open MongoDB shell
mongosh
Step 2: Use or create a database
use myDatabase
🔹 1. CREATE — Insert Data
➤ Insert One Document
db.users.insertOne({
name: "Viral",
email: "
[email protected]",
age: 25
})
➤ Insert Many Documents
db.users.insertMany([
{ name: "Ravi", email: "
[email protected]", age: 30 },
{ name: "Neha", email: "
[email protected]", age: 22 },
{ name: "Rina", email: "
[email protected]", age: 28 }
])
✅ insertOne() adds a single document.
✅ insertMany() adds multiple documents at once.
🔹 2. READ — Retrieve Data
➤ Find All Documents
db.users.find()
➤ Find Specific Document
db.users.find({ name: "Ravi" })
➤ Find With Condition
db.users.find({ age: { $gt: 25 } }) // users with age > 25
➤ Find One (Returns First Match Only)
db.users.findOne({ name: "Neha" })
➤ Pretty Print
db.users.find().pretty()
✅ find() returns a cursor to all matching documents.
✅ findOne() returns only the first match.
🔹 3. UPDATE — Modify Data
➤ Update One Document
db.users.updateOne(
{ name: "Viral" }, // filter
{ $set: { age: 26 } } // update
)
➤ Update Multiple Documents
db.users.updateMany(
{ age: { $lt: 25 } }, // users younger than 25
{ $set: { status: "young" } }
)
✅ $set operator is used to change or add fields.
✅ Other operators include $inc, $rename, $unset, etc.
🔹 4. DELETE — Remove Data
➤ Delete One Document
db.users.deleteOne({ name: "Ravi" })
➤ Delete Multiple Documents
db.users.deleteMany({ age: { $gt: 27 } })
deleteOne() removes the first matching document.
deleteMany() removes all matching documents.
Show current DB:
db
Show all collections in the current DB:
show collections
Drop a collection:
db.users.drop()
Drop the whole database:
db.dropDatabase()
LOGICAL OPERATOR
use school
db.students.insertMany([
{ name: "Alice", age: 17, marks: 85, city: "New York" },
{ name: "Bob", age: 18, marks: 70, city: "Los Angeles" },
{ name: "Charlie", age: 16, marks: 60, city: "Chicago" },
{ name: "David", age: 19, marks: 40, city: "New York" },
{ name: "Eva", age: 18, marks: 35, city: "Houston" }
])
$eq — Equal to
db.students.find({ age: { $eq: 18 } })
$gt — Greater than
db.students.find({ marks: { $gt: 60 } })
$gte — Greater than or equal to
db.students.find({ age: { $gte: 18 } })
$in — Value in list
db.students.find({ city: { $in: ["New York", "Chicago"] } })
$lt — Less than
db.students.find({ marks: { $lt: 50 } })
Operator Query Example Result
$eq { age: { $eq: 18 } } Bob, Eva
$gt { marks: { $gt: 60 } } Alice, Bob
$gte { age: { $gte: 18 } } Bob, David, Eva
$in { city: { $in: ["New York", "Chicago"] } } Alice, David, Charlie
$lt { marks: { $lt: 50 } } David, Eva
Create Database and Collection
use school
db.students.insertMany([
{ name: "Alice", age: 17, marks: 85, city: "New York" },
{ name: "Bob", age: 18, marks: 70, city: "Los Angeles" },
{ name: "Charlie", age: 16, marks: 60, city: "Chicago" },
{ name: "David", age: 19, marks: 40, city: "New York" },
{ name: "Eva", age: 18, marks: 35, city: "Houston" }
])
Logical Operators
1. $and — Logical AND
Returns documents that match all the specified conditions.
Syntax:
{ $and: [ { condition1 }, { condition2 } ] }
Example:
db.students.find({
$and: [
{ age: { $gte: 18 } },
{ marks: { $gt: 60 } }
]
})
Result: Bob (age: 18, marks: 70)
2. $or — Logical OR
Returns documents that match any of the conditions.
Syntax:
{ $or: [ { condition1 }, { condition2 } ] }
Example:
db.students.find({
$or: [
{ marks: { $lt: 40 } },
{ city: "Chicago" }
]
})
Result: Eva (marks 35), Charlie (city Chicago)
3. $not — Logical NOT
Inverts the result of a condition.
Syntax:
{ field: { $not: { condition } } }
Example:
db.students.find({
marks: { $not: { $gt: 60 } }
})
Result: Charlie (60), David (40), Eva (35)
Returns students whose marks are not greater than 60
4. $nor — Logical NOR
Returns documents that do not match any of the conditions.
Syntax:
{ $nor: [ { condition1 }, { condition2 } ] }
Example:
db.students.find({
$nor: [
{ marks: { $gt: 60 } },
{ city: "New York" }
]
})
Result: Charlie (60, Chicago), Eva (35, Houston)
Returns students whose marks are not >60 AND who are not from New York
1. $exists Operator
Purpose:
Matches documents that have (or do not have) a specified field.
Syntax:
{ field: { $exists: <boolean> } }
true: Selects documents that have the field (even if the value is null)
false: Selects documents that do not have the field
Example:
Suppose we have a collection users:
[
{ "name": "Alice", "email": "
[email protected]" },
{ "name": "Bob" },
{ "name": "Charlie", "email": null }
]
Query: Find users who have the email field:
db.users.find({ email: { $exists: true } })
Result:
[
{ "name": "Alice", "email": "
[email protected]" },
{ "name": "Charlie", "email": null }
]
Query: Find users who do not have the email field:
db.users.find({ email: { $exists: false } })
Result:
[
{ "name": "Bob" }
]
2. $type Operator
Purpose:
Matches documents where the field is of the specified BSON data type.
Syntax:
{ field: { $type: <type> } }
<type> can be either a string (e.g., "string", "number", "bool") or a BSON type number
(e.g., 2 for string, 16 for int).
Example:
Suppose the data collection contains:
[
{ "value": "123" },
{ "value": 123 },
{ "value": true }
]
Query: Find documents where value is a number:
db.data.find({ value: { $type: "number" } })
Result:
[
{ "value": 123 }
]
Query: Find documents where value is a string:
db.data.find({ value: { $type: "string" } })
Result:
[
{ "value": "123" }
]
We'll use the database sports and collection players.
Step 1: Create Database and Insert Sample Documents
use sports
db.players.insertMany([
{
name: "Alice",
games: [
{ game: "soccer", score: 4 },
{ game: "tennis", score: 8 },
{ game: "basketball", score: 7 }
],
joined: "2023-01-01",
lastLogin: "2025-06-01"
},
{
name: "Bob",
games: [
{ game: "soccer", score: 3 },
{ game: "tennis", score: 2 }
],
joined: "2022-07-01",
lastLogin: "2025-06-30"
}
])
Array Projection Operators
1. $ — Positional Operator
Returns the first matching element in the array (based on query filter).
Syntax:
db.collection.find({ "array.field": value }, { "array.$": 1 })
Example:
db.players.find(
{ "games.score": 8 },
{ name: 1, "games.$": 1 }
)
Explanation: Returns only the first game where score is 8 for matching players.
🔹 2. $elemMatch — Match Specific Conditions in Projection
Projects the first array element that matches the specified conditions.
Syntax:
db.collection.find({}, { arrayField: { $elemMatch: { condition } } })
Example:
db.players.find(
{},
{
name: 1,
games: { $elemMatch: { score: { $gt: 5 } } },
joined: 1
}
)
Explanation: For each player, shows only the first game where score > 5, plus their
name and joined date.
🔹 3. $slice — Limit Array Elements
Returns a specific number of elements from an array.
Syntax:
db.collection.find({}, { arrayField: { $slice: n } })
n = number → First n elements
[skip, limit] → Skip x, then return y elements
Examples:
👉 First 2 games:
db.players.find({}, { name: 1, games: { $slice: 2 } })
👉 Skip 1 game, show next 1:
db.players.find({}, { name: 1, games: { $slice: [1, 1] } })
use school
db.students.insertMany([
{ name: "Alice", age: 17, marks: 85, grade: "A", updatedOn: null },
{ name: "Bob", age: 18, marks: 70, grade: "B", updatedOn: null },
{ name: "Charlie", age: 16, marks: 60, grade: "C", updatedOn: null }
])
MongoDB Update Operators
$currentDate
Use: Sets a field to the current date or timestamp.
db.students.updateOne(
{ name: "Alice" },
{ $currentDate: { updatedOn: true } }
)
updatedOn is now set to the current date.
$inc
Use: Increments a numeric field by a value.
db.students.updateOne(
{ name: "Bob" },
{ $inc: { marks: 5 } }
)
Bob's marks increase from 70 to 75.
$min
Use: Updates the field only if the new value is smaller.
db.students.updateOne(
{ name: "Charlie" },
{ $min: { marks: 50 } }
)
Charlie's marks become 50 only if 50 is less than current marks.
$max
Use: Updates the field only if the new value is greater.
db.students.updateOne(
{ name: "Charlie" },
{ $max: { marks: 65 } }
)
Charlie’s marks are updated to 65 only if 65 is greater than current marks.
$mul
Use: Multiplies a numeric field by a given value.
db.students.updateOne(
{ name: "Bob" },
{ $mul: { marks: 1.1 } }
)
Bob's marks are multiplied by 1.1.
$rename
Use: Renames a field.
db.students.updateOne(
{ name: "Alice" },
{ $rename: { grade: "rank" } }
)
The grade field is renamed to rank.
$set
Use: Sets a new value or adds a field.
db.students.updateOne(
{ name: "Alice" },
{ $set: { grade: "A+", passed: true } }
)
Sets grade to A+ and adds passed: true.
$setOnInsert
Use: Sets a field only when a new document is inserted using upsert.
db.students.updateOne(
{ name: "David" },
{
$set: { age: 20 },
$setOnInsert: { marks: 90, grade: "A" }
},
{ upsert: true }
)
If David does not exist, a new document is created with all fields.
If David already exists, only age is updated (not marks or grade).
$unset
Use: Removes a field from the document.
db.students.updateOne(
{ name: "Bob" },
{ $unset: { updatedOn: "" } }
)
updatedOn field is removed from Bob's document.
Aggregation Commands:
use shop
db.orders.insertMany([
{ item: "pen", qty: 10, price: 5, category: "stationery" },
{ item: "pencil", qty: 20, price: 3, category: "stationery" },
{ item: "notebook", qty: 5, price: 50, category: "stationery" },
{ item: "eraser", qty: 15, price: 2, category: "stationery" },
{ item: "bag", qty: 2, price: 200, category: "bags" },
{ item: "bottle", qty: 3, price: 150, category: "utility" }
])
1. aggregate — Advanced Data Processing
Use: Perform complex operations like grouping, filtering, summarizing, etc.
➤ Example: Group by Category and Total Quantity
db.orders.aggregate([
{ $group: { _id: "$category", totalQty: { $sum: "$qty" } } }
])
Output:
[
{ "_id": "stationery", "totalQty": 50 },
{ "_id": "bags", "totalQty": 2 },
{ "_id": "utility", "totalQty": 3 }
]
➤ Example: Calculate total sale amount per item
db.orders.aggregate([
{ $project: { item: 1, totalSale: { $multiply: ["$qty", "$price"] } } }
])
2. count — Count Documents in a Collection
Use: Count number of matching documents.
➤ Example: Count total documents
db.orders.count()
Output: 6
➤ Example: Count only stationery items
db.orders.count({ category: "stationery" })
Output: 4
3. distinct — Get Unique Values of a Field
Use: Return all unique/distinct values for a given field.
➤ Example: Get distinct categories
db.orders.distinct("category")
Output:
["stationery", "bags", "utility"]
4. mapReduce — Custom Aggregation (for large datasets)
Use: Advanced aggregation with custom map and reduce logic.
➤ Example: Total quantity per category
db.orders.mapReduce(
function() { emit(this.category, this.qty); }, // map
function(key, values) { return Array.sum(values); }, // reduce
{ out: "category_totals" } // output collection
)
View Result:
db.category_totals.find()
Output:
{ "_id": "stationery", "value": 50 }
{ "_id": "bags", "value": 2 }
{ "_id": "utility", "value": 3 }
Basic Syntax:
db.collection.aggregate([
{ stage1 },
{ stage2 },
...
])
Aggregation Stages
Example: Total quantity per category
db.orders.aggregate([
{ $group: { _id: "$category", totalQty: { $sum: "$qty" } } }
])
Example: Filter, then project specific fields
db.orders.aggregate([
{ $match: { category: "stationery" } },
{ $project: { item: 1, qty: 1, _id: 0 } }
])
Example: Sort and limit
db.orders.aggregate([
{ $sort: { price: -1 } },
{ $limit: 3 }
])
Arithmetic expression operators
Sample Collection: sales
use business
db.sales.insertMany([
{ item: "pen", price: 10, quantity: 5 },
{ item: "notebook", price: 40, quantity: 2 },
{ item: "bag", price: 300, quantity: 1 },
{ item: "pencil", price: 5, quantity: 10 }
])
$add
Adds numbers or dates.
db.sales.aggregate([
{
$project: {
item: 1,
total: { $add: ["$price", "$quantity"] }
}
}
])
$subtract
Subtracts second value from first (number or date).
db.sales.aggregate([
{
$project: {
item: 1,
diff: { $subtract: ["$price", "$quantity"] }
}
}
])
$multiply
Multiplies numbers (used to compute total price).
db.sales.aggregate([
{
$project: {
item: 1,
totalAmount: { $multiply: ["$price", "$quantity"] }
}
}
])
$divide
Divides one number by another.
db.sales.aggregate([
{
$project: {
item: 1,
pricePerUnit: { $divide: ["$price", "$quantity"] }
}
}
])
$mod
Returns the remainder (modulus).
db.sales.aggregate([
{
$project: {
item: 1,
remainder: { $mod: ["$price", 7] }
}
}
])
$abs
Returns absolute (positive) value.
db.sales.aggregate([
{
$project: {
item: 1,
absValue: { $abs: { $subtract: ["$price", "$quantity"] } }
}
}
])
$ceil / $floor
Rounding up/down to nearest integer.
db.sales.aggregate([
{
$project: {
item: 1,
ceilPrice: { $ceil: "$price" },
floorPrice: { $floor: "$price" }
}
}
])
$round / $trunc
Round or truncate decimals.
db.sales.aggregate([
{
$project: {
item: 1,
rounded: { $round: ["$price", 0] }, // rounds to nearest integer
truncated: { $trunc: ["$price", 0] } // drops decimal
}
}
])
$sqrt / $pow / $exp
Mathematical power, root, exponential.
db.sales.aggregate([
{
$project: {
item: 1,
sqrtPrice: { $sqrt: "$price" },
priceSquared: { $pow: ["$price", 2] },
expValue: { $exp: "$price" }
}
}
])
$ln, $log, $log10
Logarithmic functions.
db.sales.aggregate([
{
$project: {
item: 1,
naturalLog: { $ln: "$price" },
log10: { $log10: "$price" },
logBase2: { $log: [ "$price", 2 ] }
}
}
])