Module-3
Introduction to Mongo DB
MongoDB
MongoDB is a document-oriented NoSQL database designed for storing, querying, and managing large volumes
of unstructured or semi-structured data.
Instead of storing data in rows and columns like traditional relational databases (RDBMS), MongoDB stores data in
JSON-like documents called BSON (Binary JSON).
Key Features:
• Schema-less (fields can vary from document to document).
• Horizontal scaling through sharding.
• Rich query language for filtering, aggregation, and indexing.
• High availability through replication.
6.1 WHAT IS MONGODB?
MongoDB is:
• Cross-platform.
• Open source.
• Non-relational.
• Distributed.
• NoSQL.
• Document-oriented data store.
6.2 WHY MONGODB?
Traditional RDBMS face challenges with:
• Handling large volumes of data.
• Managing a rich variety of data, especially unstructured data.
• Scaling to meet enterprise needs.
• MongoDB addresses these by:
• Scaling out or horizontally.
• Offering schema flexibility.
• Being fault-tolerant.
Prof. Deepika G, Dept. of CSE, SVIT Page 1
• Maintaining consistency and partition tolerance.
• Allowing easy distribution over many nodes in a cluster.
6.2.1 Using JavaScript Object Notation (JSON)
• JSON is highly expressive for data representation.
• MongoDB doesn’t directly use JSON; it uses BSON (Binary JSON).
• BSON is an open standard designed to store complex data structures.
Advantages of MongoDB (Figure 6.1)
1. Auto Sharding – Distributes data across multiple servers automatically for scalability.
2. Document Oriented – Stores data in flexible, JSON-like documents.
3. High Performance – Optimized for read and write operations.
4. Fast In-place Updates – Allows efficient updates without rewriting entire documents.
5. Replication – Ensures data redundancy and high availability.
6. High Availability – Continuous data access even during failures.
7. Easy Scalability – Simple to expand storage and processing capacity.
8. Rich Query Language – Supports expressive queries and aggregations.
9. Full Index Support – Indexing capabilities for faster data retrieval.
Prof. Deepika G, Dept. of CSE, SVIT Page 2
Example: How employee contact data can be represented in different formats — CSV, XML, and JSON — and
why JSON (and BSON) can be advantageous.
1. CSV Format
• Structure: Simple, flat table where each column is separated by commas, and each row is separated by a
carriage return.
• Problem:
o Can’t easily store multiple values for a single field (e.g., multiple contact numbers or email
addresses per employee).
o Different departments might store data differently, making merging files messy.
o Limited in handling complex, hierarchical, or repeating data.
2. XML Format
• Advantage: Highly extensible and good at representing structured and hierarchical data.
• Drawback: More complex to set up and work with, especially for simple data exchange.
• Use Case: Best for complex and highly structured datasets, but overkill for simple ones.
3. JSON Format
• Advantage:
o Readable and easy to store multiple values in arrays (e.g., multiple contact numbers).
o Flexible structure without the rigidity of CSV and without XML’s verbosity.
o No confusion in representing multiple fields of the same type.
• Example:
"FirstName": "John",
"LastName": "Mathews",
"ContactNo": ["+123 4567 8900", "+123 4444 5555"]
Prof. Deepika G, Dept. of CSE, SVIT Page 3
4. BSON
• Definition: Binary form of JSON, used in systems like MongoDB.
• Benefits:
o Consumes less space than text-based JSON.
o Faster to parse into native data structures.
o Supported by many programming languages through MongoDB drivers.
o Allows quick and efficient storage/retrieval of documents in a database.
Summary:
• CSV → Simple but flat, no repeating fields.
• XML → Powerful and extensible but verbose and complex.
• JSON → Flexible, readable, good for most use cases.
• BSON → Optimized binary JSON, great for database performance.
6.2.2 Creating or Generating a Unique Key
• Every JSON document should have a unique identifier: the _id key.
• _id is similar to a primary key in relational databases.
• Benefits:
o Facilitates quick document searches.
o Automatically indexed by MongoDB.
• You can either:
o Provide the _id value yourself.
o Let MongoDB auto-generate it.
Prof. Deepika G, Dept. of CSE, SVIT Page 4
• Auto-generated _id is a 12-byte value composed of:
1. Timestamp (first 4 bytes)
2. Machine ID (next 3 bytes)
3. Process ID (next 2 bytes)
4. Counter (last 3 bytes)
[Link] Database
• A collection of collections (like a container for them).
• Created when a collection is first referenced or on demand.
• Each database has its own files on the file system.
• One MongoDB server can store multiple databases.
[Link] Collection
• Analogy: Table in RDBMS.
• Created when a document is saved to it.
• Belongs to a single database.
• Holds multiple documents.
• No schema enforcement:
o Documents in the same collection can have different fields.
o Even with same fields, the order of fields can vary.
[Link] Document
• Analogy: Row/Record/Tuple in RDBMS.
• Has a dynamic schema:
o Fields can differ from document to document within a collection.
o Key-value pairs don’t need to be uniform across the collection.
6.2.3 Support for Dynamic Queries
• MongoDB supports dynamic queries, similar to traditional RDBMS where both static and dynamic
queries are possible.
Prof. Deepika G, Dept. of CSE, SVIT Page 5
• Dynamic queries: The ability to query data using conditions and filters at runtime without predefined
structures.
• CouchDB:
o Another document-oriented, schema-less NoSQL database.
o Takes the opposite approach: supports dynamic data but static queries.
Figure 6.2 Example
• Shows a collection named students containing 3 different documents.
Key Points from the Example
• Documents in the same collection don’t need identical fields or values.
• Some documents may omit certain fields entirely.
• Field ordering may differ.
• The flexibility of MongoDB’s schema-less design supports a variety of document structures while still
allowing dynamic, powerful queries.
6.2.4 Storing Binary Data
• MongoDB supports binary data storage through GridFS.
• Default limit: Up to 4 MB for a single piece of binary data.
o Suitable for small media files, e.g.:
▪ Profile pictures
Prof. Deepika G, Dept. of CSE, SVIT Page 6
▪ Small audio clips
• For larger files (e.g., movie clips), MongoDB uses a chunk-based storage method.
How GridFS Works
1. Metadata storage:
o Metadata (data about data) is stored in a collection named file.
o Metadata contains:
▪ File name
▪ File size
▪ Upload date
▪ Content type (e.g., image/jpeg, audio/mpeg)
2. Chunking process:
o File is split into small pieces called chunks.
o Chunks are stored in a separate chunks collection.
3. Scalability:
o Splitting into chunks makes it easier to store and retrieve large files efficiently.
o Supports streaming of files without loading the entire file into memory.
6.2.5 Replication
Why replication?
• Protects against:
o Hardware failures
o Service interruptions
• Ensures data redundancy and high availability.
How it works in MongoDB
• Uses a replica set:
o One primary node.
o Multiple secondary nodes.
• Write requests:
o Always sent to the primary.
o Primary logs write operations into the Oplog (operations log).
• Read requests:
o By default, directed to the primary.
o Can be configured (read preference) to read from secondaries.
Oplog Role
• Secondary nodes synchronize their data with the primary by replicating entries from the Oplog.
• This ensures consistency across the replica set.
Prof. Deepika G, Dept. of CSE, SVIT Page 7
Figure 6.3 – Replication
• Goal: Data redundancy and high availability.
• How it works:
1. The primary node handles all writes.
2. Secondary nodes replicate data from the primary using the Oplog.
3. Reads normally go to the primary but can be configured to read from secondaries.
• Benefit: Prevents data loss in case of node failure.
Prof. Deepika G, Dept. of CSE, SVIT Page 8
Figure 6.4 – Sharding
• Goal: Horizontal scaling of large datasets.
• How it works:
1. A large collection (e.g., 1 TB database) is split into smaller, manageable pieces called shards.
2. Example: 1 TB is divided into 4 shards of 256 GB each.
3. Together, these shards represent the logical database.
• Benefit: Distributes data across multiple servers, improving performance and storage capacity.
Key Difference
• Replication: Copies the same data to multiple servers for redundancy.
• Sharding: Splits different portions of data across servers for scalability.
6.2.7 Updating Information In-Place
Meaning: MongoDB updates the data directly where it is stored — no new space is allocated, and indexes
remain unchanged.
Lazy writes:
• MongoDB writes to disk about once per second (not immediately).
• This improves performance by reducing the number of disk operations.
Trade-off:
• Faster performance but no guarantee that the most recent data is safely stored if a crash occurs before the
next write to disk.
Performance benefit:
• Fewer disk reads/writes → faster operations (since reading/writing to memory is much faster than disk I/O).
Prof. Deepika G, Dept. of CSE, SVIT Page 9
6.3 Terms Used in RDBMS and MongoDB
RDBMS Term MongoDB Term Notes
Database Database Same term in both
Table Collection A collection stores multiple documents
Record Document Each document is like a row in a table
Columns Fields / Key-Value pairs Fields hold the actual data inside documents
Index Index Works similarly in both
Joins Embedded documents MongoDB stores related data inside the same document
Primary Key Primary key (_id is identifier) Every document has a unique _id field
Database Server & Client Examples
Feature MySQL Oracle MongoDB
Database Server mysqld oracle mongod
Database Client mysql SQL Plus mongo
6.3.1 Create Database
Syntax:
use DATABASE_Name
Prof. Deepika G, Dept. of CSE, SVIT Page 10
Example:
use myDB
Output:
switched to db myDB
• To check the current database:
db
Output:
myDB
• To list all databases:
show dbs
Example output:
admin (empty)
local 0.078GB
test 0.078GB
Note:
• A newly created database won’t appear in show dbs until it has at least one document.
• Default database in MongoDB is test.
•
6.3.2 Drop Database
Syntax:
[Link]();
Steps to drop myDB:
use myDB
[Link]();
Example output:
{ "dropped" : "myDB", "ok" : 1 }
Note:
• If no database is selected, dropping will remove the default test database.
Prof. Deepika G, Dept. of CSE, SVIT Page 11
6.4 Data Types in MongoDB
Data Type Description
String Must be UTF-8 valid. Most commonly used type.
Integer 32-bit or 64-bit depending on the server.
Boolean True/false values.
Double Floating-point (real) values.
Min/Max keys Compare a value against lowest/highest BSON elements.
Arrays Store arrays or multiple values in one key.
Timestamp Record when a document was modified or added.
Null NULL value (missing/unknown).
Date Current date/time in Unix format. Can store date objects.
Object ID Document’s unique ID.
Binary data Binary data like images, binaries, etc.
Code Store JavaScript code in the document.
Regular expression Store regular expressions.
Useful MongoDB Commands
1. Report current database:
db
Prof. Deepika G, Dept. of CSE, SVIT Page 12
Example output:
test
2. Display list of databases:
show dbs
Example output:
admin (empty)
local 0.078GB
myDB1 0.078GB
3. Switch to a new database:
use myDB1
Output:
switched to db myDB1
4. List collections in the current database:
show collections
Example output:
[Link]
[Link]
5. Display current MongoDB server version:
[Link]()
Prof. Deepika G, Dept. of CSE, SVIT Page 13
Operation SQL (RDBMS) MongoDB
INSERT INTO Students (StudRollNo,
[Link]({ _id: 1, StudRollNo: 'S101',
StudName, Grade, Hobbies, DOJ)
Insert StudName: 'Simon David', Grade: 'VII', Hobbies:
VALUES ('S101', 'Simon David', 'VII',
'Net Surfing', DOJ: '10-Oct-2012' });
'Net Surfing', '10-Oct-2012');
UPDATE Students SET Hobbies = 'Ice [Link]({ StudRollNo: 'S101' }, { $set:
Update (single)
Hockey' WHERE StudRollNo = 'S101'; { Hobbies: 'Ice Hockey' } });
Update UPDATE Students SET Hobbies = 'Ice [Link]({}, { $set: { Hobbies: 'Ice
(multiple) Hockey'; Hockey' } }, { multi: true });
DELETE FROM Students WHERE
Delete (single) [Link]({ StudRollNo: 'S101' });
StudRollNo = 'S101';
Delete (all) DELETE FROM Students; [Link]({});
Select all SELECT * FROM Students; [Link](); [Link]().pretty();
Select with SELECT * FROM Students WHERE
[Link]({ StudRollNo: 'S101' });
condition StudRollNo = 'S101';
Select specific SELECT StudRollNo, StudName, Hobbies [Link]({}, { StudRollNo: 1, StudName:
columns FROM Students; 1, Hobbies: 1, _id: 0 });
Select specific SELECT StudRollNo, StudName, Hobbies
[Link]({ StudRollNo: 'S101' }, {
columns with FROM Students WHERE StudRollNo =
StudRollNo: 1, StudName: 1, Hobbies: 1, _id: 0 });
condition 'S101';
SELECT StudRollNo, StudName, Hobbies [Link]({ Grade: 'VII', Hobbies: 'Ice
AND condition FROM Students WHERE Grade = 'VII' Hockey' }, { StudRollNo: 1, StudName: 1,
AND Hobbies = 'Ice Hockey'; Hobbies: 1, _id: 0 });
Prof. Deepika G, Dept. of CSE, SVIT Page 14
Operation SQL (RDBMS) MongoDB
SELECT StudRollNo, StudName, Hobbies [Link]({ $or: [ { Grade: 'VII' }, {
OR condition FROM Students WHERE Grade = 'VII' Hobbies: 'Ice Hockey' } ] }, { StudRollNo: 1,
OR Hobbies = 'Ice Hockey'; StudName: 1, Hobbies: 1, _id: 0 });
Pattern
SELECT * FROM Students WHERE
matching [Link]({ StudName: /^S/ }).pretty();
StudName LIKE 'S%';
(LIKE)
6.5 MONGODB QUERY LANGUAGE
CRUD Basics
• Create: Add new data with insert(), update(), or save().
• Read: Retrieve data with find().
• Update: Change data with update() (use upsert: false to avoid inserting new data).
• Delete: Remove data with remove().
Explanation Style in the Book
• Objective: What you want to do.
• Input: Data or situation to work with.
• Act: MongoDB command to run.
• Outcome: What happens after running it.
Example 1 – Creating a Collection
1. Check current collections → show collections (lists Students, food, [Link], [Link]).
2. Run → [Link]("Person").
3. Check collections again → "Person" is now in the list.
Example 2 – Dropping a Collection
1. Check current collections → shows "food".
2. Run → [Link]().
Prof. Deepika G, Dept. of CSE, SVIT Page 15
3. Check again → "food" is no longer in the list.
6.5.1. Insert Method
• Syntax:
[Link]({ field1: value1, field2: value2, ... })
• Example: Inserting a student record.
[Link]({_id:1, StudName:"Michelle Jacintha", Grade:"VII", Hobbies:"Internet Surfing"})
• Steps:
1. Check existing collections using show collections.
2. Create and insert document into Students collection.
3. Use .find() or .find().pretty() to view documents.
2. Inserting Multiple Documents
• Example:
[Link]({_id:2, StudName:"Mabel Mathews", Grade:"VII", Hobbies:"Baseball"})
• Outcome: Now the collection contains both students.
3. Update with Upsert
• Use case: Insert only if the document does not exist, else update it.
• Syntax:
[Link]({condition}, {$set:{field: value}}, {upsert:true})
• Example:
[Link]({_id:3}, { $set: { StudName:"Aryan David", Grade:"VII", Hobbies:"Skating" }}, {upsert:true})
o Changes Hobbies from Skating to Chess using:
[Link]({_id:3}, { $set: { Hobbies:"Chess" }}, {upsert:true})
Prof. Deepika G, Dept. of CSE, SVIT Page 16
4. Save Method
• Inserts a new document or replaces an existing one.
• Syntax:
[Link]({ field1: value1, field2: value2, ... })
• Example:
[Link]({ StudName:"Vamsi Bapat", Grade:"VI" })
Key Points:
• insert() → Adds a new document.
• update() with {upsert:true} → Updates existing or inserts if not found.
• save() → Inserts if no _id is given, else replaces the existing document.
• .find().pretty() → Nicely formats query results.
6.5.2 Save() Method
Save() Method and Upsert
• save() inserts a new document if _id doesn’t exist; replaces it if _id exists.
• update() with upsert flag works similarly:
o upsert:false → only updates existing documents (no insert if not found).
o upsert:true → updates if found, inserts if not found.
Example:
1. Check existing documents in Students.
2. Try inserting "Hersch Gibbs" with:
[Link]({_id:4}, {StudName:"Hersch Gibbs", Grade:"VII", $set:{Hobbies:"Graffiti"}}, {upsert:false})
o Result: No document added because _id:4 didn’t exist and upsert was false.
Prof. Deepika G, Dept. of CSE, SVIT Page 17
3. Try again with:
[Link]({_id:4}, {StudName:"Hersch Gibbs", Grade:"VII", $set:{Hobbies:"Graffiti"}}, {upsert:true})
o Result: Document inserted (nUpserted:1).
4. Confirm that "Hersch Gibbs" now exists in the collection.
6.5.3 Adding a New Field to an Existing Document (Update Method)
Goal: Add a new field "Location": "Newark" to the document with _id:4 in the Students collection.
Steps:
1. Check the document with _id:4 before the update:
[Link]({_id:4}).pretty()
Shows:
"_id": 4,
"Grade": "VII",
"StudName": "Hersch Gibbs",
"Hobbies": "Graffiti"
2. Update the document to add a new field:
[Link]({_id:4}, {$set: {Location:"Newark"}})
o $set adds the new "Location" field.
o The update result shows: Matched: 1, Modified: 1.
3. Verify the change:
Prof. Deepika G, Dept. of CSE, SVIT Page 18
[Link]({_id:4}).pretty()
Now includes:
"_id": 4,
"Grade": "VII",
"StudName": "Hersch Gibbs",
"Hobbies": "Graffiti",
"Location": "Newark"
6.5.4 Removing an Existing Field from a Document – Remove Method
Goal: Remove the "Location" field (with value "Newark") from the document where _id:4 in the Students
collection.
Steps:
1. Check document before removal
[Link]({_id:4}).pretty()
Shows "Location": "Newark" present.
2. Remove field
[Link]({_id:4}, {$unset: {Location:"Newark"}})
o $unset removes the specified field.
o Output shows: Matched: 1, Modified: 1.
3. Verify removal
[Link]({_id:4}).pretty()
"Location" field is gone.
Prof. Deepika G, Dept. of CSE, SVIT Page 19
6.5.5 Finding documents in MongoDB based on search criteria using the find method.
MongoDB find() Method Overview
Syntax:
[Link](
<selection_criteria>,
<projection>
).limit(<number>)
o Collection: Target collection (e.g., [Link])
o Selection Criteria: Filters documents (e.g., {Age: {$gt: 18}})
o Projection: Specifies fields to include/exclude (e.g., {RollNo:1, Age:1, _id:0})
o Cursor Modifier: Additional options like .limit() or .pretty()
Examples and SQL Equivalents
1. Find by Exact Match
o MongoDB:
o [Link]({StudName: "Aryan David"})
o SQL Equivalent:
o SELECT * FROM Students WHERE StudName LIKE 'Aryan David';
2. Display Only Specific Field
o MongoDB:
o [Link]({}, {StudName:1, _id:0})
o SQL:
o SELECT StudName FROM Students;
3. Display Multiple Fields Without _id
o MongoDB:
o [Link]({}, {StudName:1, Grade:1, _id:0})
o SQL:
o SELECT StudName, Grade FROM Students;
4. Find by _id and Show Specific Fields
o MongoDB:
o [Link]({_id:1}, {StudName:1, Grade:1})
o SQL:
o SELECT StudRollNo, StudName, Grade FROM Students WHERE StudRollNo = '1';
5. Find by _id Without Showing _id
o MongoDB:
o [Link]({_id:1}, {StudName:1, Grade:1, _id:0})
Using Relational Operators in Queries
• $eq → Equal to
• $ne → Not equal to
Prof. Deepika G, Dept. of CSE, SVIT Page 20
• $gte → Greater than or equal to
• $lte → Less than or equal to
• $gt → Greater than
• $lt → Less than
Examples Using Operators
6. Equal to
MongoDB:
[Link]({Grade: {$eq: 'VII'}}).pretty()
SQL:
SELECT * FROM Students WHERE Grade LIKE 'VII';
7. Not Equal to
MongoDB:
[Link]({Grade: {$ne: 'VII'}}).pretty()
SQL:
SELECT * FROM Students WHERE Grade <> 'VII';
8. Using $in
MongoDB:
[Link]({Hobbies: {$in: ['Chess','Skating']}}).pretty()
SQL:
SELECT * FROM Students WHERE Hobbies IN ('Chess','Skating');
9. Using $nin
MongoDB:
[Link]({Hobbies: {$nin: ['Chess','Skating']}}).pretty()
SQL:
SELECT * FROM Students WHERE Hobbies NOT IN ('Chess','Skating');
Using Logical Conditions
10. AND Condition
MongoDB:
[Link]({Hobbies: 'Graffiti', StudName: 'Hersch Gibbs'}).pretty()
SQL:
SELECT * FROM Students WHERE Hobbies LIKE 'Graffiti' AND StudName LIKE 'Hersch
Gibbs';
Using Regex in Queries
11. Starts with "M"
MongoDB:
[Link]({StudName: /^M/}).pretty()
SQL:
SELECT * FROM Students WHERE StudName LIKE 'M%';
12. Ends with "s"
MongoDB:
Prof. Deepika G, Dept. of CSE, SVIT Page 21
[Link]({StudName: /s$/}).pretty()
SQL:
SELECT * FROM Students WHERE StudName LIKE '%s';
13. Contains "e"
MongoDB:
[Link]({StudName: /e/}).pretty()
[Link]({StudName: /.e.*/}).pretty()
[Link]({StudName: {$regex: "e"}}).pretty()
o SQL:
SELECT * FROM Students WHERE StudName LIKE '%e%';
Purpose MongoDB Query SQL Equivalent
Find by exact [Link]({StudName: "Aryan SELECT * FROM Students WHERE StudName
match David"}) LIKE 'Aryan David';
Show only one
[Link]({}, {StudName:1, _id:0}) SELECT StudName FROM Students;
field (exclude _id)
Show multiple
[Link]({}, {StudName:1,
fields (exclude SELECT StudName, Grade FROM Students;
Grade:1, _id:0})
_id)
Find by _id with [Link]({_id:1}, {StudName:1, SELECT StudRollNo, StudName, Grade FROM
specific fields Grade:1}) Students WHERE StudRollNo = '1';
Find by _id
[Link]({_id:1}, {StudName:1, SELECT StudName, Grade FROM Students
without _id in
Grade:1, _id:0}) WHERE StudRollNo LIKE '1';
output
SELECT * FROM Students WHERE Grade
Equal to [Link]({Grade: {$eq: 'VII'}})
LIKE 'VII';
SELECT * FROM Students WHERE Grade <>
Not equal to [Link]({Grade: {$ne: 'VII'}})
'VII';
[Link]({Hobbies: {$in: SELECT * FROM Students WHERE Hobbies IN
In list
['Chess','Skating']}}) ('Chess','Skating');
[Link]({Hobbies: {$nin: SELECT * FROM Students WHERE Hobbies
Not in list
['Chess','Skating']}}) NOT IN ('Chess','Skating');
SELECT * FROM Students WHERE Hobbies
[Link]({Hobbies: 'Graffiti',
AND condition LIKE 'Graffiti' AND StudName LIKE 'Hersch
StudName: 'Hersch Gibbs'})
Gibbs';
SELECT * FROM Students WHERE StudName
Starts with “M” [Link]({StudName: /^M/})
LIKE 'M%';
SELECT * FROM Students WHERE StudName
Ends with “s” [Link]({StudName: /s$/})
LIKE '%s';
SELECT * FROM Students WHERE StudName
Contains “e” [Link]({StudName: /e/})
LIKE '%e%';
Prof. Deepika G, Dept. of CSE, SVIT Page 22
6.5.6 Dealing with NULL Values
Adding NULL Values
• Objective: Add a new field with null value to existing documents in the Students collection (_id:3 and
_id:4).
• Command:
[Link]({_id:3}, {$set:{Location:null}});
[Link]({_id:4}, {$set:{Location:null}});
• SQL Equivalent:
• UPDATE Students SET Location = NULL WHERE StudRollNo IN ('3','4');
Searching for NULL Values
• Command:
[Link]({Location:{$eq:null}});
• SQL Equivalent:
SELECT * FROM Students WHERE Location IS NULL;
Removing Fields with NULL Values
• Objective: Remove Location field with null values from _id:3 and _id:4.
• Command:
[Link]({_id:3}, {$unset:{Location:null}});
[Link]({_id:4}, {$unset:{Location:null}});
• Purpose: $unset removes a field from documents.
6.5.6 Dealing with NULL Values
• Objective:
Add a new field with NULL value to existing documents or remove NULL fields from documents in the
Students collection.
• Definition:
NULL represents a missing or unknown value that can later be updated.
•
Steps to Add NULL Values
1. View documents with _id: 3 and _id: 4:
Prof. Deepika G, Dept. of CSE, SVIT Page 23
2. [Link]({$or:[{_id:3},{_id:4}]})
3. Add a Location field with value null:
4. [Link]({_id:3}, {$set:{Location:null}});
5. [Link]({_id:4}, {$set:{Location:null}});
6. Equivalent SQL:
7. UPDATE Students SET Location = NULL WHERE StudRollNo IN (3,4);
8. Search for documents with NULL values in the Location column:
9. [Link]({Location:{$eq:null}});
o Returns documents where Location is NULL or missing.
Steps to Remove NULL Fields
1. Find documents where Location is NULL.
2. Remove Location field:
3. [Link]({_id:3}, {$unset:{Location:null}});
4. [Link]({_id:4}, {$unset:{Location:null}});
6.5.7 Count, Limit, Sort, and Skip
Count
• Count all documents in the collection:
• [Link]()
• Count documents where Grade is VII:
• [Link]({Grade:"VII"})
Limit
• Retrieve the first 3 documents where Grade is VII:
[Link]({Grade:"VII"}).limit(3)
6.5.8 Arrays
Objective: To learn how to search and retrieve MongoDB documents from a collection based on different array
search conditions.
Prof. Deepika G, Dept. of CSE, SVIT Page 24
1. Insert documents with arrays – insert() creates collection and stores data with arrays.
2. Show all documents – find({}) returns everything.
3. Exact array match – find({fruits: ['banana','apple','cherry']})
o Order and elements must be identical.
4. Element exists in array – find({fruits: 'banana'})
o Matches if "banana" is anywhere in the array.
5. Match by position – find({'fruits.1':'grapes'})
o Checks if value is at a specific index (0-based).
6. Match by size – find({fruits: {$size: 2}})
o Matches arrays with exact number of elements.
7. Return part of array – use $slice in projection to show first N or specific range of elements.
8. Multiple values present – find({fruits: {$all:['orange','grapes']}})
o Both values must be present, order doesn’t matter.
9. Match first element – find({'fruits.0':'orange'})
o Checks the very first element in the array.
Prof. Deepika G, Dept. of CSE, SVIT Page 25
[Link] Further Updates to the Array “fruits”
Add an element to an array
[Link]({_id: 4}, { $addToSet: { fruits: "orange" } })
• Purpose: Adds "orange" to the fruits array (only if it’s not already there).
2. Pop last element from an array
[Link]({_id: 4}, { $pop: { fruits: 1 } })
• Purpose: Removes the last element from the fruits array.
3. Pop first element from an array
[Link]({_id: 4}, { $pop: { fruits: -1 } })
• Purpose: Removes the first element from the fruits array.
4. Remove specific multiple elements
[Link]({_id: 3}, { $pullAll: { fruits: ["pineapple", "grapes"] } })
• Purpose: Removes all specified values from the fruits array.
5. Remove a specific element from all matching documents
[Link]({ fruits: "banana" }, { $pull: { fruits: "banana" } })
• Purpose: Removes "banana" from fruits in all documents where it exists.
6. Remove element by index (workaround)
[Link]({_id: 4}, { $unset: { "fruits.1": null } })
[Link]({_id: 4}, { $pull: { fruits: null } })
• Purpose: Removes the element at index 1 from the fruits array (2-step workaround since MongoDB
doesn’t have direct index removal).
6.5.9 Aggregate Function
Objective
• Filter documents where AccType = "S".
• Group by CustID.
• Sum the AccBal for each group.
• Filter groups where TotAccBal > 1200
Prof. Deepika G, Dept. of CSE, SVIT Page 26
Steps
1. Insert Documents
[Link]([
{CustID: "C123", AccBal: 500, AccType: "S"},
{CustID: "C123", AccBal: 900, AccType: "S"},
{CustID: "C111", AccBal: 1200, AccType: "S"},
{CustID: "C123", AccBal: 1500, AccType: "C"}
]);
Confirm Documents
[Link]().pretty();
Group by CustID and Sum
[Link]([
{ $group: { _id: "$CustID", TotAccBal: { $sum: "$AccBal" } } }
]);
Filter by AccType = "S", then Group and Sum
[Link]([
{ $match: { AccType: "S" } },
{ $group: { _id: "$CustID", TotAccBal: { $sum: "$AccBal" } } }
]);
Filter by AccType = "S", Group, Sum, and Keep TotAccBal > 1200
[Link]([
{ $match: { AccType: "S" } },
{ $group: { _id: "$CustID", TotAccBal: { $sum: "$AccBal" } } },
{ $match: { TotAccBal: { $gt: 1200 } } }
]);
2. Other Aggregate Operations
Prof. Deepika G, Dept. of CSE, SVIT Page 27
Average
[Link]([
{ $group: { _id: "$CustID", TotAccBal: { $avg: "$AccBal" } } }
]);
Maximum
[Link]([
{ $group: { _id: "$CustID", TotAccBal: { $max: "$AccBal" } } }
]);
Minimum
[Link]([
{ $group: { _id: "$CustID", TotAccBal: { $min: "$AccBal" } } }
]);
6.5.10 Mapreduce Function
Objective:
• Work with a Customers collection containing documents with CustID, AccBal, and AccType.
• Step 1: Keep only documents where AccType = "S".
• Step 2: For each CustID, sum the AccBal.
• Step 3 (optional): Only keep results where the total balance is greater than 1200.
Key MongoDB Aggregation Steps:
1. Insert documents:
[Link]([
{CustID: "C123", AccBal: 500, AccType: "S"},
{CustID: "C123", AccBal: 900, AccType: "S"},
{CustID: "C111", AccBal: 1200, AccType: "S"},
{CustID: "C123", AccBal: 1500, AccType: "C"}
]);
2. Filter and group with sum:
[Link]([
{ $match: { AccType: "S" } },
{ $group: { _id: "$CustID", TotAccBal: { $sum: "$AccBal" } } }
]);
3. Filter totals greater than 1200:
[Link]([
{ $match: { AccType: "S" } },
{ $group: { _id: "$CustID", TotAccBal: { $sum: "$AccBal" } } },
Prof. Deepika G, Dept. of CSE, SVIT Page 28
{ $match: { TotAccBal: { $gt: 1200 } } }
]);
4. Other aggregate functions:
o Average: { $avg: "$AccBal" }
o Maximum: { $max: "$AccBal" }
o Minimum: { $min: "$AccBal" }
MapReduce Version:
• Map Function:
var map = function() {
emit([Link], [Link]);
};
• Reduce Function:
var reduce = function(key, values) {
return [Link](values);
};
• Run MapReduce:
[Link](
map,
reduce,
{
query: { AccType: "S" },
out: "Customer_Totals"
}
);
• Result example in Customer_Totals:
{ "_id": "C123", "value": 1400 }
{ "_id": "C111", "value": 1200 }
6.5.11 JavaScript Programming
MongoDB – Store and Run a Factorial Function
1. Objective
Compute the factorial of a positive integer and store the function in MongoDB’s [Link] collection for reuse.
2. Check existing functions
[Link]();
(Empty initially — no stored functions.)
3. Insert factorial function
Prof. Deepika G, Dept. of CSE, SVIT Page 29
[Link]({
_id: "factorial",
value: function(n) {
if (n == 1)
return 1;
else
return n * factorial(n - 1);
}
});
This uses recursion:
• Base case: if n == 1 → return 1
• Recursive case: multiply n by factorial of n-1
4. Confirm the function is stored
[Link]();
Shows factorial with its function code.
5. Run the function with eval()
[Link]("factorial(3)"); // → 6
[Link]("factorial(5)"); // → 120
[Link]("factorial(1)"); // → 1
• [Link] is a special collection for reusable server-side JavaScript functions.
• Recursive function pattern is common for factorial.
• [Link]() lets you execute stored functions directly from MongoDB.
6.5.12 Cursors in Mongodb
1. Insert Remaining Alphabets (s–z)
[Link]({_id:19, alphabet:"s"});
[Link]({_id:20, alphabet:"t"});
[Link]({_id:21, alphabet:"u"});
[Link]({_id:22, alphabet:"v"});
[Link]({_id:23, alphabet:"w"});
[Link]({_id:24, alphabet:"x"});
[Link]({_id:25, alphabet:"y"});
[Link]({_id:26, alphabet:"z"});
2. Confirm the collection has 26 documents
[Link]();
This command lists all documents:
Prof. Deepika G, Dept. of CSE, SVIT Page 30
{ "_id": 1, "alphabet": "a" }
{ "_id": 2, "alphabet": "b" }
{ "_id": 3, "alphabet": "c" }
...
{ "_id": 26, "alphabet": "z" }
If there are exactly 26 entries, the setup is correct.
Key MongoDB concepts shown:
• Collection creation happens automatically when you first insert documents.
• _id field is mandatory and unique.
• find() returns a cursor which can be iterated.
• You can break your inserts into multiple commands — MongoDB doesn’t require all data at once.
6.5.13 Indexes
MongoDB Indexes
Sample Data
A collection named books has multiple documents with fields like:
o _id
o Category
o Bookname
o Author
o Qty
o Price
o Pages
2. Creating an Index
3. [Link]({ "Category": 1 })
o Creates an ascending index on the Category field in the books collection.
4. Checking Index Status
5. [Link]()
o Shows details like number of indexes, storage size, and other metadata.
6. Listing All Indexes
7. [Link]()
o Displays details of existing indexes (_id_ and Category_1).
8. Using an Index in Queries
9. [Link]({"Category":"Web Mining"}).pretty().hint({"Category":1})
o Forces MongoDB to use the Category index.
10. Explain Query Execution
11. [Link]({"Category":"Web Mining"}).pretty().hint({"Category":1}).explain()
o Shows execution plan and index usage statistics.
12. Covered Index
o Only query and project fields that are part of the index.
Prof. Deepika G, Dept. of CSE, SVIT Page 31
o Example:
o [Link](
o {"Category":"Web Mining"},
o {"Category":1, _id:0}
o ).hint({"Category":1}).explain()
▪ indexOnly: true means the query is fully served from the index without scanning documents.
6.5.14 MongoImport
1. Purpose
o Imports data from CSV, TSV, or JSON files into MongoDB collections from the command prompt.
2. Example Scenario
o CSV file: [Link] in D: drive
o Collection name: SampleJSON
o Database name: test
o File content:
o _id,FName,LName
o 1,Samuel,Jones
o 2,Virat,Kumar
o 3,Raul,"A Simpson"
o 4,,"Andrew Simon"
3. Import Command
4. mongoimport --db test --collection SampleJSON --type csv --headerline --file d:\[Link]
o --db test → Target database
o --collection SampleJSON → Target collection
o --type csv → File format
o --headerline → Use first row as field names
o --file → Path to the input file
5. Success Message
o Shows connection to MongoDB and the number of objects imported:
o imported 4 objects
6. Verification
o Open Mongo shell:
o > db
o test
Prof. Deepika G, Dept. of CSE, SVIT Page 32
o > show collections
o SampleJSON
o > [Link]().pretty()
o Displays imported JSON documents in formatted style.
6.5.15 MongoExport
1. Purpose
o Exports MongoDB JSON documents into CSV, TSV, or JSON format using the command prompt.
2. Example Scenario
o Database: test
o Collection: Customers
o Export to file: [Link] in D: drive
o Sample documents in Customers:
o { "CustID": "C123", "AccBal": 500, "AccType": "S" }
o { "CustID": "C123", "AccBal": 900, "AccType": "S" }
o { "CustID": "C101", "AccBal": 1200, "AccType": "C" }
o { "CustID": "C123", "AccBal": 1500, "AccType": "C" }
3. Preparation
o Create a fields file ([Link]) listing column names, one per line:
o CustID
o AccBal
o AccType
4. Export Command
5. mongoexport --db test --collection Customers --csv --fieldFile d:\[Link] --out
d:\[Link]
o --db test → Database name
o --collection Customers → Collection name
o --csv → Export format
o --fieldFile → Path to field list file
o --out → Output file path
6. Important Notes
o Field names in [Link] must exactly match collection fields.
o Only one field name per line in [Link].
o Case sensitivity matters.
7. Success Message
o After execution:
exported 4 records
6.5.16 Automatic _id Generation Using a Counter in MongoDB
Step 1 – Create a Counter Collection
Create a collection usercounters to store the sequence counter:
[Link]({
_id: "empid",
Prof. Deepika G, Dept. of CSE, SVIT Page 33
seq: 0
});
• _id → Name of the counter (e.g., "empid")
• seq → Current sequence number (starts at 0)
Step 2 – Create a Function to Get Next Sequence
Define a JavaScript function getnextseq to:
1. Find the counter document by _id
2. Increment seq by 1
3. Return the updated seq
function getnextseq(name) {
var ret = [Link]({
query: { _id: name },
update: { $inc: { seq: 1 } },
new: true
});
return [Link];
}
Step 3 – Use the Function When Inserting
When inserting into the users collection, call getnextseq() to generate a
unique _id:
[Link]({
_id: getnextseq("empid"),
Name: "sarah jane"
});
• The function automatically increments and returns a new _id number each
time you insert a document.
Why use this?
• Useful when you need sequential numeric IDs instead of MongoDB’s default
ObjectIDs.
• Keeps control over ID format and ordering.
Prof. Deepika G, Dept. of CSE, SVIT Page 34