Data Types Supported by MongoDB
String
Integer-
Boolean
Double
Max/Min Keys
Arrays
TimeStamp
Null
Date
ObjectID
Binary Data
Code
Regular Expressions
MongoDB Query Language
1. Create a Database
• Use the use command to create or switch to a database.
• MongoDB creates the database only when a collection is added
use myDatabase
• This command selects the database myDatabase.
• If it doesn't exist, it will be created after data is added.
2. Drop a Database
• Use the following command to drop/delete the currently selected database:
db.dropDatabase()
• This command permanently deletes the database, including all collections and
documents inside it.
pg. 1
Supporting Commands
Command Description
use dbName Switches to or prepares to create a database
show dbs Lists all existing databases
Db Shows the name of the current database
db.dropDatabase() Drops the current database
How to Create, Show, and Delete Collections
1. Create a Collection
db.createCollection("collectionName")
• Creates a new collection in the current database.
2. Show Collections
show collections
• Displays all collections in the current database.
3. Drop a Collection
db.collectionName.drop()
• Deletes the specified collection from the current database
Operation Command
Create Collection db.createCollection("name")
Show Collections show collections
Drop Collection db.collectionName.drop()
pg. 2
Insert Operations
1. Insert a Single Document
db.collectionName.insertOne({ field1: value1, field2: value2 })
• Inserts one document into the specified collection.
2. Insert Multiple Documents
db.collectionName.insertMany([
{ field1: value1, field2: value2 },
{ field1: value3, field2: value4 }
])
Inserts multiple documents at once into the collection.
Operation Command Format
Insert One Document db.collectionName.insertOne({ ... })
Insert Many Documents db.collectionName.insertMany([{ ... }, ...])
Update and Upsert Operations
1. Update One Document
db.collectionName.updateOne(
{ filter_condition },
{ $set: { field: new_value } }
)
• Updates the first matching document based on the filter.
2. Update Multiple Documents
db.collectionName.updateMany(
{ filter_condition },
{ $set: { field: new_value } }
)
• Updates all matching documents based on the filter.
3. Upsert Operation
db.collectionName.updateOne(
{ filter_condition },
pg. 3
{ $set: { field: value } },
{ upsert: true }
)
• Upsert = Update + Insert
Operation Command Format
Update One updateOne({ filter }, { $set: { ... } })
Update Many updateMany({ filter }, { $set: { ... } })
Condition upsert: true upsert: false (default)
Matching document
Document is updated Document is updated
exists
Matching document A new document is inserted
No action is performed
does NOT exist using filter + update values
Delete Operations
1. Delete One Document
db.collectionName.deleteOne({ filter_condition })
• Deletes the first document matching the filter criteria.
2. Delete Multiple Documents
db.collectionName.deleteMany({ filter_condition })
• Deletes all documents matching the filter criteria.
3. Delete All Documents
db.collectionName.deleteMany({})
• Deletes all documents in the collection (empty filter).
Operation Command Format
Delete One Document db.collectionName.deleteOne({ ... })
Delete Many Docs db.collectionName.deleteMany({ ... })
Delete All Docs db.collectionName.deleteMany({})
pg. 4
Find All Documents
db.collectionName.find()
• Retrieves all documents from the collection.
Find Documents with Filter
db.collectionName.find({ filter_condition })
• Retrieves documents matching the specified filter criteria.
Operation Command Format Description
Find All Documents db.collectionName.find() Get all documents in the collection
Find with Filter db.collectionName.find({ ... }) Get documents matching a filter
Example:
find() with Regex
Find Documents Where name Starts with "a"
db.collectionName.find({ name: /^a/ })
• ^a means starts with "a"
Find Documents Where name Ends with "a"
db.collectionName.find({ name: /a$/ })
• a$ means ends with "a"
Find Documents Where name Contains "a" Anywhere
db.collectionName.find({ name: /a/ })
• /a/ means "a" can be anywhere in the string
db.collectionName.find({ _id: ObjectId("60d5f4832f8fb814b56fa181") })
• Finds the document with the specified _id.
Relational Operators with find()
MongoDB supports various relational operators to filter documents based on comparison
conditions inside the find() method.
Operator Syntax Description
$eq { field: { $eq: value } } Equal to value
$ne { field: { $ne: value } } Not equal to value
pg. 5
$gt { field: { $gt: value } } Greater than value
$gte { field: { $gte: value } } Greater than or equal to value
$lt { field: { $lt: value } } Less than value
$lte { field: { $lte: value } } Less than or equal to value
Example Usage:
db.collectionName.find({ age: { $gt: 25 } })
• Finds documents where the age field is greater than 25.
Update Field Value to Null
db.collectionName.updateOne(
{ filter_condition },
{ $set: { fieldName: null } }
)
• Sets the value of fieldName to null in the matched document.
MongoDB – count(), limit(), sort(), skip()
1. Count Documents
db.collectionName.countDocuments({ filter_condition })
• Returns the number of documents matching the filter.
• If no filter is provided, counts all documents.
2. Limit Number of Documents Returned
db.collectionName.find().limit(n)
• Limits the result to n documents.
3. Sort Documents
db.collectionName.find().sort({ fieldName: 1 }) // Ascending order
db.collectionName.find().sort({ fieldName: -1 }) // Descending order
• Sorts documents by fieldName.
• Use 1 for ascending and -1 for descending.
4. Skip Documents
db.collectionName.find().skip(n)
pg. 6
• Skips the first n documents in the result set.
Operation Command Format Description
Count db.collectionName.countDocuments({ ... Count matching
}) documents
Limit db.collectionName.find().limit(n) Limit result to n
documents
Sort (Ascending) db.collectionName.find().sort({ field: 1 }) Sort ascending by field
Sort db.collectionName.find().sort({ field: -1 }) Sort descending by field
(Descending)
Skip db.collectionName.find().skip(n) Skip first n documents
MongoDB – Working with Arrays
1. Creating / Inserting Arrays
• To insert a document with an array field:
db.collectionName.insertOne({
name: "John",
hobbies: ["reading", "gaming", "coding"]
})
• The field hobbies is an array of strings.
2. Finding Documents with Array Fields
• Find documents where an array contains a specific value:
db.collectionName.find({ hobbies: "gaming" })
• Finds documents where the hobbies array contains "gaming".
3. Updating Arrays
• Add an element to an array (without duplicates):
db.collectionName.updateOne(
{ name: "John" },
{ $addToSet: { hobbies: "traveling" } }
)
pg. 7
• Adds "traveling" to hobbies only if it doesn’t already exist.
• Push (append) an element to an array (allow duplicates):
db.collectionName.updateOne(
{ name: "John" },
{ $push: { hobbies: "swimming" } }
)
• Appends "swimming" to the hobbies array.
• Remove an element from an array:
db.collectionName.updateOne(
{ name: "John" },
{ $pull: { hobbies: "gaming" } }
)
• Removes "gaming" from the hobbies array.
4. Deleting Arrays
• To delete an entire array field from a document:
db.collectionName.updateOne(
{ name: "John" },
{ $unset: { hobbies: "" } }
)
• Removes the hobbies field completely from the document.
Operation Command Example Description
Insert array field during document
Insert Array insertOne({ hobbies: [ ... ] })
creation
Find documents containing a value
Find with Array Value find({ hobbies: "value" })
in the array
Add Element (No
$addToSet Add element if not already present
Duplicates)
pg. 8
Operation Command Example Description
Append Element $push Add element allowing duplicates
Remove Element $pull Remove specific element
Delete Entire Array $unset Remove the array field completely
Find Documents by Array Size
db.collectionName.find({ arrayField: { $size: n } })
• Finds documents where the array arrayField has exactly n elements.
Return First N Elements of an Array
db.collectionName.find(
{ filter_condition },
{ arrayField: { $slice: N } }
)
• Returns only the first N elements from the array field arrayField.
Aggregate Functions
1. Insert 4 Customer details
pg. 9
2. Finding the customer details in the document
3. To group on custid and compute the sum of accbal
db.customers.aggregate({$group:{_id:"$custid",totaccbal:{$sum:"$accbal"}}});
Output:
[ { _id: 'c111', totaccbal: 1200 }, { _id: 'c123', totaccbal: 2900 } ]
4. First filter on acctype:S and then group it on custid and then compute the sum of
accbal
db.customers.aggregate({$match:{acctype:"S"}},{$group:{_id:"$custid",totaccbal:{$sum:"$
accbal"}}});
Output:
[ { _id: 'c111', totaccbal: 1200 }, { _id: 'c123', totaccbal: 1400 } ]
5. First filter on acctype:S and then group it on custid and then compute the sum of
accbal and then filter the totaccbal is greater than 1200.
db.customers.aggregate({$match:{acctype:"S"}},{$group:{_id:"$custid",totaccbal:{$sum:"$
accbal"}}},{$match:{totaccbal:{$gt:1200}}});
Output:
[ { _id: 'c123', totaccbal: 1400 } ]
6. To group on custid and compute the average of accbal
pg. 10
db.customers.aggregate({$group:{_id:"$custid",totaccbal:{$avg:"$accbal"}}});
Output:
[
{ _id: 'c111', totaccbal: 1200 },
{ _id: 'c123', totaccbal: 966.6666666666666 }
]
7. To group on custid and compute the maximum of accbal
db.customers.aggregate({$group:{_id:"$custid",totaccbal:{$max:"$accbal"}}});
Output:
[ { _id: 'c111', totaccbal: 1200 }, { _id: 'c123', totaccbal: 1500 } ]
8. To group on custid and compute the minimum of accbal
db.customers.aggregate({$group:{_id:"$custid",totaccbal:{$min:"$accbal"}}});
Output:
[ { _id: 'c111', totaccbal: 1200 }, { _id: 'c123', totaccbal: 500 } ]
MapReduce Function(repeated)
1. Map function
var map=function(){emit(this.custid,this.accbal);}
2. Reduce function
var reduce=function(key,values){return array.sum(values);}
3. Execute the query
db.customers.mapReduce(map,reduce,{out:"customer_totals",query:{acctype:"S"}});
Output:
DeprecationWarning: Collection.mapReduce() is deprecated. Use an aggregation instead.
See https://docs.mongodb.com/manual/core/map-reduce for details.
{ result: 'customer_totals', ok: 1 }
Java Script Programming
function factorial(n){if(n===0) return 1; return n*factorial(n-1);} factorial(3)
Output: 6
function factorial(n){if(n===0) return 1; return n*factorial(n-1);} factorial(5)
Output: 120
pg. 11
MongoDB WordCount and JavaScript Examples
Part 1: WordCount Using MapReduce in MongoDB
Step 1: Use/Create a Database
use wordcountDB
Step 2: Insert Sample Documents
db.documents.insertMany([
{ _id: 1, text: "hello world hello" },
{ _id: 2, text: "hello mongo map reduce" },
{ _id: 3, text: "world of mongo" }
])
Step 3: Define Map Function
var mapFunction = function() {
var words = this.text.toLowerCase().split(" ");
words.forEach(function(word) {
emit(word, 1);
});
};
Step 4: Define Reduce Function
var reduceFunction = function(key, values) {
return Array.sum(values);
};
Step 5: Run MapReduce
db.documents.mapReduce(
mapFunction,
reduceFunction,
{
out: "word_counts"
}
pg. 12
)
Step 6: View Results
db.word_counts.find().pretty()
Part 2: JavaScript Factorial and MapReduce in MongoDB
Step 1: Use/Create a Database
use factorialDB
Step 2: Insert Numbers
db.nums.insertMany([
{ num: 3 },
{ num: 4 },
{ num: 5 },
{ num: 6 }
])
Step 3: Define Map Function with Factorial Logic
var mapFunction = function() {
function factorial(n) {
if (n === 0 || n === 1) return 1;
return n * factorial(n - 1);
}
emit(this.num, factorial(this.num));
};
Step 4: Define Reduce Function
var reduceFunction = function(key, values) {
return values[0]; // Only one value per key
};
Step 5: Run MapReduce
db.nums.mapReduce(
mapFunction,
reduceFunction,
pg. 13
{
out: "factorial_results"
}
)
Step 6: View Results
db.factorial_results.find().pretty()
Understanding Indexes in MongoDB
Analogy: Index in a Book
Imagine you're looking for the word "JavaScript" in a 1000-page book.
• Without an index: You read every page one by one.
• With an index: You check the index at the back of the book and go straight to the page.
MongoDB uses indexes the same way: to quickly find data without scanning every document.
MongoDB Example
Step 1: Insert Data
use indexDB
db.students.insertMany([
{ name: "Alice", roll: 1, marks: 87 },
{ name: "Bob", roll: 2, marks: 91 },
{ name: "Charlie", roll: 3, marks: 78 },
{ name: "David", roll: 4, marks: 85 },
{ name: "Eve", roll: 5, marks: 92 }
])
Step 2: Query Without Index
db.students.find({ roll: 2 }).explain("executionStats")
Look for "stage": "COLLSCAN" in the output — this means a collection scan was done.
Step 3: Create Index
db.students.createIndex({ roll: 1 })
Step 4: Query With Index
pg. 14
db.students.find({ roll: 2 }).hint({ roll: 1 }).explain("executionStats")
Now you should see "stage": "IXSCAN", meaning an index scan was used — faster and more
efficient!
Benefits of Indexes
Without Index With Index
Slower queries Faster queries
Scans all documents Jumps to the match
Higher CPU/memory usage Optimized performance
Bad for large datasets Scalable and efficient
When Should You Use Indexes?
• Fields frequently used in find() queries
• Fields used in sort()
• Fields used in range queries (>, <, etc.)
• Fields involved in lookup (joins)
Summary
Task Command Example
Create Index db.collection.createIndex({ field: 1 })
View Indexes db.collection.getIndexes()
Force Use of Index db.collection.find().hint({ field: 1 })
Analyze Performance db.collection.find().explain("executionStats")
Drop Index db.collection.dropIndex({ field: 1 })
Indexes are one of the most powerful ways to make your MongoDB queries fast and scalable.
Understanding and using them well is essential for working with large datasets.
pg. 15
pg. 16