Intro to MongoDB

Intro to MongoDB

Hello! Nice to see you reading!
By the way, let me come to the point directly this time, I mean today I’m going to avoid my circumlocutions that’s my usual way of writing a blog. So, have you ever worked with databases? Do you know what database is? Which tool you have been using to manage your databases (e.i SQL, etc)? A couple of questions will be answered and a tool to manage a database that calls MongoDB will be discussed for beginners in this blog of mine. If you are ready then…

Okay, so you chose to continue reading. Let’s go then:-

What is a database?

It is simply the collection of data in bulk. It may be centralized or distributed. It may be relational (tables) or non-relational(collections of files).

What is MongoDB? (comparison with RDMS: relational database management sys.)

It is the tool to manage the database.

* it is no-SQL database management system.

* it does not define any permanent structure of files and fields to enter data, unlike SQL which defines tables. As it works on BSON data format.

* it has collections instead of tables.

* it has documents instead of rows.

* it has fields instead of columns.

When to use MongoDB?

*go Here:

What is Binary JSON or BSON?

BSON is an explanative version of JSON which allows the storage and manipulation of objects such as ISODate and OjbectId . It allows for MongoDB to produce a syntax and object-rich document beyond what JSON can. And JSON in itself is a non-predefined structured data, which is easier to read by humans and do not bound by limitations of attributes of tables.

From where to download?

* for the terminal based [recommended] in Linux (Ubuntu):

sudo apt install mongodb

* for GUI-windows go Here.

WORKING WITH MONGO-DB (in terminal)

Commands                               //description

* mongo //to get into the mongodb shell.

* show databases //to see the available databases, generally: admin and local are present by default.

* use blog //Now let’s create a new database by any name here I used “blog”. Use command will select the DB if it is already created otherwise will create the one.

* db //this will show/refer to the current selected DB (database).

Output (1)

:~$ mongo

MongoDB shell version: 2.6.10

connecting to: test

> show databases

admin (empty)

local 0.078GB

school 0.078GB

> use blog

switched to db blog

> db

blog

//now our blog DB is selected to operate so, let’s create a new collection in it.

* db.createCollection(“post”) //this will create a collection named as “post”. Note the capital ‘C’.

* show collections //this will show all the collections available in the database. Here “post” and “system.indexes” must be present by default.

//inserting data in the DB.

* db.post.insert({“title” : “post1”, “description” : “beginners”, “topic” : “mongodb”}) //whatever you write within “( )” will be your object, and it must be in JSON format.

* db.post.insert({“title” : “post2”, “description” : “intermediate”, ”topic”:”mongodb”})

//you may also omit the step of createCollection and just start inserting in any new collection. Like

* db.justnew.insert({“title” : “nothing”, “description” : “nothing”, “topic” : “nothing”}) //this command with insert the data in “justnew” collection if it is already created otherwise will create this new collection, initialized with this new given data.

//but we don’t need this justnew collection so let’s delete it with

Delete Collections

* show collections //to see all the collections

* db.justnew.drop() //to delete the “justnew” collection

* show collections //see the removed collection is no more.

Output (2)

> db.createCollection("post")

{ "ok" : 1 }

> show collections

post

system.indexes

> db.post.insert({"name":"post1","description":"beginners","topic":"mongodb"})

WriteResult({ "nInserted" : 1 })

> db.post.insert({"name":"post2","description":"beginners","topic":"mongodb"})

WriteResult({ "nInserted" : 1 })

> db.justnew.insert({"title":"nothing","description":"nothing","topic":"nothing"})

WriteResult({ "nInserted" : 1 })

> show collections

justnew

post

system.indexes

> db.justnew.drop()

true

> show collections

post

system.indexes

//you insert data in a collection in JSON format, it doesn’t have a permanent structure to insert, unlike tables where you need to insert data into every field. Here you may omit or insert any new field into the object like you may remove “topic” or you may add extra “reference blog” to any object.

//let’s simply extract the data from the collection to print. To see data of a collection we have

* db.post.findOne() //to see the first object with “( )” query. You put a query in “( )”. we’ll see query soon on this blog.

* db.post.find() //to print all the objects. But in this case, we don’t get the output which is easy to read. Thats-why

* db.post.find().pretty() //this will print the output in more readable form.

* db.post.renameCollection(“newpost”) //you may also rename a collection if you want.

Output (3)

> db.post.findOne()

{

 "_id" : ObjectId("59a70183b3aeff039f6be403"),

 "name" : "post1",

 "description" : "beginners",

 "topic" : "mongodb"

}

> db.post.find()

{ "_id" : ObjectId("59a70183b3aeff039f6be403"), "name" : "post1", "description" : "beginners", "topic" : "mongodb" }

{ "_id" : ObjectId("59a7027fb3aeff039f6be404"), "name" : "post2", "description" : "beginners", "topic" : "mongodb" }

> db.post.find().pretty()

{

 "_id" : ObjectId("59a70183b3aeff039f6be403"),

 "name" : "post1",

 "description" : "beginners",

 "topic" : "mongodb"

}

{

 "_id" : ObjectId("59a7027fb3aeff039f6be404"),

 "name" : "post2",

 "description" : "beginners",

 "topic" : "mongodb"

}

> db.post.renameCollection("newpost")

{ "ok" : 1 }

//now you may create DB, create collections, rename collections, insert data into them, print data from them, drop collections, but what if we have extracted the data of collections as per a required query. It means to see the data of only those students which are in V class, or whose last name is “Saxena”, etc.

//Creating a new DB to perform queries.

For this I need a collection with multiple objects and more fields so that I can perform queries on them. Because our “post” collection is quite very small, we need a bigger one. So, I have already created a Json file for this. let’s see. But first I’ll delete the current “post” DB

* db.dropDatabase()

* use school

* db

* db.student.insert([]) //here I inserted 11 student’s record. I just copied my json file and pasted in these “[ ]”. You may download my json file from Here.

* db.students.insert([{ “name” : “shiva”, “class” : “second yr”, “college” : “NIEC”, “age” : “19”, “gender” : “male” }, { “name” : “sheena”, “class” : “third yr”, “college” : “BVP”, “age” : “18”, “gender” : “female” }, { “name” : “mayank”, “class” : “first yr”, “college” : “BVP”, “age” : “18”, “gender” : “male” }, { “name” : “chayanika”, “class” : “second yr”, “college” : “USIT”, “age” : “19”, “gender” : “female” }, { “name” : “geetika”, “class” : “fourth yr”, “college” : “NSIT”, “age” : “22”, “gender” : “female” }, { “name” : “aditya”, “class” : “first yr”, “college” : “AIACT”, “age” : “18”, “gender” : “male” }, { “name” : “sharib”, “class” : “third yr”, “college” : “MAIT”, “age” : “22”, “gender” : “male” }, { “name” : “neeraj”, “class” : “second yr”, “college” : “NIEC”, “age” : “18”, “gender” : “male” }, { “name” : “shubham”, “class” : “second yr”, “college” : “NIEC”, “age” : “19”, “gender” : “male” }, { “name” : “prashant”, “class” : “third yr”, “college” : “MAIT”, “age” : “18”, “gender” : “male” }, { “name” : “saroj”, “class” : “third yr”, “college” : “MAIT”, “age” : “18”, “gender” : “female” }] )

//here we noticed that if multiple objects need to be inserted in one time then all the json objects are kept in “[ ]”, this means the insertion will happen of a list (array of objects).

You may also do : db.students.find().pretty() //for a more readable print.

Output (4)

> db.dropDatabase()

{ "dropped" : "blog", "ok" : 1 }

> use school

switched to db school

> db

school

> db.students.insert([{ "name" : "shiva", "class" : "second yr", "college" : "NIEC", "age" : "19", "gender" : "male" }, { "name" : "sheena", "class" : "third yr", "college" : "BVP", "age" : "18", "gender" : "female" }, { "name" : "mayank", "class" : "first yr", "college" : "BVP", "age" : "18", "gender" : "male" }, { "name" : "chayanika", "class" : "second yr", "college" : "USIT", "age" : "19", "gender" : "female" }, { "name" : "geetika", "class" : "fourth yr", "college" : "NSIT", "age" : "22", "gender" : "female" }, { "name" : "aditya", "class" : "first yr", "college" : "AIACT", "age" : "18", "gender" : "male" }, { "name" : "sharib", "class" : "third yr", "college" : "MAIT", "age" : "22", "gender" : "male" }, { "name" : "neeraj", "class" : "second yr", "college" : "NIEC", "age" : "18", "gender" : "male" }, { "name" : "shubham", "class" : "second yr", "college" : "NIEC", "age" : "19", "gender" : "male" }, { "name" : "prashant", "class" : "third yr", "college" : "MAIT", "age" : "18", "gender" : "male" }, { "name" : "saroj", "class" : "third yr", "college" : "MAIT", "age" : "18", "gender" : "female" }] )

BulkWriteResult({

 "writeErrors" : [ ],

 "writeConcernErrors" : [ ],

 "nInserted" : 11,

 "nUpserted" : 0,

 "nMatched" : 0,

 "nModified" : 0,

 "nRemoved" : 0,

 "upserted" : [ ]

})

> db.students.find()

{ "_id" : ObjectId("59a7121fb3aeff039f6be411"), "name" : "shiva", "class" : "second yr", "college" : "NIEC", "age" : "19", "gender" : "male" }

{ "_id" : ObjectId("59a7121fb3aeff039f6be412"), "name" : "sheena", "class" : "third yr", "college" : "BVP", "age" : "18", "gender" : "female" }

{ "_id" : ObjectId("59a7121fb3aeff039f6be413"), "name" : "mayank", "class" : "first yr", "college" : "BVP", "age" : "18", "gender" : "male" }

{ "_id" : ObjectId("59a7121fb3aeff039f6be414"), "name" : "chayanika", "class" : "second yr", "college" : "USIT", "age" : "19", "gender" : "female" }

{ "_id" : ObjectId("59a7121fb3aeff039f6be415"), "name" : "geetika", "class" : "fourth yr", "college" : "NSIT", "age" : "22", "gender" : "female" }

{ "_id" : ObjectId("59a7121fb3aeff039f6be416"), "name" : "aditya", "class" : "first yr", "college" : "AIACT", "age" : "18", "gender" : "male" }

{ "_id" : ObjectId("59a7121fb3aeff039f6be417"), "name" : "sharib", "class" : "third yr", "college" : "MAIT", "age" : "22", "gender" : "male" }

{ "_id" : ObjectId("59a7121fb3aeff039f6be418"), "name" : "neeraj", "class" : "second yr", "college" : "NIEC", "age" : "18", "gender" : "male" }

{ "_id" : ObjectId("59a7121fb3aeff039f6be419"), "name" : "shubham", "class" : "second yr", "college" : "NIEC", "age" : "19", "gender" : "male" }

{ "_id" : ObjectId("59a7121fb3aeff039f6be41a"), "name" : "prashant", "class" : "third yr", "college" : "MAIT", "age" : "18", "gender" : "male" }

{ "_id" : ObjectId("59a7121fb3aeff039f6be41b"), "name" : "saroj", "class" : "third yr", "college" : "MAIT", "age" : "18", "gender" : "female" }

Performing Queries.

* db.students.find({“name” : “shiva”}).pretty() //this will give the data entry where field “name” is “shiva”

* db.students.find({“college” : “MAIT”}) //print all those entries where “college” is “MAIT” in non-pretty format

comma as AND operator

* db.students.find({“college” : “MAIT”, “name” : “sharib”}).pretty() //here ‘,’ comma will act as an AND (&&) operator. So you’ll get o/p only where “name” is “sharib” and “college” is “MAIT”

* db.students.find({“college” : “MAIT”, “name” : “shiva”}).pretty() //here NO output since no students of MAIT is here whose name is shiva.

Logical operator AND ($and:[]) & OR ($or:[])

db.students.find({$or:[{exp1},{exp2},….{expN}]}) //you may put any number of “expressions” in the array notation of OR operator. Similarly

db.students.find({$and:[{exp1},{exp2},….{expN}]}) //same as above just replace ‘or’ with ‘and’

* db.students.find({$and:[                     //you may also write like this for simplicity

{“name” : “geetika”},

{“class” : “fourth yr”},

{“college” : “NSIT”}

]})

* db.students.find({$or:[{“name”: “chayanika”},{“class” : “third yr”},{“college” : “NIEC”}]})

//you may also combine both these operators like:-

* db.students.find({$and:[{$or:[{“name”:”neeraj”},{“name”:”sheena”}]},{“gender”:”male”}]}).pretty()

the $not operator with $eq ‘equals’, $gt ‘greater than’ and $lt ‘less than

* db.students.find( { “age” : { $not: { $eq: “18” } } } ) //this prints where age is not equal to 18

* db.students.find( { “age” : { $not: { $gt: “18” } } } )//this prints where age is not greater than 18

* db.students.find( { “age” : { $not: { $lt: “18” } } } ) //this prints where age is not less than 18

//similarly you may remove the $not: { } if you just want to use $gt, $lt, $eq (by default). Alright? Let’s see the output now.

Output (5)

> db.students.find({"name":"shiva"}).pretty()

{

 "_id" : ObjectId("59a7121fb3aeff039f6be411"),

 "name" : "shiva",

 "class" : "second yr",

 "college" : "NIEC",

 "age" : "19",

 "gender" : "male"

}

> db.students.find({"college":"MAIT"})

{ "_id" : ObjectId("59a7121fb3aeff039f6be417"), "name" : "sharib", "class" : "third yr", "college" : "MAIT", "age" : "22", "gender" : "male" }

{ "_id" : ObjectId("59a7121fb3aeff039f6be41a"), "name" : "prashant", "class" : "third yr", "college" : "MAIT", "age" : "18", "gender" : "male" }

{ "_id" : ObjectId("59a7121fb3aeff039f6be41b"), "name" : "saroj", "class" : "third yr", "college" : "MAIT", "age" : "18", "gender" : "female" }

> db.students.find({"college":"MAIT","name":"sharib"}).pretty()

{

 "_id" : ObjectId("59a7121fb3aeff039f6be417"),

 "name" : "sharib",

 "class" : "third yr",

 "college" : "MAIT",

 "age" : "22",

 "gender" : "male"

}

> db.students.find({"college":"MAIT","name":"shiva"}).pretty()

> db.students.find({$and:[{"name":"geetika"},{"class":"fourth yr"},{"college":"NSIT"}]}).pretty()

{

 "_id" : ObjectId("59a7121fb3aeff039f6be415"),

 "name" : "geetika",

 "class" : "fourth yr",

 "college" : "NSIT",

 "age" : "22",

 "gender" : "female"

}

> db.students.find({$and:[{$or:[{"name":"neeraj"},{"name":"sheena"}]},{"gender":"male"}]}).pretty()

{

 "_id" : ObjectId("59a7121fb3aeff039f6be418"),

 "name" : "neeraj",

 "class" : "second yr",

 "college" : "NIEC",

 "age" : "18",

 "gender" : "male"

}

> db.students.find({

... "age": { $not: { $eq: "18" } }

... })

{ "_id" : ObjectId("59a7121fb3aeff039f6be411"), "name" : "shiva", "class" : "second yr", "college" : "NIEC", "age" : "19", "gender" : "male" }

{ "_id" : ObjectId("59a7121fb3aeff039f6be414"), "name" : "chayanika", "class" : "second yr", "college" : "USIT", "age" : "19", "gender" : "female" }

{ "_id" : ObjectId("59a7121fb3aeff039f6be415"), "name" : "geetika", "class" : "fourth yr", "college" : "NSIT", "age" : "22", "gender" : "female" }

{ "_id" : ObjectId("59a7121fb3aeff039f6be417"), "name" : "sharib", "class" : "third yr", "college" : "MAIT", "age" : "22", "gender" : "male" }

{ "_id" : ObjectId("59a7121fb3aeff039f6be419"), "name" : "shubham", "class" : "second yr", "college" : "NIEC", "age" : "19", "gender" : "male" }

> db.students.find({

... "age": { $not: { $gt: "18" } }

... })

{ "_id" : ObjectId("59a7121fb3aeff039f6be412"), "name" : "sheena", "class" : "third yr", "college" : "BVP", "age" : "18", "gender" : "female" }

{ "_id" : ObjectId("59a7121fb3aeff039f6be413"), "name" : "mayank", "class" : "first yr", "college" : "BVP", "age" : "18", "gender" : "male" }

{ "_id" : ObjectId("59a7121fb3aeff039f6be416"), "name" : "aditya", "class" : "first yr", "college" : "AIACT", "age" : "18", "gender" : "male" }

{ "_id" : ObjectId("59a7121fb3aeff039f6be418"), "name" : "neeraj", "class" : "second yr", "college" : "NIEC", "age" : "18", "gender" : "male" }

{ "_id" : ObjectId("59a7121fb3aeff039f6be41a"), "name" : "prashant", "class" : "third yr", "college" : "MAIT", "age" : "18", "gender" : "male" }

{ "_id" : ObjectId("59a7121fb3aeff039f6be41b"), "name" : "saroj", "class" : "third yr", "college" : "MAIT", "age" : "18", "gender" : "female" }

> db.students.find({ "age": { $not: { $lt: "18" } } })

{ "_id" : ObjectId("59a7121fb3aeff039f6be411"), "name" : "shiva", "class" : "second yr", "college" : "NIEC", "age" : "19", "gender" : "male" }

{ "_id" : ObjectId("59a7121fb3aeff039f6be412"), "name" : "sheena", "class" : "third yr", "college" : "BVP", "age" : "18", "gender" : "female" }

{ "_id" : ObjectId("59a7121fb3aeff039f6be413"), "name" : "mayank", "class" : "first yr", "college" : "BVP", "age" : "18", "gender" : "male" }

{ "_id" : ObjectId("59a7121fb3aeff039f6be414"), "name" : "chayanika", "class" : "second yr", "college" : "USIT", "age" : "19", "gender" : "female" }

{ "_id" : ObjectId("59a7121fb3aeff039f6be415"), "name" : "geetika", "class" : "fourth yr", "college" : "NSIT", "age" : "22", "gender" : "female" }

{ "_id" : ObjectId("59a7121fb3aeff039f6be416"), "name" : "aditya", "class" : "first yr", "college" : "AIACT", "age" : "18", "gender" : "male" }

{ "_id" : ObjectId("59a7121fb3aeff039f6be417"), "name" : "sharib", "class" : "third yr", "college" : "MAIT", "age" : "22", "gender" : "male" }

{ "_id" : ObjectId("59a7121fb3aeff039f6be418"), "name" : "neeraj", "class" : "second yr", "college" : "NIEC", "age" : "18", "gender" : "male" }

{ "_id" : ObjectId("59a7121fb3aeff039f6be419"), "name" : "shubham", "class" : "second yr", "college" : "NIEC", "age" : "19", "gender" : "male" }

{ "_id" : ObjectId("59a7121fb3aeff039f6be41a"), "name" : "prashant", "class" : "third yr", "college" : "MAIT", "age" : "18", "gender" : "male" }

{ "_id" : ObjectId("59a7121fb3aeff039f6be41b"), "name" : "saroj", "class" : "third yr", "college" : "MAIT", "age" : "18", "gender" : "female" }

* if you want to practice and learn more about a query of MongoDB with updated version’s standards go Here!

Deleting a Document

* db.students.remove( { “name” : “aditya” } ) //where name is aditya

* db.students.remove( { “college” : “BVP” } ) //wherever college is BVP delete all.

Updating a record

* db.students.update( { “name” : “geetika” }, {$set: {“college”: ”USIT”, “age”: “21”, “class” : “third yr” } } )

//that is db.collection.update(query, $set: {fields})

Output (6)

> db.students.remove({"name":"aditya"})

WriteResult({ "nRemoved" : 1 })

> db.students.remove({"college":"BVP"})

WriteResult({ "nRemoved" : 2 })

> db.students.update( {"name":"geetika"},{$set: { "college":"USIT", "age":"21", "class":"third yr" }} )

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

Aggregate functions sum /min /max /etc.,

formate: db.collection.aggregate ( [ { $group : { _id: “$field_to_group_by”, resultTitle : { $operation(sum,max,min,etc) : flag/field_to_perform_upon } } } ] )

* db.students.aggregate( [ { $group: { _id: “$gender”, total: { $sum : 1 } } } ] )

//here sum is given the flag of 1 means you want to perform sum. of genders means this query will return you the no. of males and females (since grouped by gender).

* db.students.aggregate( [ { $group: { _id: “college”, total: { $sum : 1 } } } ] )

//this will count the number of students in each college.

* db.students.aggregate( [ { $group : { _id: “$gender”, MaxAge: { $max : “$age”} } }] )

//this will give max age of students among male and female. And similarly for minimum age we have:

* db.students.aggregate( [ { $group : { _id: “$gender”, MinAge: { $min : “$age”} } }] )

Output (7)

> db.students.aggregate( [ {$group : { _id: "$gender", total: { $sum : 1} } }] )

{ "_id" : "female", "total" : 3 }

{ "_id" : "male", "total" : 5 }

> db.students.aggregate( [ {$group : { _id: "$college", total: { $sum : 1} } }] )

{ "_id" : "MAIT", "total" : 3 }

{ "_id" : "USIT", "total" : 2 }

{ "_id" : "NIEC", "total" : 3 }

> db.students.aggregate( [ {$group : { _id: "$gender", MaxAge: { $max : "$age"} } }] )

{ "_id" : "female", "MaxAge" : "21" }

{ "_id" : "male", "MaxAge" : "22" }

> db.students.aggregate( [ {$group : { _id: "$gender", MinAge: { $min : "$age"} } }] )

{ "_id" : "female", "MinAge" : "18" }

{ "_id" : "male", "MinAge" : "18" }

With this, I think we have reached the end of this blog! Now Finally you are acquainted with MongoDB, I guess, and that exactly was the purpose of this blog. If not then you may reach the assistance of the link Here:

You will find all that you need to know about mongodb here (above link).

See you soon, till then have a nice time and this, is GeekyShacklebolt

bidding you goodbye!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s