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:
[Link]()
• 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
[Link]() Drops the current database
How to Create, Show, and Delete Collections
1. Create a Collection
[Link]("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
[Link]()
• Deletes the specified collection from the current database
Operation Command
Create Collection [Link]("name")
Show Collections show collections
Drop Collection [Link]()
pg. 2
Insert Operations
1. Insert a Single Document
[Link]({ field1: value1, field2: value2 })
• Inserts one document into the specified collection.
2. Insert Multiple Documents
[Link]([
{ field1: value1, field2: value2 },
{ field1: value3, field2: value4 }
])
Inserts multiple documents at once into the collection.
Operation Command Format
Insert One Document [Link]({ ... })
Insert Many Documents [Link]([{ ... }, ...])
Update and Upsert Operations
1. Update One Document
[Link](
{ filter_condition },
{ $set: { field: new_value } }
)
• Updates the first matching document based on the filter.
2. Update Multiple Documents
[Link](
{ filter_condition },
{ $set: { field: new_value } }
)
• Updates all matching documents based on the filter.
3. Upsert Operation
[Link](
{ 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
[Link]({ filter_condition })
• Deletes the first document matching the filter criteria.
2. Delete Multiple Documents
[Link]({ filter_condition })
• Deletes all documents matching the filter criteria.
3. Delete All Documents
[Link]({})
• Deletes all documents in the collection (empty filter).
Operation Command Format
Delete One Document [Link]({ ... })
Delete Many Docs [Link]({ ... })
Delete All Docs [Link]({})
pg. 4
Find All Documents
[Link]()
• Retrieves all documents from the collection.
Find Documents with Filter
[Link]({ filter_condition })
• Retrieves documents matching the specified filter criteria.
Operation Command Format Description
Find All Documents [Link]() Get all documents in the collection
Find with Filter [Link]({ ... }) Get documents matching a filter
Example:
find() with Regex
Find Documents Where name Starts with "a"
[Link]({ name: /^a/ })
• ^a means starts with "a"
Find Documents Where name Ends with "a"
[Link]({ name: /a$/ })
• a$ means ends with "a"
Find Documents Where name Contains "a" Anywhere
[Link]({ name: /a/ })
• /a/ means "a" can be anywhere in the string
[Link]({ _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:
[Link]({ age: { $gt: 25 } })
• Finds documents where the age field is greater than 25.
Update Field Value to Null
[Link](
{ filter_condition },
{ $set: { fieldName: null } }
)
• Sets the value of fieldName to null in the matched document.
MongoDB – count(), limit(), sort(), skip()
1. Count Documents
[Link]({ filter_condition })
• Returns the number of documents matching the filter.
• If no filter is provided, counts all documents.
2. Limit Number of Documents Returned
[Link]().limit(n)
• Limits the result to n documents.
3. Sort Documents
[Link]().sort({ fieldName: 1 }) // Ascending order
[Link]().sort({ fieldName: -1 }) // Descending order
• Sorts documents by fieldName.
• Use 1 for ascending and -1 for descending.
4. Skip Documents
[Link]().skip(n)
pg. 6
• Skips the first n documents in the result set.
Operation Command Format Description
Count [Link]({ ... Count matching
}) documents
Limit [Link]().limit(n) Limit result to n
documents
Sort (Ascending) [Link]().sort({ field: 1 }) Sort ascending by field
Sort [Link]().sort({ field: -1 }) Sort descending by field
(Descending)
Skip [Link]().skip(n) Skip first n documents
MongoDB – Working with Arrays
1. Creating / Inserting Arrays
• To insert a document with an array field:
[Link]({
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:
[Link]({ hobbies: "gaming" })
• Finds documents where the hobbies array contains "gaming".
3. Updating Arrays
• Add an element to an array (without duplicates):
[Link](
{ 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):
[Link](
{ name: "John" },
{ $push: { hobbies: "swimming" } }
)
• Appends "swimming" to the hobbies array.
• Remove an element from an array:
[Link](
{ name: "John" },
{ $pull: { hobbies: "gaming" } }
)
• Removes "gaming" from the hobbies array.
4. Deleting Arrays
• To delete an entire array field from a document:
[Link](
{ 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
[Link]({ arrayField: { $size: n } })
• Finds documents where the array arrayField has exactly n elements.
Return First N Elements of an Array
[Link](
{ 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
[Link]({$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
[Link]({$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.
[Link]({$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
[Link]({$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
[Link]({$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
[Link]({$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([Link],[Link]);}
2. Reduce function
var reduce=function(key,values){return [Link](values);}
3. Execute the query
[Link](map,reduce,{out:"customer_totals",query:{acctype:"S"}});
Output:
DeprecationWarning: [Link]() is deprecated. Use an aggregation instead.
See [Link] 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
[Link]([
{ _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 = [Link]().split(" ");
[Link](function(word) {
emit(word, 1);
});
};
Step 4: Define Reduce Function
var reduceFunction = function(key, values) {
return [Link](values);
};
Step 5: Run MapReduce
[Link](
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
[Link]([
{ 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([Link], factorial([Link]));
};
Step 4: Define Reduce Function
var reduceFunction = function(key, values) {
return values[0]; // Only one value per key
};
Step 5: Run MapReduce
[Link](
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
[Link]([
{ 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
[Link]({ roll: 2 }).explain("executionStats")
Look for "stage": "COLLSCAN" in the output — this means a collection scan was done.
Step 3: Create Index
[Link]({ roll: 1 })
Step 4: Query With Index
pg. 14
[Link]({ 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 [Link]({ field: 1 })
View Indexes [Link]()
Force Use of Index [Link]().hint({ field: 1 })
Analyze Performance [Link]().explain("executionStats")
Drop Index [Link]({ 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