Tuesday, May 12, 2020

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:



Introduction to MongoDB

MongoDB is a cross-platform, open-source, NoSQL database, used by many modern Node-based web applications to persist data.

MongoDB is a document-oriented database. This means that it doesn’t use tables and rows to store its data, but instead collections of JSON-like documents. These documents support embedded fields, so related data can be stored within them.

MongoDB is also a schema-less database, By means of ‘schema less’ is that we can store different documents having different schema inside a same collection.

Here’s an example of what a MongoDB document might look like:

{
    _idObjectId(3da252d3902a),
    type"Tutorial",
    title"An Introduction to MongoDB",
    author"Pankaj_Kapoor",
    tags: [ "mongodb""compass""crud" ],
    categories: [
      {
        name"javascript",
        description"Tutorialss on client-side and server-side JavaScript programming"
      },
      {
        name"databases",
        description"Tutorialss on different kinds of databases and their management"
      },
    ],
    content"MongoDB is a cross-platform, open-source, NoSQL database..."

  } 

As you can see, the document has a number of fields (typetitle etc.), which store values (“Tutorial”, “An Introduction to MongoDB” etc.). These values can contain strings, numbers, arrays, arrays of sub-documents (for example, the categories field), geo-coordinates and more.

The _id field name is reserved for use as a primary key. Its value must be unique in the collection, it’s immutable, and it may be of any type other than an array.

History of MongoDB

MongoDB was created by Eliot and Dwight (founders of DoubleClick) in 2007, when they faced scalability issues while working with relational database. The organization that developed MongoDB was originally known as 10gen.

In Feb 2009, they changed their business model and released MongoDB as an open source Project. The organization changed its name in 2013 and now known as MongoDB Inc.

Important Features of MongoDB

  • Queries: It supports ad-hoc queries and document-based queries.
  • Index Support: Any field in the document can be indexed.
  • Replication: It supports Master–Slave replication. MongoDB uses native application to maintain multiple copies of data. Preventing database downtime is one of the replica set’s features as it has self-healing shard.
  • Multiple Servers: The database can run over multiple servers. Data is duplicated to foolproof the system in the case of hardware failure.
  • Auto-sharding: This process distributes data across multiple physical partitions called shards. Due to sharding, MongoDB has an automatic load balancing feature.
  • MapReduce: It supports MapReduce and flexible aggregation tools.
  • Failure Handling: In MongoDB, it’s easy to cope with cases of failures. Huge numbers of replicas give out increased protection and data availability against database downtime like rack failures, multiple machine failures, and data center failures, or even network partitions.
  • GridFS: Without complicating your stack, any sizes of files can be stored. GridFS feature divides files into smaller parts and stores them as separate documents.
  • Schema-less Database: It is a schema-less database written in C++.
  • Document-oriented Storage: It uses BSON format which is a JSON-like format.
  • Procedures: MongoDB JavaScript works well as the database uses the language instead of procedures.

Where do we use MongoDB?

MongoDB is preferred over RDBMS in the following scenarios:

·       Big Data: If you have huge amount of data to be stored in tables, think of MongoDB before RDBMS databases. MongoDB has built in solution for partitioning and sharding your database.

·       Unstable Schema: Adding a new column in RDBMS is hard whereas MongoDB is schema-less. Adding a new field, does not effect old documents and will be very easy.

·       Distributed data Since multiple copies of data  are stored across different servers, recovery of data is instant and safe even if there is a hardware failure.

Language Support by MongoDB

MongoDB currently provides official driver support for all popular programming languages like C, C++, C#, Java, Node.js, Perl, PHP, Python, Ruby, Scala, Go and Erlang.

Where to Use MongoDB?

·      Big Data

·      Content Management and Delivery

·      Mobile and Social Infrastructure

·      User Data Management

·      Data Hub 

Organizations that use MongoDB

Below are some of the big and notable organizations which are using MongoDB as database for most of their business applications.

  • Adobe
  • LinkedIn
  • McAfee
  • FourSquare
  • eBay
  • MetLife
  • SAP

 

MongoDB  Architecture

MongoDB consists of a set of databases. Each database again consists of Collections. Data in MongoDB is stored in collections. The below figure depicts the typical database structure in MongoDB.

Database in MongoDB

Database in MongoDB is nothing but a container for collections. We will learn how to create a new Database, drop a Database and how to use an existing Database in the coming lessons.

Collections in MongoDB

Collection is nothing but a set of MongoDB documents. These documents are equivalent to the row of data in tables in RDBMS. But, collections in MongoDB do not relate to any set schema as compared to RDBMS. Collections are a way of storing related data. Being schemaless, any type of Document can be saved in a collection. Document's can have a maximum size of 4MB. A collection is physically created as soon as the first document is created in it.

Document in MongoDB

Document in MongoDB is nothing but the set of key-value pairs. These documents will have dynamic schema which means that the documents in the same collection do not need to possess the same set of fields.

Since MongoDB is considered as a schema-less database, each collection can hold different type of objects. Every object in a collection is known as Document, which is represented in a JSON like (JavaScript Object Notation) structure(nothing but a list of key-value pair). Data is stored and queried in BSON, its binary representation of JSON-like data.  


Fields

Fields (key and value pairs) are stored in document, documents are stored in collection and collections are stored in database.

This is how a document looks in MongoDB: As you can see this is similar to the row in RDBMS. The only difference is that they are in JSON format.


Table vs Collection

Here we will see how a table in relational database looks in MongoDB. As you see columns are represented as key-value pairs(JSON Format), rows are represented as documents. MongoDB automatically inserts a unique _id(12-byte field) field in every document, this serves as primary key for each document.


Another cool thing about MongoDB is that it supports dynamic schema which means one document of a collection can have 4 fields while the other document has only 3 fields. This is not possible in relational database.

Mapping Relational Databases to MongoDB

If you are coming from a relational database background then it might be difficult for you to relate the RDBMS terms with MongoDB. In this guide, we will see the mapping between relational database and MongoDB.

Mapping relational database to MongoDB


Collections in MongoDB is equivalent to the tables in RDBMS.
Documents in MongoDB is equivalent to the rows in RDBMS.
Fields in MongoDB is equivalent to the columns in RDBMS.

Difference between MongoDB & SQL Database

Below are some of the key term differences between SQL Database and MongoDB 

SQL Database

NoSQL Database (MongoDB)

Relational database

Non-relational database

Supports SQL query language

Supports JSON query language

Table based

Collection based and key-value pair

Row based

Document based

Column based

Field based

Support foreign key

No support for foreign key

Support for triggers

No Support for triggers

Contains schema which is predefined

Contains dynamic schema

Not fit for hierarchical data storage

Best fit for hierarchical data storage

Vertically scalable - increasing RAM

Horizontally scalable - add more servers

Emphasizes on ACID properties (Atomicity, Consistency, Isolation and Durability)

Emphasizes on CAP theorem (Consistency, Availability and Partition tolerance)