mongo db notes s3 & s4
mongo db notes s3 & s4
Let’s Start
Working with Database
• Show all databases
Show dbs
use databasename
db.createCollection(“newcollectionname”)
If you try to insert documents into a collection that does not exist, MongoDB will create the collection
automatically.
Working with Collections (Creation)
[
{ "name": "Raj", "age": 20, "hobby": "Cricket", "marks": 85 },
{ "name": "Priya", "age": 19, "hobby": "Painting", "marks": 92 },
{ "name": "Vikram", "age": 21, "hobby": "Photography", "marks": 78 },
{ "name": "Anjali", "age": 18, "hobby": "Dancing", "marks": 88 },
{ "name": "Rohit", "age": 22, "hobby": "Cycling", "marks": 80 },
{ "name": "Sneha", "age": 20, "hobby": "Reading", "marks": 91 },
{ "name": "Aditya", "age": 19, "hobby": "Gaming", "marks": 75 },
{ "name": "Meena", "age": 21, "hobby": "Writing", "marks": 87 },
{ "name": "Amit", "age": 18, "hobby": "Running", "marks": 89 },
{ "name": "Kavya", "age": 20, "hobby": "Singing", "marks": 93 }
]
Working with Collections (Creation)
use school
db.students.insertMany([
{ "name": "Raj", "age": 20, "hobby": "Cricket", "marks": 85 },
{ "name": "Priya", "age": 19, "hobby": "Painting", "marks": 92 },
{ "name": "Vikram", "age": 21, "hobby": "Photography", "marks": 78 },
{ "name": "Anjali", "age": 18, "hobby": "Dancing", "marks": 88 },
{ "name": "Rohit", "age": 22, "hobby": "Cycling", "marks": 80 },
{ "name": "Sneha", "age": 20, "hobby": "Reading", "marks": 91 },
{ "name": "Aditya", "age": 19, "hobby": "Gaming", "marks": 75 },
{ "name": "Meena", "age": 21, "hobby": "Writing", "marks": 87 },
{ "name": "Amit", "age": 18, "hobby": "Running", "marks": 89 },
{ "name": "Kavya", "age": 20, "hobby": "Singing", "marks": 93 }
])
Working with Documents (Creation)
To display documents from a MongoDB collection, you can use the find() method in the MongoDB shell
or programmatically
db.collectionName.find()
db.students.find().pretty()
db.students.find().limit(5)
Working with Documents (Creation)
Using MongoDB Compass
2.Click on the Documents tab, and it will display all documents in the selected collection.
Filtering with find() (Retrieval)
In MongoDB, the find() method allows you to query or filter documents from a collection based on
specified conditions.
You can apply different criteria using query operators inside the find() method.
Example:
This will return all documents where the name is exactly “Mini".
Filtering using find(Retrieval)
Filter by Multiple Conditions
This will return documents where both name is “Mini" and age is 20.
Filtering using find(Retrieval)
Using Comparison Operators
•Greater Than ($gt):
To filter documents where a field is within a certain range, you can combine operators:
This will return documents where age is between 18 and 22, inclusive.
To match documents where a field is one of several values, use the $in operator:
This will return documents where age is either 20, 21, or 22.
Filtering using find(Retrieval)
You can use $ne for "not equal" and $nin for "not in" conditions.
This will return documents where age is not 18, 19, or 20.
Filtering using find(Retrieval)
This will return documents where age is greater than 18 and name is "Alice".
This will return documents where neither the age is 20 nor the name is "Alice".
Example:
•Find students who are older than 21:
Projection allows you to specify which fields to include or exclude in the query result.
This will show only the name and age fields for each document, excluding the _id.
db.students.find({}, { age: 0 })
This will display all fields except age for each document.
Sorting Query Results
You can sort the results of a query using the sort() method.
db.students.find().sort({ age: 1 })
db.students.find().sort({ name: -1 })
MongoDB in Action
Let’s Start
Database Basics
Database types
Why MongoDB?
NoSQL vs SQL
History of MongoDB
What is MongoDB?
Key Features
MongoDB and JSON
How MongoDB Uses JSON
What is JSON?
JSON in Practice
Types of MongoDB
MongoDB Download and installation
MongoDB Shell Download and installation
MongoDB and VSCode
Working with Database
Working with Collections (Creation)
Filtering with find() (Retrieval)
Projection using filter()
Sorting Query Results
Sorting Query Results
You can sort the results of a query using the sort() method.
db.students.find().sort({ age: 1 })
db.students.find().sort({ name: -1 })
Changing information-(Updating)
Updating data in MongoDB is like changing or modifying information in a database.
What is an Update?
An update means changing the existing information stored in a database. For example, if you have a student's record and they
change their age or add a new subject, you need to update that information.
How Does Updating Work in MongoDB?
In MongoDB, we use the updateOne() and updateMany() methods to modify records.
• updateOne(): This method updates the first document that matches a specific condition.
db.collection.updateOne(
collection: This is the name of the collection (like a table) you’re updating.
$set: This operator specifies which field(s) to change and what new value to assign.
Why Use Update?
Accuracy: Keeps data up to date, which is important for making informed decisions.
• Use updateOne() for changing a single record and updateMany() for multiple records.
To delete a specific record from a collection, we use the deleteOne() method. This removes only one
document that matches the condition.
To delete more than one record, we use deleteMany(). This removes all documents that match the
condition.
db.students.deleteMany({ age: 18 })
Remove Data in MongoDB(Deletion)
Delete All Records
If you want to clear all the records from a collection, you can use deleteMany() with an empty query.
This will delete everything in the collection.
db.students.deleteMany({})
You can delete records based on more than one condition using multiple fields.
db.students.deleteMany({
$or: [
{ name: "John" },
{ age: { $gt: 18 } }
]
})
Arrays in MongoDB
An array in MongoDB is like a list or group of items that you want to keep together in a single place. You
can think of it as a collection of related things, such as a shopping list, a list of favorite movies, or the
different subjects a student is studying
In a document database like MongoDB, arrays allow you to store multiple values in a single field. Each
item in the array can be a number, word, or even another list!
{
"name": "ShoppingList",
• items: This is the array. It contains multiple items in one field — "Milk", "Eggs", "Bread", and "Butter".
Why Arrays in MongoDB
Arrays are useful when you want to store multiple related values in a single place. In our shopping list, it’s
better to store all the items in one list (items) instead of creating separate fields like item1, item2, etc.
Real-Life Example
{
"name": “Ani",
"age": 18,
"subjects": ["Math", "Science", "History"]
}
subjects: This is the array that contains all the subjects Ani is studying — "Math", "Science", and "History".
Advantages of Arrays in MongoDB
1.Organized: Arrays keep related items together in one place.
2.Flexible: You can add or remove items from the array easily.
3.Efficient: Instead of creating a separate field for each subject or item, an array helps store everything
neatly in a single field.
Working with Arrays in MongoDB
• Adding Items to the Array: Just like you can add new items to a shopping list, you can add new
subjects to the array.
db.students.updateOne(
{ name: “Ani" },
{ $push: { subjects: "English" } }
• Finding Items in the Array: )You can check whether something is in the list.
• Removing Items from the Array: If Ani stops studying "History," you can remove it from his subjects
db.students.updateOne(
{ name: “Ani" },
{ $pull: { subjects: "History" } }
)
Key Points
•Array = List: It’s a simple way to group multiple items.
•Why arrays? They keep related things together and are easy to manage.
•Examples: A shopping list, list of favorite movies, or subjects a student is studying are all arrays.
Key MongoDB Array Operators
•$push: Adds an element to the end of an array.
•$addToSet: Adds elements to an array only if they don’t already exist (avoids duplicates).
•$elemMatch: Matches documents that contain an array with at least one element that matches all
specified criteria.
Advanced Querying & Aggregation in MongoDB
Let’s Start
Advanced Querying and Aggregation in MongoDB refers to ways of retrieving, filtering, and analyzing data stored in the
database.
What is Querying?
Querying is like asking questions or searching for specific information in your data.
Imagine you're looking for certain books in your bookstore’s database—maybe books that are under a certain price or
written by a particular author
Basic Querying
• Show me all the books published after 2015 and have more than 4 stars in reviews.
What is Aggregation?
Imagine you want to gather some overall insights from your bookstore’s data, such as:
The aggregation framework processes data in stages, kind of like a factory production line
•$group: Group documents together based on some common field, such as grouping all books by author.
•$sum: Add up values, like summing up the total sales of all books.
•$avg: Calculate the average of values, like finding the average rating of all books.
•$sort: Arrange data in a certain order, like sorting books by price from highest to lowest.
MongoDB Aggregation Pipeline
•Mongodb Aggregation Pipeline consist of stages and each stage transforms the document. It is a multi-stage pipeline and in
each state and the documents are taken as input to produce the resultant set of documents.
•In the next stage (ID available) the resultant documents are taken as input to produce output, this process continues till the last
stage.
•The speed of MongoDB aggregation depends on various factors such as the complexity of the aggregation pipeline,
the size of the data set, the hardware specifications of the MongoDB server and the efficiency of the indexes.
•In general, MongoDB’s aggregation framework is designed to efficiently process large volumes of data and complex
aggregation operations. When used correctly it can provide fast and scalable aggregation capabilities.
•So with any database operation, the performance can vary based on the specific use case and configuration. It is
important to optimize our aggregation queries and use indexes where appropriate and ensure that our MongoDB
server is properly configured for optimal performance.