MongoDB is an open-source document-oriented database. Document-oriented means it stores the data in a file. MongoDb comes under the category of NoSql database. It stores the data in BSON (Binary JSON) format. It can be accessed through javascript notation and comes with their own shell. It is written in C++.
Why use MongoDB
1. It stores the data in JSON format.
2. Full index support.
3. Replication and high availability.
4. Auto-sharding
How to Install MongoDB on Linux, Windows and Mac OS
Go to the download page of MongoDB and choose the production release for the operating system you use.
If you are using Ubuntu here is a complete installation doc for Ubuntu
MongoDB Terminology
Before going to create our first database with MongoDB let’s first familiar with their terms.
1. Database – It is a set of collections.
2. Collections – Collection in MongoDB is like a table in MySql. But it does not have schema.
3. Document – It is like a record or row in relational databases (like mysql). In mongoDB record is stored in BSON (Binary Json) format.
4. Field – It is similar to column in relational databases .
Creating Database with MongoDB
I assume you have installed MongoDB successfully in your system. Go to the terminal (ctrl + Alt + T) and type mongo and press enter. It opens up a mongo shell.
To check all the database
1 |
# show dbs |
Let’s insert some records in our emp collection. We have not created any database yet but mongodb creates when record is inserted.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
db.emp.insert({ firstname: 'raj', lastname: 'kumar', dob: '09/07/1989', designation:'SE', nationality:'India', gender:'M' }); db.emp.insert({ firstname: 'robin', lastname: 'yadav', dob: '10/08/1984', designation:'Manager', nationality:'India', gender:'M' }); db.emp.insert({ firstname: 'tang', lastname: 'sharma', dob: '12/04/1986', designation:'TL', nationality:'India', gender:'M' }); db.emp.insert({ firstname: 'parul', lastname: 'iti', dob: '13/08/1983', designation:'Emp', nationality:'India', gender:'F' }); |
Now the value is inserted successfully, you can check through find() command.
1 |
# db.emp.find(); |
_id field is created by mongoDB automatically. It is the auto-increment field.
To view the output in proper format
1 |
db.emp.find().forEach(printjson); |
In next post i will talk about queries on mongoDB.