0% found this document useful (0 votes)
15 views9 pages

Advance Web Application Long Answer WEEK - 2

Uploaded by

narensk6
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)
15 views9 pages

Advance Web Application Long Answer WEEK - 2

Uploaded by

narensk6
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/ 9

Advanced Web Application Development

Long Descriptive Questions WEEK – 2

1.Explain in detail about CRUD operation in MongoDB.


CRUD stands for Create, Read, Update, and Delete, which are the basic operations
performed on data in a database. MongoDB, being a NoSQL database, follows the same
principles but with some variations compared to traditional SQL databases. Here's a detailed
explanation of each CRUD operation in MongoDB:

Create (Insert):

To create a new document in MongoDB, you use the insertOne() or insertMany() method.
insertOne() is used to insert a single document into a collection.
insertMany() is used to insert multiple documents into a collection in a single operation.
Example:

// Insert a single document


db.collection.insertOne({ name: "John", age: 25 });

// Insert multiple documents


db.collection.insertMany([
{ name: "Alice", age: 30 },
{ name: "Bob", age: 35 }
]);
Read (Retrieve):

To read or retrieve documents from a MongoDB collection, you use the find() method.
find() retrieves documents based on a query/filter and returns a cursor to iterate over the
matched documents.
Example:

// Find all documents in a collection


db.collection.find();

// Find documents with a specific condition


db.collection.find({ age: { $gt: 25 } });
Update:

To update existing documents in a MongoDB collection, you use the updateOne() or


updateMany() method.
updateOne() updates a single document that matches the given filter.
updateMany() updates multiple documents that match the given filter.
Example:

// Update a single document


db.collection.updateOne(
{ name: "John" },
{ $set: { age: 30 } }
);

// Update multiple documents


db.collection.updateMany(
{ age: { $lt: 30 } },
{ $inc: { age: 5 } }
);
Delete:
To delete documents from a MongoDB collection, you use the deleteOne() or deleteMany()
method.
deleteOne() deletes a single document that matches the given filter.
deleteMany() deletes multiple documents that match the given filter.
Example:

// Delete a single document


db.collection.deleteOne({ name: "John" });

// Delete multiple documents


db.collection.deleteMany({ age: { $gt: 40 } });
These are the basic CRUD operations in MongoDB. Along with these, MongoDB provides
powerful querying capabilities, aggregation framework, indexing, and more to handle
complex data operations efficiently. It's important to note that the exact syntax and usage of
these operations may vary depending on the MongoDB driver or ORM library you are using.

2.What is a namespace in MongoDB?

In MongoDB, a namespace refers to a combination of a database name and a collection


name, separated by a dot (.). It is a unique identifier for a specific collection within a
database. The namespace allows MongoDB to organize and locate collections in a structured
manner.

The general format of a MongoDB namespace is as follows:


<database_name>.<collection_name>

Here's an example to illustrate the concept:

Suppose you have a MongoDB database named "mydb" and within that database, you have
two collections: "users" and "orders". The namespaces for these collections would be:
Namespace for the "users" collection: mydb.users
Namespace for the "orders" collection: mydb.orders
Namespaces play a vital role in distinguishing and accessing collections within a database.
They are used in various MongoDB operations, including CRUD operations, indexing,
querying, and administrative tasks. For example, when performing a find() operation, you
would specify the namespace to indicate the collection you want to retrieve data from:

db.users.find(); // Retrieves documents from the "users" collection


Namespaces also help in maintaining data isolation and encapsulation within a database.
Each namespace represents a separate entity where documents of a particular collection
reside.

It's important to note that MongoDB has certain naming conventions for namespaces. For
example, namespaces cannot contain certain characters like $ or .. Additionally, the
maximum length of a namespace is 120 bytes.

Understanding namespaces is crucial when working with MongoDB to interact with specific
databases and collections efficiently.

3.How do I handle 404 responses?

In an Express application, you can handle 404 responses (Not Found) by defining a
middleware that will be executed when no other routes or middleware match the requested
path. Here's how you can handle 404 responses in Express:

Place the middleware at the end of your route and middleware definitions to ensure it is
executed only if no other routes match the requested path.
// Your other routes and middleware definitions

// 404 handler middleware


app.use((req, res, next) => {
res.status(404).send("404: Page Not Found");
});
In the above example, we define a middleware function using app.use(). This function takes
three parameters: req (request object), res (response object), and next (next middleware
function). It will be executed for any request that doesn't match any of the defined routes.

Inside the middleware function, we set the status code to 404 using res.status(404) to
indicate that the requested resource was not found.

We then use res.send() to send the response body, which in this case is a simple text
message "404: Page Not Found". You can customize this message or send an HTML page or
JSON response depending on your application's requirements.

With this setup, whenever a request is made to a route that doesn't exist in your application,
the 404 middleware will be triggered, and the appropriate response will be sent to the
client.

Note: It's important to place the 404 middleware at the end of your middleware chain or
route definitions. If it is placed before any other routes, it will be triggered for all requests,
even if a valid route matches the requested path.

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

To connect to a running MongoDB instance, use a database named "mongo_practice," and


perform the requested queries, follow these steps:
Install the MongoDB driver for Node.js using npm (Node Package Manager) by running the
following command in your project directory:
shell

npm install mongodb


In your Node.js application file, require the MongoDB driver and create a connection to the
MongoDB instance:

const { MongoClient } = require('mongodb');

const url = 'mongodb://localhost:27017'; // MongoDB connection URL


const dbName = 'mongo_practice'; // Database name

MongoClient.connect(url, function(err, client) {


if (err) {
console.error('Error connecting to MongoDB:', err);
return;
}

console.log('Connected to MongoDB successfully!');

const db = client.db(dbName);

const moviesCollection = db.collection('movies');

// Perform the queries here

// Close the MongoDB connection


client.close();
});
Replace 'mongodb://localhost:27017' with the appropriate connection URL for your
MongoDB instance. By default, MongoDB runs on localhost with port 27017.

Once connected, use the moviesCollection object obtained from the db.collection() method
to perform the queries.

Here are the queries for the movies collection:

Get all documents in the movies collection:

moviesCollection.find().toArray(function(err, documents) {
if (err) {
console.error('Error retrieving documents:', err);
return;
}

console.log('All documents:');
console.log(documents);
});
Get all documents with the writer set to "Quentin Tarantino":

moviesCollection.find({ writer: "Quentin Tarantino" }).toArray(function(err, documents) {


if (err) {
console.error('Error retrieving documents:', err);
return;
}
console.log('Documents with writer set to "Quentin Tarantino":');
console.log(documents);
});
Get all documents where actors include "Brad Pitt":

moviesCollection.find({ actors: "Brad Pitt" }).toArray(function(err, documents) {


if (err) {
console.error('Error retrieving documents:', err);
return;
}

console.log('Documents with actors including "Brad Pitt":');


console.log(documents);
});
Get all documents with the franchise set to "The Hobbit":

moviesCollection.find({ franchise: "The Hobbit" }).toArray(function(err, documents) {


if (err) {
console.error('Error retrieving documents:', err);
return;
}

console.log('Documents with franchise set to "The Hobbit":');


console.log(documents);
});
Get all movies released in the 90s:
moviesCollection.find({ releaseYear: { $gte: 1990, $lte: 1999 } }).toArray(function(err,
documents) {
if (err) {
console.error('Error retrieving documents:', err);
return;
}

console.log('Movies released in the 90s:');


console.log(documents);
});
Get all movies released before the year 2000 or after 2010:

moviesCollection.find({ $or: [{ releaseYear: { $lt: 2000 } }, { releaseYear: { $gt: 2010 } }]


}).toArray(function(err, documents) {
if (err) {
console.error('Error retrieving documents:', err);
return;
}

console.log('Movies released before 2000 or after 2010

You might also like