Unit 2 (MongoDB)
Unit 2 (MongoDB)
1. Download MongoDB
1. Visit the MongoDB Community Edition Download Page.
2. Select the appropriate version for Windows and download the .msi installer.
2. Install MongoDB
1. Run the Installer:
Double-click the downloaded .msi file to launch the setup wizard.
2. Choose Setup Type:
Select "Complete" to install all features, including the MongoDB
server and tools like mongosh.
3. Service Configuration:
Choose to run MongoDB as a Windows service (recommended).
Specify the data directory (default is C:\Program
Files\MongoDB\Server\<version>\bin).
4. Install Compass (Optional):
During installation, you can opt to install MongoDB Compass, a
graphical interface for MongoDB.
5. Complete the Installation:
Click "Install" to proceed. After the installation is complete, MongoDB
will be available on your system.
3. Configure MongoDB
Create Data and Log Directories
MongoDB requires specific directories to store data and logs:
1. Open File Explorer and create the following directories:
Data Directory: C:\data\db
Log Directory: C:\data\log
Create a Log File
1. Create an empty file mongod.log in C:\data\log.
4. Start MongoDB
Option 1: Using Command Prompt
1. Open a command prompt.
2. Navigate to the MongoDB installation directory (e.g., C:\Program
Files\MongoDB\Server\<version>\bin).
3. Start the MongoDB server:
mongod --dbpath "C:\data\db" --logpath "C:\data\log\mongod.log" --logappend --
port 27017
Option 2: Run as a Windows Service
1. By default, MongoDB is installed as a service and starts automatically.
2. You can manually manage the service:
Start: net start MongoDB
Stop: net stop MongoDB
7. Optional Configuration
Edit MongoDB Configuration File
1. Locate mongod.cfg (default: C:\Program
Files\MongoDB\Server\<version>\bin\mongod.cfg).
2. Open it in a text editor and modify key settings as needed:
Bind IP Address: Allow MongoDB to accept remote connections:
net:
bindIp: 0.0.0.0
Port: Change the default port (27017) if required:
net:
port: 27017
Enable Authentication: Secure your database:
security:
authorization: enabled
3. Restart the MongoDB service for changes to take effect:
net stop MongoDB
net start MongoDB
1. 1. Create Operations
Create operations add new documents to a collection.
Insert a Single Document
db.collection.insertOne({ name: "John", age: 25, city: "New York" });
Insert Multiple Documents
db.collection.insertMany([ { name: "Alice", age: 30, city: "London" },
{ name: "Bob", age: 22, city: "Paris" }
]);
2. Read Operations
Read operations retrieve data from collections.
Find All Documents
db.collection.find();
Find Documents with a Query
Use a query object to filter results:
db.collection.find({ city: "New York" });
Find One Document
db.collection.findOne({ name: "John" });
Format Output (Pretty Print)
db.collection.find().pretty();
Projection (Select Specific Fields)
db.collection.find({ city: "London" }, { name: 1, age: 1, _id: 0 });
3. Update Operations
Update operations modify existing documents.
Update a Single Document
db.collection.updateOne(
{ name: "John" }, // Filter
{ $set: { age: 26 } } // Update
);
Update Multiple Documents
db.collection.updateMany( { city: "London" }, // Filter
{ $set: { country: "UK" } } // Update
);
Replace a Document
Replace an entire document:
db.collection.replaceOne( { name: "Alice" }, // Filter
{ name: "Alice", age: 35, city: "Berlin" } // New document
);
4. Delete Operations
Delete operations remove documents from collections.
Delete a Single Document
db.collection.deleteOne({ name: "John" });
Delete Multiple Documents
db.collection.deleteMany({ city: "London" });
Drop an Entire Collection
Remove all documents and the collection itself:
db.collection.drop();
db.users.insertMany([
{ name: "Emma", age: 28, city: "New York" },
{ name: "Liam", age: 35, city: "London" },
{ name: "Sophia", age: 22, city: "Paris" }
]);
Step 2: Read Documents
db.users.find();
Step 3: Update Documents
db.users.updateOne({ name: "Emma" }, { $set: { age: 29 } });
Step 4: Delete a Document
db.users.deleteOne({ name: "Sophia" });
Managing Indexes
1. View Indexes:
db.collection.getIndexes();
2. Drop an Index:
db.collection.dropIndex("indexName");
3. Drop All Indexes:
db.collection.dropIndexes();
2. Querying in MongoDB
MongoDB provides a flexible query language for retrieving data. Queries are
performed using the find() method.
Basic Queries
1. Find All Documents:
db.collection.find();
2. Find with Filters:
db.collection.find({ fieldName: value });
3. Find Specific Fields (Projection):
db.collection.find({ fieldName: value }, { field1: 1, field2: 0 }); // 1 to include, 0 to
exclude
1. Query Operators
1. Comparison Operators:
db.collection.find({ age: { $gt: 18 } }); // Greater than
db.collection.find({ age: { $gte: 18 } }); // Greater than or equal
db.collection.find({ age: { $lt: 30 } }); // Less than
db.collection.find({ age: { $lte: 30 } }); // Less than or equal
db.collection.find({ age: { $ne: 25 } }); // Not equal
db.collection.find({ age: { $in: [18, 25, 30] } }); // In array
db.collection.find({ age: { $nin: [18, 25] } }); // Not in array
2. Logical Operators:
db.collection.find({ $and: [{ age: { $gt: 18 } }, { city: "London" }] });
db.collection.find({ $or: [{ age: { $lt: 18 } }, { city: "Paris" }] });
db.collection.find({ $not: { age: { $gte: 18 } } });
3. Element Operators:
db.collection.find({ fieldName: { $exists: true } }); // Field exists
db.collection.find({ fieldName: { $type: "string" } }); // Field is of type
4. Array Operators:
db.collection.find({ tags: { $all: ["tag1", "tag2"] } }); // Match all elements
db.collection.find({ tags: { $size: 2 } }); // Array size
db.collection.find({ tags: { $elemMatch: { key: "value" } } }); // Match specific
element
5. Regular Expressions:
db.collection.find({ name: /john/i }); // Case-insensitive search
json
{
"_id": 1,
"title": "Introduction to MongoDB",
"author": { "name": "John", "email":
"[email protected]" },
"tags": ["MongoDB", "Database", "NoSQL"],
"comments": [
{ "user": "Jane", "comment": "Great
article!" },
{ "user": "Doe", "comment": "Very helpful,
thanks!" }
]
}
Flexible Schema: You can add new fields to documents without affecting
other documents in the collection.
Example:
json
// Document 1
{ "name": "Alice", "age": 25 }
MongoDB allows you to represent relationships between data in two main ways:
json
{
"name": "Product A",
"category": "Electronics",
"reviews": [
{ "user": "Alice", "rating": 5 },
{ "user": "Bob", "rating": 4 }
]
}
Store related data in separate collections and reference them using foreign
keys.
Suitable for one-to-many or many-to-many relationships.
Example:
o Products Collection:
json
{ "_id": 1, "name": "Product A", "category":
"Electronics" }
o Reviews Collection:
json
Copy code
{ "product_id": 1, "user": "Alice", "rating":
5 }
{ "product_id": 1, "user": "Bob", "rating": 4 }
a. One-to-One Relationship
json
{
"user_id": 1,
"name": "John",
"profile": { "email": "[email protected]", "age":
30 }
}
b. One-to-Many Relationship
json
Copy code
{
"post_id": 1,
"title": "MongoDB Guide",
"comments": [
{ "user": "Alice", "comment": "Great!" },
{ "user": "Bob", "comment": "Thanks!" }
]
}
c. Many-to-Many Relationship
json
{ "_id": 1, "name": "Alice" }
o Courses Collection:
json
Copy code
{ "_id": 101, "course_name": "MongoDB Basics" }
o Enrollment Collection:
json
Copy code
{ "user_id": 1, "course_id": 101 }
5. Aggregation Framework
You can use operators like $group, $match, $lookup, and $unwind.
Example: Join referenced data using $lookup for a many-to-many
relationship.
6. Data Redundancy