My Brain Cells

Easiest (and best) learning materials for anyone with a curiosity for machine learning and artificial intelligence, Deep learning, Programming, and other fun life hacks.

MongoDB in 10 minutes

 

1. Download and install MongoDB on your PC

2. Now in MongoDB folder, Create a “data” folder it that a “db” folder

                  C:> mkdir data/db C:> cd data C:> mkdir db

3. Now set up your environment variable. copy the path of the bin and hit ok.

4. You can see in bin folder, you have “mongod” , “mongo” files

4. In the terminal, Go to that bin directory 

                >> mongod    {Now our MongoDB server is up and running}

          then >> mongo

5.  Now a mongodb terminal shows in that you can do all the database operation

Operation:

 

1. Finding the current database you’re in

>> db

This command will show the current database you are in. test is the initial database that comes by default.

2. Listing databases

>> show databases

I currently have four databases. They are: CrudDBadminconfig and local.

3. Go to a particular database

>> use <your_db_name>

Here I’ve moved to the local database. You can check this if you try the command db to print out the current database name.

4. Creating a Database

With RDBMS (Relational Database Management Systems) we have Databases, Tables, Rows and Columns.

But in NoSQL databases, such as MongoDB, data is stored in BSON format (a binary version of JSON). They are stored in structures called “collections”.

In SQL databases, these are similar to Tables.

Alright, let’s talk about how we create a database in the mongo shell.

>> use <your_db_name>

If the database is not present already, then MongoDB server is going to create the database for you. Then, it will navigate into it.

5. Creating a Collection


Actually, there are two ways to create a collection. Let’s see both.

One way is to insert data into the collection:

>> db.myCollection.insert({“name”: “john”, “age” : 22, “location”: “colombo”})

This is going to create your collection even if the collection does not exist. Then it will insert a document with name and age. These are non-capped collections.

The second way is shown below:

2.1 Creating a Non-Capped Collection

>> db.createCollection("myCollection")

2.2 Creating a Capped Collection

>> db.createCollection(“mySecondCollection”, {capped : true, size : 2, max : 2})

6. Inserting Data

We can insert data to a new collection, or to a collection that has been created before.

There are three methods of inserting data.

  1. insertOne() is used to insert a single document only.
  2. insertMany() is used to insert more than one document.
  3. insert() is used to insert documents as many as you want.

Below are some examples:

  • insertOne()
db.myCollection.insertOne(
{
"name": "navindu",
"age": 22
}
)
  • insertMany()
db.myCollection.insertMany([
{
"name": "navindu",
"age": 22
},
{
"name": "kavindu",
"age": 20
},

{
"name": "john doe",
"age": 25,
"location": "colombo"
}
])

The insert() method is similar to the insertMany() method.

Also, notice we have inserted a new property called location on the document for John DoeSo if you use findthen you’ll see only for john doe the location property is attached.

This can be an advantage when it comes to NoSQL databases such as MongoDB. It allows for scalability.

7. Querying Data

db.myCollection.find()

If you want to see this data in a cleaner, way just add .pretty() to the end of it. This will display document in pretty-printed JSON format.

db.myCollection.find().pretty()

Well, whenever you insert a document, MongoDB automatically adds an _id field which uniquely identifies each document. If you do not want it to display, just simply run the following command

db.myCollection.find({}, _id: 0).pretty()

Next, we’ll look at filtering data.

If you want to display some specific document, you could specify a single detail of the document which you want to be displayed.

db.myCollection.find(
{
name: "john"
}
)

Let’s say you want only to display people whose age is less than 25. You can use $lt to filter for this.

db.myCollection.find(
{
age : {$lt : 25}
}
)

Similarly, $gt stands for greater than, $lte is “less than or equal to”, $gte is “greater than or equal to” and $ne is “not equal”.

8. Updating documents

Let’s say you want to update someone’s address or age, how you could do it? Well, see the next example:

>> db.myCollection.update({age : 20}, {$set: {age: 23}})

The first argument is the field of which document you want to update. Here, I specify age for the simplicity. In production environment, you could use something like the _id field.

It is always better to use something like _id to update a unique row. This is because multiple fields can have same age and name. Therefore, if you update a single row, it will affect all rows which have same name and age.

If you need to remove a property from a single document, you could do something like this (let’s say you want age to be gone):

db.myCollection.update({name: "navindu"}, {$unset: age});

9. Removing a document

As I have mentioned earlier, when you update or delete a document, you just need specify the _id not just nameagelocation.

db.myCollection.remove({name: "navindu"});

10. Removing a collection

db.myCollection.remove({});

Note, this is not equal to thedrop()method. The difference is drop() is used to remove all the documents inside a collection, but the remove() method is used to delete all the documents along with the collection itself.

Logical Operators

MongoDB provides logical operators. The picture below summarizes the different types of logical operators.

reference: MongoDB manual

Let’s say you want to display people whose age is less than 25, and also whose location is Colombo. What we could do?

We can use the $and operator!

>> db.myCollection.find({$and:[{age : {$lt : 25}}, {location: “colombo”}]});

Last but not least, let’s talk about aggregation.

Aggregation

A quick reminder on what we learned about aggregation functions in SQL databases:

Simply put, aggregation groups values from multiple documents and summarizes them in some way.

Imagine if we had male and female students in a recordBook collection and we want a total count on each of them. In order to get the sum of males and females, we could use the $group aggregate function.

db.recordBook.aggregate([
{
$group : {_id : "$gender", result: {$sum: 1}}
}
]);

Anthony

Leave a Reply

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

Back to top