You are on page 1of 21

EXPERIMENT NO.

AIM:8.1 EXECUTE AGGREGATE FUNCTIONS ON COLLECTION. 8.2


IMPLEMENT PIPELINE OPERATIONS ON COLLECTION.

Aggregation functions in MongoDB are a powerful suite of tools that empower

you to condense and manipulate data stored in your collections. They enable you

to efficiently perform calculations and group results on even very large datasets.

Let's delve a bit deeper:

● Calculations: Aggregation functions provide a rich set of mathematical

operations you can perform on your data. Need to find the total number of

documents in a collection, the average value of a specific field, or the

minimum and maximum values? Aggregation functions have you covered.

They include a comprehensive toolbox, featuring:

 $sum for calculating totals (e.g., total sales or number of items in

stock)

 $avg for computing averages (e.g., average rating of a product or

average order value)

 $min and $max for finding minimums and maximums (e.g., finding

the lowest or highest price of an item)

SM22CO004
 $count for getting document counts within groups (e.g., counting the

number of customers in each country)

 $push to create arrays containing unique values from a field across

multiple documents (e.g., finding all distinct product categories)

 $first and $last to retrieve the first or last occurrence of a field value

within a group (e.g., identifying the first or last order placed by a

customer)

● Grouping: Aggregation functions also shine when it comes to grouping

documents. By grouping documents that share common values in a

particular field, you can categorize your data and analyze it from different

perspectives. This is instrumental for uncovering patterns and trends within

your collection. For instance, you can group products by category to see

which categories are selling the most, or group orders by customer to

identify your most frequent buyers. Additionally, you can group by multiple

fields to create even more granular analyses. Let's say you're running an

online store and want to see which product categories are most popular

among customers in a specific country. By grouping your sales data by both

product category and customer location, you can gain valuable insights into

your customer base and tailor your marketing strategies accordingly.

How they work:

● Used within the aggregation pipeline, a series of stages that process data.

SM22CO004
● Each stage takes the output of the previous stage and performs an

operation.

● Common functions include:

 $sum: calculates the total sum of a field across documents.

 $avg: computes the average value of a field.

 $min: finds the minimum value of a field.

 $max: finds the maximum value of a field.

 $count: counts the number of documents in a group.

Benefits:

 Efficient data processing: Aggregation functions excel at handling large

datasets efficiently. By processing and summarizing data at the collection

level, they significantly reduce the amount of data that needs to be

transferred between the database server and the application. This

translates to faster query execution times and improved application

performance, especially when dealing with millions or even billions of

documents.

 Meaningful data summaries: Aggregation functions are adept at

transforming raw data into insightful summaries. They enable you to

condense large collections of documents into sets of key metrics that reveal

patterns and trends within your data. This makes it significantly easier to

SM22CO004
identify outliers, track changes over time, and gain a deeper understanding

of the information stored in your MongoDB database.

 Complex data analysis with filtering and grouping: When combined with

filtering and grouping operations, aggregation functions unlock the door to

powerful data analysis. By filtering your data to target specific subsets of

documents and then grouping those documents based on shared

characteristics, you can conduct highly granular analyses that would be

cumbersome or even impossible with traditional querying methods. For

example, you could filter your sales data to include only orders from a

particular country in a specific quarter, and then group those orders by

product category to see which categories are driving the most sales in that

region.

In short, aggregation functions are like calculators for your MongoDB data,

allowing you to analyze and understand trends and patterns within your

collections.

Output:

SM22CO004
SM22CO004
EXPERIMENT NO. 9

AIM: CREATE DIFFERENT TYPES OF INDEX ON COLLECTION:


SIMPLE/SINGLE INDEX, COMPOUND INDEX, MULTIKEY INDEX.

9.2 EXECUTE COVERED QUERIES ON COLLECTION.

INDEXING

Indexing support efficient execution of queries in mongodb. Indexing Without


indexes mongodb has to scan every document in the collection. Indexes limits the
documents to be scanned. If index is created on a collection mongodb can use
indexes to directly locate the document that matches the query. If index is
present on any collection mongodb does index scan otherwise collection scan.
Index requires more storage space. It is efficient for intense read operation .
When more number of write and update operations are performed then it
becomes complex and time consuming to work with indexes.

Structure

· We can create index on any field in the document.

· Index is stored as a separate data structure in the sorted order.

· The address that is stored with the value work as a pointer to access
the document matching the query.

 TYPES OF INDEXES
 Default Index

Mongodb creates a unique index as the collection is created.

This index do not allows clients to insert duplicate values for index.

We cannot drop this index.

SM22CO004
Example:

_id:ObjectID(“123gh456m”)

 Single Value Index

This index is created on the single field of the collection. It is used to retrieve the
data in ascending and descending order.

Syntax:

db.<collection>.createIndex( { <field1>: <type>, <field2>: <type2>, … } )

Example:

db.Student.createIndex(“sid”:1);

 Compound Index:

Compound index does indexing on multiple field values store them in ascending
and descending order. the compound index will store the data of the field and
inside that it will store the data of another field, In other word compound index is
index where the single field value has multiple reference to the field . compound
index can have only one hashed single index . multiple hashed index will show
error.

Syntax:

db.<collection name>.createIndex({<field>:<type>,<field>:<type>});

Example:

db.students.createIndex({“Id”:1,”age”:-1}

 Multikey Index

SM22CO004
Multikey index index the value stored in the array. When we index a field that
hold an array then mongodb will attomatical creates the index for every value in
the array. It is used to easily locate the document in the collection where the
array value matches the specified value. In mongodb we donot need to explicitly
specify multikey value mongodb will atomatically determines whether to create
multikey index if index field contains a array value.

Syntax:

db.<collection name>.createIndex({<array>:<type>,<array>:<type>});

Example:

db.students.createIndex({“hobbies”:1})

 Text Index

MongoDB supports query operations that perform a text search of string content.
Text index allows us to find the string content in the specified collection. It can
include any field that contains string content or an array of string items. A
collection can contain at most one text index. We are allowed to use text index in
the compound index.

Syntax:

db.<collection name>.createIndex({<field>:”text”});

Example:

db.<collection name>.createIndex({“Name”:”text”});

Single Field Index:

SM22CO004
Compound Index :

Multikey Index :

SM22CO004
EXPERIMENT NO.4

AIM: HOST MONGODB ON CLOUD

MongoDB Atlas is a cloud-based service for managing MongoDB databases . It

provides an easy way to deploy, operate, and scale your MongoDB databases in

the cloud.

Here are some key features of MongoDB Atlas:

 Multi-cloud deployment: You can deploy your MongoDB Atlas clusters on

various cloud providers like Amazon Web Services (AWS), Google Cloud

Platform (GCP), and Microsoft Azure. This allows you to choose the cloud

provider that best suits your needs, whether you consider factors like cost,

existing infrastructure, or regional availability.

 Scalability: MongoDB Atlas can easily scale up or down to meet the

changing needs of your applications. Whether you're anticipating a sudden

influx of users or just need to adjust resources for ongoing maintenance,

Atlas can handle it.

 Security: MongoDB Atlas offers a variety of security features to protect

your data, including fine-grained access controls, encryption at rest and in

transit, and comprehensive auditing capabilities. You can define granular

permissions for users and roles, ensuring that only authorized users have

SM22CO004
access to specific data. Data encryption ensures that even if unauthorized

users manage to access your database, they will not be able to decrypt the

information. Auditing allows you to track all data access attempts,

providing valuable insights for security analysis.

 Ease of use: MongoDB Atlas is designed to be easy to use, even for those

who are new to MongoDB. It provides a web-based interface for managing

your clusters, as well as integrations with popular development tools. You

can create, monitor, and manage your MongoDB clusters through a user-

friendly interface that simplifies common database administration tasks.

Additionally, MongoDB Atlas integrates with popular development tools

and frameworks, streamlining the development process for MongoDB

applications.

If you're looking for a way to easily deploy and manage your MongoDB databases

in the cloud, MongoDB Atlas is a great option to consider. You can find more

information about MongoDB Atlas on the MongoDB website

Deploying mongodb on cloud

There are two main approaches to deploying MongoDB on cloud platforms:

 Using MongoDB Atlas:

 This is the simplest and most recommended approach for most users,

especially those new to MongoDB or cloud deployments.

SM22CO004
 MongoDB Atlas is a fully-managed Database-as-a-Service (DaaS) offered by

MongoDB itself

 With Atlas, MongoDB handles all the heavy lifting: provisioning,

configuration, scaling, security, and backups. You can focus on developing

your application.

Here's how to deploy MongoDB using Atlas:

 Sign up for a free MongoDB Atlas account: [invalid URL removed] offers a

free tier for development and testing purposes.

 Choose your cloud provider and region: Atlas is multi-cloud, so you can

pick the provider that best suits your needs (AWS, GCP, Azure).

 Configure your cluster: Define details like cluster name, instance size, and

authentication. Atlas offers a user-friendly interface to guide you through

this process.

 Connect your application: Once deployed, Atlas provides connection

details to integrate your application with the MongoDB database.

 2. Self-managed MongoDB on cloud providers:

 This approach offers greater control over the configuration and resources

but requires more technical expertise to manage.

 You'll be responsible for setting up, securing, scaling, and maintaining the

MongoDB instance on your chosen cloud platform (GCP, AWS, Azure).

SM22CO004
 Here's a general guideline for self-managed deployment (specific steps may

vary depending on the cloud provider):

 Choose your cloud provider: Select your preferred cloud platform (GCP,

AWS, Azure) and create an account.

 Provision a virtual machine (VM): Launch a VM instance with appropriate

specifications to run MongoDB.

 Install MongoDB: Download and install the latest MongoDB version on

your VM following the official documentation for your chosen cloud

provider.

 Configure MongoDB: Secure your MongoDB instance with access controls,

encryption, and firewalls as needed.

 Manage and maintain: Be responsible for backups, performance

optimization, and scaling your MongoDB instance as required.

Choosing the right approach:

 Go for MongoDB Atlas if: You prioritize ease of use, scalability, and built-in

security. It's ideal for development, testing, and even production use cases

for many applications.

 Consider self-managed MongoDB if: You need fine-grained control over

your database configuration or have existing infrastructure on a specific

SM22CO004
cloud provider and require more customization. However, be prepared to

invest time and resources in managing the database yourself.

 Remember, plenty of resources are available to help you with either

approach.

 MongoDB Atlas documentation: provides detailed guides and tutorials for

deploying and managing databases on Atlas.

 Cloud provider documentation: Each cloud platform (GCP, AWS, Azure)

offers extensive documentation on deploying and managing various

software, including MongoDB.

Output:

 Create a Mofigodb atlast accoufit

SM22CO004
 Create a fiew Cluster

 Cofifigure Cluster.

 Create database users

SM22CO004
Irfan123

Cofifiected created cluster with mofigoShell

SM22CO004
EXPERIMENT NO.10

AIM: EXECUTE COMMANDS TO CREATE DATABASE BACKUP


AND TO RESTORE DATA.

Mongodump is a command-line utility included with MongoDB that allows you to

create backups of your database in the form of binary BSON files. These backups

can then be restored using the companion mongorestore utility. Mongodump is a

versatile tool that can be used to backup various MongoDB deployments

including:

● Standalone server

● Replica sets

● Sharded clusters

Here are some key points about mongodump for backing up your MongoDB

database:

 Simple and Easy to Use: Mongodump offers a straightforward approach to

creating database backups. With a single command, you can dump your

entire database or specific collections into a BSON file.

 Flexible Control: Mongodump provides options to customize your backups.

You can choose to dump specific databases, collections, or exclude

unwanted data.

SM22CO004
 Portable Backups: The BSON files generated by mongodump are portable

and can be easily transferred to different systems for restoration.

Here are some resources to get you started with mongodump for backing up your

MongoDB database:

● Official Documentation: The official MongoDB documentation provides a

comprehensive guide on using mongodump, including various options and

functionalities.

● Simple Backups Guide: This guide offers a detailed explanation of

mongodump with examples, helping you understand the process effectively

Remember, while mongodump is a valuable tool for creating backups, it's

essential to have a robust backup strategy in place. This may involve

scheduling regular backups and storing them in a secure location.

Mongodump: Backing up your MongoDB Database

Mongodump is a command-line utility that comes with MongoDB and lets you

create backups of your database in a binary format called BSON. These backups

can be restored later using the mongorestore utility.

Here's a breakdown of what mongodump can do:

● Backup Types:

 Standalone Server: Back up a single MongoDB server.

SM22CO004
 Replica Sets: Backup data from a replica set deployment.

 Sharded Clusters: Create backups of sharded cluster deployments.

● Key Benefits:

 Simplicity: Easy to use with a single command for full or partial

backups.

 Flexibility: Choose specific databases, collections, or exclude data for

customized backups.

 Portability: BSON files are transferable between systems for

restoration.

Mongorestore:

Mongorestore is the counterpart to mongodump in the MongoDB world. It's a

command-line utility used to restore your database from backups created with

mongodump.

Here's what mongorestore does:

● Restores Backups: It takes BSON files generated by mongodump and

restores them into a running MongoDB instance (mongod or mongos).

● Flexibility: Similar to mongodump, mongorestore allows for selective

restoration of specific databases, collections, or data from the backup.

● Database Creation: If the target database doesn't exist, mongorestore can

create it during the restore process.

SM22CO004
Here's a quick guide to using mongorestore:

 Navigate: Open your terminal and use the cd command to navigate to the

directory containing your mongodump BSON files.

 Run mongorestore: Use the following syntax:

 mongorestore [options] [dump directory/file]

● Replace [options] with any specific restore options you might need (e.g.,

specifying database or collection).

● Replace [dump directory/file] with the path to your BSON dump file or

directory.

Here are some resources to learn more about mongorestore:

● Official Documentation: The official MongoDB documentation provides a

comprehensive guide on using mongorestore, including various options and

functionalities .

● Ultimate Mongorestore Guide: This guide offers a detailed explanation of

mongorestore with examples to help you understand the restore process

effectively .Remember, a successful restore depends on a compatible

mongodump backup. Make sure your mongodump and mongorestore

SM22CO004
versions are compatible with your MongoDB instance for a smooth

restoration process.

Output:

SM22CO004

You might also like