mongodb

MongoDB For Beginners – Learn MongoDB In A Snap

By Rasyue | On August 2, 2020

MongoDB For Beginners

Okay, the reason for this writing is that recently I got the opportunity to work on a project that involves huge and really complex data structure that I actually have to read back all MongoDB operations. I figured that it might be a good idea to write this down hoping that this will be helpful to others.

As this is a writing on MongoDB for beginners, I won’t be using any language specific operation instead I will be using the basic MongoDB operations and run it through the command prompt. Once you got the basic down, it will be a breeze for you when working with MongoDB using any kind of language.

MongoDB Installation For Beginners

If you are new to MongoDB, you can go to MongoDB site and download the Community Edition, install it and you can run you MongoDB locally.

During the installation, if you are running on Windows you may choose to install it as a Service. If you choose to install it as a Service, then every time your machine boot up, it will automatically boot up MongoDB and run it on 127.0.0.1:27017. You can open up MongoDB Compass to access your MongoDB, and you can view your database and collections.

Starting MongoDB locally and connecting to it.

If you choose not to install it as Service, you can open up you command line prompt, cd C:Program Files/MongoDB/Server/4.2/bin and mongod to start your MongoDB.

mongod from command line

Now, open another command line and run mongo to connect to your local MongoDB.

Okay, now we have local MongoDB running and we are connected to it. Its time to run some operations and learn the queries (If you come from SQL)

Starting from here, we will use the command prompt to run the operations.

MongoDB Operations

Alright, let’s start with the basic CRUD operations. If you come from SQL, its the same things with SELECT, INSERT, UPDATE, DELETE. The syntax/command is a bit different though in MongoDB but won’t be too hard for you to understand.

Also to help you better understand this article, a MongoDB collection is equivalent to SQL table. A document is equivalent to a row or a record in SQL.

Insert Document

First, let’s start with inserting document into MongoDB collection.

Go to your your command prompt, make sure you are already connected to your MongoDB, if you are not, run mongo to connect.

In MongoDB, to insert document into your collection is as simple as running db.collection.insertOne() or db.collection.insertMany()

You can replace the collection with any name you like. Remember, collection is equivalent to table in SQL

For example:

use rasyue
// when you run use rasyue, you are changing your database to rasyue
// feel free to use any name you like, if the database does not exists, it will be //automatically created.

db.user.insertOne({ name: "Rasyue", website: "rasyue.com" })

//you can use insertMany() to insert multiple documents
db.user.insertMany([
   { name: "RasyueTwo", website: "www.rasyuetwo.com" },
  { name: "RasyueThree", website: "www.rasyuethree.com" },
  { name: "RasyueFour", website: "www.rasyuefour.com" }
])

//if you want to insert an embed document or an array of object, you can do //like so
db.user.insertOne({    
    {
      name: "RasyueEmbed", website: "www.rasyueembed.com" ,
      address: [ 
             {
                   postal: 23040,
                   country : "Somewhere in the World"
             } 
      ]
    }
})

//what if you have an array inside an array?
db.user.insertOne({
     name: "Rasyue",
     address: [{
           postal: 23040,
           country: "Somewhere in the World",
           alternate : [  
                 {
                      postal : 23050,
                       country : "Somewhere in the World Too"
                 }      
             ]
          }
     ]
})

Select Document

To query or select document in MongoDB, the basic operation will be to use db.collection.find(). This is equivalent to SQL SELECT FROM. MongoDB does have another method if you want to build a complex select query which is known as db.collection.aggregate(). We will talk more about the aggregate() method in another section.

For example:

use rasyue
// again you may use any kind of database name and collection name

db.user.find({})
//db.use.find({}) this will return all the document in the collection.

db.user.find({ name: "Rasyue" })
// will return a document with the name "Rasyue"

// so how do you find an embed document? you may use the dot notation
db.user.find({ "address.postal" : 23040 })


// so how do you find an object in a second level array?
db.user.find({ "address.alternate.postal" : 23050 })

Okay that’s it for finding document. Move along now.

Update Document

To update document in MongoDB, we can use either db.collection.updateOne() or db.collection.updateMany().

We can also use db.collection.replaceOne() to totally replace a document.

Example on updating document

use rasyue

db.user.updateOne({ name: "RasyueEmbed"}, {$set: { name : "RasyueUpdated"  }}  )

DeleteDocument

To delete document in MongoDB, you can use either db.collection.deleteOne() or db.collection.deleteMany()

For example:

use rasyue

db.user.deleteOne({name: "Rasyue"})

aggregate()

Okay, now that we have gone through the basic CRUD operations, it is time that we can get down to business and learn about the aggregate()method.

Since this post is already too long, I feel like its a good idea to write another article to cover the aggregate method. You can read the article regarding the aggregate method here. I will also talk about other things like MongoDB limitations, data structure problem, relational problem among others.

Stay tuned for my next post.

The End…

You can read more on MongoDB, the article I wrote is a quick and precise summary to help you understand MongoDB faster and better.

That’s it folks! Ohh before you go, a few things to remember, when working with MongoDB:

  1. SQL approach and NoSQL approach are different, in SQL you might be thinking about relational stuff between tables, but in MongoDB, although you are able to use relational between collections, sometimes it might be a better idea to just store everything in one collection.
  2. A document’s maximum size is 16MB. Use that to your advantage. If you are storing a lot of nested object/embedded document and if you think that it might grow larger, relational approach might be a good idea.
  3. Don’t get too attached to MongoDB, although MongoDB is a really good database, but certain situation calls for a certain solution.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*
*