Skip to main content

CRUD Operations on MongoDB ( Insertion, Udpation, Deletion and Retrieval)





Mongo DB , as I have explained in one of my previous post(What is MonGODB), is a Non- Relational Document Oriented Database.
Consider, an Relational database like MYSQL, when we want to perform operations on MySQL DB, we have a query language named SQL. But in MongoDB, we don’t have another query language to perform these operations. For every operation, there exists a programming language API, that is used to perform the operations.

So, Basically there are four operations that can be performed on a database known as(CRUD operations)
    a)      Insertion
    b)      Getting data from database
    c)       Updating data in database
    d)      Removing data
Before moving forward lets just get familiar with few terms:
    a)      Document : its like a record/ row in mysql database. But here it is a json object)
For example :   { “name” : “ankit” , age : 10 }

    b)       Collection : It stores the documents in it. i.e. a collection can have many documents in it.
You can think of it as a Mysql database table. But obviously Document and Collection are lot different than MySQL rows or table, but it will give you an idea what they actually are.

So lets look at each of these in detail.
     a)      Insertion :  To insert the data in MySQL database we have a query like
“insert into table_name(col1,col2) values(val1, val2)”
 But in mongoDB we have  insert method.
So lets try to understand this using example.
(Assume you are using users collection, and you have mongodb server running)
So, to insert to document in collection
db.users.insert({"name":"bansal" , age : 10})
The insert operation is done. It is quite simple. Just a JSON object needs to be passed to the insert function  and the insert operation is done.
But whenever we insert any document, we don’t see any result. So, we will see below how to see the inserted documents .

2)  Fetching data from database
To get the data from database, we have two function findOne() and find().
      a)      findOne() : This is basically used to get a single document from the database. This can be used in case someone wants to have a look at the schema etc.. It can give any random document from the collection.
so lets do a query.
db.users.findOne()

The output of this is like
{
        "_id" : ObjectId("52e4b9723196214f8dcabe1f"),
        "name" : "bansal",
        "age" : 10
}

We have inserted a document with name and age field only. But here there is an extra field _id.
This is PRIMARY KEY for this document. In MongoDB, there will always be a _id(PRIMARY KEY) associated with document. If you want you can provide the _id field by your own  but if you don’t provide this field, mongoDB will automatically add this field to some alphanumeric number. It is basically generated by considering few things which make it unique : current time, identifier of the machine generating this id, the process id of the process that is creating this object id and a global counter.(You need not to go into detail of this.)

findOne can take two arguments  : first argument is similar to where clause in select query which specifies which document to select It is a JSON document specifies the where condition.
Like
db.users.findOne({name : "bansal"})

This will print a single document having name equal to “bansal”

Second argument specifies which field of the documents user really needs. Like if we need only age field then our query looks like,
db.users.findOne({},{age : true , _id : false})
This will ouput
{ "age" : 10 }

We have set the age to true, meaning we want the age field. By default every field is set to false but _id field is  set to true, that’s why we have to manually set it to false.

Lets have a look at SQL query,
“select age from users where name = ‘bansal’ “

So to write this using findOne(), our query looks like,

db.users.findOne({name : "bansal"},{age : true , _id : false})

But this method fetches only single document from the database.
To fetch multiple documents we have find() method.

This also takes same argument. First argument as Condition and second as what fields we want to fetch.
Before moving forward, lets add some more records to our database, use the following queries,
> db.users.insert({"name":"abcd" , age : 20})
> db.users.insert({"name":"pqrs" , age : 30})
> db.users.insert({"name":"Hello" , age : 34})
> db.users.insert({"name":"World" , age : 35})
> db.users.insert({"name":"Mongo" , age : 15})
> db.users.insert({"name":"database" , age : 50})

This will insert six more documents to your users collection.
Now to view all the stored documents,
Use db.users.find()
This will output

{ "_id" : ObjectId("52e4b9723196214f8dcabe1f"), "name" : "bansal", "age" : 10 }
{ "_id" : ObjectId("52e4bf273196214f8dcabe20"), "name" : "abcd", "age" : 20 }
{ "_id" : ObjectId("52e4bf323196214f8dcabe21"), "name" : "pqrs", "age" : 30 }
{ "_id" : ObjectId("52e4bf413196214f8dcabe22"), "name" : "Hello", "age" : 34 }
{ "_id" : ObjectId("52e4bf4a3196214f8dcabe23"), "name" : "World", "age" : 35 }
{ "_id" : ObjectId("52e4bfca3196214f8dcabe24"), "name" : "Mongo", "age" : 15 }
{ "_id" : ObjectId("52e4bfd23196214f8dcabe25"), "name" : "database", "age" : 50
}

Looking at the shell, this output is not clear especially when we have fields in documents. So there is one more way to get the result in much more pretty way.

db.users.find().pretty()
The output of this will be
{
        "_id" : ObjectId("52e4b9723196214f8dcabe1f"),
        "name" : "bansal",
        "age" : 10
}
{
        "_id" : ObjectId("52e4bf273196214f8dcabe20"),
        "name" : "abcd",
        "age" : 20
}
{
        "_id" : ObjectId("52e4bf323196214f8dcabe21"),
        "name" : "pqrs",
        "age" : 30
}
{
        "_id" : ObjectId("52e4bf413196214f8dcabe22"),
        "name" : "Hello",
        "age" : 34
}
{
        "_id" : ObjectId("52e4bf4a3196214f8dcabe23"),
        "name" : "World",
        "age" : 35
}
{
        "_id" : ObjectId("52e4bfca3196214f8dcabe24"),
        "name" : "Mongo",
        "age" : 15
}
{
        "_id" : ObjectId("52e4bfd23196214f8dcabe25"),
        "name" : "database",
        "age" : 50
}
As you can see, this is more suitable and more clear.
Ø  Now Suppose we want a query where we want the age to 20 AND name must match abcd i.e. combining two conditions.
db.users.find({name : "abcd" ,age : 20 })
Ø  Now Suppose we want all those documents having age more than 30 (i.e using $gt and $lt)
db.users.find({age : { $gt : 30 }})   // $gt – greater than, $gte -> Greater than or equal to
Ø  All those documents having age less than 30

db.users.find({age : { $lt : 30 }}) // $lt – Lesser than, $lte -> Less than or equal to

Ø  All those documents with age between 30 and 40

db.users.find({age : { $gt : 30 , $lt : 40 }})

Note : Lets have a look at below query,

db.users.find({age : { $gt : 30 } , age : {$lt : 40}})

This query seems to be similar to above query..??? But NO . Both are different. As we have to add all conditions on one field once else it will override the previous condion if we try to apply the condition again on the same field.

Now lets add one more documents to the database
db.users.insert({name :"ankit",grades : 50})

As we know, MongoDB is schema-less, different documents can have different fields in a collection.

Now suppose, I want to see all those documents in which grades fields exists(Using $exists)

db.users.find({grades : {$exists : true}})

We can also provide regular expressions to find the documents like if I like to fetch documents whose name starting with ‘a’

db.users.find({name : {$regex : '^a'}})

or ending with ‘d’, would be like,

db.users.find({name : {$regex : 'd$'}})

Now we have seen that we can have apply two condition with the intersection of them i.e. where name is abcd AND age is 20.

Suppose , I want to fetch the documents with name is abcd OR age is 20.
For this, we use $or. This takes an array of params to be ORed.

db.users.find({$or : [{name : "abcd"},{age :35} ]})

More practical query like we want all users information whose name begins with ‘a’ or these age greater  than 30.
(try to write this yourself)
db.users.find({$or : [{name : {$regex : '^a'}},{age : {$gt : 30}}]})

Now you must have use ORDER By and LIMIT is SQL .
For this we have sort(), limit() and skip() method.

Important thing about them in irrespective of the order we apply them, they execute in their fix order.
First we SORT, then we SKIP and then we LIMIT.
Now Suppose I want to fetch the get users information with highest age(in Descending order).
We just sort the data by age and get the first data using limit.

db.users.find().sort({age : -1}).limit(1)

here we have sorted by age in Descending Order( -1 for Descending / 1 for Ascending)

Remember, as I mentioned order of sort and limit doesn’t matter,

db.users.find().limit(1).sort({age : -1})

Both the query will give same result.

There are many more operation that you can apply with find() but we will limit to this now.

3) Updatating the Result in database.

Update can do a) Complete Replacement of existing document, b) Modify the existing document.

 First argument is where clause, so everything we have learned in find(), is applicable here also.
Suppose
db.users.update({age : 20 }, { name : "rahul"})

After that just fire the db.users.find(), you will see a document with name rahul but with no age fiels, as this method replaces the complete existing document with second parameter.

To update only a single field, use $set
db.users.update({age : 35 }, { $set : {name : "Updated_World"}})

This will update the name of the user to Updated_World with age 35, without affecting the other fields.
Important thing in Update is by default, it updates only one document. To Update multiple documents, you need to set the options.
db.users.update({}, { $set : {name : "Updated_World"}})

This query has no where condition, so it matches every document critera, but it will update the name of only single randomly selected document name.
To do update on multiple documents, we need to pass 3rd parameter as {multi  : true}
db.users.update({}, { $set : {name : "Updated_World"}}, {multi : true})

There is also $upsert used in 3rd paramters.This will insert the document in matching criteria in updates dos not matches any dcument (You can study this by your own)

4) Remove the data from Database.(remove() function)

It takes 1st argument as condition for deletion.
db.users.remove({age : 15})
This will remove all documents having age = 15.

To remove all documents,
Use either,
db.users.remove() or db.users.drop()
// drop will remove the collection so you need to re-create the collection but it is fast as compared to remove() as remove() will delete the documents one –by- one while drop() removes the collection once as it removes a bigger data structure.

Note : All those queries which affect multiple documents are NON_ATOMIC. Ie. If any query affects 10 rows, then it may be possible it first affects 2 rows then gets paused for another process , then updated another 4 and then gets paused for another and soon.
But the operation on single document is completely atomic.

That’s it. Hope you all like it,




You can also check our Microservices post

Introduction to Microservices



Comments

Popular posts from this blog

Login with Google Account using PHP / Javascript using OAuth2.0

Login with Google Account using PHP with code This post have Complete Code for Login / Sign-in  with google Account  using PHP / Javascript with oAuth2.0 Basically today we have seen almost every website needs you to register yourself before you can post or take part in any discussions to the website. But it become a tedious task to register and login to many different sites. Solution is to provide the users the option to Login with existing Google / Facebook account as almost everyone have Facebook and Google account.. In this post, I am going to explain how to integrate the Google Login / Sign in  for your website. For this,  First you need to create your Client ID, Client Secret and your developer API key. For this go to https://developers.google.com/identity/sign-in/web/sign-in Click on the button Create Project. A new window will open up. Please select Create Project / or select already created Project. It will then ask for about type of Project. Please

How To Set Up Apache Virtual Hosts on Ubuntu

How to setup Virtual Host in Ubuntu 16 / Ubuntu 18 on localhost / local machine To run the website with host on localhost(With LAMP) becomes important in many cases. This blog post will demonstrate how to achieve this. Assuming you have LAMP already installed and reading the code from (/var/www/html) Follow the simple steps below Create the code base To Create the code, simply create a directory named localweb inside /var/www/html. Create a file index.php inside localweb directory Content of index.php file <?php  echo "Local Website"; ?> Now our code base is set, so we need to configure apache Go to apache directory cd  /etc/apache2/sites-available/ Create one file named localweb.conf with content <Directory /var/www/html/localweb/>     AllowOverride All </Directory> <VirtualHost *:80>     ServerAdmin admin@localweb.com     ServerName localweb.com     ServerAlias www.localweb.com     Documen

What is Natural Language Processing(NLP)

Introduction to Natural Language Processing(NLP) Natural Language Processing is a technique where in we need to process the normal human language and     makes sense out of it.   Basically this tutorial has two part one is theory and another is practical. We will post few posts on examples of Natural Language Processing on both Stanford CoreNLP / Apache OpenNLP. There are some steps that needs to be follow in processing the Natural Language. Actually there are many Natural Language Processing tools like Apache OpenNLP, Stanford CoreNLP etc. But major steps are same for everyone. a)     Sentence Detection :   In this part, the individual sentence are detected from the main sentence. As for example ,as seen in two different colours, Natural Processing Language is a good Technique. It has various parts ,   there are two different sentences. Using this step we detect this two individual sentence from the main sentence and do the processing for the next step.