UNIT-III-MongoDB
UNIT-III-MongoDB
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.
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.
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.
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.
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.
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
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 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.
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 } }
])
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"]
}
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.
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
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
5. Null
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") }
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) }
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 }
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.
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.
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.).
In MongoDB, there are two main ways to model relationships between data:
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
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.
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.
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:
If you're looking to set up MongoDB on your local machine for development or testing purposes, follow
these steps.
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.
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.
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.
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.
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.
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]" } })
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.
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.
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.
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.
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
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"
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" }
]
})
To list all users in the admin database (which includes the root user), use:
use admin
db.getUsers()
If you need to update a user’s password or roles, you can use the following commands.
5. Deleting a User
You can also delete users from the admin database to remove administrative users.
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.
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).
By following these steps, you can maintain a secure and well-organized user account management
system for your MongoDB database.
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.
} catch (error) {
console.error("Error connecting to MongoDB:", error);
} finally {
// Close the connection
await client.close();
}
}
28
consturi = "mongodb://localhost:27017"; // Replace with your MongoDB connection URI
constdbName = "mydatabase"; // Replace with your database name
} 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.
} catch (error) {
console.error("Error connecting to MongoDB:", error);
} finally {
// Close the connection
await client.close();
console.log("Connection closed");
}
}
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');
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]'
};
insertDocument();
Example: Inserting Multiple Documents
async function insertMultipleDocuments() {
const users = [
{ name: 'Bob', age: 30, email: '[email protected]' },
{ name: 'Charlie', age: 35, email: '[email protected]' }
];
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
);
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'
);
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)
];
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');
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]'
};
insertDocument();
Example: Inserting Multiple Documents
async function insertMultipleDocuments() {
const users = [
{ name: 'Bob', age: 30, email: '[email protected]' },
{ name: 'Charlie', age: 35, email: '[email protected]' }
];
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
);
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'
);
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)
];
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