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

UNIT-III-MongoDB

NoSQL databases, such as MongoDB, are preferred for their scalability, flexible schema, and ability to handle unstructured data, making them ideal for applications with high data volumes and evolving data structures. MongoDB is a document-oriented NoSQL database that supports various data types, horizontal scalability, and high availability through replication. It is widely used in scenarios like content management, real-time analytics, and e-commerce due to its flexibility and ease of use.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

UNIT-III-MongoDB

NoSQL databases, such as MongoDB, are preferred for their scalability, flexible schema, and ability to handle unstructured data, making them ideal for applications with high data volumes and evolving data structures. MongoDB is a document-oriented NoSQL database that supports various data types, horizontal scalability, and high availability through replication. It is widely used in scenarios like content management, real-time analytics, and e-commerce due to its flexibility and ease of use.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 43

UNIT III

MongoDB
1. NEED OF NOSQL

NoSQL databases are needed for several reasons, particularly when traditional relational databases
(SQL) are not the best fit for certain use cases. Here are some of the key reasons why NoSQL databases
are preferred:

1. Scalability

 NoSQL databases are designed to scale out horizontally across many servers, unlike SQL
databases, which typically scale up vertically (adding more power to a single machine).
 This makes NoSQL ideal for handling large amounts of data and high-velocity workloads (like
social media feeds, sensor data, or IoT applications) that require massive scalability.

2. Flexible Schema

 NoSQL databases often allow schema-less or flexible schema designs, meaning you don't have to
define a rigid structure before inserting data. This is perfect for applications where data types or
structures evolve over time or where the data can vary.
 Examples: MongoDB uses documents (JSON-like structures), while Cassandra uses wide-column
stores.

3. Handling Unstructured Data

 SQL databases are typically designed to handle structured data with fixed schema, while NoSQL
databases are great for unstructured or semi-structured data. NoSQL can store documents, key-
value pairs, graphs, or columns of data that don’t conform to a rigid relational model.
 Examples: Media files, logs, user-generated content, and JSON-based data from APIs are often
stored in NoSQL databases.

4. High Availability and Fault Tolerance

 NoSQL systems are often designed to be fault-tolerant and ensure high availability by replicating
data across multiple nodes or data centers. This reduces the risk of downtime and ensures
continuous availability, even during network partitions or node failures.

5. Performance and Speed

 NoSQL databases can provide faster reads and writes in certain scenarios because they are
optimized for specific use cases, like fast retrieval of key-value pairs or document-based
searches, making them more efficient in some real-time applications.

6. Big Data and Analytics

For applications that need to process large amounts of unstructured or semi-structured data (e.g., big
data analytics, log management, recommendation engines), NoSQL databases can handle high-volume
and high-velocity data better than traditional SQL databases.
1
 Examples: Hadoop, Apache Cassandra, and MongoDB are often used in big data environments.

7. Agility in Development

 NoSQL databases support rapid development and deployment by allowing developers to work
with data that is not constrained by a predefined schema. They are also more accommodating
to evolving business needs, enabling faster iterations in software development.

8. Geo-Distributed Systems

 Many NoSQL databases are designed for distributed environments, making them ideal for
applications that span multiple geographical locations, like content delivery networks (CDNs),
global applications, and distributed caches.

Use Cases for NoSQL:

 Social Networks: Storing user profiles, posts, comments, and real-time interactions.
 Content Management Systems: Managing dynamic and unstructured data like images, videos,
and blog posts.
 E-Commerce: Handling product catalogs, user shopping carts, and large amounts of real-time
transactional data.
 IoT: Storing sensor data and telemetry in real time from a wide range of devices.

2. UNDERSTANDING MONGODB

MongoDB is one of the most popular NoSQL databases, specifically known for its flexibility, scalability,
and ease of use. Here's a breakdown of what MongoDB is and how it works:

1. Document-Oriented Database

 MongoDB is a document-oriented NoSQL database, meaning it stores data in documents


instead of rows and tables like traditional relational databases (SQL).
 These documents are stored in a format called BSON (Binary JSON), which is similar to JSON
(JavaScript Object Notation) but with added data types, such as Date or Binary.

Example of a MongoDB document:


{
"_id": ObjectId("60c72b2f5f1b2c3e8f0f5e1d"),
"name": "John Doe",
"email": "[email protected]",
"age": 29,
"address": {
"street": "123 Main St",
"city": "New York",
"zipcode": "10001"
}
}

2. Collections (Not Tables)

 In MongoDB, data is stored in collections. A collection is similar to a table in a relational


database, but unlike tables, collections do not require a fixed schema.
2
 Each collection can store documents that may have different fields, data types, or structures,
which makes it flexible and suitable for dynamic or evolving data.

3. No Fixed Schema

 One of the main benefits of MongoDB is its schema-less nature. This means you don't need to
define a fixed structure for the data in advance. Each document in a collection can have its own
structure.
 This flexibility is useful when the data model changes over time or when the data is not uniform.

4. Indexing

 MongoDB supports indexing, which helps to improve the speed of data retrieval. By default,
MongoDB creates an index on the _id field, but you can create custom indexes on other fields to
optimize queries.
 Indexing improves query performance, especially for large datasets.

5. Querying Data

 MongoDB uses a rich query language to retrieve and manipulate data. Queries can include
filtering, sorting, and aggregation.
 Example of a simple query:
 db.users.find({ "age": { "$gte": 18 } })

This retrieves all documents in the users collection where the age is greater than or equal to 18.

 MongoDB supports aggregation pipelines (a powerful tool to perform complex data


transformations and computations).

6. Horizontal Scalability (Sharding)

 MongoDB is designed to scale horizontally, meaning you can distribute data across multiple
servers. This is achieved using sharding, where data is partitioned into different chunks, and
each chunk is stored on a different server (called a shard).
 Sharding helps MongoDB handle very large datasets and high throughput by balancing the load
across many machines.

7. Replication for High Availability

 MongoDB supports replication, which ensures that copies of your data are stored across
multiple servers (replica sets). This helps with data availability, redundancy, and failover.
 A replica set is a group of MongoDB servers that maintain the same data set. One of the servers
acts as the primary node, while others are secondary nodes that replicate the data from the
primary.

8. Atomic Operations

 MongoDB provides atomic operations at the document level. This means that operations like
updating a single document, inserting, or deleting documents are done in an all-or-nothing
fashion, ensuring consistency.
 Multi-document transactions were introduced in MongoDB 4.0, allowing more complex
operations involving multiple documents or collections to be executed atomically.
3
9. Aggregation Framework

 MongoDB has a powerful aggregation framework for transforming, filtering, and analyzing data
in complex ways. It's similar to SQL GROUP BY or JOIN operations but more flexible.
 The aggregation pipeline allows you to perform operations like filtering ($match), grouping
($group), sorting ($sort), and projecting ($project) data.

Example:
db.orders.aggregate([
{ "$match": { "status": "completed" } },
{ "$group": { "_id": "$customerId", "totalSales": { "$sum": "$amount" } } },
{ "$sort": { "totalSales": -1 } }
])

10. Data Types

 MongoDB supports various data types such as strings, integers, arrays, objects, binary data, and
dates. These data types allow for a wide range of data to be stored within documents.
 Example of an array in MongoDB:
 {
 "_id": 1,
 "name": "John Doe",
 "hobbies": ["reading", "traveling", "coding"]
 }

11. Use Cases for MongoDB

 Content Management Systems: Ideal for managing blog posts, articles, media files, etc.
 Real-Time Analytics: MongoDB is suitable for storing time-series data or logs from sensors,
devices, or user activity.
 E-Commerce Platforms: MongoDB's flexible schema is useful for managing product catalogs,
customer data, and inventory.
 Mobile Applications: MongoDB can store user profiles, preferences, and activity logs in a way
that adapts to evolving data.

12. MongoDB Atlas (Managed Service)

 MongoDB Atlas is the fully-managed cloud service provided by MongoDB. It offers features like
automated backups, scaling, security, and performance monitoring without having to manage
the infrastructure yourself.
 It supports all MongoDB features while providing easy integration with cloud platforms like
AWS, Google Cloud, and Azure.

3. MONGODB DATATYPES

MongoDB supports a variety of data types to store different kinds of information in documents. These
data types are key to how MongoDB handles and stores data in a flexible and efficient manner. Here's a
detailed list of the most commonly used MongoDB data types:

1. String

 Description: Used to store text or string data.


4
 Example:
 { "name": "John Doe" }

2. Integer

 Description: Used to store whole numbers. In MongoDB, integers are typically stored as either
32-bit or 64-bit, depending on the system's architecture and the value.
 Example:
 { "age": 29 }

3. Double

 Description: Used to store floating-point numbers (i.e., numbers with decimal points).
 Example:
 { "price": 19.99 }

4. Boolean

 Description: Used to store true or false values.


 Example:
 { "isActive": true }

5. Null

 Description: Represents a null or missing value.


 Example:
 { "middleName": null }

6. Object (Embedded Document)

 Description: Used to store embedded documents, which are documents inside another
document. This allows for complex and nested data structures.
 Example:
 {
 "name": "John Doe",
 "address": {
 "street": "123 Main St",
 "city": "New York",
 "zipcode": "10001"
 }
 }

7. Array

 Description: Used to store a list of values or multiple items, which can be of any data type (e.g.,
strings, numbers, embedded documents).
 Example:
 { "tags": ["mongodb", "database", "nosql"] }

8. Binary Data

5
 Description: Used to store binary data, like images, audio, or files. This is typically represented
using the BinData type.
 Example:
 { "image": BinData(0, "iVBORw0KGgoAAAANSUhEUgAAAAUA") }

9. ObjectId

 Description: A special data type used to uniquely identify documents within a collection. Each
ObjectId is a 12-byte identifier that MongoDB automatically generates when a document is
inserted if no _id field is specified.
 Example:
 { "_id": ObjectId("60c72b2f5f1b2c3e8f0f5e1d") }

10. Date

 Description: Used to store Date and Time values. MongoDB uses the ISODate format, which is
essentially a wrapper around the JavaScript Date object.
 Example:
 { "createdAt": ISODate("2025-02-20T14:30:00Z") }

11. Regular Expression (RegEx)

 Description: Used to store regular expressions for pattern matching in queries. This is useful for
searching and filtering data based on patterns.
 Example:
 { "email": { "$regex": "^[email protected]$" } }

12. JavaScript

 Description: Used to store JavaScript code as a function. You can store JavaScript functions in
the database, but they are mostly used for internal MongoDB operations (like map-reduce).
 Example:
 { "code": new Code("function() { return this.name; }") }
13. Timestamp
 Description: Represents a timestamp value, commonly used for tracking document creation or
modification times. It’s a 64-bit value representing the seconds since the Unix epoch.
 Example:
 { "lastModified": Timestamp(1234567890, 1) }

14. MinKey and MaxKey

 Description: These are special types used to compare values that are lower (MinKey) or higher
(MaxKey) than any other value.
 Use Case: Used mainly in queries for special indexing operations.
 Example:
 { "value": MinKey }
 { "value": MaxKey }

Summary of Common MongoDB Data Types


Data Type Description Example
String Textual data. { "name": "John" }
Integer Whole numbers. { "age": 25 }
6
Data Type Description Example
Double Floating-point numbers. { "price": 19.99 }
Boolean True or False. { "isActive": true }
Null Represents null or missing values. { "middleName": null }
Embedded documents (objects within
Object { "address": { "city": "New York" } }
objects).
Array Lists or collections of values. { "tags": ["mongodb", "database"] }
Stores binary data, such as images or
Binary Data { "data": BinData(0, "imageData") }
files.
{ "_id":
ObjectId Unique identifier for documents.
ObjectId("5f8d0b0c9d93b2a7d7f04ef7") }
{ "createdAt": ISODate("2025-02-
Date Date and time values.
20T14:30:00Z") }
Regular expression for pattern
RegEx { "email": { "$regex": "^abc@" } }
matching.
{ "code": new Code("function() { return
JavaScript JavaScript code or functions.
1+1; }") }
Timestamp Unix timestamp value. { "lastLogin": Timestamp(1618542060, 1) }
Special markers for the lowest/highest
MinKey/MaxKey { "value": MinKey } or { "value": MaxKey }
possible value.

MongoDB's flexibility in data types enables you to work with a wide range of data formats and
structures, making it a powerful tool for modern, dynamic applications.

4. PLANNING USER DATA MODEL

When planning a user data model for an application, it's important to think about the kinds of data you
need to store, how that data relates to each other, and how it will scale over time. A well-designed user
data model ensures that your application can efficiently store, retrieve, and manipulate user
information, while also allowing for flexibility and scalability.

Below, I'll guide you through the steps and key considerations for planning a user data model, especially
with a database like MongoDB, which is schema-less and allows flexible data modeling.

1. Identify Key User Information

The first step is to define the key pieces of information you need to store about each user. This will vary
depending on your application, but some common fields include:

 Basic Information: Username, full name, email address, password (hashed), phone number, etc.
 Profile Information: Bio, profile picture, date of birth, gender, location, etc.
 Preferences/Settings: Language, theme (dark/light mode), notification settings, privacy settings.
 Activity Data: Last login date, registration date, activity history (posts, interactions).
 Security Information: Failed login attempts, account lock status, two-factor authentication
status.
 Social or Network Data: Friends, followers, following, groups, etc.
 Custom Fields: Any other data specific to your app (e.g., subscription status, role permissions,
etc.).

2. Design the Data Model with Relationships in Mind


7
Since MongoDB is a document-based database, you typically don't need to define strict relational
structures. However, you will still need to organize the data so that it makes sense and is efficient to
query.

In MongoDB, there are two main ways to model relationships between data:

 Embedding (Storing related data within the document).


 Referencing (Storing references to other documents, like foreign keys in SQL).

3. Decide on Embedding vs. Referencing

 Embedding: Use this when the related data is tightly bound to the user and isn't shared across
many documents. Embedding reduces the need for complex joins (which MongoDB doesn’t
support) and can improve performance for read-heavy applications.
o Example: If you store a user's posts or messages directly inside the user document, this
is embedding.
 Referencing: Use referencing when the data is large, frequently updated, or shared across many
users. This keeps the user document from growing too large.
o Example: If you have a friends list or roles (where a user can belong to multiple
groups/roles), you might store references to other documents (e.g., a list of ObjectIds
referencing the users collection).
4. Consider the Data Structure for the User Document
Here’s an example of how you could structure a User document in MongoDB:
{
"_id": ObjectId("60c72b2f5f1b2c3e8f0f5e1d"),
"username": "john_doe",
"email": "[email protected]",
"passwordHash": "hashed_password",
"fullName": "John Doe",
"bio": "Lorem ipsum...",
"profilePicture": "profilePicUrl",
"dateOfBirth": ISODate("1990-05-15T00:00:00Z"),
"location": {
"city": "New York",
"country": "USA"
},
"preferences": {
"language": "en",
"theme": "light",
"notifications": {
"email": true,
"sms": false
}
},
"social": {
"followers": [ObjectId("60c72b2f5f1b2c3e8f0f5e1e"), ObjectId("60c72b2f5f1b2c3e8f0f5e2f")],
"following": [ObjectId("60c72b2f5f1b2c3e8f0f5e3f")]
},
"security": {
"failedLoginAttempts": 3,
"isLocked": false,
"twoFactorEnabled": true

8
},
"activity": {
"lastLogin": ISODate("2025-02-20T14:30:00Z"),
"createdAt": ISODate("2025-01-01T00:00:00Z")
}
}

Breakdown:

 Basic Info: The user’s username, email, and fullName are stored as strings.
 Password: The password is stored in a hashed format for security.
 Profile Information: bio, profilePicture, and dateOfBirth are user-specific data.
 Location: The location object can store city and country.
 Preferences: Stores user-specific preferences like language, theme, and notification settings.
 Social: Stores references to other users (followers, following). These references can be ObjectIds
that link to other documents in the users collection.
 Security: Stores account-related security information such as failed login attempts, account lock
status, and two-factor authentication status.
 Activity: Tracks the last login time and the account creation date.

5. Design Indexes

 Indexes are crucial for optimizing query performance. MongoDB allows you to create indexes on
specific fields to make querying more efficient.
 Common fields to index for a user data model:
o username (for login or user search).
o email (for email-based login).
o followers, following (if you’re searching for users based on social relationships).
o lastLogin (to find recently active users or implement login analytics).

Example:
db.users.createIndex({ "username": 1 })
db.users.createIndex({ "email": 1 })

6. Scaling Considerations

MongoDB is designed to scale horizontally, so consider:

 Sharding: If you anticipate having millions of users, you can distribute user data across multiple
servers using sharding. One common approach is to shard by the user's _id or by using an
attribute like email or username (depending on your query patterns).
 Data Duplication vs. Normalization: MongoDB allows for some level of data duplication. For
instance, if the user's preferences are frequently queried, you might duplicate some of that data
in an easily accessible way.

7. Handling User Privacy and Security

 Ensure that sensitive data like passwords are hashed (never store plain-text passwords) using
libraries like bcrypt.
 Consider encrypting personal or sensitive data (e.g., email, phone number) at rest if needed.
 For security, track failed login attempts and implement account lock mechanisms to protect
against brute-force attacks.

9
Summary of Key Considerations:

 Embed vs Reference: Decide whether to embed data (e.g., posts or messages) or reference
other collections (e.g., friends, roles).
 Schema Design: MongoDB is schema-less but maintaining some structure with field consistency
is important.
 Indexes: Ensure critical fields like username or email are indexed for efficient querying.
 Scalability: Plan for sharding and horizontal scaling from the beginning if you expect the
application to grow significantly.
 Security: Implement best practices for password hashing, data encryption, and account
protection.

By following these guidelines and customizing them based on your application's specific needs, you'll be
able to build a solid and flexible user data model that scales well with MongoDB.

5. BUILDING MONGODB ENVIRONMENT

Building a MongoDB environment involves setting up MongoDB on your local machine or in a cloud
environment (like MongoDB Atlas). Here’s a step-by-step guide on how to build and set up a MongoDB
environment for development or production use:

1. Setting Up MongoDB Locally

If you're looking to set up MongoDB on your local machine for development or testing purposes, follow
these steps.

A. Install MongoDB on Your Local Machine

You can install MongoDB on your local machine using different methods depending on your operating
system. Here’s a guide for installing MongoDB on Windows, macOS, and Linux:

For Windows:

1. Download MongoDB:
o Go to the official MongoDB website: MongoDB Download Center.
o Download the latest MSI installer for MongoDB.

2. Run the Installer:


o After downloading, run the MSI installer and follow the prompts to install MongoDB.
o Choose "Complete" installation to install all the necessary components.

3. Configure MongoDB as a Service (Optional):


o During installation, you can configure MongoDB to run as a Windows service, so it starts
automatically when your system starts.

4. Start MongoDB:
o Once installed, you can run MongoDB using the mongod command in the terminal or
command prompt:
o mongod
 By default, MongoDB will run on port 27017.

10
5. Connect to MongoDB:
o In a new terminal window, open the MongoDB shell using:
o mongo
o This will connect you to the running MongoDB instance.

2. Setting Up MongoDB Atlas (Cloud Version)

If you prefer to use a cloud-based version of MongoDB for scalability and ease of use, MongoDB Atlas is
a fully-managed cloud service for MongoDB.

A. Create a MongoDB Atlas Account

1. Go to the MongoDB Atlas website and sign up for an account.

B. Create a Cluster

1. After signing up and logging in, click “Build a Cluster” to start the cluster creation process.
2. Choose a cloud provider (AWS, GCP, or Azure), and select a region closest to your users.
3. Choose the Cluster Tier (a free tier is available for small applications).
4. Configure any additional options (backups, etc.) if needed.
5. Click "Create Cluster" to provision the cluster.

C. Create a Database User

1. Go to the Database Access section under Security.


2. Click Add New Database User.
3. Create a username and password for your database user. This user will have access to the
database.

D. Connect to Your Cluster

1. After the cluster is created, click Connect.


2. Choose "Connect with MongoDB Compass" or "Connect with Mongo Shell". For a development
environment, Compass is a GUI tool that makes working with MongoDB easier.
3. You’ll be given a connection string. Copy this, and use it to connect to your database either
through MongoDB Compass or the Mongo shell.

3. Installing MongoDB Tools

For more efficient management of your MongoDB instance, you can install MongoDB tools:

 MongoDB Compass: A graphical user interface (GUI) that allows you to manage your MongoDB
data visually, inspect the structure, and perform queries.
o Download it from: MongoDB Compass.

 Mongo Shell: The MongoDB shell (mongo command) allows you to interact with MongoDB from
the command line, performing queries and administrative tasks.

 MongoDB Compass is especially useful if you prefer working with a GUI instead of command-
line interfaces for database interactions.

11
4. Interacting with MongoDB

Once MongoDB is running (either locally or in Atlas), you can interact with it using the MongoDB shell or
a client application like MongoDB Compass.

Using MongoDB Shell:

 After connecting to your instance, you can run basic operations like:
o Show Databases:
o show dbs
o Switch Database:
o use myDatabase
o Create/Insert Documents:
o db.users.insertOne({ name: "John Doe", email: "[email protected]" })
o Query Data:
o db.users.find({ name: "John Doe" })
o Update Data:
o db.users.updateOne({ name: "John Doe" }, { $set: { email:
"[email protected]" } })

Using MongoDB Compass:

1. Open MongoDB Compass and paste the connection string from MongoDB Atlas.
2. Once connected, you can:
o Visualize data in a graphical interface.
o Run queries using the built-in query editor.
o Insert, update, and delete documents directly from the interface.

5. Backup and Monitoring

 Backup: MongoDB Atlas provides automated backups for your database. You can configure your
backups and restore data from them if needed.
 Monitoring: MongoDB Atlas offers built-in performance monitoring and alerts. You can monitor
key metrics like CPU usage, memory, and disk I/O directly through the Atlas dashboard.

Summary of MongoDB Setup

1. Local Setup: Install MongoDB on your local machine (Windows, macOS, or Linux) and run
MongoDB as a service.
2. Cloud Setup (MongoDB Atlas): Create a MongoDB Atlas cluster for a fully-managed cloud
database solution with automatic backups, scaling, and monitoring.
3. MongoDB Tools: Install MongoDB Compass for GUI-based database management, or use the
Mongo shell for command-line interactions.
4. Interacting with MongoDB: Use MongoDB shell or Compass to insert, query, and manage data
in your MongoDB instance.

This setup gives you a fully functional MongoDB environment either locally or in the cloud, and you'll be
ready to start developing your application using MongoDB as your backend database.

ADMINISTERING USER ACCOUNTS


12
Administering user accounts in MongoDB involves managing users, their roles, and their permissions.
MongoDB has built-in mechanisms for creating, updating, and deleting users, as well as assigning them
roles that define what actions they can perform on the database.

Here’s a guide to administering user accounts in MongoDB, including user creation, role management,
and best practices for security.

1. Enabling Authentication

By default, MongoDB does not have authentication enabled. If you want to create and manage users
securely, you need to enable authentication.

To enable authentication in MongoDB:

1. Edit the mongod.conf file:


o Find the security section and set authorization to "enabled":
o security:
o authorization: "enabled"

2. Restart MongoDB: After modifying the configuration file, restart the MongoDB service:
o For Linux:
o sudosystemctl restart mongod
o For macOS (using Homebrew):
o brew services restart mongodb/brew/mongodb-community

3. Create the First Admin User: After enabling authentication, you must create an admin user
before you can create any other users. You can do this by connecting to MongoDB using the --
noauth option temporarily (so you don't need authentication yet):
4. mongod --noauth

Then, in the shell, create the first admin user:


use admin
db.createUser({
user: "admin",
pwd: "admin_password", // Ensure this is a strong password
roles: [{ role: "root", db: "admin" }]
})

5. Reconnect with Authentication: Once the admin user is created, reconnect to MongoDB with
authentication enabled:
6. mongo -u "admin" -p "admin_password" --authenticationDatabase "admin"

2. Creating and Managing Users

In MongoDB, user accounts are created and managed at the database level, and each user is assigned
roles that grant specific privileges.

A. Creating a User

You can create users with specific roles that allow them to perform different actions in MongoDB.

13
1. Create a Regular User: Here’s an example of creating a user who can read and write to a specific
database (e.g., mydb):
2. use mydb
3. db.createUser({
4. user: "username",
5. pwd: "user_password", // Strong password
6. roles: [{ role: "readWrite", db: "mydb" }]
7. })

8. Create an Admin User: An admin user can perform administrative actions, such as
creating/deleting databases and users:
9. use admin
10. db.createUser({
11. user: "admin_user",
12. pwd: "admin_password",
13. roles: [
14. { role: "dbAdmin", db: "mydb" },
15. { role: "userAdmin", db: "mydb" },
16. { role: "readWrite", db: "mydb" }
17. ]
18. })

B. Assigning Roles

MongoDB has built-in roles that provide different levels of access. Here are some common roles:

 readWrite: Grants the ability to read and write data in a specific database.
 dbAdmin: Grants administrative privileges within a database, such as creating and dropping
collections.
 userAdmin: Grants the ability to manage users and their roles within a database.
 read: Grants the ability to only read data from a specific database.
 root: A superuser role with full access to all databases and system operations (most powerful
role).
 You can assign multiple roles to a user. For example:
db.createUser({
user: "user1",
pwd: "password123",
roles: [
{ role: "readWrite", db: "mydb" },
{ role: "read", db: "otherdb" }
]
})

C. Built-in MongoDB Roles:

Here are some common built-in roles in MongoDB:

 root: Grants full access to all administrative actions.


 readWrite: Allows users to read and write in the specified database.
 dbAdmin: Allows users to manage a database's schema, collections, and indexes.
 userAdmin: Allows users to manage user roles for the specified database.
 clusterAdmin: Allows users to perform administrative actions at the cluster level, such as
managing sharding and replication.
14
You can see a full list of built-in roles and their privileges in MongoDB's official documentation.

3. Viewing Users and Roles

To list all users in the current database, use:


db.getUsers()

To list all users in the admin database (which includes the root user), use:
use admin
db.getUsers()

To view roles assigned to a specific user:


use admin
db.getUser("username")

4. Updating User Information

If you need to update a user’s password or roles, you can use the following commands.

1. Change a User’s Password:


2. db.updateUser("username", { pwd: "new_password" })

3. Add Roles to a User:


4. db.grantRolesToUser("username", [{ role: "dbAdmin", db: "mydb" }])

5. Remove Roles from a User:


6. db.revokeRolesFromUser("username", [{ role: "read", db: "mydb" }])

5. Deleting a User

To delete a user, you can use:


db.dropUser("username")

You can also delete users from the admin database to remove administrative users.

6. Best Practices for User Administration

1. Principle of Least Privilege:


o Always assign users the minimum required permissions they need to perform their job.
This reduces the risk of accidental or malicious data manipulation.

2. Strong Passwords:
o Ensure that users’ passwords are strong and complex. MongoDB supports password
hashing, so always store hashed passwords rather than plain text.

3. Role-Based Access Control (RBAC):


o Use MongoDB's Role-Based Access Control (RBAC) system to assign specific roles to
users rather than giving broad permissions.

4. Use a Root Account Sparingly:


o Avoid using the root role unless absolutely necessary. Create user-specific roles that
limit access to only what’s needed.
15
5. Monitor User Activity:
o Use MongoDB’s built-in auditing features (available in MongoDB Enterprise) to track
user activities for better security and compliance.

6. Avoid Hardcoding Credentials:


o Avoid hardcoding usernames and passwords into your application code. Use
environment variables or a secure credentials manager for storing sensitive information.

7. Regularly Review User Accounts:


o Periodically review user roles and permissions to ensure users still have the appropriate
access level for their tasks.

7. Setting Up External Authentication (Optional)

MongoDB also supports external authentication mechanisms such as:

 LDAP Authentication: MongoDB can integrate with LDAP (Lightweight Directory Access
Protocol) for centralized authentication management, allowing organizations to use existing
user directories for MongoDB authentication.

 X.509 Certificate Authentication: You can use X.509 certificates to authenticate users based on
SSL certificates instead of usernames and passwords.

To configure external authentication, you need to adjust the mongod.conf file and enable the relevant
authentication mechanism (e.g., ldap).

Administering user accounts in MongoDB involves several key tasks:

1. Enabling authentication for secure access.


2. Creating users and assigning them specific roles and permissions.
3. Managing users by updating, deleting, and reviewing their access.
4. Best practices such as using strong passwords, applying the principle of least privilege, and
regularly auditing user accounts.

By following these steps, you can maintain a secure and well-organized user account management
system for your MongoDB database.

CONFIGURING ACCESS CONTROL


Configuring access control in MongoDB involves setting up authentication, authorization, and role-based
access control (RBAC) to ensure that only authorized users can access and perform operations on the
database. This is critical for securing your MongoDB deployment.
Here's an overview of the steps involved in configuring access control:
1. Enable Authentication
MongoDB uses authentication to ensure that only authorized users can access the database. By default,
MongoDB does not require authentication (i.e., access is open to anyone), but enabling authentication is
essential for securing the system.
 Edit MongoDB Configuration File (mongod.conf): You need to enable authentication in the
MongoDB configuration file.
o Open the mongod.conf file (usually located in /etc/mongod.conf on Linux or C:\Program
Files\MongoDB\Server\<version>\bin\mongod.cfg on Windows).

16
o Under the security section, enable authentication by setting the authorization option to
enabled.
Example mongod.conf:
security:
authorization: "enabled"
 Restart MongoDB: After making changes to the configuration file, restart MongoDB to apply the
settings.
On Linux:
sudosystemctl restart mongod
On Windows, use the Services app or restart MongoDB via the command prompt.
2. Create an Admin User
After enabling authentication, you need to create an administrative user who can manage other users
and roles.
 Connect to MongoDB (without authentication, as the admin database is open by default):
 mongo
 Switch to the admin Database:
 use admin
 Create the Admin User: Create a user with the root role, which has full access to all databases
and operations.
 db.createUser({
 user: "admin",
 pwd: "admin_password",
 roles: [{ role: "root", db: "admin" }]
 });
 Exit the Mongo Shell:
 exit
After creating the admin user, you’ll need to authenticate as this user when performing further
administrative tasks.
3. Authenticate as the Admin User
Now that authentication is enabled, you must authenticate before performing any operations.
 Login with the Admin User:
 mongo -u admin -p --authenticationDatabase admin
You’ll be prompted to enter the admin password.
4. Create Other Users and Assign Roles
MongoDB uses Role-Based Access Control (RBAC) to define what actions users are allowed to perform.
A user is assigned one or more roles, which grant specific permissions.
 Switch to the Database: Create users in the database that they need access to (e.g.,
mydatabase).
 use mydatabase
 Create a User with Specific Roles: For example, you might create a user who can read and write
data in a specific database.
 db.createUser({
 user: "myuser",
 pwd: "mypassword",
 roles: [
 { role: "readWrite", db: "mydatabase" }

17
 ]
 });
In this example, the myuser has readWrite access to the mydatabase database, meaning they can insert,
update, and query data but cannot perform administrative operations like creating users or managing
indexes.
 Assigning Multiple Roles: You can assign multiple roles to a user. For instance, you may want a
user to have both readWrite and dbAdmin roles.
 db.createUser({
 user: "editor",
 pwd: "editor_password",
 roles: [
 { role: "readWrite", db: "mydatabase" },
 { role: "dbAdmin", db: "mydatabase" }
 ]
 });
5. Roles in MongoDB
MongoDB has a set of built-in roles that you can assign to users. Some of the commonly used roles are:
 Root: Full access to all resources.
 ReadWrite: Read and write access to the database.
 dbAdmin: Ability to manage indexes, validate data, and other administrative tasks on a specific
database.
 Read: Read-only access to the database.
 ClusterAdmin: Full control over the cluster.
 Backup: Allows backing up and restoring data.
You can also create custom roles with more specific permissions if needed.
6. Use Roles for Specific Access Control
MongoDB provides predefined roles to limit user permissions to specific actions. Here are some
examples of roles you might assign:
 read: Provides read-only access to a specific database.
 db.createUser({
 user: "readonlyUser",
 pwd: "readonlyPassword",
 roles: [
 { role: "read", db: "mydatabase" }
 ]
 });
 readWrite: Provides both read and write access to a specific database.
 db.createUser({
 user: "readwriteUser",
 pwd: "readwritePassword",
 roles: [
 { role: "readWrite", db: "mydatabase" }
 ]
 });
 dbAdmin: Allows the user to perform administrative tasks like creating indexes, running
validation, etc.
18
 db.createUser({
 user: "dbAdminUser",
 pwd: "dbAdminPassword",
 roles: [
 { role: "dbAdmin", db: "mydatabase" }
 ]
 });
7. Enable Auditing (Optional)
MongoDB provides auditing features to track actions taken by users. This can be useful for security and
compliance purposes.
 To enable auditing, edit the mongod.conf file and add the following configuration under the
auditLog section:
 auditLog:
 destination: file
 path: /var/log/mongodb/audit.log
 filter: "{ atype: { $in: [\"createUser\", \"dropUser\"] } }"
 This configuration logs certain actions (e.g., creating or dropping users) to a file. You can adjust
the filter to capture more specific events.
 Restart MongoDB to apply the changes:
 sudosystemctl restart mongod
8. Secure Connections with TLS/SSL
MongoDB can be configured to encrypt data in transit using TLS/SSL.
 Enable TLS/SSL in MongoDB:
o Edit the mongod.conf file to enable TLS/SSL and provide the necessary certificates.
 net:
 tls:
 mode: requireTLS
 certificateKeyFile: /path/to/your/certificate.pem
 CAFile: /path/to/your/CA.pem
o Restart MongoDB for the changes to take effect.
 Client Connection Over TLS/SSL: When connecting, specify the use of TLS/SSL.
 mongo --tls --tlsCertificateKeyFile /path/to/client/certificate.pem --tlsCAFile /path/to/CA.pem
9. Role-Based Access Control (RBAC) Overview
MongoDB’s RBAC system lets you define permissions at a granular level for different users. There are
two main components in RBAC:
 Roles: Define a set of permissions that determine what actions a user can perform.
 Privileges: Define specific actions (CRUD operations, index management, etc.) a user can
execute on specific resources (databases, collections, etc.).
MongoDB allows custom roles, which can be defined to tailor the permissions based on the use case.
10. Best Practices for Access Control
 Use the Principle of Least Privilege: Only give users the minimum permissions they need to
perform their tasks.
 Create Admin Roles Carefully: Limit the number of users with root access to ensure security.
 Audit and Monitor: Regularly audit user access and monitor logs for unusual activities.

19
 Enforce Strong Authentication: Use strong passwords for user accounts and consider using
more advanced authentication mechanisms like X.509 certificates or LDAP integration for larger
deployments.
Conclusion
Configuring access control in MongoDB involves enabling authentication, creating users, and assigning
roles to control who can access and modify data. MongoDB's role-based access control (RBAC) system
allows administrators to fine-tune permissions based on specific roles. It’s essential to enforce the
principle of least privilege and regularly review and audit user access to maintain the security of your
MongoDB deployment.

ADMINSTERING DATABASES
Administering MongoDB databases involves tasks related to managing and maintaining the database
system, ensuring its performance, security, availability, and data integrity. This includes installing and
configuring MongoDB, performing backups, monitoring performance, securing the system, handling
replication, sharding, and much more. Below is a comprehensive guide to key tasks involved in
administering MongoDB databases.
1. Installation and Setup
Before administering MongoDB, you need to install and configure it.
 Installing MongoDB: You can install MongoDB on various operating systems like Linux, macOS,
and Windows. You can also use containerized environments like Docker.
o For Ubuntu:
o sudo apt-get install -y mongodb
o For macOS using Homebrew:
o brew tap mongodb/brew
o brew install [email protected]
 MongoDB Configuration: The MongoDB configuration file (mongod.conf) allows you to
configure various settings:
o Set the bindIp to restrict which IP addresses MongoDB listens to.
o Configure authentication settings (authorization: "enabled") for security.
2. Database Management
Administering MongoDB databases requires regular tasks such as managing collections, databases, and
documents.
 Create and Drop Databases:
o Create a new database by simply switching to a new database.
o use mydatabase
o Drop a database:
o db.dropDatabase();
 Create and Drop Collections:
o Create a collection (MongoDB creates collections automatically when you insert data,
but you can manually create them as well).
o db.createCollection("mycollection");
o Drop a collection:
o db.mycollection.drop();
 Insert and Query Documents:
o Inserting documents into a collection:
o db.mycollection.insertOne({ name: "Alice", age: 30 });
20
o Query documents:
o db.mycollection.find({ name: "Alice" });
3. User Management and Access Control
Configuring proper authentication and authorization is crucial for securing MongoDB databases. You
can define users with specific roles that determine their access to data and operations.
 Create a User:
o Admin users are created in the admin database, and regular users can be created in the
specific databases they will interact with.
o db.createUser({
o user: "myuser",
o pwd: "password123",
o roles: [{ role: "readWrite", db: "mydatabase" }]
o });
 Grant and Revoke Roles: MongoDB has predefined roles like read, readWrite, dbAdmin, and
root that you can assign to users.
o Assign a role:
o db.grantRolesToUser("myuser", [{ role: "dbAdmin", db: "mydatabase" }]);
o Revoke a role:
o db.revokeRolesFromUser("myuser", [{ role: "dbAdmin", db: "mydatabase" }]);
4. Backups and Data Recovery
Backup and restore are critical to ensure data availability and disaster recovery.
 Backup: MongoDB provides tools like mongodump for creating backups of databases.
 mongodump --out /path/to/backup
 Restore: You can use mongorestore to restore the data from a backup.
 mongorestore /path/to/backup
 Backup Strategy: It is a good practice to automate backups and ensure they are stored securely,
either on-site or off-site (cloud storage, for example).
5. Monitoring and Performance Tuning
Proper monitoring is essential for ensuring that your MongoDB system is performing optimally.
 Monitoring Tools:
o MongoDB Atlas: A fully managed service that provides detailed metrics and dashboards
for monitoring your MongoDB instance.
o mongostat: A command-line tool that shows real-time statistics on the health of the
MongoDB server.
o mongostat
o mongotop: Displays the time spent on various collections and can help identify
performance bottlenecks.
o mongotop
 Performance Tuning:
o Indexes: Proper indexing can significantly speed up queries. MongoDB allows creating
indexes on fields that are frequently queried.
o db.mycollection.createIndex({ "name": 1 });
o Query Optimization: Use the explain() method to analyze query performance and
ensure queries are efficient.
o db.mycollection.find({ "name": "Alice" }).explain("executionStats");

21
o WiredTiger Cache: MongoDB’s default storage engine, WiredTiger, uses memory
efficiently. Ensure that your server has adequate memory resources to handle working
sets.
6. Replication and High Availability
Replication provides redundancy and increases data availability. In a MongoDB replica set, one node is
the primary, and others are secondaries that replicate the data from the primary.
 Setup Replica Set:
1. Start each mongod instance with the --replSet option.
2. Initiate the replica set:
3. rs.initiate();
 Add Members to Replica Set: After initiating, you can add secondary nodes to the replica set.
 rs.add("secondaryNode:27017");
 Automatic Failover: If the primary node fails, MongoDB will automatically promote a secondary
node to primary.
7. Sharding and Horizontal Scaling
Sharding is a method of distributing data across multiple machines to support horizontal scaling. This is
useful for very large datasets.
 Setup Sharding:
o You need at least three components for sharding: shards, config servers, and mongos
(the routing service).
o Enable Sharding:
o sh.enableSharding("mydatabase");
o Shard a Collection:
o sh.shardCollection("mydatabase.mycollection", { "user_id": 1 });
 Sharding Key: The choice of shard key affects performance and data distribution. It should be a
field that provides an even distribution of data.
8. Security Management
Securing MongoDB involves authentication, role-based access control (RBAC), and encryption.
 Authentication: Ensure that authentication is enabled, so that only authorized users can access
the database.
 security:
 authorization: "enabled"
 Role-Based Access Control (RBAC): Use RBAC to assign roles to users and control what actions
they can perform.
o For example, a user might have the readWrite role in a database:
o db.createUser({
o user: "user1",
o pwd: "password123",
o roles: [{ role: "readWrite", db: "mydatabase" }]
o });
 Encryption:
o Encryption in Transit: Use TLS/SSL to encrypt data transferred between clients and
servers.
o Encryption at Rest: Enable disk encryption for sensitive data stored on disk.
o security:
o enableEncryption: true
22
o encryptionKeyFile: /path/to/encryptionKeyFile
9. Log Management
MongoDB logs useful information about operations, errors, and performance. You should manage logs
effectively to monitor and troubleshoot the system.
 Log File Location: By default, MongoDB stores logs in /var/log/mongodb/mongod.log.
 Log Rotation: MongoDB can rotate logs automatically to prevent the log files from growing too
large. You can configure log rotation in the mongod.conf file.
 Audit Logs: MongoDB can be configured to keep an audit log that records actions taken by
users. This is important for security and compliance.
 auditLog:
 destination: file
 path: /var/log/mongodb/audit.log
10. Upgrades and Patches
Keeping MongoDB up to date is crucial for maintaining performance and security.
 Upgrade MongoDB: You can upgrade MongoDB using package managers (e.g., apt on Ubuntu,
brew on macOS) or manually by downloading and installing the latest version from MongoDB’s
website.
 Rolling Upgrade: MongoDB allows for rolling upgrades, meaning you can upgrade replica set
members one by one without taking the entire system down.
 sudo apt-get update &&sudo apt-get upgrade mongodb
Conclusion
Administering MongoDB databases involves various tasks to ensure performance, security, and data
availability. Proper setup, monitoring, backups, and maintenance, including features like replication and
sharding, are crucial for managing MongoDB in production environments. Additionally, effective security
management with roles and encryption, alongside keeping up with updates and performance
optimization, ensures that MongoDB remains a reliable and efficient database system for your
applications.

MANAGING COLLECTIONS
Managing collections in MongoDB is an essential aspect of working with the database. Collections in
MongoDB are analogous to tables in relational databases, and they are used to store documents
(records). Managing collections involves tasks such as creating, modifying, indexing, and managing data
storage and performance.
Here’s a comprehensive guide to managing MongoDB collections:
1. Creating Collections
MongoDB automatically creates collections when you insert data into them. However, you can also
explicitly create collections with specific configurations.
 Creating a Collection Explicitly: To create a collection explicitly, you use the createCollection()
method. This is useful if you want to specify options like validation rules, capped collections, or
size limits.
Example:
db.createCollection("mycollection");
o Capped Collections: A capped collection is a fixed-size collection that automatically
overwrites the oldest documents when it reaches its size limit.
o db.createCollection("myCappedCollection", {
o capped: true,
23
o size: 5242880, // 5 MB
o max: 1000 // Maximum number of documents
o });
o Collection Validation: You can apply validation rules when creating a collection.
o db.createCollection("validatedCollection", {
o validator: { $jsonSchema: { bsonType: "object", required: ["name", "age"], properties:
{ name: { bsonType: "string" }, age: { bsonType: "int" } } } }
o });
2. Listing Collections
You can list all the collections within a database using the getCollectionNames() method.
 List Collections:
 db.getCollectionNames();
This will return an array of collection names present in the current database.
3. Modifying Collections
While MongoDB does not allow you to modify the schema of a collection directly (since it's schema-
less), you can perform operations such as renaming a collection, dropping collections, or changing
collection options.
 Renaming a Collection: Use the renameCollection() method to rename an existing collection.
 db.mycollection.renameCollection("newCollectionName");
o Renaming Across Databases: MongoDB allows renaming collections across databases as
long as both the source and destination databases are in the same replica set.
o db.mycollection.renameCollection("newdb.newCollectionName");
 Dropping a Collection: If you no longer need a collection, you can drop it. Be cautious, as this
operation is irreversible.
 db.mycollection.drop();
4. Inserting Data into Collections
To add documents to a collection, use the insertOne() or insertMany() methods.
 Insert One Document:
 db.mycollection.insertOne({ name: "Alice", age: 30 });
 Insert Multiple Documents:
 db.mycollection.insertMany([
 { name: "Bob", age: 25 },
 { name: "Charlie", age: 35 }
 ]);
5. Querying Data in Collections
MongoDB provides a flexible query language that allows you to search for documents in a collection
based on various criteria.
 Basic Find Operation:
 db.mycollection.find({ name: "Alice" });
 Find with Projection: You can limit which fields are returned in the query results.
 db.mycollection.find({ name: "Alice" }, { age: 1 });
 Query with Condition:
 db.mycollection.find({ age: { $gte: 30 } });
 Count Documents: You can count the number of documents in a collection that match a query.
 db.mycollection.find({ age: { $gte: 30 } }).count();
6. Updating Data in Collections
24
MongoDB provides methods like updateOne(), updateMany(), and replaceOne() for updating
documents.
 Update One Document: Updates a single document that matches the query.
 db.mycollection.updateOne(
 { name: "Alice" },
 { $set: { age: 31 } }
 );
 Update Multiple Documents: Updates all documents that match the query.
 db.mycollection.updateMany(
 { age: { $gte: 30 } },
 { $set: { status: "senior" } }
 );
 Replace a Document: Replaces a document completely with a new one.
 db.mycollection.replaceOne(
 { name: "Alice" },
 { name: "Alice", age: 32 }
 );
7. Deleting Data from Collections
MongoDB allows you to delete documents from collections using deleteOne() or deleteMany().
 Delete One Document: Deletes the first document that matches the query.
 db.mycollection.deleteOne({ name: "Alice" });
 Delete Many Documents: Deletes all documents that match the query.
 db.mycollection.deleteMany({ age: { $gte: 30 } });
8. Indexing Collections
Indexes help improve query performance by providing efficient ways to look up documents. You can
create indexes on fields that are frequently queried.
 Create an Index: You can create indexes using the createIndex() method.
 db.mycollection.createIndex({ name: 1 }); // 1 for ascending order, -1 for descending
 List Indexes: To view the indexes on a collection:
 db.mycollection.getIndexes();
 Drop an Index: If an index is no longer needed, you can drop it.
 db.mycollection.dropIndex("indexName");
 Compound Index: MongoDB also allows you to create compound indexes (indexes on multiple
fields).
 db.mycollection.createIndex({ name: 1, age: -1 });
9. Managing Data Storage
MongoDB stores its data in files, and you can configure storage parameters to optimize data storage and
performance.
 Setting a Maximum Size for a Collection (Capped Collections): As mentioned earlier, capped
collections automatically overwrite old data when the size limit is reached. This can be used for
scenarios like logging or caching.
 db.createCollection("myLogCollection", {
 capped: true,
 size: 5242880, // 5 MB
 max: 1000 // Maximum of 1000 documents
 });

25
 Compact a Collection: MongoDB allows you to compact a collection to reclaim space that was
previously occupied by deleted or updated documents.
 db.runCommand({ compact: "mycollection" });
10. Using Aggregation with Collections
MongoDB provides a powerful aggregation framework to perform complex queries, including filtering,
grouping, and sorting data.
 Basic Aggregation: The aggregation framework uses the aggregate() method, and it's useful for
transforming and analyzing data.
Example of counting documents by a field:
db.mycollection.aggregate([
{ $group: { _id: "$age", count: { $sum: 1 } } }
]);
o Other Stages in Aggregation:
 $match: Filters documents.
 $group: Groups documents by a specified field.
 $sort: Sorts the results.
 $project: Modifies the shape of the documents.
11. Sharding Collections for Horizontal Scaling
If you are dealing with large datasets, you might need to shard your collection to distribute data across
multiple servers. Sharding improves scalability by allowing you to horizontally scale your database.
 Enable Sharding: To shard a database:
 sh.enableSharding("mydatabase");
 Shard a Collection: You need to choose a shard key (a field that will be used to distribute
documents across multiple shards).
 sh.shardCollection("mydatabase.mycollection", { "user_id": 1 });
Conclusion
Managing MongoDB collections involves various tasks such as creating, querying, updating, indexing,
and deleting data. Additionally, managing performance through indexing and storage management is
crucial for large datasets. MongoDB’s flexible schema and powerful aggregation framework make it
suitable for a variety of applications, while features like sharding allow it to scale horizontally to handle
growing datasets. By mastering these collection management operations, you can effectively work with
MongoDB to build high-performance, scalable applications.

ADDING MONGODB DRIVER TO NODE.JS


To interact with MongoDB from a Node.js application, you need to add the MongoDB driver to your
Node.js project. The MongoDB Node.js driver provides a way to connect, query, and perform operations
on a MongoDB database using JavaScript in a Node.js environment.
Here’s a step-by-step guide on how to add the MongoDB driver to your Node.js project:
Step 1: Initialize a Node.js Project
If you haven’t already created a Node.js project, you can start by initializing one.
1. Open your terminal/command prompt and navigate to your project directory.
2. Run the following command to create a package.json file:
3. npminit -y
This will generate a default package.json file for your project.
Step 2: Install the MongoDB Driver
You can install the MongoDB Node.js driver using npm (Node Package Manager).
26
 To install the MongoDB driver:
 npm install mongodb
This command will add the mongodb driver as a dependency in your project. You will see a
node_modules folder and an updated package.json file.
Step 3: Set Up MongoDB Connection in Your Node.js App
Now that the MongoDB driver is installed, you can use it to connect to a MongoDB server and perform
database operations.
Example Code: Connecting to MongoDB
Create a file (e.g., app.js) in your project directory and add the following code:
const{ MongoClient } = require("mongodb");

// MongoDB URI - Replace with your MongoDB connection string


consturi = "mongodb://localhost:27017"; // Replace with your MongoDB connection URI
constdbName = "mydatabase"; // Replace with the name of your database

// Create a new MongoClient


const client = new MongoClient(uri);

async function connectToDatabase() {


try {
// Connect to the MongoDB server
await client.connect();
console.log("Connected to MongoDB");

// Access the database


constdb = client.db(dbName);

// Example of performing an operation: Fetch collections


const collections = await db.listCollections().toArray();
console.log("Collections in the database:", collections);

} catch (error) {
console.error("Error connecting to MongoDB:", error);
} finally {
// Close the connection
await client.close();
}
}

// Run the function to connect to MongoDB


connectToDatabase();
Key Points:
 MongoClient: The MongoClient class is used to establish a connection to the MongoDB server.
 URI: The connection string (uri) is required to connect to MongoDB. This is usually
mongodb://localhost:27017 for local MongoDB instances. If you're using MongoDB Atlas (the
cloud service), you'll need to use the connection string provided by Atlas.
27
 dbName: This is the name of the database you want to work with.
 client.connect(): This method establishes the connection to MongoDB.
 client.db(dbName): Access a specific database.
 client.close(): Always close the connection when you're done to free resources.
Step 4: Perform CRUD Operations
You can perform Create, Read, Update, and Delete (CRUD) operations on your MongoDB collections
using the MongoDB driver.
Example CRUD Operations:
1. Insert Data (Create):
2. async function insertData() {
3. const collection = db.collection('users');
4. const result = await collection.insertOne({ name: "Alice", age: 25 });
5. console.log('Inserted document:', result.insertedId);
6. }
7. Query Data (Read):
8. async function findData() {
9. const collection = db.collection('users');
10. const user = await collection.findOne({ name: "Alice" });
11. console.log('User found:', user);
12. }
13. Update Data:
14. async function updateData() {
15. const collection = db.collection('users');
16. const result = await collection.updateOne(
17. { name: "Alice" },
18. { $set: { age: 26 } }
19. );
20. console.log('Updated document:', result.modifiedCount);
21. }
22. Delete Data:
23. async function deleteData() {
24. const collection = db.collection('users');
25. const result = await collection.deleteOne({ name: "Alice" });
26. console.log('Deleted document:', result.deletedCount);
27. }
Step 5: Run Your Node.js Application
To run your Node.js application, open your terminal and run the following command:
node app.js
This will execute your code, and you should see output based on your operations (e.g., connected to
MongoDB, inserted documents, or found documents).
Step 6: Handle Errors and Ensure Connections are Closed
Make sure to handle errors and always close the MongoDB connection after performing operations.
Using finally ensures that the connection is closed regardless of whether the operations succeed or fail.
Example with Full CRUD Implementation:
const{ MongoClient } = require("mongodb");

28
consturi = "mongodb://localhost:27017"; // Replace with your MongoDB connection URI
constdbName = "mydatabase"; // Replace with your database name

const client = new MongoClient(uri);

async function connectToDatabase() {


try {
// Connect to MongoDB server
await client.connect();
console.log("Connected to MongoDB");

// Get the database


constdb = client.db(dbName);

// Example of Create - Insert Data


constusersCollection = db.collection('users');
await usersCollection.insertOne({ name: "Alice", age: 25 });

// Example of Read - Find Data


const user = await usersCollection.findOne({ name: "Alice" });
console.log('Found user:', user);

// Example of Update - Update Data


await usersCollection.updateOne(
{ name: "Alice" },
{ $set: { age: 26 } }
);

// Example of Delete - Delete Data


await usersCollection.deleteOne({ name: "Alice" });

} catch (error) {
console.error("Error connecting to MongoDB:", error);
} finally {
// Close the MongoDB connection
await client.close();
}
}

connectToDatabase();
Conclusion:
By following the above steps, you can successfully connect your Node.js application to MongoDB using
the official MongoDB driver. You can then perform CRUD operations such as inserting, reading,
updating, and deleting documents in collections. MongoDB's flexible schema allows you to store and
manipulate your data easily in a variety of formats.

29
Be sure to use the async/await pattern for handling asynchronous operations, as it ensures your code is
clean and readable when dealing with MongoDB's operations.

CONNECTING TO MONGODB FROM NODE.JS


To connect to MongoDB from a Node.js application, you need to use the MongoDB Node.js driver,
which allows you to interact with a MongoDB database. Here's a step-by-step guide to connect to
MongoDB from Node.js:
Step 1: Install the MongoDB Node.js Driver
First, you need to install the official MongoDB Node.js driver to your project using npm (Node Package
Manager).
Run the following command in your project directory:
npm install mongodb
Step 2: Set Up MongoDB Connection in Node.js
Once you've installed the MongoDB driver, you can start setting up the connection to your MongoDB
instance.
1. Require the MongoDB DriverIn your Node.js application, you need to require the MongoDB
driver and the MongoClient class, which will help you connect to the MongoDB server.
2. Provide the MongoDB Connection URI MongoDB uses a URI to connect. The basic URI format is:
3. mongodb://<username>:<password>@<host>:<port>/<database>?options
For a local MongoDB server, the connection string typically looks like this:
consturi = "mongodb://localhost:27017";
If you're using MongoDB Atlas (the cloud-based MongoDB service), you'll get a URI from your Atlas
cluster, which looks like this:
consturi = "mongodb+srv://<username>:<password>@cluster0.mongodb.net/mydatabase?
retryWrites=true&w=majority";
Step 3: Connect to MongoDB from Node.js
Below is an example of how to connect to MongoDB and perform a simple operation (e.g., querying for
a collection):
// Import MongoDB Driver
const{ MongoClient } = require('mongodb');

// Connection URI (Replace with your MongoDB URI)


consturi = "mongodb://localhost:27017"; // For local MongoDB instance
// consturi = "mongodb+srv://<username>:<password>@cluster0.mongodb.net/mydatabase?
retryWrites=true&w=majority"; // For MongoDB Atlas

// Create a new MongoClient


const client = new MongoClient(uri);

// Define the database name


constdbName = "mydatabase"; // Replace with your database name

async function connectToDatabase() {


try {
// Connect to the MongoDB server
await client.connect();
30
console.log("Connected to MongoDB");

// Access the database


constdb = client.db(dbName);

// Example: List collections in the database


const collections = await db.listCollections().toArray();
console.log("Collections in the database:", collections);

// Example: Query a collection (let's assume 'users' collection exists)


constusersCollection = db.collection("users");
const user = await usersCollection.findOne({ name: "Alice" });
console.log("User found:", user);

} catch (error) {
console.error("Error connecting to MongoDB:", error);
} finally {
// Close the connection
await client.close();
console.log("Connection closed");
}
}

// Call the function to connect to MongoDB


connectToDatabase();
Explanation:
 MongoClient: The MongoClient class is used to manage the connection to MongoDB. It requires
the URI that specifies the MongoDB server location.
 client.connect(): This function establishes the connection to MongoDB.
 db.collection(): After connecting, you can access specific collections within your database by
calling db.collection().
 findOne(): This method is used to query a single document from a collection. You can replace it
with other query methods, such as find(), to retrieve multiple documents.
Step 4: Run the Node.js Application
To run the above code, save it in a file (e.g., app.js), and then run it using Node.js from the command
line:
node app.js
Example Output:
If MongoDB is running and the connection is successful, you should see output like this:
Connected to MongoDB
Collections in the database: [ { name: 'users' }, { name: 'orders' } ]
User found: { name: 'Alice', age: 30 }
Connection closed
Error Handling:
Make sure to handle errors correctly, especially when dealing with asynchronous code. Using try/catch
blocks ensures you can manage any issues like connection failures or query problems.
31
Step 5: Closing the Connection
After performing database operations, it's important to close the connection to MongoDB by calling
client.close() in the finally block. This ensures that the connection is closed properly even if an error
occurs.
Additional Considerations:
 Authentication: If you're connecting to a secure MongoDB instance (e.g., using MongoDB Atlas),
make sure to include your credentials in the connection URI.
Example:
consturi = "mongodb+srv://<username>:<password>@cluster0.mongodb.net/mydatabase?
retryWrites=true&w=majority";
 MongoDB Atlas: If you’re using MongoDB Atlas, remember to whitelist your IP address to allow
connections from your server or local environment.
 Environment Variables: For security, it's a good practice to store sensitive information like
database URIs or credentials in environment variables instead of hardcoding them in your code.
You can use dotenv for managing environment variables.
Example .env file:
MONGODB_URI=mongodb+srv://<username>:<password>@cluster0.mongodb.net/mydatabase?
retryWrites=true&w=majority
And in your code:
require('dotenv').config();
consturi = process.env.MONGODB_URI;
Conclusion:
Connecting to MongoDB from Node.js is straightforward using the MongoDB Node.js driver. By following
the above steps, you can establish a connection, perform database operations, and manage MongoDB
from your Node.js applications. Just make sure to handle errors, close connections properly, and
manage sensitive data securely.

UNDERSTANDING THE OBJECTS USED IN THE MONGODB NODEJS DRIVER


In MongoDB, when you interact with a database from Node.js using the MongoDB Node.js Driver,
several key objects and classes are used. These objects facilitate managing databases, collections, and
documents, as well as performing various CRUD (Create, Read, Update, Delete) operations.
Here’s a breakdown of the main objects used in the MongoDB Node.js Driver:
1. MongoClient
The MongoClient object is the main interface to connect to a MongoDB server or a cluster. It's used to
manage the connection to MongoDB and allows you to perform database operations.
 Usage: You use MongoClient to connect to the MongoDB server or a specific cluster (for
example, MongoDB Atlas).
 Example:
 const{ MongoClient } = require('mongodb');
 const client = new MongoClient('mongodb://localhost:27017');
 Connecting: To connect to the database, you use client.connect() and then access databases and
collections.
 await client.connect();
 constdb = client.db("mydatabase");
 Disconnecting: After performing the required operations, you close the connection using
client.close().
32
 await client.close();
2. Database (Db)
The Db object represents a MongoDB database. You can access a database from a connected client
instance using the client.db() method. The Db object provides methods to interact with collections, run
commands, and manage indexes and users.
 Accessing the database:
 constdb = client.db("mydatabase");
 Example Methods:
o db.collection(): Accesses a specific collection within the database.
o db.listCollections(): Lists all collections in the database.
o db.command(): Executes database commands.
o db.createCollection(): Explicitly creates a collection.
3. Collection (Collection)
The Collection object represents a single collection within a MongoDB database. You can access
collections via the db.collection() method.
 Example:
 constusersCollection = db.collection("users");
 Example Methods:
o collection.insertOne(), collection.insertMany(): Insert one or multiple documents into
the collection.
o collection.find(): Find documents in a collection.
o collection.updateOne(), collection.updateMany(): Update one or more documents.
o collection.deleteOne(), collection.deleteMany(): Delete documents.
4. Document
A document in MongoDB represents a record in a collection. It’s a JavaScript object (in the case of the
Node.js driver) that is used to store data in BSON format (Binary JSON). When you insert or retrieve data
from MongoDB, you're dealing with documents.
 Example Document:
 const user = {
 name: "Alice",
 age: 30,
 email: "[email protected]"
 };
 When inserting a document:
 await usersCollection.insertOne(user);
 MongoDB automatically generates an _id field for each document unless specified otherwise.
5. Cursor (Cursor)
A cursor in MongoDB is a pointer to the result set of a query. In the Node.js driver, when you run a
query (like find()), it returns a cursor object, which allows you to iterate over the results.
 Example:
 const cursor = usersCollection.find({ age: { $gte: 18 } });
 Methods:
o cursor.toArray(): Converts the result to an array.
o cursor.forEach(): Iterates over the result set, one document at a time.
o cursor.limit(): Limits the number of documents returned.
o cursor.sort(): Sorts the result set.
33
Example of using forEach():
cursor.forEach(doc => {
console.log(doc);
});
6. ObjectId
An ObjectId is a special type used for unique identifiers of documents. MongoDB automatically
generates an ObjectId for the _id field if no other value is provided. The ObjectId is 12 bytes in length
and is typically used for the _id field, but you can also use it as a general-purpose unique identifier.
 Usage:
 const{ ObjectId } = require('mongodb');
 constobjectId = new ObjectId();
 console.log(objectId);
 Example with ObjectId:
To query for a specific document by _id:
 const doc = await usersCollection.findOne({ _id: new
ObjectId("60d9f7db8e2b4d100c7fb03b") });
7. WriteResult
A WriteResult object is returned when performing write operations like insertOne(), updateOne(),
deleteOne(), etc. It provides information about the result of the write operation, such as the number of
documents matched or modified.
 Example:
 const result = await usersCollection.updateOne({ name: "Alice" }, { $set: { age: 31 } });
 console.log(result.modifiedCount); // Shows the number of documents modified
8. Aggregation (AggregationCursor)
MongoDB's aggregation framework processes data in stages and allows complex queries, such as
grouping, sorting, filtering, and transforming data. The AggregationCursor object is used when running
aggregation operations.
 Example:
 constaggregationCursor = usersCollection.aggregate([
 { $match: { age: { $gte: 18 } } },
 { $group: { _id: "$age", totalUsers: { $sum: 1 } } }
 ]);
 Methods:
o aggregationCursor.toArray(): Converts the aggregation results to an array.
o aggregationCursor.forEach(): Iterates over the aggregation results.
9. Index
Indexes are used to improve the performance of queries in MongoDB. The Index object represents an
index in a collection, and you can create, list, and drop indexes using the Node.js driver.
 Creating an Index:
 await usersCollection.createIndex({ age: 1 }); // Ascending index on 'age'
 Listing Indexes:
 const indexes = await usersCollection.indexes();
 console.log(indexes);
10. ChangeStream
A ChangeStream is an object that allows you to watch for real-time changes in your MongoDB
collections. It enables you to react to changes like inserts, updates, and deletes in a collection.
34
 Usage:
 constchangeStream = usersCollection.watch();
 changeStream.on("change", (change) => {
 console.log("Change detected:", change);
 });
11. DB Command (CommandResult)
You can execute commands directly on a database using db.command(). These commands can perform
administrative operations or interact with MongoDB features that aren't exposed through collections.
 Example:
 const result = await db.command({ ping: 1 });
 console.log(result); // Should print { ok: 1 }
12. Bulk Operations
MongoDB allows you to perform multiple write operations in bulk using the BulkWrite object. This is
particularly useful for updating or inserting many documents in a single operation.
 Example:
 constbulkOps = [
 { insertOne: { document: { name: "Bob", age: 25 } } },
 { updateOne: { filter: { name: "Alice" }, update: { $set: { age: 32 } } } }
 ];

 const result = await usersCollection.bulkWrite(bulkOps);
 console.log(result);
Summary of Key Objects in MongoDB Node.js Driver
Object Purpose
MongoClient Connects to MongoDB server or cluster.
Db Represents a MongoDB database.
Collection Represents a MongoDB collection within a database.
Document A record in a collection (a BSON object).
Cursor Allows iteration over query results.
ObjectId A unique identifier for documents.
WriteResult Provides result details for write operations.
AggregationCursor Returns results from aggregation operations.
Index Represents and manages indexes within collections.
ChangeStream Watches for changes in a collection in real-time.
CommandResult Represents the result of a database command.
BulkWrite Allows bulk write operations (inserts, updates, deletes).
These objects and methods form the core of the MongoDB Node.js driver, enabling you to connect to
MongoDB, perform operations on databases and collections, and interact with your data in a highly
flexible and efficient manner.

ACCESSING AND MANIPULATING DATABASES


In MongoDB, accessing and manipulating databases is a core part of working with data. Using the
MongoDB Node.js Driver, you can easily connect to a MongoDB instance, select databases, perform
CRUD operations, and execute complex queries.

35
Below, we’ll break down the key steps involved in accessing and manipulating databases in MongoDB
using Node.js.
1. Installing MongoDB Node.js Driver
Before you start working with MongoDB, you need to install the MongoDB driver for Node.js. You can do
this using npm:
npm install mongodb
2. Connecting to MongoDB
To access a MongoDB database, you need to first connect to a MongoDB server using the MongoClient
object. Once connected, you can access the database and manipulate it.
Example: Connecting to MongoDB
const{ MongoClient } = require('mongodb');

consturl = 'mongodb://localhost:27017'; // MongoDB URI


constdbName = 'mydatabase'; // Database name

async function connectToDatabase() {


const client = new MongoClient(url);
try {
await client.connect(); // Establish the connection to MongoDB server
console.log('Connected to MongoDB');

constdb = client.db(dbName); // Access the 'mydatabase' database


return db;
} catch (error) {
console.error('Error connecting to MongoDB:', error);
}
}

connectToDatabase();
 MongoClient(url): Creates a client instance to connect to the MongoDB server. The url
parameter can also point to a MongoDB Atlas cluster if using a cloud database.
 client.connect(): Establishes a connection to MongoDB.
 client.db(dbName): Accesses the database with the given name (mydatabase in this case).
3. Selecting a Database
Once connected, you can select the database you want to work with. If the database does not exist,
MongoDB will create it once you insert data.
Example: Accessing a Database
constdb = client.db('mydatabase'); // Access a database
You can perform operations like finding collections, creating collections, and running commands once
you have a reference to the database.
4. Working with Collections
Collections in MongoDB are like tables in relational databases. They store documents (records), and you
interact with them to perform operations.
Accessing a Collection
const collection = db.collection('users'); // Access the 'users' collection
5. Inserting Documents
36
You can insert one or more documents into a collection. MongoDB will automatically create the
collection if it doesn't exist.
Example: Inserting a Single Document
async function insertDocument() {
constnewUser = {
name: 'Alice',
age: 28,
email: '[email protected]'
};

const result = await collection.insertOne(newUser); // Insert a single document


console.log(`New document inserted with _id: ${result.insertedId}`);
}

insertDocument();
Example: Inserting Multiple Documents
async function insertMultipleDocuments() {
const users = [
{ name: 'Bob', age: 30, email: '[email protected]' },
{ name: 'Charlie', age: 35, email: '[email protected]' }
];

const result = await collection.insertMany(users); // Insert multiple documents


console.log(`${result.insertedCount} documents inserted`);
}

insertMultipleDocuments();
6. Querying Documents
Once you've inserted data, you can retrieve it by querying the collection. The find() method is commonly
used to search for documents that match specific criteria.
Example: Querying Documents
async function findUsers() {
const users = await collection.find({ age: { $gte: 18 } }).toArray(); // Find users age >= 18
console.log(users); // Logs all the users that meet the criteria
}

findUsers();
 find(): Returns a cursor to iterate over the documents that match the query.
 toArray(): Converts the cursor to an array of documents.
Example: Finding a Single Document
async function findOneUser() {
const user = await collection.findOne({ name: 'Alice' }); // Find a document by name
console.log(user); // Logs the user object
}

findOneUser();
37
7. Updating Documents
You can update existing documents using the updateOne() or updateMany() methods, which update one
or more documents that match the filter.
Example: Updating a Single Document
async function updateUser() {
const result = await collection.updateOne(
{ name: 'Alice' }, // Find the document with name 'Alice'
{ $set: { age: 29 } } // Set the new value for the 'age' field
);

console.log(`${result.modifiedCount} document(s) updated`);


}

updateUser();
 $set: Used to set the value of a field (or fields).
 updateOne(): Updates a single document that matches the query.
Example: Updating Multiple Documents
async function updateMultipleUsers() {
const result = await collection.updateMany(
{ age: { $gte: 30 } }, // Find users age >= 30
{ $set: { status: 'senior' } } // Set status field to 'senior'
);

console.log(`${result.modifiedCount} document(s) updated`);


}

updateMultipleUsers();
8. Deleting Documents
You can delete documents using deleteOne() or deleteMany().
Example: Deleting a Single Document
async function deleteUser() {
const result = await collection.deleteOne({ name: 'Alice' }); // Delete the document with name 'Alice'
console.log(`${result.deletedCount} document(s) deleted`);
}

deleteUser();
Example: Deleting Multiple Documents
async function deleteMultipleUsers() {
const result = await collection.deleteMany({ age: { $lt: 18 } }); // Delete users under 18
console.log(`${result.deletedCount} document(s) deleted`);
}

deleteMultipleUsers();
9. Creating Indexes
To improve the performance of frequent queries, you can create indexes on one or more fields in a
collection.
38
Example: Creating an Index
async function createIndex() {
const result = await collection.createIndex({ age: 1 }); // Create an index on the 'age' field (ascending)
console.log(`Index created: ${result}`);
}

createIndex();
10. Aggregation
MongoDB provides an aggregation framework that allows you to perform complex data transformations
and analyses. You can use the aggregate() method to process data in stages.
Example: Aggregation Pipeline
async function aggregateUsers() {
const pipeline = [
{ $match: { age: { $gte: 18 } } }, // Filter users age >= 18
{ $group: { _id: '$age', count: { $sum: 1 } } }, // Group by 'age' and count the number of users
{ $sort: { _id: 1 } } // Sort by age (ascending)
];

const result = await collection.aggregate(pipeline).toArray();


console.log(result); // Logs the aggregation result
}

aggregateUsers();
11. Closing the Connection
After completing the operations, you should close the MongoDB connection to free resources.
Example: Closing the Connection
async function closeConnection() {
await client.close(); // Close the connection
console.log('MongoDB connection closed');
}

closeConnection();
Summary of Key Operations
Operation Method(s) Example Usage
Connecting to DB MongoClient.connect() client.connect()
Selecting Database client.db(dbName) db = client.db('mydatabase')
Accessing Collection db.collection(collectionName) const users = db.collection('users')
Inserting Documents insertOne(), insertMany() collection.insertOne({ name: 'Alice' })
Querying Documents find(), findOne() collection.find({ age: { $gte: 18 } })
Updating Documents updateOne(), updateMany() collection.updateOne({ name: 'Alice' }, {...})
Deleting Documents deleteOne(), deleteMany() collection.deleteOne({ name: 'Alice' })
Creating Indexes createIndex() collection.createIndex({ age: 1 })
Aggregation aggregate() collection.aggregate([...])
By using these operations, you can easily access, manipulate, and query data in a MongoDB database
with Node.js.

39
ACCESSING AND MANIPULATING DATABASES
In MongoDB, accessing and manipulating databases involves connecting to the database, interacting
with collections (equivalent to tables in relational databases), and performing various CRUD (Create,
Read, Update, Delete) operations. With the MongoDB Node.js Driver, you can perform these tasks
efficiently.
1. Setting Up MongoDB Node.js Driver
Before you start working with databases, you need to install the MongoDB Node.js driver if you haven't
done so already.
npm install mongodb
2. Connecting to MongoDB
You need to connect to your MongoDB instance (local or cloud) using the MongoClient from the
MongoDB driver.
Example: Connecting to MongoDB
const{ MongoClient } = require('mongodb');

consturl = 'mongodb://localhost:27017'; // MongoDB URI (local MongoDB instance)


constdbName = 'mydatabase'; // Database name

async function connectToDatabase() {


const client = new MongoClient(url, { useUnifiedTopology: true });
try {
await client.connect(); // Establish the connection
console.log('Connected to MongoDB');

constdb = client.db(dbName); // Access the database


return db;
} catch (error) {
console.error('Error connecting to MongoDB:', error);
}
}

connectToDatabase();
3. Selecting a Database
Once connected to MongoDB, you can select a database using client.db(dbName).
 If the database doesn’t exist: MongoDB will create it when you insert data.
constdb = client.db('mydatabase'); // Select the database
4. Accessing a Collection
In MongoDB, data is stored in collections, which are analogous to tables in relational databases. To
interact with a collection, use db.collection(collectionName).
const collection = db.collection('users'); // Access the 'users' collection
5. Inserting Data (Documents)
MongoDB stores data as documents, which are JSON-like objects. You can insert documents into a
collection using the insertOne() or insertMany() methods.
Example: Inserting One Document
async function insertDocument() {
40
const user = {
name: 'Alice',
age: 25,
email: '[email protected]'
};

const result = await collection.insertOne(user); // Insert a single document


console.log(`New document inserted with _id: ${result.insertedId}`);
}

insertDocument();
Example: Inserting Multiple Documents
async function insertMultipleDocuments() {
const users = [
{ name: 'Bob', age: 30, email: '[email protected]' },
{ name: 'Charlie', age: 35, email: '[email protected]' }
];

const result = await collection.insertMany(users); // Insert multiple documents


console.log(`${result.insertedCount} documents inserted`);
}

insertMultipleDocuments();
6. Querying Data (Finding Documents)
To retrieve documents, use the find() method. It returns a cursor, which you can iterate over to access
the results.
Example: Querying All Documents
async function findUsers() {
const users = await collection.find().toArray(); // Find all documents
console.log(users); // Print the result
}

findUsers();
Example: Querying with a Filter
async function findUserByName() {
const user = await collection.findOne({ name: 'Alice' }); // Find a single document by name
console.log(user); // Print the user document
}

findUserByName();
You can also use filters in find() to narrow down the results:
const users = await collection.find({ age: { $gte: 30 } }).toArray(); // Find users with age >= 30
7. Updating Data
MongoDB provides updateOne() and updateMany() methods to update documents. These methods
allow you to set new values or modify existing ones.
Example: Updating One Document
41
async function updateUser() {
const result = await collection.updateOne(
{ name: 'Alice' }, // Filter: Find user by name
{ $set: { age: 26 } } // Update the 'age' field
);

console.log(`${result.modifiedCount} document(s) updated`);


}

updateUser();
Example: Updating Multiple Documents
async function updateMultipleUsers() {
const result = await collection.updateMany(
{ age: { $gte: 30 } }, // Filter: Find users with age >= 30
{ $set: { status: 'senior' } } // Set the 'status' field to 'senior'
);

console.log(`${result.modifiedCount} document(s) updated`);


}

updateMultipleUsers();
8. Deleting Data
To delete documents from a collection, use the deleteOne() or deleteMany() methods.
Example: Deleting One Document
async function deleteUser() {
const result = await collection.deleteOne({ name: 'Alice' }); // Delete the document with name 'Alice'
console.log(`${result.deletedCount} document(s) deleted`);
}

deleteUser();
Example: Deleting Multiple Documents
async function deleteMultipleUsers() {
const result = await collection.deleteMany({ age: { $lt: 18 } }); // Delete users with age < 18
console.log(`${result.deletedCount} document(s) deleted`);
}

deleteMultipleUsers();
9. Creating Indexes
Indexes improve the performance of queries. You can create indexes on specific fields in a collection
using createIndex().
Example: Creating an Index
async function createIndex() {
const result = await collection.createIndex({ age: 1 }); // Create an ascending index on the 'age' field
console.log(`Index created: ${result}`);
}

42
createIndex();
10. Aggregation
MongoDB’s aggregation framework allows for more complex queries, including grouping, filtering, and
transforming data.
Example: Aggregating Data
async function aggregateUsers() {
const pipeline = [
{ $match: { age: { $gte: 18 } } }, // Filter users aged >= 18
{ $group: { _id: "$age", totalUsers: { $sum: 1 } } }, // Group by age and count users
{ $sort: { _id: 1 } } // Sort by age (ascending)
];

const result = await collection.aggregate(pipeline).toArray();


console.log(result); // Print aggregation result
}

aggregateUsers();
11. Closing the Connection
After completing your database operations, always close the connection to MongoDB to free up
resources.
Example: Closing the Connection
async function closeConnection() {
await client.close(); // Close the MongoDB connection
console.log('MongoDB connection closed');
}

closeConnection();
Summary of Common Operations
Operation Method(s) Example
Connecting to
MongoClient.connect() client.connect()
MongoDB
Selecting Database client.db() constdb = client.db('mydatabase')
Accessing Collection db.collection() const collection = db.collection('users')
Inserting Documents insertOne(), insertMany() collection.insertOne({ name: 'Alice' })
Querying Documents find(), findOne() collection.find({ age: { $gte: 18 } })
updateOne(), collection.updateOne({ name: 'Alice' }, { $set: { age:
Updating Documents
updateMany() 26 } })
Deleting Documents deleteOne(), deleteMany() collection.deleteOne({ name: 'Alice' })
Creating Indexes createIndex() collection.createIndex({ age: 1 })
Aggregation aggregate() collection.aggregate([{ $match: { age: { $gte: 18 } } }])
These are the fundamental operations for accessing and manipulating MongoDB databases using
Node.js. With this, you can efficiently handle CRUD operations and work with complex data queries in
MongoDB.

43

You might also like