0% found this document useful (0 votes)
5 views10 pages

Week 2 - Advance Web Application Dev

AWT assignment

Uploaded by

Deepak Kumbhar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
5 views10 pages

Week 2 - Advance Web Application Dev

AWT assignment

Uploaded by

Deepak Kumbhar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 10

Week 2 – Advance web application development

1) Explain in detail about CRUD operation in MongoDB.

Ans: - CRUD stands for Create, Read, Update, and Delete. These are the four basic operations that
are performed on data in most database systems. MongoDB, a popular NoSQL database, supports
these CRUD operations as well. Below is a detailed explanation of each CRUD operation in the
context of MongoDB:

1. Create (C)

In MongoDB, the insertOne() and insertMany() methods are used to create new documents in a
collection.

insertOne()

The insertOne() method inserts a single document into a collection.

db.collection('users').insertOne({

name: 'John Doe',


age: 30,

email: 'john.doe@example.com'

});

insertMany()

The insertMany() method inserts multiple documents into a collection.

db.collection('users').insertMany([

name: 'Jane Smith',

age: 25,

email: 'jane.smith@example.com'
},

name: 'Alice Johnson',

age: 35,

email: 'alice.johnson@example.com'
}

]);

2. Read (R)

In MongoDB, the find() method is used to read documents from a collection.

find()

The find() method retrieves documents from a collection. You can also use query criteria to filter the
documents.

// Find all documents in the 'users' collection

db.collection('users').find().toArray();

// Find documents where age is greater than 30

db.collection('users').find({ age: { $gt: 30 } }).toArray();

// Find a single document

db.collection('users').findOne({ name: 'John Doe' });

3. Update (U)

In MongoDB, the updateOne() and updateMany() methods are used to update documents in a
collection.

updateOne()

The updateOne() method updates a single document that matches the filter criteria.

// Update the age of John Doe to 32

db.collection('users').updateOne(

{ name: 'John Doe' },

{ $set: { age: 32 } }

);

updateMany()

The updateMany() method updates all documents that match the filter criteria.

// Update the age of all users older than 30 to 40

db.collection('users').updateMany(

{ age: { $gt: 30 } },

{ $set: { age: 40 } }
);

4. Delete (D)

In MongoDB, the deleteOne() and deleteMany() methods are used to delete documents from a
collection.

deleteOne()

The deleteOne() method deletes a single document that matches the filter criteria.
// Delete the document where name is 'Alice Johnson'

db.collection('users').deleteOne({ name: 'Alice Johnson' });

deleteMany()

The deleteMany() method deletes all documents that match the filter criteria.

// Delete all documents where age is 40

db.collection('users').deleteMany({ age: 40 });

Create (C)

insertOne(): Insert a single document.

insertMany(): Insert multiple documents.

Read (R)
find(): Retrieve documents from a collection.

findOne(): Retrieve a single document.

Update (U)

updateOne(): Update a single document.

updateMany(): Update multiple documents.

Delete (D)

deleteOne(): Delete a single document.

deleteMany(): Delete multiple documents.

2) What is a namespace in MongoDB?

Ans: - In MongoDB, a namespace refers to the combination of a database name and a collection
name. It uniquely identifies a collection within a database. The namespace is used to perform CRUD
operations on a specific collection within a database.

Format of a Namespace
The format of a namespace in MongoDB is:

<database_name>.<collection_name>

<database_name>: The name of the database.

<collection_name>: The name of the collection within the database.

Examples

Namespace for a collection named users in a database named myDatabase:

myDatabase.users

Namespace for a collection named products in a database named eCommerce:

eCommerce.products
Importance of Namespace

The namespace is crucial for:

Identifying Collections: It helps to uniquely identify a collection within a database.

Performing CRUD Operations: When performing CRUD operations, you need to specify the
namespace to indicate on which collection the operation should be performed.

Usage in CRUD Operations

When performing CRUD operations in MongoDB, you specify the namespace to target a specific
collection.

Example:

To insert a document into a collection named users in a database named myDatabase, you would
use the following namespace:
db.myDatabase.users.insertOne({

name: 'John Doe',

age: 30,

email: 'john.doe@example.com'

});

Here, db.myDatabase.users is the namespace for the users collection in the myDatabase database.

3) How do I handle 404 responses?

Ans: - Handling 404 responses is crucial in web development to gracefully manage situations where
a requested resource is not found. In a MongoDB context, 404 errors often occur when trying to
access or manipulate data that does not exist in the database. Here are some ways to handle 404
responses in a MongoDB application:

1. Express.js with Node.js

If you are using Express.js with Node.js, you can handle 404 responses using the app.use()
middleware at the end of all other routes.

const express = require('express');

const app = express();

// Other routes

app.get('/users/:id', (req, res) => {

const userId = req.params.id;

// Find user by ID in MongoDB

db.collection('users').findOne({ _id: ObjectId(userId) }, (err, user) => {

if (err) {

return res.status(500).json({ error: 'Internal Server Error' });

if (!user) {

return res.status(404).json({ error: 'User not found' });

res.json(user);

});

});

// Handle 404 - Not Found

app.use((req, res) => {


res.status(404).json({ error: 'Not Found' });

});

app.listen(3000, () => {

console.log('Server is running on port 3000');

});

2. Express.js Error Handling Middleware

You can also create a custom error-handling middleware to handle 404 responses.

const express = require('express');


const app = express();

// Other routes

app.get('/users/:id', (req, res, next) => {

const userId = req.params.id;

// Find user by ID in MongoDB

db.collection('users').findOne({ _id: ObjectId(userId) }, (err, user) => {

if (err) {

return next(err); // Pass error to the next middleware

if (!user) {

const error = new Error('User not found');

error.status = 404;

return next(error); // Pass error to the next middleware

res.json(user);

});

});

// Custom error-handling middleware

app.use((err, req, res, next) => {


const status = err.status || 500;

const message = err.message || 'Internal Server Error';

res.status(status).json({ error: message });

});

app.listen(3000, () => {

console.log('Server is running on port 3000');

});

3. Async/Await with Try/Catch

Using async/await with try/catch blocks is another approach to handle 404 responses.
const express = require('express');

const app = express();

app.get('/users/:id', async (req, res) => {

try {

const userId = req.params.id;

// Find user by ID in MongoDB

const user = await db.collection('users').findOne({ _id: ObjectId(userId) });

if (!user) {

return res.status(404).json({ error: 'User not found' });

res.json(user);

} catch (err) {

res.status(500).json({ error: 'Internal Server Error' });

});

app.listen(3000, () => {

console.log('Server is running on port 3000');

});
4) Connect to a running mongo instance, use a database named mongo_practice.
Document all your queries.
Insert the documents into a movies collection.
query the movies collection to

1. get all documents.

2. get all documents with writer set to "Quentin Tarantino".

3. get all documents where actors include "Brad Pitt".

4. get all documents with franchise set to "The Hobbit".

5. get all movies released in the 90s.

6. get all movies released before the year 2000 or after 2010.

Ans: - To perform the mentioned tasks, you can use the MongoDB shell or a MongoDB client.
Below are the queries to connect to a running MongoDB instance, use a database named
mongo_practice, and insert documents into a movies collection. I will also include the queries to
perform the requested operations on the movies collection.

Step 1: Connect to a running MongoDB instance and use the mongo_practice database

Open the MongoDB shell or a MongoDB client and execute the following commands to connect
to the running MongoDB instance and switch to the mongo_practice database.

use mongo_practice

Step 2: Insert documents into the movies collection

Execute the following command to insert documents into the movies collection.

db.movies.insertMany([

title: "Pulp Fiction",

writer: "Quentin Tarantino",

actors: ["John Travolta", "Uma Thurman", "Samuel L. Jackson"],


franchise: "No",

releaseYear: 1994

},

title: "Inglourious Basterds",

writer: "Quentin Tarantino",

actors: ["Brad Pitt", "Diane Kruger", "Eli Roth"],

franchise: "No",

releaseYear: 2009

},

title: "The Hobbit: An Unexpected Journey",

writer: "J.R.R. Tolkien",

actors: ["Martin Freeman", "Ian McKellen", "Richard Armitage"],

franchise: "The Hobbit",

releaseYear: 2012

},

title: "The Hobbit: The Desolation of Smaug",

writer: "J.R.R. Tolkien",

actors: ["Martin Freeman", "Ian McKellen", "Richard Armitage"],

franchise: "The Hobbit",

releaseYear: 2013

},

title: "Fight Club",

writer: "Chuck Palahniuk",

actors: ["Brad Pitt", "Edward Norton", "Helena Bonham Carter"],


franchise: "No",

releaseYear: 1999

]);

Step 3: Query the movies collection

1) Get all documents

db.movies.find().pretty();

2) Get all documents with writer set to "Quentin Tarantino"

db.movies.find({ writer: "Quentin Tarantino" }).pretty();

3) Get all documents where actors include "Brad Pitt"

db.movies.find({ actors: "Brad Pitt" }).pretty();

4) Get all documents with franchise set to "The Hobbit"

db.movies.find({ franchise: "The Hobbit" }).pretty();

5) Get all movies released in the 90s

db.movies.find({ releaseYear: { $gte: 1990, $lt: 2000 } }).pretty();

6) Get all movies released before the year 2000 or after 2010

db.movies.find({ $or: [ { releaseYear: { $lt: 2000 } }, { releaseYear: { $gt: 2010 } }

You might also like