Tuesday, May 12, 2020

MongoDb Data Types

Data type is an essential component of a language or script that is used to define the type of data being used in framing the database. It is important for you to know that MongoDB stores data in BSON format. In this chapter, you will learn about the different data types that exist in MongoDB, along with their implementation techniques.


What Are JSON and BSON?

JavaScript Object Notation (JSON) is a standard file format that uses human type readable text to transmit data with attribute-value pairs and array data types. This is one of the most common data formats which are mainly used for asynchronous browser-server communication. JSON is a language-independent format. BSON, on the other hand, is a computer interchange format that is mainly used for data storage and as a network transfer format in the MongoDB database. It is a simple binary form which is used to represent data structures and associative arrays (often called documents or objects in MongoDB).

 

Key Differences between JSON and BSON

Both are popular choices in the market; let us discuss some of the major difference:

BSON is a serialization format encoding format for JSON mainly used for storing and accessing the documents whereas JSON is a human-readable standard file format mainly used for transmission of data in the form of key-value attribute pairs.

BSON is designed such that it consumes less space, but it is not extremely efficient than JSON. BSON in fact in some cases uses more space than JSON. The reason for this is traversability which means that BSON adds some additional information to documents like string length and sub-objects which in turn makes the traversing faster.


Different MongoDB Data Types

Remote procedure calls in MongoDB can be made by using the BSON format. MongoDB has a unique way of representing data types in which each data type is associated with an alias as well as a number that is usually used to search or find any specific record within a MongoDB database. MongoDB allows its users to implement different variations of data types:

                         

Integer

Integer is a data type that is used for storing a numerical value, i.e., integers as you can save in other programming languages. 32 bit or 64-bit integers are supported, which depends on the server.

db.TestCollection.insert({"Integer example": 62})

Output:


String

String is one of the most frequently implemented data type for storing the data.

db.TestCollection.insert({"string data type" : "This is a sample message."})

Output:

Double

Double, as we know, is used to store float values. It represents the float value and is of 8 bytes. Double is preferred to store and retrieve decimal values as known in SQL. 

db.TestCollection.insert({"double data type": 3.1415})

Output:

Null

Null is implemented for storing a Null value.

db.TestCollection.insert({" EmailID ": null})

Output:

Date

Date is implemented for storing the current date and time as UNIX-time format.

var date=new Date()

var date2=ISODate()

var month=date2.getMonth()

db.TestCollection.insert({"Date":date"Date2":date2"Month":month})

Output:


Boolean

Boolean is implemented for storing a Boolean (i.e., true or false) values.

db.TestCollection.insert({"Nationality Indian": true})

Output::


Arrays

Arrays are implemented for storing arrays or list type or several values under a single key.

var degrees = ["BCA""BS""MCA"]

db.TestCollection.insert({" Array Example" : " Here is an example of array"," Qualification" : degrees})

Output:

Object

Object is implemented for embedded documents.

var embeddedObject = {"English" : 94"ComputerSc." : 96"Maths" : 80,

"GeneralSc." : 85}

db.TestCollection.insert({"Object data type" : "This is Object",

"Marks" : embeddedObject})

Output:

Min/Max Keys

Min / Max keys are implemented for comparing a value adjacent to the lowest as well as highest BSON elements.

                         

Regular expression

Regular expression is implemented for storing regular expression.

 

Code

Code is implemented for storing JavaScript code for your MongoDB document. 


Binary data

Binary data is implemented for storing binary data.


Object ID

Object ID is implemented for storing the ID of the document.


Basic Database Operations

The Mongo Shell

Open the command prompt and navigate to the /bin folder of the MongoDB using the cd command and execute the command mongod there. This will initiate the MongoDB server. We have to keep this command prompt window alive, as this is running MongoDB.

To stop the MongoDB server, simply enter exit and press Enter.

Now, Open another command prompt and navigate to the /bin folder of the MongoDB again and execute the command mongo. This will open up the client to run the MongoDB commands. Please note that you can exit the Mongo shell by running quit() and the Mongo daemon by pressing Ctrl + C at any time.

MongoDB: Creating a Database

In the command prompt window in which we ran the mongo command, after successfully connecting to the mongodb, just type the command the following :

use database_name

This will create a new database with the name database_name if there is no database already present with the same name. If a database already exists with the mentioned name, then it just connects to that database.

            use studentdb

switched to db studentdb

> 

In the above picture, it creates a new database called studentdb and will also connect to the same.

To check the currently connected database, type in db in the command prompt window, and you will get the name of the current database as a result.

db

studentdb

>  

To see the list of all the databases in MongoDB, use command show dbs

show dbs

admin     0.000GB

config    0.000GB

local     0.000GB

>  

Please note that the newly created database studentdb has not been listed after running the above command. This is because, there is no records have been inserted into that database yet. Just insert one record and then run the command again as shown below:

To Insert data, run the following command. Don’t worry about it, we will learn this in detail in next lessons.

db.studentdb.insert({name : "Pankaj Kapoor" }) 

NOTE: In MongoDB, test will be the default database. If no database is created, then all the data will be stored in the test database.

MongoDB: Drop a Database

First check the list of databases available as shown below, using the show dbs command.

show dbs

admin            0.000GB

config           0.000GB

local            0.000GB

studentdb        0.000GB

test             0.000GB

>  

If you want to delete newly created database studentdb. Run the below command to delete the database. Before deleting the database, connect to the required database which is to be deleted.

db.dropDatabase()                                                                       

       use studentdb

switched to db studentdb

db.dropDatabase()

"dropped" : "studentdb""ok" : 1 }

>  

Now again check the list of databases, to verify whether the database is deleted or not.

show dbs

admin     0.000GB

config    0.000GB

local     0.000GB

test      0.000GB

>  

Note that the database studentdb has been deleted and hence, it will not be listed in the list of the databases. 


MongoDB: Creating a Collection

In traditional databases, we generally use schema (or tables), but there's no such hard and fast rule for NoSQL Databases. We have Collections instead of Tables. Basically, collections hold the documents or records.

In MongoDB a collection is automatically created when it is referenced in any command. For example, if you run an insert command :

db.employee.insert({

    name: "Pankaj Kapoor"

})

MongoDB: Creating Collection Explicitly 

Above command will create a collection named student if it doesn't exist already in the database. But we can explicitly create a collection using the createCollection() command. The syntax of createCollection method is:

db.createCollection(nameoptions)

In the above command, name will be the name of the collection and options is a document which can be used to specify configurations for the collection.

Following are the available configuration options for creating a collection in MongoDB:

Field

Type

Description

capped

boolean

(Optional) To create a capped collection, where in we specify the the maximum size or document counts to prevent it from growing beyond a set maximum value.

size

number

(Optional) To specify the maximum size in bytes for a capped collection. If a collection is capped and reaches its maximum size limit, MongoDB then removes older documents from it to make space for new.

max

number

(Optional) This can be used to specify the maximum number of documents allowed in a capped collection.

validator

document

(Optional) Validates any document inserted or updated against provided validation rules.

MongoDB: Creating a Capped Collection

We can create a capped collection using the following command.

db.createCollection("employee", { capped : truesize : 5242880max : 2000 } )

This will create a collection named student, with a maximum size of 5 megabytes and a maximum of 2000 documents.

MongoDB: Drop a Collection

Any collection in a database in MongoDB can be dropped easily using the following command:

db.collection_name.drop()

drop() method will return true is the collection is dropped successfully, else it will return false.

 


Monday, May 11, 2020

Install MongoDB on Windows

This is a complete step by step guide to install MongoDB on Windows.

Step 1: Go to MongoDB download Page and click download as shown in the screenshot. A .msi file like this mongodb-win32-x86_64-2008plus-ssl-3.4.7-signed will be downloaded in your system. Double click on the file to run the installer.

Step 2: Click Next when the MongoDB installation windows pops up.

Step 3: Accept the MongoDB user Agreement and click Next.

Step 4: When the setup asks you to choose the Setup type, choose Complete.

Step 5: Click Install to begin the installation.

Step 6: That’s it. Click Finish once the MongoDB installation is complete.

We are not done here. There are couple of steps we need to do before we can start using MongoDB.

 

MongoDB Configuration

Once you have installed MongoDB, add the bin directory to the path. You need to be aware of two binary executable files.

  • mongod - This is the daemon (a program that always runs in the background as a service) for MongoDB Server.
  • mongo - This is the command line client shell interface for MongoDB.

MongoDB requires a data folder to store its files. The default location for the MongoDB data directory is c:\data\db. So you need to create this folder using the Command Prompt. Execute the following command sequence.

C:\>md data

C:\md data\db

 Then you need to specify set the dbpath to the created directory in mongod.exe. For the same, issue the following commands.

 

In the command prompt, navigate to the bin directory current in the MongoDB installation folder. Suppose my installation folder is C:\Program Files\MongoDB

C:\Users\XYZ>d:cd C:\Program Files\MongoDB\Server\4.2\bin

C:\Program Files\MongoDB\Server\4.2\bin>mongod.exe --dbpath "C:\data" 

 

This will show waiting for connections message on the console output, which indicates that the mongod.exe process is running successfully.

Now to run the MongoDB, you need to open another command prompt and issue the following command.

C:\Program Files\MongoDB\Server\4.2\bin>mongo.exe

MongoDB shell version v4.2.1

connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb

Implicit session: session { "id" : UUID("4260beda-f662-4cbe-9bc7-5c1f2242663c") }

MongoDB server version: 4.2.1

> 

 

Install the Compass GUI

We’ll be using the command line in this tutorial, but MongoDB also offers a tool called Compass to connect to and manage your databases using a GUI.

If you’re on Windows, Compass can be installed as part of the main Mongo installation (just select the appropriate option from the wizard). Otherwise, you can download Compass for your respective OS here.

This is what it looks like: