Make a mess with MongoDB

To give you a bit of context, this topic will be for those who aren’t familiar with MongoDB or those who just started using it. I will be running through some basic operations (aka query) and hopefully give some tips at the end of it.

Before we begin, 
You will need to setup MongoDB with node ( I’m hoping you know node a bit , if not YouTube to the rescue ). 
IF you don’t know how to do that , i had a github repo made for just in case.

Alright. Time for some “Definitions

So What is NoSQL ?
 In a nutshell, NoSQL means its not SQL because it does not follow a tabular data structure. Instead NoSQL offers several different types, 
such as Document Store, key-Value Store, Graph etc..
(If you want a much thorough explanation , id recommend this article … or you can always Google It)

What is MongoDB ?
 Well MongoDB is a free and open-source cross-platform document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with schema. MongoDB is developed by MongoDB Inc. and is free and open-source. (Yup , i stole this from Wikipedia. you can check out the full definition here)

Now Then , shall we create a database .
Q: Don’t we have to install mongodb ?
We probably should... ( UGH , Its too annoying to do right now).
Lets do it the easy way and use mLab,

(mLab provides Database-as-a-Service , not entirely free. but the Sandbox Database is actually free. So go create an account and come back… please)

Alright now you have to go create a database, ( make sure you select Amazon Web Services and select Sandbox … unless you want to pay of course , then by all means go ahead )

Now that you have created your Database, lets connect our application.
But before you do that click on users in the mLab console and create a user, so you can access the DB. ( don’t make the user read-only )

And then copy down the URL mentioned in mLab

once you copied that down, open up the source code in your favorite IDE 
( make sure you run “npm install” before you start coding )
and replace the URL value with your connection string 
( aka what you copied before )

so now, you can successfully connect to your Database.

Lets do some basic queries shall we.

scroll down until you see this, this is where we will be testing out our queries.

Here is a list of what ill be covering ( in case you want to skip some )

  • Create Collection (Table)
  • Insert Data
  • Retrieve Data
  • Update Data
  • Delete Data

Create Collection (Table )

You can create a collection ( that’s what they named tables in mongodb ).

.then(collection => {
// other query
.catch(err => res.send(err))

After you type this in, open a command Terminal in the location where app.js is in and run the node script

> node app.js

make sure you visit http://localhost:3000/ too.
Now if you go to the mLab collection section, you will see your new collection.
( yup its that simple )

Insert Data

Now lets insert a document to our collection ( A document is equivalent to a tuple/record in MongoDB… but they aren’t the same)

Alright let me break this down.

firstly you have to be able to access the collection, ive done this using line number 1( const collection = db.collection(‘newCollection’) ).

Now you can insert one document using the insertOne function.
the highlighted JSON object you see is the document we are inserting.

Now if you run this, you can see it appear inside the collection.

The “_id” attribute you see is the unique identifier ( primary key ) for each document, it is an Object ID which has multiple uses ( i’m not going to get into that, but here is the official documentation)

We can insert multiple documents at once using insertMany(), where you can pass the documents in an array and insert them all at once.
( here is some extra info about it… its pretty much the same thing )

Retrieve Data

In MongoDB, the basic way to get data is using the find() or findOne() functions.

The best thing about mongo is that you can retrieve data using any key-value pair in the document ( yes, even nested values … its a bit complicated when it comes to embedded documents in an array ).

So whatever value you pass inside, mongodb will retrieve the first document that matches the query you have passed. 
This is just the basic method of querying, there are advance ways to use this using query operators ( i’m not going to get into it but here is a link)

The find() method is almost the same , but since it returns an array so its a bit different. It kinda looks like this.

Update Data

Now lets update our record from before
There are several methods you can use to update a document, such as updateOne, updateMany, findOneAndUpdate, etc.

The main difference between these two is that updateOne will not return the updated document. however findOneAndUpdate will.
but the core code is very similar.

The first object you see inside updateOne is the selector, which tells mongo which document you want to update. If you do leave an empty object, it will update the first document it finds, much like our findOne query.

The “$set” key is a query operator used in update, it can either specifically overwrite one key or the entire document depending on how it is used.
( It’s not really that complicated , try it out and make a little bit of a mess )

Recently i learned something really cool about the update operation , where you can remove one element from an array of objects using $pull.
( ill leave a link to a document explaining how it works so you can try it out ).

Delete Data

Finally lets delete a document, much like our previous queries it follows the same principle.

See, it looks pretty much the same. And much like the update operations, delete has deleteOne , findOneAndDelete as well as remove.

That’s pretty much it with the delete operation , its self explanatory if you followed the article from the top.

So This is the end.
I hope you learnt something and have fun messing around with MongoDB. 
Dont worry ill leave some useful links at the bottom to help you with much more advanced operations as well.
Cheers :D

MongoDB NodeJS Driver API
MongoDB Documentation
Stack Overflow MongoDB Documentation