FSD 3 Unit
FSD 3 Unit
UNIT-III
MongoDB stores data using BSON (Binary JSON), which supports a variety of data types
beyond standard JSON. Here are some key MongoDB data types:
• String: Used for storing text data (UTF-8 format).
• Integer: Supports both 32-bit and 64-bit signed integers.
• Double: Stores floating-point numbers.
• Boolean: Represents true or false values.
• Null: Represents missing or undefined values.
• ObjectId: A unique identifier for documents.
• Date: Stores date and time values
Planning your data model in MongoDB is crucial for optimizing performance and
scalability. Since MongoDB is a document-oriented NoSQL database, its schema
design differs significantly from relational databases. Here are some key
considerations:
1. Understand Your Application's Workload
• Identify how your application queries and updates data.
• Optimize for read-heavy or write-heavy operations.
2. Choose Between Embedded vs. Normalized Data Models
• Embedded Model: Stores related data within a single document, improving
read performance but potentially increasing redundancy.
• Normalized Model: Uses references between documents, reducing duplication
but requiring additional queries.
3. Apply Schema Design Patterns
• Bucket Pattern: Groups related data into a single document to reduce query
overhead.
• Extended Reference Pattern: Stores frequently accessed data within a
document while keeping detailed data in separate collections.
4. Indexing for Performance
• Use indexes to speed up queries but avoid excessive indexing, which can
impact write performance.
5. Plan for Scalability
• Consider sharding strategies if your dataset grows significantly.
You can explore more details in the MongoDB documentation.
17
Full Stack Development (MERN)-CS631PE Department of CSE
db.createUser({
user: "adminUser",
pwd: "securePassword",
roles: [{ role: "userAdminAnyDatabase", db: "admin" }]
})
This creates an admin user with privileges to manage users across all databases.
2. Assigning Roles
MongoDB provides built-in roles such as:
• read: Allows read-only access.
• readWrite: Grants permission to read and write data.
• dbAdmin: Enables database administration tasks.
• userAdmin: Allows user management.
• clusterAdmin: Grants control over cluster-wide operations.
You can also create custom roles using db.createRole().
3. Listing Users
To view existing users in a database:
db.getUsers()
4. Updating User Credentials
To change a user's password:
db.changeUserPassword("adminUser", "newSecurePassword")
5. Deleting a User
To remove a user:
db.dropUser("adminUser")
Configuring access control in MongoDB ensures that only authorized users can interact with
the database. Here’s how you can set it up:
1. Enable Authentication
MongoDB requires authentication to restrict access. Start MongoDB with the --auth flag:
mongod --auth --port 27017 --dbpath /data/db
This ensures that users must authenticate before accessing the database.
2. Create an Admin User
Use the createUser() method to add an admin user:
use admin
db.createUser({
user: "adminUser",
pwd: "securePassword",
roles: [{ role: "userAdminAnyDatabase", db: "admin" }]
})
This user will have privileges to manage other users.
3. Assign Roles
MongoDB provides built-in roles such as:
• read: Allows reading data.
• readWrite: Allows reading and writing data.
• dbAdmin: Grants database administration privileges.
• userAdmin: Allows managing users.
You can also create custom roles using createRole().
18
Full Stack Development (MERN)-CS631PE Department of CSE
4. Configure IP Whitelisting
Restrict access to trusted IPs by modifying the mongod.conf file:
net:
bindIp: 127.0.0.1,192.168.1.100
This ensures only specified IPs can connect.
5. Use TLS/SSL for Secure Connections
Enable TLS/SSL encryption to protect data in transit:
mongod --sslMode requireSSL --sslPEMKeyFile /etc/ssl/mongodb.pem
Managing collections in MongoDB involves creating, updating, deleting, and querying data
efficiently. Here’s a breakdown:
1. Creating a Collection
MongoDB automatically creates collections when you insert data, but you can explicitly create
one using:
db.createCollection("users")
You can also specify options like validation rules.
2. Inserting Documents
Add a single document:
db.users.insertOne({ name: "Sai", age: 25 })
Insert multiple documents:
db.users.insertMany([{ name: "Kishore", age: 30 }, { name: "Aditi", age: 28 }])
3. Querying Data
Find all documents:
db.users.find({})
Find specific documents:
db.users.find({ age: { $gt: 25 } })
4. Updating Documents
Modify a single document:
db.users.updateOne({ name: "Sai" }, { $set: { age: 26 } })
Update multiple documents:
db.users.updateMany({}, { $inc: { age: 1 } })
5. Deleting Documents
Remove a single document:
db.users.deleteOne({ name: "Sai" })
Delete multiple documents:
db.users.deleteMany({ age: { $lt: 25 } })
6. Dropping a Collection
To delete an entire collection:
db.users.drop()
To connect Node.js to MongoDB, follow these steps:
1. Install the MongoDB Driver
Run the following command in your Node.js project:
npm install mongodb
This installs the official MongoDB Node.js driver.
19
Full Stack Development (MERN)-CS631PE Department of CSE
2. Connect to MongoDB
Create a connection using the MongoDB client:
const { MongoClient } = require("mongodb");
mongoose.connect("mongodb://localhost:27017/myDatabase", {
useNewUrlParser: true,
useUnifiedTopology: true,
}).then(() => console.log("Connected to MongoDB!"))
.catch(err => console.error("Connection error:", err));
Mongoose provides schema validation and easier data handling.
Understanding the Objects Used in the MongoDB Node.js Driver
The MongoDB Node.js driver provides several key objects to interact with MongoDB efficiently. Here
are the most important ones:
1. MongoClient
The MongoClient object is used to establish a connection to MongoDB.
const { MongoClient } = require("mongodb");
const client = new MongoClient("mongodb://localhost:27017");
It allows you to connect to a MongoDB instance and perform operations.
2. Db
The Db object represents a specific database within MongoDB.
const db = client.db("myDatabase");
You use this object to interact with collections and execute queries.
3. Collection
The Collection object represents a collection within a database.
const users = db.collection("users");
It provides methods for inserting, updating, deleting, and querying documents.
4. Cursor
A Cursor object is returned when querying data, allowing iteration over results.
const cursor = users.find({ age: { $gt: 25 } });
cursor.forEach(doc => console.log(doc));
20
Full Stack Development (MERN)-CS631PE Department of CSE
Manipulating Databases
• Create a new database: Just switch to it and insert data.
• use newDB
• db.myCollection.insertOne({ name: "Sai" })
• Drop a database:
• db.dropDatabase()
21