Mongo DB Basics

This article gives you an intro into no sql database mongo and explains it's basics

Hello all. Today we will see basics of  Mongo DB.

What is Mongo db?

     It's a  NoSQL  and  document database. Document means similar to  dictionary in python.

If you are familiar with sql Databases,  record ->  document in mongo db.


Take Mysql(for sql database):

 Databases(contains) -> tables(contains) -> records

In Mongo db:

  Databases(contains) -> collections(contains) -> documents


Install Mongo db

In debian based systems

 sudo apt-get install mongodb-org

other users refer here
Hope you are having/installed mongo in your system

Enter into Mongo Shell by

mongo 

MongoDB shell version: 3.2.9
connecting to: test

It shows the version and connecting to database test by default

create database in mongo shell

 use mydatabase 

Note: mydatabase is my db name . You can give any name

Create collection(table in mysql) in mongo

>db.mynames.insert({"name": "balaji"}) 

WriteResult({ "nInserted" : 1 })

>db.mynames.insert({"name": "hari", "age": 25})

WriteResult({ "nInserted" : 1 })

Note:  mynames is my table/collection name. You can give any name. As you see i didn't define schema. In one doc i have age field in another doc i didn't have. Unlike Mysql it won't throw any error. Thats why it's NoSQL database. It doesn't care about your fields.

Read/find document in Mongo by

> db.mynames.find({"name": "balaji"})
{ "_id" : ObjectId("58864b6f85fb58f1919bafc7"), "name" : "balaji" }

_id -> is the default id field in mongo. It's alpha numeric unlike integer in mysql

Read/ find all documents in collections

>db.mynames.find()

{ "_id" : ObjectId("58864b6f85fb58f1919bafc7"), "name" : "balaji" }

{ "_id" : ObjectId("58864c5285fb58f1919bafc8"), "name" : "hari", "age" : 25 }

Update a document in Mongo

>db.mynames.update({"name": "balaji"}, {"$set": {"country": "India"}})

  WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Note: use {} to update all documents in collection

Check the update by reading a document

>db.mynames.find()
{ "_id" : ObjectId("58864c5285fb58f1919bafc8"), "name" : "hari", "age" : 25 }

{ "_id" : ObjectId("58864b6f85fb58f1919bafc7"), "name" : "balaji", "country" : "India" }

Remove a document in mongo

  > db.mynames.remove({"name": "hari"}) # removes all documents named hari

   > db.mynames.remove({}) # removes all documents

 Remove/drop a collection in mongo

> db.mynames.drop()  # drops collection mynames


Remove or drop database in mongo

  db.dropDatabase() # drops database which is selected/current db


That's it for basics. See You in my next post with advanced queries in Mongo db. Thanks for taking your time to read my blog .

Happy coding!!!

Leave a comment

(Note: Comments are moderated)