Getting Started With MongoDB

Image for post
Image for post
mongoDB logo

#INTRODUCTION

Hey! Let’s look at mongoDB and we will find out how amazing it is, and why you should use it or know How it really works!.

Since mongoDB is a database, we might as well look at what a database is first. this might be boring to you especially if you’re already using one database or another, but you’ll survive.

##What Is A Database?

A structured set of data held in a computer, especially one that is accessible in various ways.

source: https://www.lexico.com/en/definition/database

So in reality, a database is very easy to understand, it’s just a structured set of data that can be later accessed when need for use arises.

#How Does MongoDB differ from the ‘traditional’ database we have already?

MongoDB is a NoSQL {non-relational) database as compared with the traditional relational database (SQL) we have. While a relational database stores data in row and columns (as in a tabular manner), a non-relational database stores data in a BSON format ( Binary JSON), very similar to JSON,

BSON consist a list of ordered elements which includes a field name, type, and a value, field names are usually strings too. so data is stored as BSON objects (in collections) and can be accessed be key..value pairs just like a JSON object.

One good thing about non-relational databases is the simplicity of setup: In a traditional relational database, you will need to design your tables, relations, data structures first, before you think about coding. Whereas in a non-relational database (like mongoDB), you can start coding without worrying about designing a table because the data is not stored in tables but in collections, key-value pair (keep reading, you’ll understand theses terms as we progress). Non-relational databases are also considered faster than relational databases when dealing with large databases, this is mainly because it allows users to query in a manner that is more sensitive to workload.

## Working With MongoDB

when querying a database, you basically perform four functions known as CRUD

C — Create

R — Read

U — Update

D — Delete

No matter how big your application get’s these are the four basic things you would be doing inside of it.

Without further ado, lets dive into using mongoDB!

Image for post
Image for post
https://i.pinimg.com/originals/f0/85/c8/f085c85642b21ce95b70b892a28d1321.gif

# Installation

WINDOWS

Go to https://www.mongodb.com/ (the official mongoDB website)

click on the “Try free” button contained in the top navbar

the landing page on mongodb official site
the landing page on mongodb official site

since we want to run mongoDB locally on our machine, we would go ahead to select server

Image for post
Image for post

It’s quite easy to download from here, you’ll want to select the windows 64 bit which is the only one available (hey! it’s high time you switch to a 64 bit OS!), and download as an ‘msi’ package.

You should just leave everything as default during installation and you’ll be fine.

Now you’ve successfully installed mongoDB as a service!!

To run mongoDB, open up your command prompt or terminal and paste this:

Change the ‘4.0’ to the version of mongoDB available at the time you use this tutorial.

#INSTALLATION FOR MAC USERS:

the steps for this are quite easy too. Follow the directions here:

https://treehouse.github.io/installation-guides/mac/mongo-mac.html

if you’re seeing this:

Image for post
Image for post

CONGRATULATIONS!! you’ve successfully setup the mongoDB service on your local machine.

NOTE: whenever you want to use mongoDB in your commend prompt, you should run this command first and start up the mongoDB service, you can either bookmark this page or copy the command and save in a text file on your machine. If you’re on a mac, use the command suitable to always startup the mongo service.

After the installation, you can continue with this tutorial with any OS you use..

# CRUD Operations — Getting Started

Basically everything that is done in a normal application routine is based on CRUD operations: from creating a new tweet, deleting a tweet or a Facebook post, retweeting a tweet, uploading a profile image, purchasing from an online store, etc. are all based on the CRUD operations!

NOTE: We are going to be working on our terminal, using the mongoDB service and not node or any other programming language. The best part about this is that once you learn how to use mongoDB from the terminal you can use the exact same commands in any programming language you work with mongoDB from.

Let’s look at some of these commands in mongoDB and see how they work😎🐱‍🏍

The first command you might want to try out in your terminal after starting the mongo service is:

this simply shows you all databases created in your computer. By default, you would see about three names of already created DBs, keep calm, it’s absolutely normal!👍

To perform these CRUD operations, we have to create a new database..

type this command to create a new database for all product in an online store:

now a new DB has been created with the name products, but at the moment even if you run the first command to show all databases, you won’t see it. This is because, in mongoDB, until you save some data or add some collection into your database the database won’t be fully created.

Now that we’ve switched to the new database we just created… let’s get going!..

C — CREATE

create can be referred to as creating in an active state, so whenever we are creating a new entry in our document or database we are utilizing the create operation, this might be from creating a new user, making a post, etc.

We can perform create operations using two commands

insertOne(data, options)

insertMany(data, options)

  • insertOne() — Let’s see how to use the insertOne command works

db always refers to our database which we have already switched to, productDetail refers to our collection which would be created inside of our database (the collection is created with the insert operation if it doesn’t exist, so just name it what you want, but stick with my name to follow accordingly), and the insertOne command is a mongoDB command that inserts a document into our new collection. Using the insertOne, documents are inserted as objects with key — value pairs. Also note that the insertOne method, you can only insert one data/object at a time. MongoDB gives your data a default id for every document you insert into your collection, this unique id would help you reference that document later on and seperate it from every other document in the database. Our result should be something like this:

Image for post
Image for post
db.productDetail.insertOne()
  • insertMany() — let’s see how to use the insertMany command works

the insertMany command would allow us to insert more documents or objects at a time into a collection. To do this we wrap all the documents in an array (square brackets) thereby making it an array of comma separated objects.

You’ll notice that no matter the number of documents passed into the array, each document still has a unique id. In our example above, we have three objects and as such, we expect three distinct id’s as seen in the image below

Image for post
Image for post

R — READ

when using the read operation, I am trying to read something from the database, from checking how many students we have in the database to checking how many items are currently in my shopping cart, all these are read operations.

Let’s perform our first read operation!

By using .find, this would return all the data currently stored in our collection

Image for post
Image for post
db.productDetail.find()

but we’ll notice that at this point, our data looks hard to read, to properly format our data, lets write our command this way:

Image for post
Image for post

There are time when we don’t want to read everything in the database but something specific. In this case we’ll introduce another find operation.

findOne(query, projection)

The findOne operation returns the first document it finds in the collection that matches the criteria or query given to it. the query should alway be a unique thing specific to the document you are searching for.

Let’s try to read only the document with the name “white T-shirt” from our collection:

Image for post
Image for post
db.productDetail.findOne({name: “white T-shirt”})

Some other times we might want to omit certain fields from the documents being returned, this can be because of privacy or because we don’t want to make use of it, this is where using the projection parameter comes in. We specify the field we want to omit and use a Boolean (true, false, 1, 0) operator for the value.

Let’s return find the same item but this time without the category field.

Here’s our result:

Image for post
Image for post
category field has been omitted

Now let’s find the same item but this time with only the category field.

Here’s our result:

Image for post
Image for post
Only category field is returned

Let’s find the same item but this time with only the category field and the name field.

Here’s our result:

Image for post
Image for post
Only the category and name fields are being returned

You’ll notice that the id field is being returned as default every time and that fine because it’s totally normal😉.

Experiment with this as much as you like until you get comfortable with it.

U — UPDATE

We would use the update operation when we’re trying to update an entry that already exists in our database, whether this is changing a users’ username to changing the price of a product in an e commerce store.

We will look at two ways to update a document.

updateOne(filter, update)

updateMany(filter, update)

The update takes in as much as three arguments, but we are going to look at two of them in this tutorial.

filter — This is the unique field you use to identify the document. for this tutorial we would just pick a field but note that in a real world project, you might have to consider some factors before choosing a field, most times the id field is used too because of its unique nature.

update — This contains the update you’re about to make on the document. in the update property an atomic operator is used (an atomic operator is just a keyword that starts with a $ sign, I’ll leave a link to the official docs at the end of this tutorial where you’ll learn more on atomic operators). We would be using a $set atomic operator to set the new value in our document.

updateOne() — Let’s update our document with the name “red gown” to have a quantity of 250 instead of 100

you should get this result

Image for post
Image for post

Now run the .find command and see that the quantity value have been successfully updated.

udpateMany() — let’s say you want to update several documents with a similar field, you use the updateMany() command. In our case, lets update all the documents that have the same category “shirts” and increase their quantities.

Now run the .find command and see that the quantity value of the different documents has been successfully updated.

D — DELETE

The delete operation should always be used with extra caution because once your data has been deleted, it cannot be recovered.

Let’s look at two operations

deleteOne(filter)

deleteMany(filter)

deleteOne()Lets use the deleteOne command to delete a particular document from our collection

try using the .find command after this and you’ll see that the document no longer exists in our collection.

deleteMany()Using the deleteMany() command, we can choose to delete everything in our collection or, we can choose to delete only documents that match certain.

  • Let’s delete all documents in the category of shirts:

try using the .find command after this and you’ll see that the documents in the category of shirts no longer exists in our collection.

  • Finally let’s delete all documents in our collection:

Wheeew!!! If you got to this point, a huge thumbs up to you!! you’ve successfully learned a huge part about mongoDB and CRUD operations.

Is there more to learn???

YES! sure! But once you’re able to master this commands, you’ll have a solid ground to learn other commands!

I’ll Leave some links to recommended materials, you can study and how to use mongoDB in node. You can google things too😎😎.

RECOMMENDED:

MongoDB Official Docs

Using mongoDB with node js: https://flaviocopes.com/node-mongodb/

Using MongoDB with django: https://www.freecodecamp.org/news/using-django-with-mongodb-by-adding-just-one-line-of-code-c386a298e179/

difference between BSON and JSON: https://www.educba.com/json-vs-bson/

CONNECT WITH ME

Follow me on twitter @spillcode

Drop claps 👏👏 and engage in the comment section, I’m willing to learn more and to meet you!.

Thanks.

Hi, I’m a web developer and an amazing person. I intentionally have a lot of fun writing code… I also come up with nice articles too. feel me?

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store