Lab 05 - Database

MongoDB

MongoDB is a popular NoSQL database that stores data in a document-oriented format. Unlike traditional relational databases that store data in tables with rows and columns, MongoDB uses collections of documents. Each document is a flexible, schema-less structure that stores data as key-value pairs, typically in JSON format (BSON in MongoDB). This allows for greater flexibility in data modeling, making it easy to handle a variety of data types.

Relational databases, such as MySQL or PostgreSQL, rely on predefined schemas, which means the structure of the data must be fixed and the relationships between entities are explicitly defined. This can make them rigid and less adaptable to changes. In contrast, MongoDB’s document model enables dynamic schemas, which allows for faster development, especially when dealing with complex or evolving data structures.

As a NoSQL database, MongoDB does not use SQL (Structured Query Language) for querying data. Instead, it uses its own query language that supports powerful, flexible querying capabilities, including searching within documents and aggregating data. This makes MongoDB particularly suited for handling large volumes of unstructured or semi-structured data, such as user-generated content, logs, and real-time analytics.

Example of a document stored in MongoDB:

{
  "id": 1,
  "description": "SE Lab5",
  "completed": false
}

The advantages of using documents are:

  • Documents correspond to native data types in many programming languages.
  • Embedded documents and arrays reduce need for expensive joins.
  • Dynamic schema supports fluent polymorphism.

MongoDB Operations

We can perform a variety of operations in MongoDB, including inserting, finding, updating, and deleting documents. Additionally, we can perform aggregation queries to process and transform our data. These operations allow us to efficiently manage and manipulate large volumes of data.

Find

We can use the find() method to retrieve documents from a collection based on specified criteria. This operation allows us to query data with simple or complex conditions.

// Find all documents in the collection
db.Todos.find({})

// Find a specific document by its 'id'
db.Todos.findOne({ id: 1 })

Insert

In MongoDB, we can insert new documents into a collection using the insertOne() or insertMany() methods. These operations add data to our database.

// Insert a single document
db.Todos.insertOne({
  id: 2,
  description: 'Startup Engineering Lab 5',
  completed: false
})

// Insert multiple documents
db.Todos.insertMany([
  { id: 3, description: 'Milestone 3', completed: false },
  { id: 4, description: 'Milestone 4', completed: false }
])

Update

The updateOne() and updateMany() methods allow us to modify existing documents in the collection based on specified criteria.

// Update a single document
db.Todos.updateOne(
  { id: 1 },
  { $set: { completed: true } }
)

// Update multiple documents
db.Todos.updateMany(
  { completed: false },
  { $set: { completed: true } }
)

Delete

In MongoDB, we can remove documents from a collection using the deleteOne() or deleteMany() methods. These operations allow us to delete either a single document or multiple documents based on specific criteria.

// Delete a single document by its 'id'
db.Todos.deleteOne({ id: 1 })

// Delete all completed todos
db.Todos.deleteMany({ completed: true })

Aggregation

Aggregation operations allow us to perform complex queries, such as grouping, filtering, and transforming our data.

// Count the number of completed todos
db.Todos.aggregate([
  { $match: { completed: true } },
  { $count: "completedTodos" }
])

// Group todos by 'completed' status and count them
db.Todos.aggregate([
  { $group: { _id: "$completed", count: { $sum: 1 } } }
])

MongoDB Atlas

To create our MongoDB database we are going to use Atlas, MongoDB Atlas is an integrated suite of data services centered around a cloud database designed to accelerate and simplify how you build with data, or for short, a database in the cloud.

First, we need to create an account on https://cloud.mongodb.com and create a new project, you can name your project however you like. After that we need to create a cluster, make sure you select the free tier (M0), the provider and location doesn't matter for now so you can use the default settings (AWS and Frankfurt).

MongoDB Cluster

After that make sure to create your database user.

MongoDB User

Now that our cluster is ready we need to create our database (and our collection). To do that go to Clusters → Our Cluster → Browse Collections → Add my own data. For database name use “SE2024” and for Collection name use “Todos”, after that click on “Create”.

Our next step is to find our connection string (we use this to connect to the database), to find our connection string go to Clusters → Out Cluster → Connect → Drivers and copy paste your connection string.

MongoDB User

Make sure to replace <db_password> with the password that you set up earlier. Also, you need to add SE2024 in your connection string like this

mongodb+srv://<db_username>:<db_password>@cluster0.bpou2.mongodb.net/SE2024?retryWrites=true&w=majority&appName=Cluster0.

SE2024 represents our database name, if you chose another name for your database, use that. Your connection string will be different, so don't just copy and paste the connection string from above!

Your connection string should NOT be made public due to security reasons. You should encrypt and decrypt the connection strings using your own keys.

Tasks

Mongoose is an ODM (Object Data Modeling) library for MongoDB. While you don’t need to use an Object Data Modeling (ODM) or Object Relational Mapping (ORM) tool to have a great experience with MongoDB, some developers prefer them. Many Node.js developers choose to work with Mongoose to help with data modeling, schema enforcement, model validation, and general data manipulation. You can check out the official docs to understand how can you use Mongoose.

  1. Download the Lab5 Archive for this lab and run npm install and npm run dev.
  2. Follow the tutorial to create a MongoDB database using Atlas.
  3. Look through the source code to see how Mongoose is utilised to connect to our database and create our Schema. The files you need to watch for are db/mongoose.ts and model/todo.ts
  4. Update the MongoDB connection string in .env.local with your own.
  5. Go to Atlas and manually create one document to test that the connection and find query works. To create a document go to Clusters → Browse Collections → Select the collection → Insert document. The document needs to have a text (string) and a completed (boolean) field. MongoDB will automatically assign an _id field.
  6. Go to actions.ts and look at the new getItems() function, if you did everything correctly until now your ToDo list should contain one item (the document that you created earlier).
  7. Look at the new createItem() function, by creating a new todo item, a new document should be inserted in our collection.
  8. Using Mongoose, implement the remaining functions in actions.ts by following the TODOs.

Feedback

Please take a minute to fill in the feedback form for this lab.

se/labs/05.txt · Last modified: 2024/11/12 13:07 by gabriel.nicolae3103
CC Attribution-Share Alike 3.0 Unported
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0