MongoDB Guide for Beginners

MongoDB is an open source document based database, schema less and one of the most popular NoSQL Database. MongoDB has cross platform support by providing high performance and easy to scale it.

This article will explain you about MongoDB installation procedure, fundamentals, usage of MongoDB and comparing the MongoDB with SQL Server database.

MongoDB Architecture
MongoDB Installation

Please visit and download the MongoDB installer from the official website using below link.



Install the downloaded installer as like similar to any other software you install. If you want to install the MongoDB in custom location rather than the default (C:\Program Files\MongoDB\) change it when the installer asks you to choose the target location upon install starts.

Once you install the MongoDB, you will see the different types of MongoDB executables in bin directory of the install location as shown below.

MongoDB Install

MongoDB requires a dedicated location to store the database files which is called data folder. The default data folder location used by the MongoDB is C:\data\db. So you need to make sure this folder is available to use the MongoDB. If this data folder doesn’t exist, let’s go and create it.

In case, if you would like to change the data folder location then open the command prompt, navigate the bin folder from MongoDB installation (shown the above picture) and use the below statement.

[pre class="brush:sql; toolbar: false;" title=""]
>mongod.exe --dbpath "E:\MongoDB\data"
[/pre]
Here is my data folder files show you how the MongoDB storing the files in it. (Which is not exactly similar compared to your data folder)

MongoDB data folder

In order to use the MongoDB, you need to start the MongoDB server with the help of command mongod.exe as shown below

MongoDB Server

Always keep open the above MongoDB server command prompt open to listen the MongoDB database requests and process them.

Now open another command prompt and execute mongo.exe to get enter into MongoDB client as shown below:

MongoDB Client

The default database of the MongoDB is test. If you not create any database on your own or not switched to another database then any commands you execute from the above screen will run against test database.

If you reach to this place then you are successfully installed the MongoDB and ready to use it.

MongoDB Fundamentals

The primary components of MongoDB are Database, Collection and Document.

Database

A database in MongoDB is a container in file system. The container is used to store the set of collections. Typically MongoDB server can have multiple databases.

Collection

A collection in MongoDB is nothing but grouping set of documents, which mean that collection of documents is called a collection in MongoDB. A collection is similar to table in SQL Server. Typically a collection doesn’t have any specific schema.

Document

A document in MongoDB is the actual data which is in the form of key and value pairs. A document is similar to a row in SQL Server table, where key will act as column and value will act a column value.

Documents in MongoDB collection can have a dynamic schema, which mean that all the documents (rows) in a collection (table) may not have the same amount of keys (columns)

Terminology

Here is the below with MongoDB terminology showing how it differs from SQL Server (may be other RDBMS)

SQL Server
MongoDB
Database
Database
Table
Collection
Row
Document
Column
Field
Join (Related Records)
Embedded Documents
Primary Key
Primary Key (By default MongoDB will add _id)

Database Operations

You need to execute the MongoDB commands in the command prompt based on need. Here is the example screen shows you show to the input commands and results returns from the MongoDB to console.

MongoDB Commands

Create Database

If you want to create the database in MongoDB, just use the below statement.

[pre class="brush:sql; toolbar: false;" title=""]
>use dotnet4techies
[/pre]
Your database will not be created unless you insert at least one document into it. Use below command to insert a document.

[pre class="brush:sql; toolbar: false;" title=""]
>db.authors.insert({"name":"Dotnet4Techies"},{"author":"Srinivasa Rao Dhulipalla”})
[/pre]

Now if you execute the below command, you will get to see dotnet4techies is one of the available database.

[pre class="brush:sql; toolbar: false;" title=""]
>show dbs
[/pre]

Create Collection (Create Table)

Use the db.createCollection(name, options) command in MongoDB client to create the collection, where first parameter name is the name of collection and second parameter options is an optional parameter to provide collection parameters like size, no. of documents allowed etc.

[pre class="brush:sql; toolbar: false;" title=""]
>db.createCollection("Employee")
[/pre]
The above command will create an Employee collection in the current database.

[pre class="brush:sql; toolbar: false;" title=""]
>db.createCollection("Employee1", { capped : true, autoIndexID : true, size : 5000, max : 1000 } )
[/pre]
The above command will create an Employee1 collection in current database by allowing only 1000 documents in it. If capped is set to true then once 1000 records limit is reached, further records will overwrite the existing old records from beginning. If autoIndexId is set to true then it will create an index on default field _id

Delete Collection (Delete Table)

Use the db.nameofcollection.drop() command to remove the collection from the current database.

[pre class="brush:sql; toolbar: false;" title=""]
>db.Employee.drop()
[/pre]

The above command will remove the Employee collection from the current database.

Insert Document (Add Row to Table)

Use the db.collectionName.insert(documentData) command to insert the document into the collection as shown below

[pre class="brush:sql; toolbar: false;" title=""]
>db.authors.insert({"name":"Dotnet4Techies"},{"author":"Srinivasa Rao Dhulipalla”})
[/pre]

The above command will insert a document with name and author fields into authors collection.

Query Document (Select query of Table)

Use the db.collectionName.find() command to get the all documents from the collection

[pre class="brush:sql; toolbar: false;" title=""]
>db.authors.find()      -> to list all documents from authors collection
>db.authors.findOne()    -> to list only top one document from authors collection
[/pre]
Update Document (Update query to Table)

Use the db.collectionName.update(criteria, newData) command to update the document based on the section criteria.

[pre class="brush:sql; toolbar: false;" title=""]
>db.authors.update({'name':'Dotnet4Techies'}, {$set:{'name':'New Dotnet4Techies'}},{multi:true})
[/pre]

This will change the name field from all the documents of authors collection from Dotnet4Techies to New Dotnet4Techies

Delete Document (Remove row from Table)

Use the db.collectionName.remove(criteria) command to remove the document from the collection.

[pre class="brush:sql; toolbar: false;" title=""]
>db.authors.remove({'name':'New Dotnet4Techies'})
[/pre]

The above command will remove all the documents from authors collection where the name field have New Dotnet4Techies

[pre class="brush:sql; toolbar: false;" title=""]
>db.authors.remove()
[/pre]

The above command remove all the documents from authors collection

Delete Database

Use the db.dropDatabase() command to delete the current database in MongoDB

[pre class="brush:sql; toolbar: false;" title=""]
>db.dropDatabase()
[/pre]

MongoDB handy commands

Here are the list of basic helpful command in MongoDB and their usage:

Command
Purpose
db.help()
List of DB methods which can be performed
show dbs
List all the databased and their sizes
use database_name (ex: use dotnet4techies)
Switched to another database
db.createcollection(name, options)
Used to create a collection in current database
db.collectionname.drop()
Used to remove the collection
show collections
Lists the all the collections from current database
db.collectionname.insert(documentdata)
Used to insert a document into collection
db.collectionname.find()
Lists the all documents in a collection
db.collectionname.update(criteria, newdata)
Update document based on criteria
db.collectionname.remove(criteria)
Remove the document from collection based on criteria
db.collectionname.remove ()
To remove all the documents from collection
db.dropdatabase()
Used to remove the database
db.collectionname.find().sort({field:1})
Used to sort the documents from the collection. 1 is for ascending order and -1 is for descending order
db.collectionname.ensureindex({field:1})
Used to create an index on given field. 1 is for ascending order and -1 is for descending order
db.collectioname.aggregate(operation)
Used to perform the aggregate operation. Ex: $sum, $avg, $min, $max, $first, $last, etc.
db.stats()
Shows the statistics about the current database in terms of no. of collections, DB size, etc.

Hope this article gives you a complete picture about MongoDB and its command usage. If have any queries let’s use the below comment box to discuss them.

No comments:

Powered by Blogger.