> For the complete documentation index, see [llms.txt](https://wiki.berkie.ee/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://wiki.berkie.ee/techops/getting-started-projects/web-demo-project/assignment-2-mongodb.md).

# Assignment 2: MongoDB

Please follow [MongoDB Setup](/techops/getting-started-projects/web-demo-project/assignment-2-mongodb/mongodb-setup.md) to make sure you can use MongoDB locally *and* access MongoDB Compass (the browser for MongoDB projects).&#x20;

Most of our database stack uses MongoDB for simplicity. Some more antiquated stacks (e.g. Ghost CMS) uses SQL but it's never directly exposed.

## Part 1: Writing MongoDB queries

To set up, navigate to the left panel after you connect to localhost:

<figure><img src="/files/aGWnNb9O0HhUHC8ljEFk" alt=""><figcaption></figcaption></figure>

Click the `+` button and add a database. You may call the database whatever you want. I'll name it `ieee-library` for the sake of the exercise. You may also enter `books` or any other collection name. This creates a collection upon database creation.

> Note: In SQL, you may recognize some of these terms. "Database" refers to an overall database that contains information. However, in SQL, you may be more familiar with the word "table." A collection is similar to a table. The reason that it's different is because NoSQL (MongoDB-like) databases do not contains "rows," so it makes no sense to call something without rows and columns a "table." Instead of rows, we have "documents" that store a JSON aggregation of data.&#x20;

### Manipulating Data

Recall the command to open the mongo shell. Let's open it. Then we need to switch to use our new database we just created.

```bash
use ieee-library # switch to new db
db # should print the new database name
```

Then let's insert a book:

```javascript
db.books.insertOne({ title: 'Computer Architecture: A Quantitative Approach', author: 'John L. Hennessy, David A Patterson'});
```

Then let's insert multiple books. You can probably see these update in MongoDB Compass after you refresh.&#x20;

```javascript
db.books.insertMany({ title: 'Design of Analog CMOS Integrated Circuits', author: 'Behzad Razavi' }, { title: 'Low Power Design Essentials', author: 'Jan M. Rabaey'})
```

Now, let's list all the books:

```javascript
db.books.find()
```

If we wanted to find a specific entry, you can do:

```javascript
db.books.findOne()
```

If we wanted to update a document, you can do the following:

```javascript
db.books.updateOne()
```

If we wanted to delete something, you can do:

```javascript
db.books.deleteOne()
```

If you wanted to count the number of documents:

```javascript
db.books.countDocuments()
```

If we wanted to filter by a field, you can do&#x20;

```javascript
db.books.find( search_field: value )
```

You can sort a retrieve by

```javascript
db.books.find().sort(field)
```

There are many more actions you can do! Please feel free to Google any of them at any time.&#x20;

## Your assignment

Since you operate a library, you want to hold information about users! Let's start thinking about how we want to store this information!&#x20;

### Question 1:&#x20;

List out what information you want your user to have. Structure them in a key: value\_type structure like below in JSON format. This is your "schema."

```javascript
{
    key: string
}
```

### Question 2:

Go ahead and insert 1 new user into the database. What commands do you run?

### Question 3:

Now it gets a bit harder! We're going to try and adapt the code from `nodejs-demo` to work with your local MongoDB database!&#x20;

First of all, we need a package that allows NodeJS to interface with MongoDB. Thankfully MongoDB curates their own package called MongoDB Client.&#x20;

{% embed url="<https://www.npmjs.com/package/mongodb>" %}

What command do you need to run to install this package? Go ahead and do so!

### Question 4:

Let's start editing our code. Here are some lines of code that you may want to add to the project. You won't be adding this as a block somewhere. Each line is separate! They go in different places in the file. See if you can figure out where to add these.&#x20;

<pre class="language-javascript"><code class="lang-javascript">const { MongoClient, ObjectId } = require('mongodb');
<strong>const uri = 'mongodb://localhost:27017';
</strong>const dbName = 'techopsLibrary';
const client = new MongoClient(uri);
</code></pre>

Even after you put these in, it won't work fully. Why is that the case? What crucial step are we missing?

We won't talk about how to complete the integeration for this assignment. If you're ambitious, please go ahead and try to finish the integration! We will cover more of this in 1 or 2 weeks.&#x20;


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://wiki.berkie.ee/techops/getting-started-projects/web-demo-project/assignment-2-mongodb.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
