0% found this document useful (0 votes)
6 views

mongo db notes s3 & s4

The document provides a comprehensive guide on using MongoDB, covering database and collection management, data insertion, retrieval, updating, and deletion. It also explains advanced querying and aggregation techniques, including filtering with various operators and working with arrays. Key methods and commands are illustrated with examples to facilitate understanding of MongoDB functionalities.

Uploaded by

vasam.sravsri99
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

mongo db notes s3 & s4

The document provides a comprehensive guide on using MongoDB, covering database and collection management, data insertion, retrieval, updating, and deletion. It also explains advanced querying and aggregation techniques, including filtering with various operators and working with arrays. Key methods and commands are illustrated with examples to facilitate understanding of MongoDB functionalities.

Uploaded by

vasam.sravsri99
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

MongoDB in Action

Let’s Start
Working with Database
• Show all databases

Show dbs

• Change or Create a Database

use databasename

• Create Collection using mongosh

db.createCollection(“newcollectionname”)

 In MongoDB, a database is not actually created until it gets content!

 In MongoDB, a collection is not actually created until it gets content!


Working with Collections (Creation)
• Insert Documents

To insert data into a collection, use the insertOne() or insertMany() methods.

Insert one document

db.collectionName.insertOne({ name: "Alice", age: 25 });

Insert multiple documents

db.collectionName.insertMany([ { name: "Bob", age: 30 }, { name: "Charlie", age: 35 } ]);

 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

Using the MongoDB Shell

To display all documents in a collection

db.collectionName.find()

Display Documents in a Pretty Format

db.students.find().pretty()

Limit the Number of Documents

db.students.find().limit(5)
Working with Documents (Creation)
Using MongoDB Compass

If you're using MongoDB Compass (GUI):

1.Select the database and the collection you want to view.

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.

Filter by Exact Match

To find documents where a field matches a specific value:

Example:

db.students.find({ name: “Mini" })

This will return all documents where the name is exactly “Mini".
Filtering using find(Retrieval)
Filter by Multiple Conditions

To match documents that meet multiple criteria:

db.students.find({ name: “Mini", age: 20 })

This will return documents where both name is “Mini" and age is 20.
Filtering using find(Retrieval)
Using Comparison Operators
•Greater Than ($gt):

db.students.find({ age: { $gt: 20 } })

Returns documents where age is greater than 20.

•Less Than ($lt):

db.students.find({ age: { $lt: 25 } })

Returns documents where age is less than 25.

•Greater Than or Equal To ($gte):


db.students.find({ age: { $gte: 18 } })

Returns documents where age is 18 or more.

•Less Than or Equal To ($lte):


db.students.find({ age: { $lte: 22 } })

Returns documents where age is 22 or less.


Filtering using find(Retrieval)
Filter by Range (Between Two Values)

To filter documents where a field is within a certain range, you can combine operators:

db.students.find({ age: { $gte: 18, $lte: 22 } })

This will return documents where age is between 18 and 22, inclusive.

Filter by Values in an Array

To match documents where a field is one of several values, use the $in operator:

db.students.find({ age: { $in: [20, 21, 22] } })

This will return documents where age is either 20, 21, or 22.
Filtering using find(Retrieval)

Negating a Condition ($ne and $nin)

You can use $ne for "not equal" and $nin for "not in" conditions.

•Not Equal ($ne):

db.students.find({ age: { $ne: 20 } })

This will return documents where age is not 20.


•Not In ($nin):

db.students.find({ age: { $nin: [18, 19, 20] } })

This will return documents where age is not 18, 19, or 20.
Filtering using find(Retrieval)

Using Logical Operators ($or, $and, $nor)

You can combine multiple conditions using logical operators:

•OR Condition ($or):

db.students.find({ $or: [{ age: 20 }, { name: "Bob" }] })

This will return documents where either age is 20 or name is "Bob".

•AND Condition ($and) (though normally implied by multiple conditions):

db.students.find({ $and: [{ age: { $gt: 18 } }, { name: "Alice" }] })

This will return documents where age is greater than 18 and name is "Alice".

•NOR Condition ($nor):

db.students.find({ $nor: [{ age: 20 }, { name: "Alice" }] })

This will return documents where neither the age is 20 nor the name is "Alice".
Example:
•Find students who are older than 21:

•Find students whose major is "Mathematics" or "Engineering":


Projection using filter()(Retrieval)

Projection allows you to specify which fields to include or exclude in the query result.

By default, MongoDB returns all fields in documents that match a query.

•Include specific fields (show only name and age):

db.students.find({}, { name: 1, age: 1, _id: 0 })

This will show only the name and age fields for each document, excluding the _id.

•Exclude specific fields (exclude the age field):

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.

•Sort students by age in ascending order:

db.students.find().sort({ age: 1 })

•Sort students by name in descending order:

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.

•Sort students by age in ascending order:

db.students.find().sort({ age: 1 })

•Sort students by name in descending order:

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.

• updateMany(): This method updates all documents that match a condition.


Basic Structure of an Update Command

db.collection.updateOne(

{ condition }, // What to look for (filter)

{ $set: { field: value } } // What to change


)

 collection: This is the name of the collection (like a table) you’re updating.

 condition: This tells MongoDB which document(s) to update.

 $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.

Flexibility: Allows you to modify any piece of information as needed.


Key Points to Remember

• Use updateOne() for changing a single record and updateMany() for multiple records.

• The $set operator is crucial for specifying which fields to change.

• Updating helps keep the database accurate and relevant.


Remove Data in MongoDB(Deletion)
• Delete means removing information from the database. In MongoDB, we use the deleteOne()
method to delete a specific record.

Delete One Record

To delete a specific record from a collection, we use the deleteOne() method. This removes only one
document that matches the condition.

db.students.deleteOne({ name: “Ani" })

Delete Multiple Records

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({})

Deleting Based on Multiple Conditions

You can delete records based on more than one condition using multiple fields.

db.students.deleteOne({ name: "John", age: 18 })


Remove Data in MongoDB(Deletion)

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!

Simple Example: A Shopping List


 Imagine you have a list of items you want to buy from the store

{
"name": "ShoppingList",

"items": ["Milk", "Eggs", "Bread", "Butter"]


}
• name: This is the name of the list, and it’s a single value.

• 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

Student and Subjects


Imagine a student is studying multiple subjects. In MongoDB, you can store the student's information and
their subjects together using an array.

{
"name": “Ani",
"age": 18,
"subjects": ["Math", "Science", "History"]
}

name: The student's name, which is just one value.

age: The student's age, also a single value.

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.

db.students.find({ subjects: "Math" })

• 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.

•$pop: Removes the first or last element of an array.

•$pull: Removes all elements of an array that match a specified condition.

•$addToSet: Adds elements to an array only if they don’t already exist (avoids duplicates).

•$each: Adds multiple elements to an array in a single operation.

•$slice: Limits the number of elements returned from an array.

•$size: Matches arrays that have a specified number of elements.

•$all: Matches arrays that contain all the specified elements.

•$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

You can search for exact matches,

Show me all the students with Address “Hyderabad”


Advanced Querying

With advanced querying, you can ask more complex questions,

• Show me all the books that cost less than $10.

• Show me all the books published after 2015 and have more than 4 stars in reviews.
What is Aggregation?

Aggregation is like summarizing or analyzing your data.

Imagine you want to gather some overall insights from your bookstore’s data, such as:

•“What’s the average price of all the books?”


•“How many books are there in total?”
Aggregation Framework
MongoDB uses a tool called the aggregation framework to handle these types of questions.

The aggregation framework processes data in stages, kind of like a factory production line

•$match: Filter documents, like selecting specific data based on a condition.

•$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 basic pipeline stages are defined below:

• filters that will operate like queries.


• the document transformation that modifies the resultant document.
• provide pipeline provides tools for grouping and sorting documents.
MongoDB Aggregation Pipeline
How Fast is MongoDB Aggregation?

•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.

You might also like