Lets learn how MongoDB works in this simple tutorial . NoSQL databases are very interesting to learn and MongoDB is the easiest NoSQL DB you can learn in very short amount of time.
Depending on your platform you have to download the executable that installs the mongodb. In case of linux you need to download the zip archive and then compile it on your own. You can also download from repository of 10gen and update the version on regular basis. If you are confused, follow the instructions in the online docs.
You can also try mongodb online shell on their official website.
Once you install the monogodb, you can test If the installation is successful by typing the following command in terminal.
You’ll get prompt of mongodb with other official messages.
Creating a Database
Now that mongodb is installed, lets get it to work by creating a simple database. First let’s check the available databases on our system. Type the following command :
This will show list of other databases. But we want to create our own database, so let’s first create our own database.
This will switch the prompt to use a new database with name “jobcard”.
Inserting Records into Database
We have to now add records into our database “jobcard”. We are adding the data in this format :
In order to do that we use the insert() method in following way.
If you don’t add id field then mongodb does that for you automatically. Each record must have an id and either you or the mongodb needs to create it.
We can check if the data is inserted or not by calling find() method.
You’ll see the output that shows the database contents. You can also use the selectors to specify which data you’re interested in and how do you want to access it.
e.g. You can add multiple entries in our jobcard database and then access the record by sorting as per key value pair.
If you have one or more records that has domain: php then those results will be returned by the MongoDB.
If you want, there is a way to update your records with the update() method. Check the following example.
You can check the updated records and confirm the update.
It is important to note that delete() method if used without any specific selectors will delete the records and the database itself. If you want to delete entire database then and only then you should use delete() method on db without any selectors.
//deletes the domain from database
//deletes entire database with all the records
That’s it for now. You learned how to work with mongodb in this tutorial. You can learn more about selecting records and searching them in our next tutorial.
If you know Python and wish to use MongoDB in your project then the below tutorial will definitely help you.
Please feel free to let me know your questions and suggestions in the comments. You can follow me on twitter @maheshkale.