0% found this document useful (0 votes)
0 views5 pages

FSD 3 Unit

The document provides an overview of MongoDB data types, data modeling, user account administration, and database management. It covers key concepts such as BSON data types, schema design, user roles, and methods for creating, updating, and querying collections. Additionally, it includes instructions for connecting Node.js to MongoDB and using the MongoDB Node.js driver effectively.

Uploaded by

s.rajeshgoud2223
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views5 pages

FSD 3 Unit

The document provides an overview of MongoDB data types, data modeling, user account administration, and database management. It covers key concepts such as BSON data types, schema design, user roles, and methods for creating, updating, and querying collections. Additionally, it includes instructions for connecting Node.js to MongoDB and using the MongoDB Node.js driver effectively.

Uploaded by

s.rajeshgoud2223
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Full Stack Development (MERN)-CS631PE Department of CSE

UNIT-III

MongoDB Data Types:

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

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.

Administering User Accounts in mongo db

Administering user accounts in MongoDB involves managing authentication, roles, and


permissions to ensure secure access control. Here are the key steps:
1. Creating a User
MongoDB allows you to create users with specific roles using the db.createUser()
method:

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");

const uri = "mongodb://localhost:27017";


const client = new MongoClient(uri);

async function connectDB() {


try {
await client.connect();
console.log("Connected to MongoDB!");
} catch (error) {
console.error("Connection failed:", error);
}
}
connectDB();
This establishes a connection to a local MongoDB instance.
3. Using Mongoose (Optional)
Mongoose simplifies MongoDB interactions. Install it using:
npm install mongoose
Then, connect using:
const mongoose = require("mongoose");

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

It helps efficiently process large datasets.


5. ObjectId
The ObjectId is a unique identifier for MongoDB documents.
const { ObjectId } = require("mongodb");
const id = new ObjectId();
console.log(id);
It ensures uniqueness across collections.

Accessing and manipulating databases in MongoDB is straightforward and powerful. Here's a


practical breakdown to get you rolling:
Accessing Databases
• Switch to a database (or create one if it doesn’t exist yet):
• use myDatabase
MongoDB creates the database only when you insert data into it.
• List all databases:
• show dbs
• Check current database:
• db

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

Working with Collections


Create a collection:
db.createCollection("users")
Insert documents:
db.users.insertOne({ name: "Kishore", age: 25 })
Query documents:
db.users.find({ age: { $gt: 20 } })
Update documents:
db.users.updateOne({ name: "Kishore" }, { $set: { age: 26 } })
Delete documents:
db.users.deleteOne({ name: "Kishore" })
Drop a collection:
db.users.drop()

21

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy