Quantcast
Viewing latest article 3
Browse Latest Browse All 26

Top 20 MongoDB Interview Questions

In order to build a MEAN-based web application, MongoDB plays the key role along with AngularJS, NodeJS and Express. In this MongoDB Tutorial, our focus is to start learning MongoDB from beginning. This article can also be taken as Part-1 in Series of MongoDB Interview Questions with practical and detailed answers. We will start will very basic questions about MongoDB including What it is? How to create a NoSql database using MongoDB and then moving to more advanced topics.Image may be NSFW.
Clik here to view.
MongoDB Interview Questions

Getting Started MEAN Stack Tutorial Series

We already have covered other components of Full Stack JavaScript by cover the followings:


MongoDB Interview Questions Tutorial – From Beginner to Professional

What is MongoDB, explain MongoDB as Nosql database in detail and how it is different from relational database?

MongoDB is cross platform document based database. It is a NoSql database and very different from traditional relational databases like Oracle, MS SQL, MySQL etc. MongoDB provides high availability, high performance and easy scalability. Easy scalability means it is very easy to scale MongoDB database in comparison of relational databases.

MongoDb works on the concept of document and collections. We will go through each and dig down in detail. Lets first quickly understand what NoSql databases is?

What is NoSql database?

NoSql referred as non-sql databases that enables us to store and retrieve data in non-tabular format. When we say non-tabular format then we want to say there will no tabular database like relational database. So the data will be present in non-tabular formats.

Now lets understand what document and collection is, with respect to MongoDB, which are backbone of this database.

Document:

Document in MongoDb is a set of key value pairs. Each document has schema associated with it. These schema are dynamic in nature. MongoDb stores documents as BSON data, that stands for Binary representation of JSON data. BSON is binary serialization format that is used to store JSON data. As we discussed above MongoDb documents are key-value pair set and have the following structure.

{
    Key1: value1,
    Key2: value2,
    Key3: value3,
    Key4: value4,
    Key5: value5
    ...
    ...
    keyN: valueN
}

Value can be any of the datatype that BSON supports. BSON supports number of datatypes.

Collection:

In MongoDb collections are used to store documents. Collections can be taken as tables in relational databases.

If we compare MongoDb with relational databases, then Table of relational database is called Collection in MongoDb, Row of relational database is document in MongoDb, Column is called field here and joins are referred as embedded documents.

Below is the simple example of a document:

{
    _id: ObjectId(76dede33htfeed4)
    employeId: 299377,
    employeName: "Jerry",
    address: "Street3, NY",
    technologyKnown: ['java', 'python'],
    salary: 108770,
    education: [
        {
            degree:"MCA", 
            dateCompleted: new Date(2009,2,10,1,11)
        },
        {
            degree:"BSC", 
            dateCompleted: new Date(2006,2,10,1,11)
        }
    ]
}

In the example above we have created a simple document, that contains information about a employee.

_id is the identity of document, it is basically a hexadecimal value, that ensures uniqueness of a document. As we can see employeeId is type of int, address is String, technlogyKnown is array of Strings. In the education field, there is date field. There are verify of datatype that MongoDb supports.

Although there are few restrictions with key or field names:

  • Field names cannot be null.
  • Field names cannot contain dot (.)
  • Field names cannot start with dollar sign($).

_id is reserved for primary key in MongoDb.

Back to top

What are key advantages of MongoDB?

Key Advantages of MongoDB:

Following are  the  key advantages of using MongoDB i.e. a NoSQL database:

  • Removal of Complex Joins:
    unlike relational databases where tables are referentially connected, and to retrieve data, we need to build a complex query using joins. To write such complex queries one need to have a very good command on db. In MongoDb you need not to write such complex queries, all you need to do is to design a good schema that will contain these documents
  • Easy to scale:
    MongoDb enables us to horizontal scale the database. For this purpose there is technique called sharding is used.
  • Clear structure of object:
    In MongoDb if there is good schema defined, there will be a very clear structure of object and one can easily identity the collection and document structure.
  • Failover:
    Failover is automatically handled, that means , in a cluster if a node goes down which is primary, secondary node automatically comes up.

Back to top

Learn the #1 Resource to Become a MEAN Stack Developer

Plus, Quick and Easy way to develop your First Angular 2/ Angular 4 Real-world Application with a NodeJS Backend.
  • Learn MEAN Stack Development
  • How AngularJS interacts with BackEnd
  • Use MongoDB with Mongoose
  • Using ExpressJS as NodeJS Framework
  • Front End Optimistic updation

Learn More Now…Click Here

Explain with steps how to configure MongoDB in details, attach code snippet and diagram whereever applicable?

To configure MongoDb on our local machine or on some remote machine, first we need to download the extract of MongoDb from MongoDb official website (https://www.mongodb.com/download-center).

Based on the operations system, we need to download the extract or installation file. Make sure you are downloading the latest version of MongoDb.

One you have downloaded the extract from web. Now we need to install and configure it. Here we will be talking about installation and configuration on Windows operating system. First we need to install the extract file that is downloaded from MongoDb official site.

First we need to create two folders data and under data we need to create db folder. Following will be commands for the same.

Here I am creating these two folders in C drive.Image may be NSFW.
Clik here to view.
MongoDB Tutorial

Once we have created these two directories, we need to navigate to bin folder of mongodb insallation directory. After that we need to run the command as below :

mongod.exe –dbpath “C:\data\db”

Image may be NSFW.
Clik here to view.
MongoDB Installation Tutorial
If every things goes fine then, console will show waiting for connections, which indicates that mongodb has been installed and configured successfully.Image may be NSFW.
Clik here to view.
MongoDB Configuration

Now to run MongoDb, open console in other console. And run mongo.exe command.Image may be NSFW.
Clik here to view.
MongoDB Commands

In the snap above, we have connected to mongodb and created a test record and executed a find command which ensures that mongodb has been installed and executed successfully. These find and save commands will be covered in next questions.

Back to top

Explain how to define schema in MongoDB with example, how these schemas are different with RDBMS schema, explain with example?

Data in MongoDb is stored in form of key , value pairs. And a set of these data is called document in terms of MongoDb. Each document has a flexible schema. Documents don’t need to have the same set of fields, structure. MongoDb provides such flexibility.

While designing mongodb schema , there are few things that we need to keep in mind.

  • Objects that are intended to use together, should be kept in a document. If not then its better to separate these objects in different documents.
  • Schema should be optimized for the queries or use cases that are most frequently used.
  • Joins can be used but make sure to use joins while writing data on data base not while reading data from database.
  • Schema should be designed particularly on the requirement and should be flexible.

Lets try to understand it with an example and we will compare the schema of MongoDb with RDBMS schema.

Lets suppose we are designing a online shopping web application. Which have the following requirements:

  • There will be multiple items with some tags.
  • Each item will have unique name and description.
  • Each item will have information about seller, name and id.
  • Each item will have then number of comments given by users with likes and dislikes
  • On each item can have multiple comments or no comments.

Lets see how RDBMS schema will look like:Image may be NSFW.
Clik here to view.
MongoDB Schema Example

As we can see, as per our requirement, there will three tables, which will have relation to each other. There will be an item table with some fields, which will have connected with tags table. Tags table will have referential relation with item table, Same goes for comments table, which will also have referential relation with item table.

Now lets try to achieve the same with MongoDb. Lets design schema for the same in MongoDb. MongoDb schema will have a well defined collection, which will adhere to the requirement. Below is the schema for the same.Image may be NSFW.
Clik here to view.
MongoDB Schema Tutorial

Now if we compare both the schemas, we can see in relational database we need to create three different tables with referential relation, where as in MongoDb the same can be achieved by just a well defined collection.

Back to top

Explain how to create database in MongoDB?

To create database in MongoDb, ‘use’ command is used. This command is used to create database in MongoDb. It will create database if doesnot exists if exists it will return the existing database name. In MongoDb the default database is ‘test’. If we don’t create any database the collections will be stored in the default test database.

Syntax of this command is as follows:

use <DATABASE_NAME>

Lets try to understand this command with example :

Suppose we need to create database with name BookStore. Syntax for the same will be:Image may be NSFW.
Clik here to view.
Create MongoDB Database
Lets say we want to check the list of database, we will use the show dbs command. Below is the syntax for the same.Image may be NSFW.
Clik here to view.
MongoDB Database Tutorial

Wondering ! why our newly created database is not in the list. The answer is the database should have at least one document stored. Once our db will have records or documents, it will be displayed in the list.

Lets create a record in db and try to check the same with show dbs command.Image may be NSFW.
Clik here to view.
Show DBS Command

Here we have created a document and stored a record in this. Now if we check with the same command , as you can see our newly created database BookStoreDb is top on the list.

If you want to  check on which database you are currently on, db command will be used, below is the syntex:Image may be NSFW.
Clik here to view.
BookStoreDB in MongoDB

Back to top

What are collections in MongoDB, explain with example?

Collections in MongoDb:

Collections in MongoDb are similar to tables in relational databases. Collections contains the documents in MongoDB. These documents may or may not be in the same structure.

To create collections in MongoDb createCollection is used. Syntex to create collection in MongoDb is :

db.createCollection(name, options)

This method takes two parameters, name and options. Name is implicit that is name of collection that is being created. Options is the optional parameter and of document type. Which will have configuration related to document.

Below are the configuration options for collection:

  • autoIndexID, which is Boolean type of field, optional parameter, true means index should be creted on the _id. Default value is false.
  • max , number type of field, optional parameter, indicates max number of documents allowed in the collection.
  • capped , Boolean type of field, optional parameter, if true creates a capped collection.
  • size , number type of field, indicates the size of capped collection.

Lets try to understand with creating a collection:Image may be NSFW.
Clik here to view.
Creating Collections in MongoDB

Here we have created a collection with ComputerProgramming name.

Now lets check the created collection. To list the collections in MongoDb, the following command will be used:

show collections

Lets try it:Image may be NSFW.
Clik here to view.
Show Collections

As we can see it has the list of collections and our newly created collection(ComputerProgramming) as well.

Now lets create collection with the optional fields:Image may be NSFW.
Clik here to view.
MongoDB Collections Tutorial

As we can see, MongoDb has created collection with the options provided. Lets try to list collections now, it should both the collections that we have created.Image may be NSFW.
Clik here to view.
MongoDB Collections List

In MongoDb, we don’t need to explicitly create collections. MongoDb automatically creates the collections once we insert document. Lets try to create  a collection not with createCollection command, but directly inserting records.Image may be NSFW.
Clik here to view.
Show Collections in MongoDB

As you can see now, we have directly inserted document in ScienceBooks collection, which was not present. MongoDb automatically created ScienceBooks document and inserted records in it. In show collection command now it has the collection, ScienceBooks. It is all about collection and database in MongoDb.

Back to top

Learn Professional Web Development in AngularJS while building 10 unique Web Apps.
77 lectures, 14.5 Hours Video, All Levels
  • Your First Angular Website
  • Web Template Store
  • myContacts App
  • ngSocial Facebook App
  • Job Directory
  • KnowledgeBase
  • User Authentication App
  • Instagram Gallery
  • PubNub Chat
  • AutoFind

And also we will find Quiz at the end of each application to verify the skill improvement.

Intermediate to Advanced MongoDB Interview Questions Tutorial

How to create backup and restore the MongoDB database? Explain with example?

Backup is basically to create a dump of existing database, that can be restored as and when required. As in relational database, MongoDB also provides the functionality to create dump of database and use it dump when required, with restoring functionality.

Creating Backup with MongoDB:

In order to create backup of existing database in MongoDB, MongoDB provides mongodump command. Using this command we can create dump of database. This command will create the entire dump of your database in the dump directory.

mongodump

There are few options available with this command, that can be used as needed. Following are the options available with this command:

mongodump  --host <host-name> --port <portnumber>
This command will create the db dump on the given mongodb instance.
For Example:
mongodump –host bookstore.com –port 34889

mongodump --dbpath <path_of_db_that_needs_to_be_backedup> --out <output_directory_for_backup>
This command will create db dump of specified database on the specified output directory.
For Example:
mongodump --dbpath /data/db/ --out ../backup/

mongodump --collection <collection_name> --db <database_name>
This command will create dump of specified collection of specified database.
For Example:
Mongodump --collection OrganicChemistry --db ScienceBooks

Now lets create a backup of db. For this we need to traverse to bin directory of Mongodb installation. Once we are on the bin directory on command prompt, run ‘mongodump’ command. This command will create a dump directory in bin directory of MongoDB. And it will keep all the backup in this folder. Lets try to run the command:Image may be NSFW.
Clik here to view.
MongoDB Tutorial Taking Dump

As we can see, it has created dump of our database successfully. Let’s traverse through the folder structure and try to see dump folder contents:Image may be NSFW.
Clik here to view.
MongoDB Dump Folder Structure

So this will be the folder structure of dump folder. It has created the dump and as we have created BookStoreDB, we can see the dump of that db as well.

Restore Backup with MongoDB:

Similarly to restore the backup, MongoDb comes up the mongorestore command, this command will restore the backup created.

mongorestore

To run this command we need to traverse to bin directory from command prompt and once we are on bin directory, we need to run this command. Lets try to run this command and see:Image may be NSFW.
Clik here to view.
MongoDB Restore Tutorial

As we can see, our created backup has been restored with this command.

This is all about backup and restore database in MongoDb.

Back to top

What are CRUD operations and how these crud operations are performed in MongoDB? Implment a proper example with PHP to connect with MongoDB and perform all CRUD Operations.

CRUD operations in database terms stands for Create, Retrieved, Update, Delete. All databases irrespective of Sql or Non sql have these functions in place. We will go through one by one with example in MongoDB and PHP.

MongoDB and PHP Example:

Like relational database connection, first we need driver to connect. For this we need to download driver from official site. Once we are done with download of driver, we need to put the dll file that is php_mongo.dll in ext directory. After adding the file to ext directory in php.ini file we need to add a line that will have a reference to this dll file.

extension = php_mongo.dll

Once we are done with this, we are set to go with our php code that will create database connection and perform these operations. Lets start with connecting to db and creating a collection:

<?php
   $connection = new MongoClient();
   $database = $connection->BookStore;
   $collection = $db->createCollection("ScienceBooks");
   echo "Collection ScienceBooks created succsessfully, on BookStore database";
?>

The code above will create connection to MongoDb database instance. It will take the database which is BookStore in our case. Once we have selected BookStore database, we are good to go with creating a collection. createCollection() function will create a collection in our case we are taking collection as ScienceBooks. If everything goes fine, we will able to see the below on console.Image may be NSFW.
Clik here to view.
MongoDB and PHP Tutorial

Once our collection is created, we are good to go with performing CRUD operations.

Lets start with C, that is create a record. To create a record, insert() method is used in MongoDb, that takes document as argument, which contains the data that needs to be inserted.

Lets suppose in our bookstore, we need to create records for ScienceBooks, that will have BookName, BookAuthor, ISBN fields. Now are already created collection for ScienceBooks, all we need to do is to create a records underneath it. Below is the example to achieve the same.

<?php
   $connection = new MongoClient();
   $database = $connection->BookStore;
   $collection = $db->ScienceBooks;

   $record = array(
      "BookName" => "Organic Chemistry",
      "BookAuthor" => "James",
      "ISBN" => "45387644"
   );

   $collection->insert($record);

   echo "Created a record in BookStore Db.";

?>

Lets try to understand the above code, we have already created a collection. Now we need to create a record underneath it, what we have done is we have created a record with the fields, for example purpose and make code readable I have hardcoded the values, which will never be in real world scenario, values will be dynamic and not static. We can add as many records in the array as we want. Once our array is ready with the records, all we need to do is to pass it to insert method. If everything goes fine, the below message will be displayed on our console.Image may be NSFW.
Clik here to view.
CRUD Operations with MongoDB

Now lets come to R, that is for read operations in CRUD. Lets try to find out the record that we have just created. To read or in other words to find document in MongoDb term, find() method is used. Lets simulate from code and try to retrieve record from BookStore database.

<?php
   $connection = new MongoClient();
   $database = $connection->BookStore;
   $collection = $db->ScienceBooks;

   $records = $collection->find();

   foreach ($records as $record) {
      echo "BookAuthor :: " . $record[“BookAuthor"] . "\n";
   }
?>

In the above code fragment what we have done is, we have fetched records from ScienceBooks collection, and print BookAuthor. So basically find method will return me list of all records, once I get list of records, we need to traverse through is to get records and print the required value from key associated with it. Like in the code above we have printed book author, which was stored with BookAuthor key.

In crud operations, U stands for updating records in the database. In MongoDb, updations on a record is done though update() method. Just now we have created a records in BookStore database and in ScienceBooks collection. Now we need to updated it through and lets suppose we need to update ISBN number which was by mistake entered incorrect. Below is the code for the same:

<?php
   $connection = new MongoClient();
   $database = $connection->BookStore;
   $collection = $db->ScienceBooks;

   $collection->update(array("ISBN"=>"45387644"),
      array('$set'=>array("ISBN"=>"45387984")));

   $records = $collection->find();

   foreach ($records as $record) {
      echo "ISBN :: " . $record[ISBN"] . "\n";
   }

?>

In the example above, we have just updated the ISBN number that was stored incorrect, we have updated to correct one and finally printed the updated entry. After successful run of the above code fragment we will get ISBN number as 45387984.

Finally lets come to D, that is delete operation in CRUD. To delete a record or in MongoDb terms, to delete a document from database, remove() method is used. Lets try to remove the document with ISBN key as 45387984, which we have just updated:

<?php
   $connection = new MongoClient();
   $database = $connection->BookStore;
   $collection = $db->ScienceBooks;

   $collection->remove(array("ISBN"=>"45387984"));

?>

In the code fragment above we have deleted a record with ISBN key as 45387984. Now if we add the fetch code here and try to traverse over it, it will print nothing. Since the document is no more in the database.

Back to top

What are indexes with respect to a database, how indexing is performed in MongoDB, explain with example?

Indexes are basically a special kind of data structure in database term, which helps to optimize the query performance. Basically while searching in MongoDB , in a normal search, let suppose you have millions of documents in a collection, then for a particular document search, MongoDB have to search through each and every document in the collection which is time taking. While having indexes in place, MongoDB will limit the search with help of these indexes.

In principle Indexes stores the value of a specific field or a set of fields ordered by the value of the field. Since the data is partial, it becomes easier to read this data.

Creating Indexes in MongoDb:

To create index in MongoDb, createIndex method is used. Below is the syntax to create index in MongoDB.

db.<collection_name>.createIndex(<key>:<ascending parameter>)

Collection name will the name of collection. Key will the key on which index needs to be created, next parameter indicates that the key on which index to be created, it’s values should be in ascending or descending order. 1 indicates that values will be in ascending order, whereas -1 indicates that values will be descending order.

Lets take an example, Suppose we have a BookStore database which have collection as ScienceBooks. Document in this collection looks as:

{
	BookName : <Some Book Name>
	BookAuthor: <Some Book Author>
	ISBN: <ISBN>
}

Lets assume we need to create index on BookName field. Below will be code for the same:

db.BookStore.createIndex({BookName:1});

The above code will create a index on BookName field and the values will be in sorted in ascending order.

Indexes can be created on more than one fields, that mean, if we want to add other keys in index, we can and the index will be created on both key fields. Lets try to run the command and create the index:Image may be NSFW.
Clik here to view.
MongoDB Indexes Tutorial

Lets try to understand the output now :

  • numIndexesBefore indicates that how many indexes are present before this command is executed.
  • numIndexesAfter indicates that how many indexes are present after this command is executed.
  • ok represents that the operation was successful and indexes are successfully created in database.

Lets say we want to know how many indexes are there in databases and on what keys they are, getIndexes() command is used. Below is the syntax for the same:

db.<collection_name>.getIndexes()

Lets try to run the command and try to get the list of indexes present in our ScienceBooks collection:Image may be NSFW.
Clik here to view.
MongoDB Indexes Interview Questions

As we can see there are two indexes displayed in the output, one is on _id field and other is on OrganicChemistry field. ‘1’ , as we have discussed, indicates that field values are sorted in ascending order.

Now lets suppose, I want to delete an index from my database. There are basically two methods for dropping indexes from MongoDb. One is to delete an individual index and other is delete all indexes from database.

To drop a particular index, dropIndex() method is used, which takes key as parameter. Below is the syntax for the same:

db.<collection_name>.dropIndex({<Key_Name>:<Order>})

Drop Indexes from MongoDB:

To drop all indexes from database, dropIndexes() method is used. That will drop all the indexes present on collection.

Lets try to run and delete the index that we just created on OrganicChemistry key field:Image may be NSFW.
Clik here to view.
Drop Indexes MongoDB

In output we got nIndexesWas , which indicates that how many indexes were present before execution of this command, where as ok, indicates that the command run was successful.

This is all about creating. Finding and dropping indexes from database.

Back to top

What is projection with respect to MongoDB, how sorting is performed in MongoDB, explain with example?

Whenever we try to find some data from MongoDb, find() method is being used. This method will return me the documents of collection on which this is invoked. Now I can have the where clause as well in my MongoDb query so I can limit the output. Consider a scenerio where I want to retrieve particular fields of document, how to do so?

Lets dig more into it, for an example let say in our bookstore database, from ScienceBooks collection I want to find books with Author James. Whenever I will execute the find method MongoDb will return me the all the documents in the ScienceBooks collection in which Author is James. Now lets suppose I just want ISBN number of the books whose author is James. In order to achieve this there is a concept in MongoDb that is used and called Projection. Below is the syntax for the same:

db.<collection_name>.find({},{<Key_Name>:<Flag to display>})

In the command above, KeyName will be key whose corresponding fields we need to display. Flag to display takes 1 or 0 as input. 1 indicates that the corrospoinding values will be displayed where as 0 indicates that the corresponding values will not been displayed.

Lets try to simulate the same with example:Image may be NSFW.
Clik here to view.
MongoDB Projection Tutorial
As we can see, the output of find command displayed all records of ScienceBooks collection. Now I want to have projection in place and want to see only name and not _id. Lets see how we can achieve this:Image may be NSFW.
Clik here to view.
MongoDB Projection Interview Questions

As we can see in the output, only name is in the output and not _id. And why it is, because if you see the find method, we have used display parameter ‘1’ with name and ‘0’ with _id.

This way we can use projection in our code to find the results which we want.

Back to top

This mini NodeJS course will help you learn how to design your own eCommerce website using NodeJS, Express and Kraken. NodeJS is a brilliant open-source JavaScript runtime environment that allows developers to create powerful and dynamic server-side web applications.

In this project-based course, you will build an entire Bookstore from scratch. You will be able to add, edit and delete books to the backend and customers will be able to browse, add and delete books from their cart as well as purchase it using Paypal.

Image may be NSFW.
Clik here to view.
NodeJS Course

Take this Course Online Now

So far, we have covered beginners to intermediate level MongoDB Interview Questions in this Series. Next part in this series contains more advanced MongoDB FAQs/Interview Questions with detailed examples and source code. Keep in touch 🙂

Top Technical Interview Questions and Answers Series:

The post Top 20 MongoDB Interview Questions appeared first on Web Development Tutorial.


Viewing latest article 3
Browse Latest Browse All 26

Trending Articles