UNIT 1 : CONCEPTS OF NOSQL : MONGODB
Unit-1: Concepts of NoSQL: MongoDB
Syllabus
1.1 Concepts of NoSQL. Advantages and features.
1.1.1 MongoDB Datatypes (String, Integer, Boolean, Double, Arrays, Objects)
1.1.2 Database creation and dropping database
1.2 Create and Drop collections
1.3 CRUD operations (Insert, update, delete, find, Query and Projection operators)
1.4 Operators (Projection, update, limit(), sort()) and Aggregation commands
----------------------------------------------------------------------------------------------------------------
1.1 Concepts of NoSQL
What is NoSQL?
NoSQL (“Not Only SQL”) databases are non-relational databases that provide mechanisms
for storage and retrieval of data modeled in ways other than the tabular relations used in
relational databases. NoSQL databases are designed for simplicity, horizontal scalability, and
high availability, and are often used in big data and real-time web applications.
Features of NoSQL
Non-relational
NoSQL databases never follow the relational model
Never provide tables with flat fixed-column records
Work with self-contained aggregates or BLOBs
Doesn’t require object-relational mapping and data normalization
No complex features like query languages, query planners,referential
integrity joins, ACID
Schema-free
NoSQL databases are either schema-free or have relaxed schemas
Do not require any sort of definition of the schema of the data
Offers heterogeneous structures of data in the same domain
Simple API
Offers easy to use interfaces for storage and querying data provided
APIs allow low-level data manipulation & selection methods
Text-based protocols mostly used with HTTP REST with JSON
Mostly used no standard based NoSQL query language
Web-enabled databases running as internet-facing services
MS. ESHA VINAY PATEL 1
UNIT 1 : CONCEPTS OF NOSQL : MONGODB
Distributed
Multiple NoSQL databases can be executed in a distributed fashion
Offers auto-scaling and fail-over capabilities
Often ACID concept can be sacrificed for scalability and throughput
Mostly no synchronous replication between distributed nodes
Asynchronous Multi-Master
Replication, peer-to-peer, HDFS Replication
Only providing eventual consistency
Shared Nothing Architecture. This enables less coordination and higher
distribution.
Advantages of NoSQL
High Scalability: Uses sharding for horizontal scaling.
High Availability: Auto-replication ensures data is available even if some nodes fail.
Flexible Schema: Schema-less design allows storage of structured, semi-structured,
or unstructured data.
Big Data Capability: Efficiently handles large and growing datasets.
No Single Point of Failure: Data is distributed and replicated.
Disadvantages of NoSQL
Narrow Focus: Limited transaction management compared to relational databases.
Lack of Standardization: No universal query language.
Management Challenges: More complex to manage than relational databases.
Limited GUI Tools: Fewer user-friendly tools are available.
Backup Issues: Some NoSQL databases (like MongoDB) have limited backup
solutions.
Large Document Size: JSON/BSON documents can be large due to descriptive key
names.
Types of NoSQL Databases
Type Examples Description
Document-based MongoDB, CouchDB, Cloudant Stores data as JSON/BSON documents
Key-value Store Redis, Memcached, Coherence Stores data as key-value pairs
Column-oriented HBase, BigTable, Accumulo Stores data in columns
Graph-based Neo4j, OrientDB Stores data as nodes and edges
MS. ESHA VINAY PATEL 2
UNIT 1 : CONCEPTS OF NOSQL : MONGODB
1.1.1 MongoDB Datatypes
MongoDB supports a variety of data types:
Data
Description Example
Type
String UTF-8 encoded text "name": "SSA"
Integer 32-bit or 64-bit number "age": 30
Boolean true/false value "isActive": true
Double Floating point number "score": 98.6
Arrays List of values "tags": ["mongodb", "database", "NoSQL"]
"address": {"city": "Delhi", "zip":
Object Embedded document 110001}
Date/time in UNIX "createdAt": new Date("2023-01-01")
Date
format
"_id":
ObjectId Unique identifier ObjectId("507f191e810c19729de860ea")
Null Null value "middleName": null
1.1.2 Database Creation and Dropping Database
Creating a Database in MongoDB
MongoDB does not require an explicit command to create a database. Instead, you "create" a
database by switching to it using the use command and then adding content to it. The
database is physically created only after you insert at least one document into it.
Steps and Example
1. Switch to New Database
2. Check Current Database
This confirms you're working in the mydb database.
3. Insert Data (Creates Database and Collection)
MS. ESHA VINAY PATEL 3
UNIT 1 : CONCEPTS OF NOSQL : MONGODB
4. View All Databases
(Now you'll see your new database listed)
The database won't show up with show dbs until you insert some data.
Dropping (Deleting) a Database in MongoDB
Dropping a database in MongoDB is simple but irreversible. The command deletes all
collections and data in the selected database.
Steps and Example
1. Switch to the Database You Want to Drop
text
use mydb
Output:
text
switched to db mydb
2. Drop the Database
This message confirms the operation was successful.
3. Verify Deletion
MS. ESHA VINAY PATEL 4
UNIT 1 : CONCEPTS OF NOSQL : MONGODB
Now, mydb will not appear in the database list, confirming its deletion.
Explanation
Database Creation: In MongoDB, using the use <database_name> command
prepares a database context. The actual database is only physically created after you
store the first record (document) in it. This approach means you can switch to any
database name at any time, but it won’t appear in listings until it stores data.
Database Dropping: The db.dropDatabase() command must be run when you are
switched into the target database. It permanently deletes the database and all
associated data. This action cannot be undone, so use it carefully.
Quick Reference Table
Command Purpose Output / Effect
use mydb Switch to (or create) database switched to db mydb
db Show current database mydb
db.movies.insertOne({...}) Add data (triggers creation) { acknowledged: true, ... }
show dbs List all databases Shows database list
db.dropDatabase() Drop current database { "dropped": "mydb", "ok": 1 }
Key Points:
MongoDB only creates a new database after you insert data.
Implicit creation and dropping of databases is fast and simple compared to traditional
relational databases.
Dropping is permanent: all collections and documents in the database are erased
MS. ESHA VINAY PATEL 5
UNIT 1 : CONCEPTS OF NOSQL : MONGODB
1.2 Create and Drop collections
Creating Collections in MongoDB
1. Explicit Collection Creation
You can create a collection explicitly using the createCollection() method:
db.createCollection('collection_name', options)
Example:
db.createCollection('Students')
This creates a collection named "Students".
With Options:
db.createCollection('logs', { capped: true, size: 1048576, max: 1000 })
o capped: Creates a fixed-size collection, ideal for logs. Once the specified size
is reached, the oldest documents are overwritten.
o size: The maximum size in bytes for the capped collection.
o max: (Optional) The maximum number of documents allowed in the capped
collection.
Other Options You Can Use:
Validator: To enforce document schema validation.
db.createCollection('inventory', {
validator: {
$jsonSchema: {
bsonType: "object",
required: [ "item", "qty" ],
properties: {
item: {
MS. ESHA VINAY PATEL 6
UNIT 1 : CONCEPTS OF NOSQL : MONGODB
bsonType: "string",
description: "must be a string and is required"
},
qty: {
bsonType: "int",
minimum: 1,
description: "must be an integer greater than 0 and is required"
}
}
}
}
})
AutoIndexId (deprecated after MongoDB 3.2): Controls creation of a default _id
index.
Storage Engine Options: Fine-tune collection storage for wiredTiger or mmapv1
(rarely used directly).
Errors will be prompt :
MS. ESHA VINAY PATEL 7
UNIT 1 : CONCEPTS OF NOSQL : MONGODB
2. Implicit Collection Creation
MongoDB is dynamic. If you try to insert a document into a collection that doesn’t exist,
MongoDB will create that collection automatically.
Example:
db.Students.insertOne({ name: "Alice", age: 20 })
After running this command, the "Students" collection appears in your database.
Note: When using insertOne, insertMany, or any other insertion command on a
nonexistent collection, the collection is created for you, without you having to specify options.
Dropping Collections in MongoDB
To delete a collection (removing all documents, indexes, and metadata), use the drop()
method.
db.collection_name.drop()
Example:
db.Students.drop()
MS. ESHA VINAY PATEL 8
UNIT 1 : CONCEPTS OF NOSQL : MONGODB
If successful, this returns true.
What Happens When You Drop a Collection?
All data, indexes, and metadata in that collection are permanently deleted.
This action cannot be undone unless you have a backup.
The collection is no longer visible in show collections.
Additional Useful Drop Commands:
Check if a Collection Exists:
db.getCollectionNames().includes("Students")
Drop All Collections in a Database:
Loop over all collections:
db.getCollectionNames().forEach(function(c) { db[c].drop(); })
Key Points
Use db.createCollection() for explicit creation and customization.
Insert into a new name for implicit collection creation.
Use db.collection_name.drop() to irreversibly delete a collection.
Be careful—dropped collections cannot be recovered unless backed up!
MS. ESHA VINAY PATEL 9
UNIT 1 : CONCEPTS OF NOSQL : MONGODB
1.3 CRUD operations
(Insert, update, delete, find, Query and Projection operators)
1. Create (Insert) Operations
insertOne()
Inserts a single document into a collection.
If the collection doesn’t exist, MongoDB automatically creates it.
Automatically generates a unique _id if not provided.
Supports additional options like writeConcern.
Example:
db.emp.insertOne(
{ name: "Alice", age: 25 },
{ writeConcern: { w: "majority", wtimeout: 5000 } }
);
insertMany()
Inserts multiple documents efficiently in a single operation.
Supports options like ordered (whether to continue on errors) and writeConcern.
Returns inserted IDs and counts.
Example:
db.employee.insertMany(
[
{ name: "Bob", age: 30 },
{ name: "Charlie", age: 28 }
],
{ ordered: false }
MS. ESHA VINAY PATEL 10
UNIT 1 : CONCEPTS OF NOSQL : MONGODB
);
2. Read (Query) Operations
find()
Returns a cursor to iterate over documents matching the filter.
Uses powerful query operators for filtering.
Can be combined with projection, sorting, skip, limit.
Supports cursor options like batch size.
Examples:
1. Find all documents where age ≥ 25:
db.employee.find({ age: { $gte: 25 } });
2. Find documents projecting only name and age fields (excluding _id):
db.employee.find(
{ age: { $gte: 25 } },
{ name: 1, age: 1, _id: 0 }
);
MS. ESHA VINAY PATEL 11
UNIT 1 : CONCEPTS OF NOSQL : MONGODB
3. Sort results by age descending, limit 5:
db.employee.find({}).sort({ age: -1 }).limit(5);
3. Update Operations
updateOne()
Updates specific fields of one document matching the filter.
Supports update operators like $set, $inc, $unset, $push, $pull.
Can specify upsert to insert if no document matches.
Example:
db.employee.updateOne(
{ name: "Bob" },
{ $set: { age: 26, city: "New York" } }
);
updateMany()
MS. ESHA VINAY PATEL 12
UNIT 1 : CONCEPTS OF NOSQL : MONGODB
Updates multiple documents matching the filter using update operators.
Example:
db.employee.updateMany(
{ age: { $lt: 30 } },
{ $inc: { age: 1 } }
);
replaceOne()
Replaces the entire document matched by filter except the immutable _id.
With upsert: true, inserts the document if no match.
Example:
db.employee.replaceOne(
{ name: "Bob" },
{ name: "Bob", age: 31, city: "Chicago" },
{ upsert: true }
);
Additional Update Operators
MS. ESHA VINAY PATEL 13
UNIT 1 : CONCEPTS OF NOSQL : MONGODB
1. $inc — Increment numeric value
Increments the value of a field by a specified amount.
db.collection.updateOne(
{ name: "Alice" },
{ $inc: { age: 1 } } // increases age by 1
);
2. $unset — Remove field from document
Removes a field from a document.
db.collection.updateOne(
{ name: "Alice" },
{ $unset: { city: "" } } // removes the field "city"
);
3. $rename — Rename a field
Renames a field within a document.
db.collection.updateOne(
{ name: "Alice" },
{ $rename: { "age": "years_old" } } // renames "age" to "years_old"
);
4. $mul — Multiply a field by a value
Multiplies the numeric value of a field by the specified number.
db.collection.updateOne(
{ name: "Alice" },
{ $mul: { score: 1.1 } } // multiplies "score" by 1.1 (i.e., increases by 10%)
);
5. $push — Append an element to an array
Adds a value to an array field.
db.collection.updateOne(
{ name: "Alice" },
{ $push: { hobbies: "reading" } } // adds "reading" to the hobbies array
);
You can also push multiple values with $each:
db.collection.updateOne(
{ name: "Alice" },
{ $push: { hobbies: { $each: ["swimming", "jogging"] } } }
MS. ESHA VINAY PATEL 14
UNIT 1 : CONCEPTS OF NOSQL : MONGODB
);
6. $pull — Remove items from an array
Removes elements matching a condition from an array.
db.collection.updateOne(
{ name: "Alice" },
{ $pull: { hobbies: "reading" } } // removes "reading" from hobbies array
);
You can also remove based on a condition, e.g., remove numbers less than 5:
db.collection.updateOne(
{ name: "Bob" },
{ $pull: { scores: { $lt: 5 } } } // removes all elements in "scores" array less than 5
);
4. Delete Operations
deleteOne()
Deletes a single document matching the filter.
Example:
db.employee.deleteOne({ name: "Charlie" });
deleteMany()
Deletes all documents matching the filter.
Example:
db.employee.deleteMany({ age: { $gte: 30 } });
MS. ESHA VINAY PATEL 15
UNIT 1 : CONCEPTS OF NOSQL : MONGODB
5. Query Operators
Operator Description Example
$eq Equal to { age: { $eq: 25 } }
$ne Not equal { age: { $ne: 25 } }
$gt Greater than { age: { $gt: 20 } }
$gte Greater than or equal to { age: { $gte: 20 } }
$lt Less than { age: { $lt: 30 } }
$lte Less than or equal to { age: { $lte: 30 } }
$in Matches any value in an array { status: { $in: ["A", "B"] } }
Matches none of the values in
$nin array { status: { $nin: ["D"] } }
Logical AND for multiple { $and: [ { age: { $gt: 20 } }, { age: { $lt:
$and conditions 30 } } ] }
Logical OR for multiple
$or conditions { $or: [ { age: 25 }, { name: "Alice" } ] }
A few additional operators you can use beyond the basics:
$regex: Regular expressions for pattern matching.
$exists: Checks if a field exists.
$type: Matches documents where the field is of a specific BSON type.
$elemMatch: Matches documents with array elements meeting multiple criteria.
$size: Matches arrays with a specified length.
Example using regex:
db.collectionName.find({ name: { $regex: "^A", $options: "i" } });
6. Projection Operators
Inclusion—specify fields to include with 1.
Exclusion—fields to exclude with 0. You cannot mix inclusion and exclusion except
for _id.
MS. ESHA VINAY PATEL 16
UNIT 1 : CONCEPTS OF NOSQL : MONGODB
Use $slice to return subset of array fields.
$elemMatch to project only matching elements of an array.
Example—to include first 3 elements of an array field:
db.collectionName.find({}, { comments: { $slice: 3 } });
7. Bulk Operations
For large-scale, mixed operations, use bulkWrite():
db.collectionName.bulkWrite([
{ insertOne: { document: { name: "Eve", age: 22 } } },
{ updateOne: { filter: { name: "Alice" }, update: { $set: { age: 27 } } } },
{ deleteOne: { filter: { name: "Charlie" } } }
]);
8. Useful Tips
Always check the result object after updates, inserts, deletes for matched, modified,
inserted counts.
Use explain() on queries to understand performance.
Use limit(), skip(), and sort() to control result sets.
Index fields used frequently in queries for performance.
Example Full Workflow
// Insert multiple documents
db.students.insertMany([
{ name: "Alice", age: 25, grade: "A" },
{ name: "Bob", age: 30, grade: "B" },
{ name: "Charlie", age: 28, grade: "C" }
]);
// Find students aged 25+, projecting only name and age, sorted by age descending limit 2
db.students.find(
{ age: { $gte: 25 } },
{ name: 1, age: 1, _id: 0 }
).sort({ age: -1 }).limit(2);
// Update Bob's grade and add city
db.students.updateOne(
{ name: "Bob" },
{ $set: { grade: "A+", city: "New York" } }
);
// Replace Charlie's entire document
db.students.replaceOne(
{ name: "Charlie" },
{ name: "Charlie", age: 29, grade: "B+", city: "Boston" }
);
// Delete students with grade "C"
db.students.deleteMany({ grade: "C" });
MS. ESHA VINAY PATEL 17
UNIT 1 : CONCEPTS OF NOSQL : MONGODB
1.4 Operators (Projection, update, limit(), sort())
and Aggregation commands
1. Projection Operators
Projection specifies which fields to return when querying documents.
Inclusion (1): Show a field
Exclusion (0): Hide a field
Example: Return only name and age; hide _id:
db.students.find(
{ age: { $gte: 20 } },
{ name: 1, age: 1, _id: 0 }
)
Array projection with $slice: Return only first 2 elements of an array:
db.posts.find({}, { comments: { $slice: 2 } })
Array projection with $elemMatch: Show only array elements that match criteria:
db.students.find(
{ name: "Alice" },
{ grades: { $elemMatch: { type: "exam" } } }
)
2. Update Operators
Used with updateOne(), updateMany(), or bulkWrite() to modify documents.
Common Update Operators and Examples:
Operator Purpose Example
$set Set a field’s value { $set: { age: 22 } }
$inc Increment numeric value { $inc: { age: 1 } }
$unset Remove field { $unset: { city: "" } }
$rename Rename field { $rename: { "age": "years_old" } }
$mul Multiply field by value { $mul: { score: 2 } }
$push Add value to array { $push: { hobbies: "reading" } }
$pull Remove array value by match { $pull: { hobbies: "reading" } }
MS. ESHA VINAY PATEL 18
UNIT 1 : CONCEPTS OF NOSQL : MONGODB
Operator Purpose Example
$addToSet Add to array if not present { $addToSet: { skills: "MongoDB" } }
Example with updateOne:
db.students.updateOne(
{ name: "Alice" },
{ $inc: { age: 1 }, $push: { hobbies: "music" } }
)
3. limit() and sort()
Control result size and order in queries.
limit(n): Restrict to n documents
sort({ field: 1 or -1 }): 1=ascending, -1=descending
Examples:
// Get the top 2 oldest students
db.students.find().sort({ age: -1 }).limit(2)
// Get 3 students with grade 'B', sorted by name
db.students.find({ grade: "B" }).sort({ name: 1 }).limit(3)
You can also chain sort and limit for precise queries.
4. Aggregation Commands (Aggregation Pipeline)
Aggregation provides advanced data analysis, computation, and transformation.
Common Pipeline Stages:
$match: Filter documents (like find).
$group: Group and summarize (sum, avg, count).
$project: Reshape documents or make new fields.
$sort: Sort results.
$limit: Limit results.
$unwind: Flatten array fields.
Examples
Count students by grade:
db.students.aggregate([
{ $group: { _id: "$grade", count: { $sum: 1 } } }
])
MS. ESHA VINAY PATEL 19
UNIT 1 : CONCEPTS OF NOSQL : MONGODB
Average age per grade, sorted descending:
db.students.aggregate([
{ $group: { _id: "$grade", avgAge: { $avg: "$age" } } },
{ $sort: { avgAge: -1 } }
])
Projection in aggregation:
db.students.aggregate([
{ $project: { name: 1, isAdult: { $gte: ["$age", 18] } } }
])
Full pipeline — combine stages:
db.students.aggregate([
{ $match: { grade: { $in: ["A", "B"] } } },
{ $group: { _id: "$grade", avgAge: { $avg: "$age" }, total: { $sum: 1 } } },
{ $sort: { total: -1 } },
{ $limit: 2 }
])
Summary Table
Feature Command/Operator Example
Projection { field: 1/0 } db.find({}, {name:1, _id:0})
Update $set, $inc... db.updateOne({}, { $inc: {age: 1} })
Limit .limit(n) db.find().limit(5)
Sort .sort({field: 1/-1}) db.find().sort({age:-1})
Aggregation $match, $group, $sort… db.aggregate([...])
MS. ESHA VINAY PATEL 20