KEMBAR78
Module 5 Answer | PDF | Relational Database | Databases
0% found this document useful (0 votes)
18 views7 pages

Module 5 Answer

In MongoDB, collections are groups of documents similar to tables in relational databases, while documents are individual records composed of field and value pairs. Unlike relational databases, MongoDB has a flexible schema, allowing documents in a collection to have different fields, and uses a JSON-based query language. Webpack is a tool for modularizing and bundling front-end code, optimizing performance through features like code splitting, minification, and hot module replacement.

Uploaded by

sarbjotsingh1804
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)
18 views7 pages

Module 5 Answer

In MongoDB, collections are groups of documents similar to tables in relational databases, while documents are individual records composed of field and value pairs. Unlike relational databases, MongoDB has a flexible schema, allowing documents in a collection to have different fields, and uses a JSON-based query language. Webpack is a tool for modularizing and bundling front-end code, optimizing performance through features like code splitting, minification, and hot module replacement.

Uploaded by

sarbjotsingh1804
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/ 7

Ques: What are collections and documents in MongoDB?

How do they
differ from relational databases?

In MongoDB, collections and documents are fundamental concepts for


organizing and storing data .

* **Collections:** A collection is a group of MongoDB documents, similar


to a table in a relational database . Collections can have primary keys and
indexes, but unlike relational databases, MongoDB doesn't require a
predefined schema for collections . While all documents in a collection must
have a unique `_id`, they can have completely different fields, although in
practice, they usually have the same fields.
* **Documents:** A document is the equivalent of a record in a relational
database and is the unit of storage in MongoDB . Documents are composed
of field and value pairs and can contain nested objects and arrays .
MongoDB documents are similar to JSON objects and can support various
data types, including Booleans, numbers, strings, dates, and binary data.

Here's how they differ from relational databases :

* **Structure:** Relational databases store data in tables with rows and


columns, while MongoDB is a document-oriented database . In MongoDB,
an entire object can be stored as a single document, even with nested
objects and arrays, which would typically require multiple tables in a
relational database .
* **Schema:** MongoDB has a flexible schema, meaning that documents
in a collection do not need to have the same set of fields. Relational
databases, on the other hand, typically require a strict schema to be defined
.
* **Query Language:** Relational databases use SQL as a query
language, while MongoDB uses a JSON-based query language with
methods for various operations .
* **Denormalization:** MongoDB encourages denormalization, where
related data is stored as embedded subdocuments within a single
document, rather than as separate collections (tables) in a relational
database .
* **Object Relational Mapping (ORM):** MongoDB eliminates the need for
an ORM layer because data can be persisted as objects or documents, just
as they appear in the application code .

Ques: Write a MongoDB command to insert a new document into a


collection named users.
javascript
db.users.insertOne({
// Specify the fields and values for the new document here
// Example:
name: { first: 'John', last: 'Doe' },
age: 30,
email: 'john.doe@example.com'
})
```

This command uses the `insertOne()` method on the `users` collection to


insert a new document . You should replace the comments with the actual
fields and values you want to insert into the document. The `insertOne()`
method acknowledges the insertion and returns the `insertedId` of the new
document . MongoDB automatically creates the primary key `_id` if you
don't specify one . You can also specify your own `_id` value .

Here are some additional points to keep in mind:

* **Collections:** A collection in MongoDB is a group of MongoDB


documents . It is similar to a table in a relational database .
* **Documents:** A document is equivalent to a record in a relational
database and is the unit of storage in MongoDB . Documents are composed
of field and value pairs and can contain nested objects and arrays .
* **Data Types:** MongoDB documents support various data types,
including strings, numbers, Booleans, dates, and binary data .
* **Flexible Schema:** MongoDB has a flexible schema, meaning
documents in a collection do not need to have the same set of fields .

The `insertMany()` method can be used to insert multiple documents into a


collection .

Ques: How do you retrieve all documents where age is greater than 25
from a customer’s collection?

To retrieve all documents from a `customer` collection where the age is


greater than 25, you can use the `find()` method with a filter . Here’s how:

db.customer.find({ age: { $gt: 25 } })


```
In this command:

* `db.customer.find()` specifies that you want to find documents in the


`customer` collection .
* `{ age: { $gt: 25 } }` is the filter that selects documents where the `age`
field is greater than 25 . The `$gt` operator stands for "greater than" .

This command will return a cursor containing all documents in the


`customer` collection where the age is greater than 25 .

Ques: What is Webpack, and why is it used in modern web development?

Webpack is a tool used in modern web development to modularize code,


especially on the front end . It treats dependencies as modules, figures out
the order of dependent modules, and bundles them into one or a few
JavaScript files that can be included in an HTML file .

Here's why Webpack is used :

* **Modularity:** Webpack helps split front-end code into component-


based files . It allows developers to use `require()` statements (Node.js
style) or ES2015-style `import` statements to define dependencies .
* **Dependency Management:** It automatically determines the
application's dependent modules and third-party library dependencies .
* **Bundling:** Webpack puts individual files together into one or a few
bundles of pure JavaScript, which include all the required code that can be
included in the HTML file .
* **Transformation:** Webpack can transform code using loaders, such as
the Babel loader for JSX and ES2015 transformations .
* **Watching for Changes:** Webpack can watch for changes to files and
generate new bundles quickly .
* **Optimizations:** Webpack offers optimizations like minifying the output
JavaScript when building for production . It can also split code into smaller
pieces and load bundles only when required (lazy loading) .
* **Hot Module Replacement (HMR):** Webpack's HMR feature changes
modules in the browser while the application is running, removing the need
for a refresh altogether .
* **Browser Caching:** Webpack can use content hashes as part of the
bundle's name to address browser caching issues .
Ques: What does the webpack mean by “Transform and bundle”? How
does it optimize front-end performance?

"Transform and bundle" in Webpack refers to the process of converting


code (like JSX or ES2015) and other assets into a format that browsers can
understand and then combining these transformed files into one or more
bundles for efficient delivery .

Here's how Webpack optimizes front-end performance :

* **Loaders:** Webpack uses loaders to transform different types of files


into JavaScript modules . For example, `babel-loader` transforms JSX and
ES2015 code into plain JavaScript .
* **Bundling:** Webpack combines multiple files into one or a few bundles,
reducing the number of HTTP requests a browser needs to make .
* **Minification:** Webpack can minify the output JavaScript, reducing its
file size .
* **Code Splitting:** Webpack can split code into smaller chunks and load
them only when required (lazy loading), improving initial load time . It can
create separate bundles for third-party libraries (vendor bundle) and
application code, so that the browser can cache the libraries and only
download the application code when it changes .
* **Hot Module Replacement (HMR):** Webpack's HMR feature allows
modules to be updated in the browser without a full page refresh, preserving
the application state and improving development speed .
* **Browser Caching:** Webpack can use content hashes in the bundle
names to ensure that browsers cache the correct version of the files .

Ques: What is aggregation in MongoDB? Provide an example where


you calculate the average price of products in a sales collection.

AI: Aggregation in MongoDB is a way to process data and compute results,


similar to the `GROUP BY` clause in SQL . It allows you to perform
operations like calculating sums, averages, minimums, and maximums on
grouped data . The `aggregate()` method works in a pipeline, where each
stage transforms the documents from the previous stage .

Here's an example of how to calculate the average price of products in a


`sales` collection using the `aggregate()` method:

First, let’s assume each document in the `sales` collection has fields like
`product_id`, `product_name`, and `price`.
To calculate the average price, you can use the `$group` stage with the
`$avg` operator :

```javascript
db.sales.aggregate([
{
$group: {
_id: null, // Group all documents together
average_price: { $avg: '$price' } // Calculate the average of the 'price'
field
}
}
])
```

In this example:

* `db.sales.aggregate()`: Calls the aggregate method on the `sales`


collection .
* `$group`: This stage groups the documents together. `_id: null` groups
all the documents in the collection into a single group to calculate the overall
average .
* `average_price: { $avg: '$price' }`: This calculates the average of the
`price` field for all documents in the group and assigns it to the
`average_price` field . The `$` prefix is used to refer to the `price` field in
the documents .

This command will return a document with the average price of all products
in the `sales` collection:

```json
{ "_id" : null, "average_price" : <average price value> }
```

Ques: How do you connect to MongoDB using the Node.is MongoDB


driver? Provide an example.

To connect to MongoDB using the Node.js MongoDB driver, you first need
to install the driver :

```
$ npm install mongodb@3
```

Then, you can connect to the database server using the following steps :

1. **Import the `MongoClient` object:**


```javascript
const { MongoClient } = require('mongodb');
```
2. **Create a new client object with a connection URL:** The URL should
start with `mongodb://` followed by the hostname or IP address of the
server. If the MongoDB server is running on the default port (27017), you
don't need to specify the port. The database name can be included as part
of the URL .
```javascript
const url = 'mongodb://localhost/issuetracker';
const client = new MongoClient(url, { useNewUrlParser: true });
```
It's good practice to store the connection parameters in a configuration
file instead of hardcoding them .
3. **Call the `connect()` method:** The `connect()` method is asynchronous
and requires a callback function. The callback takes two arguments: an
error object and the client object itself. You can obtain a connection to the
database by calling the `db()` method of the client object within the callback
.
```javascript
client.connect(function(err, client) {
if (err) {
console.error(err);
return;
}
const db = client.db();
console.log("Connected to MongoDB");
// ... perform database operations here
client.close(); // Close the connection when done
});
```
4. **Using async/await (ES2017 and later):** A more convenient way to
connect is using the `async/await` paradigm .
```javascript
async function connectToDb() {
const client = new MongoClient(url, { useNewUrlParser: true });
try {
await client.connect();
console.log('Connected to MongoDB at', url);
db = client.db(); //assign the connection to a global variable
} catch (err) {
console.error('ERROR:', err);
}
}

//To call the connectToDb function


(async function() {
await connectToDb();
//...Your code here
})();
```

Note that you should close the connection to the server when you are done,
otherwise, the Node.js program will not exit .

You might also like