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:
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.
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 })
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 } ])
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 } } )
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 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 } } } ])
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).
After that make sure to create your database 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.
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!
Please take a minute to fill in the feedback form for this lab.