Getting started with MongoDB 🌿
Tags: database, opensource, beginners, tutorial
Published: 2022-04-24 15:17:37

In today's fast tech world, we are producing more data per second than ever before. The amount of data in the world was estimated to be _44 zettabytes_ at the dawn of 2020. To put it in perspective, _one zettabyte_ is equivalent to the data on about 250 billion DVDs. Uff! that's a crazy lot. That is on average, every human created at least _1.7 MB_ of data per second in 2020. By 2025, the amount of data generated each day is expected to reach 463 exabytes globally. Dude we are already in 2022. D-day is coming.

Okay so why am I blabbering all this now? I'll get straight to the point. We consume and produce two types of data on a daily basis:
* [Structured data](https://www.geeksforgeeks.org/what-is-structured-data/) _(Eg. names, dates, addresses, credit card numbers, stock information, geolocation etc..)_
* [Unstructured data](https://www.geeksforgeeks.org/what-is-unstructured-data/) _(Eg. rich media - Media and entertainment data, surveillance data, geo-spatial data, audio, weather data etc..)_

We store all this data in something called the databases. We store all this structured data in relational databases like postgresql, mysql etc. [Relational databases (RDBMS)](https://en.wikipedia.org/wiki/Relational_database) have been around for over 40 years. Historically, they’ve worked well, for the times when data structures were much more simple and static. However, as technology and big data applications advanced, the traditional SQL-based relational database was less equipped to handle rapidly expanding data volumes and the growing complexities of data structures. In the last decade, the non-relational, [NoSQL](https://en.wikipedia.org/wiki/NoSQL) databases became more popular for offering a more flexible, scalable, cost-efficient, alternative to the traditional SQL-based relational databases. 

__It is incredibly important for a developer to excel in his/her database skills in today's data-driven world__. Being able to harness the power of databases like MongoDB is extremely important. Now lets take a look at what MongoDB actually is.

## What is MongoDB?
As the official website puts it
> [MongoDB](https://www.mongodb.com) is an open-source document database built on a horizontal scale-out architecture that uses a flexible schema for storing data.

Yes, MongoDB is a non-relational database that leverages the simple documented-oriented model instead of the conventional schema-oriented model used in most RDBMSs. MongoDB’s document model is simple for developers to learn and use, while still providing all the capabilities needed to meet the most complex requirements at any scale. 

## Why MongoDB?
With some other big players like Amazon and Microsoft making their bet in this NoSQL market with their DynamoDB and CosmosDB, why choose MongoDB? Well, because of the following reasons:
* MongoDB is opensource.
* It is faster than most of it's competition, even the proprietory ones.
* MongoDB's document-oriented model supports better scalability.
* It has a huge online community of developers

Alright enough of the history and chit-chat, let's install MongoDB in our machine and give it a whirl.

----------

### Installing MongoDB
You can download the MongoDB community edition server for all the platforms [here](https://www.mongodb.com/try/download/community).

After successfully downloading and installing MongoDB server in your machine, we would need to download the mongo shell to interact with your mongo database. To install MongoDB in mac OS, you can simply do 
```brew install mongosh```
or you can head to this [link](https://www.mongodb.com/docs/mongodb-shell/install/#std-label-mdb-shell-install) and get the GUI installer.

To check if both mongoDB and mongosh has been installed successfully, simply do
```> mongosh ```
or
```> mongo ```
If everything goes well, this command will boot up the MongoDB server and start the mongo shell and you'll receive a confirmation like this.
![booting up mongo shell](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jp2e8no7grbxpxl0ki96.png)
 
By default, Mongo server will start at `https://127.0.0.1:27017`. By running the `show dbs` command to display the active databases in the server.

### Create our first mongo database
Before we create our first database, let's take a look at the technical stuff. The database model in MongoDB has these four following components: 
1) database 
2) collection 
3) document 
4) fields

Now if you are familiar this with some RDBMS like postgresql, you can compare mongo's collection with psql's schema and document with table. The overall relation and internal structure would look something like this. Image credits to beginnersbook.com

![psql compared to mongodb](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vbt1y9ryvhtozulhihyz.png)

Alright, assuming you are clear with the above architecture, now let's create our first mongo database. To create your database simply do the below command in your mongosh.
```use <database_name>```
In my case, I'm naming my database mongo_test. After running this command, if you do `show dbs` again, it will not show our database in the list yet. Because mongosh will not create an empty database. A database will only be initialized if any of its collection has atleast one datapoint. So without further ado, lets see how we can insert data into our new empty database.

### Insert into database
To insert some data into our empty database we run the below query in mongosh, assuming that I am going to name my first collection in my database as 'friends'.

```python
db.friends.insert({name:'Chandler Bing',trait:'Annoyingly Sarcastic'})
```

On running the query in mongosh, you would receive a confirmation or acknowledgement stating that the data got inserted successfully. Something like...

```python
{
  acknowledged: true,
  insertedIds: { '0': ObjectId("62655a2b05e6a1546bbf8a04") }
}
```

Let's insert some more data, and check if our data has been inserted correctly by running the command

```python
db.friends.find().pretty()
```
![db.collection.find()](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qez5wkpumg749y1wfaay.png)

There we go we have all of our favourite characters!

### Querying with Mongosh
With our friends collection, now let's see how to do conventional where queries with mongosh.

Lets say we wanna find our friend Joey's trait, we might wanna run the below query:
```python
db.friends.find({name:'Joey Tribbiani'},{trait:1})
```
This is like the equivalent of doing a SELECT statement with WHERE clause in traditional RDBMS.
```SQL
SELECT trait FROM db.friends WHERE name='Joey Tribbiani';
```


This will return:
```python
[
  {
    _id: ObjectId("62655cca05e6a1546bbf8a07"),
    trait: 'Suave But Stupid'
  }
]
```
Yes, not surprisingly, Joey is suave 😎

MongoDB is a great database for any developer whose first time it is interacting with a database because of it's JSON-like query syntax, that too without limiting your ability to query.

You can do every query that you normally do with other RDBMS. MongoDB doesn't limit our ability to do queries. If you want a quick cheatsheet version of all the commands you can do with mongosh, I'll link below. That's it for now, thanks for sticking with me until the end, will see you in the next post.

Oops almost forgot! in case you don't like querying with your command line using mongosh, there is a GUI tool called [MongoCompass](https://www.mongodb.com/products/compass). Have a peep.

{% embed https://www.mongodb.com/developer/quickstart/cheat-sheet/ %}