MongoDB interview questions and answers


The MongoDB database is operated and developed by MongoDB.Inc under the SSPl. In February 2009, the platform was released in the market. It delivers driver support for all programming languages such as C, C++, C# and .net, Go, Node.js, Perl, Python, Motor, Java, Ruby, Swift, Scala, and Mongoid.

MongoDB is a document database well-known for storing data in JSON documents. It acts over the documents and assembles the concept. It offers a flexible data model that will allow you to save unstructured data and offers indexing support and replication with intuitive APIs.

In today’s time, the internet is filled with big data, big complexity, and big users, and it is becoming increasingly complex every day. MongoDB can keep several databases and offers higher performance than scalability and redundancy.

MongoDB operates based on JSON-like documents to provide scalability. It also offers a server from which developers can start and create several databases on it with MongoDB. Since it is a NoSQL database, it will store the data in the documents and collections. Therefore, the collection, database, and documents are related.

Because companies are looking for MongoDB talent, corporations ask several questions before finalizing the job application. Find the top MongoDB interview questions and answers that we wrote specially to offer candidates basic ideas about the type of interview questions.

Generally, during the interview, recruiters will begin by asking basic questions and gradually increase the difficulty of the questions. So, in this MongoDB interview questions, we will cover the basic questions and slowly move to the complex questions. You can easily prepare for your job interview through these personalized interview questions.

Facts

Find the Facts

  • It is easy to scale down or up.
  • It supports field, string, and range-based pattern matching type queries. Developers can use it to search for the date in the database.
  • It uses a dynamic database schema.
  • It comes with support for data partitioning.

1 . What is Mongo shell?

Mongo shell is a JavaScript interface to MongoDB that you can use to query and update data. It is interactive and you can also use to execute administrative operations.

 List out the important features.

Some of the important features are:

  • Uses a schema-less database
  • No complex joins
  • Faster access to data because of the presence of the working set (internal memory)
  • Features like aggregation, sharding, and replication make it easy to use
  • Cross-platform and document-based
  • Automatic fail-over and high-availability

2 . MongoDB is popular as a schema-less database. If yes, how do you create the schema in MongoDB?

It would be more correct to say that MongoDB has a dynamically typed schema because it relies on JSON, which is a schema-free data structure. To create a schema, create and insert a document. Once there is a document, it creates a corresponding collection in the database.

 3 . What is a namespace?

A namespace is the concatenation of the database name and collection name. Example: students.the subject, where students are the database and subject, is the collection.

4 . How do you perform CRUD operations in MongoDB?

  • – Create: db.collection.insert();
  • – Read: db.collection.find();
  • U – Update: db.collection.update();
  • D – Delete: db.collection.remove({“fieldname” : ”value”});

5 . What is BSON?

BSON or binary JSON is the binary- encoded format of JSON. It extends JSON and provides more data types and fields.

6 . Name the default index created for a new collection.

The default index created for the new collection is _id

7 . Name the two storage engines.

MMAPv1 and WiredTiger are the two storage engines in MongoDB.

8 . How do you create and drop a collection in MongoDB?

  • Create collection: db.createCollection();
  • Drop collection: db.collection.drop();

9 . What is the default interval to write updates to the disk?

The default interval is 60 seconds.

10 . How can applications access real-time data changes?

Applications can access real-time data changes using Change streams which acts as a subscriber to all the collection operations like insert, delete and update.

11 . Name the programming languages that you can use

The programming languages that you can use with MongoDB are Java, C, C++, Node.js, Python, PHP, Scala, Erlang, and also Ruby. 

12 . What are the features of MongoDB?

The features of MongoDB are:

  • It is faster and high-performing.
  • It provides efficient indexing.
  • It offers useful features such as sharding and transactions.
  • It is easier to write queries.

13 . How is MongoDB better than MySQL?

MongoDB is better than MySQL because:

  • It is faster than MySQL.
  • It is easier to learn and use.
  • It offers better flexibility.
  • It is easier to scale.

14 . Give a scenario explaining MongoDB is better than RDBMS.

 Suppose we have a table in RDBMS with three columns – id, name, and age. Now suppose we have a new record that contains the id, name, age, and location. If we try to add this record to the existing table, it will throw an error. We have to alter the table before adding the record. But there is no need to alteration with MongoDB because we do not need to add any schema with it.

15 . When to use MongoDB?

use MongoDB when:

  • There is a huge amount of unstructured data.
  • Also, Cloud computing and storage are being considered.
  • Development time is also less

16 . How to create the login page in node.js using MongoDB?

For creating the login page in node.js, first install the following modules

  • Ejs
  • express –save
  • mongoose
  • body-parser –save
  • express-session –save

Run your login code(node js) file. Now also open the login code in the Browser.

17 . Mention the Datatypes

There is a vast range of data types that MongoDB supports. Some of the important ones are:

  • String − This is the most usually utilized datatype to store the information. String in MongoDB should be UTF-8 substantial. 
  • Integer − This sort is utilized to store a mathematical worth. The whole number can be 32 bits or also 64 bits, relying on your worker. 
  • Object ID − Utilize this datatype to store the report’s ID. 
  • Binary data − Generally, utilize this datatype to store paired information. 
  • Code − Generally, utilize this datatype to store JavaScript code into the record. 
  • Regular expression −Generally, utilize this datatype to store standard articulation.
  • Boolean − Generally, utilize this sort to store a boolean (valid/bogus) esteem. 
  • Double − Generally, utilize this sort to store drifting point esteems. 
  • Min/Max keys − Generally, utilize this sort to analyze a worth against the most reduced and most elevated BSON components. 
  • Arrays − Generally, utilize this sort to store exhibits or list or different qualities into one key. 
  • Timestamp −Generally, utilize this can be convenient for recording when you change or add a report. 
  • Object − Generally, utilize this datatype for implanted reports. 
  • Null − Generally, utilize this sort to store a Null worth. 
  • Symbol − Generally, utilize this datatype is indistinguishably from a string; notwithstanding, it’s for the most part held for dialects that utilization a particular image type. 
  • Date − Generally, utilize this datatype to store the current date or time in the UNIX time design. You can indicate your own date time by making an object of Date and spending day, month, year into it. 

18 . How to see the MongoDB connection?

Type the following command to see the MongoDB connection:

db_adminCommand (“connPoolStats”)

19 . How to use MongoDB?

To use MongoDB, open your command prompt and type mongod. MongoDB will start, then you can use it.

20 . How to connect to MongoDB?

To connect to MongoDB, use the following code

  • For windows: 

Open Command Prompt, type the following code:

mongo.exe mongodb://$[hostlist]/$[database]?authSource=$[authSource] –username $[username]
  • For Ubuntu/Mac:

Open the terminal, type the following code in it:

mongo mongodb://$[hostlist]/$[database]?authSource=$[authSource] –username $[username]

21 . How to create a collection in MongoDB?

Using the insert command, you can create a collection in MongoDB. Syntax of using the command is:

DB.collection_name.insert({key:value, key:value…})

22 . How to store the image in MongoDB using node JS?

In the following way, you can store an image in MongoDB using Node JS

  • Setup your Node JS modules
  • Create a view folder (containing the HTML and JS code) for uploading an image
  • Create the middleware for storing the uploaded image
  • Create a controller for the view folder
  • Create a controller for uploading the image(s)
  • Properly define the routes with Express Router
  • Create the Express app server as server.js
  • Run the command: node src/server.js
  • Check the results

23 . How to create a database in MongoDB? How to find all the databases?

The “use” command is used to create a database in MongoDB. The following command creates a database named “company”.

use company

To get the list of all the databases, use the “show” command like the following.

show dbs

24 . Suppose there are two records – A and B. Document A has the name and age of an employee while document B has the location and phone number of another employee. Do you think these two documents can be added to the same collection? Justify your answer.

Yes, it is possible to add these two documents to a collection but only if no schema is defined.

25 . Give the different ways of creating collections

The different ways of creating collections here:

  • by using the createCollection() method.
  • by using the createIndex() method.
  • by using insertOne() or insertMany() method.

26 . Which field is created automatically for every document? 

The “_id” field is created automatically by MongoDB for every document. 

27 . How to drop collection in MongoDB?

To drop collection in MongoDB, use the following method:

DB. collection. drop()

It eliminates an assortment from the data set and doesn’t leave any files related to the dropped assortments.

28 . What is the significance of “_id”?

The “_id” denotes the unique index for every document in a collection. The value of “_id” will be different for every document in a collection. 

29 . What is the difference between drop() and remove()?

The drop() method removes the entire collection including indexes while the remove() method removes the documents from the collection.

30 . How to connect MongoDB with java in eclipse?

To connect MongoDB with Java in eclipse following the steps given below:

  • At first, open the Eclipse IDE, create a Java class
  • Name the class MongoConnect
  • Once the class is created, type the following command: 
MongoClient mongo = new MongoClient(“127.0.0.1”, 27017);

  • Presee shift+ctrl+O  to import the resources
  • To check whether the connection was successful or not, type the following command:

System.out.println(“Connection Established”);

Then you can run your Java application as required.

31 . What are the differences between MySQL and MongoDB?

MySQLMongoDB
Written in C and C++Written in C++ and JavaScript
Follows RDBMS database structureDocument-based structure
Vertical scalingHorizontal and vertical scaling
Rigidly defined data-structure, the schema is strict and should be defined in the beginningDynamic and flexible schema creation of complex documents

32 . Suppose there is a collection named “employees” and it has the following three documents in it:

{
“_id”: “507c35dd8fada716c89d0013”,
“name”: “John”,
“age”: 21,
“YOJ”: 2016
},
{
“_id”: “507c35dd8fada716c89d0014”,
“name”: “Mike”,
“age”: 25,
“YOJ”: 2016
},
{
“_id”: “507c35dd8fada716c89d0015”,
“name”: “Leh”,
“age”: 34,
“YOJ”: 2016
}

34 . What is ObjectId? How is it structured?

ObjectId is a class that is the default primary key for the document in MongoDB. It is found in the _id field of the inserted document. It is a 12-byte BSON type generated using a default algorithm. The structure is:

  • A 4-byte value that represents seconds since Unix epoch
  • 3-byte machine id
  • 2-byte process id
  • 3-bytes counter that starts with a random number

35 .What is the MongoDB compass?

MongoDB Compass analyzes your reports and shows rich constructions inside your assortments through a natural GUI. It permits you to rapidly imagine and investigate your mapping to comprehend the recurrence, types, and scopes of fields in your informational collection.

36 . How to connect MongoDB with node JS?

Use the following steps to connect MongoDB with node JS:

  • Install Node JS
  • Install the MongoDB driver for Node JS
  • Create a free MongoDB Atlas cluster
  • Load the sample data
  • With the help of CONNECT command, get the cluster’s connection details
  • Import MongoClient, to connect the database with the Node JS application
  • Create the main function
  • List the databases in the cluster
  • Save the file
  • Execute the Node JS script in your terminal.

37 . How to connect MongoDB with PHP?

The following steps will help you to connect MongoDB using PHP:

  • Select the MongoDB database
  • Create a collection
  • Using the insert() method, insert a document in MongoDB
  • Using the find() method, find all the documents
  • Using the update() method, update the document in MongoDB

38 . What is the different storage engine used in MongoDB?

Three main storage engines supported are:

  • WiredTiger Storage Engine.
  • In-Memory Storage Engine.
  • MMAPv1 Storage Engine.

40 . What is journaling and how does it work?

MongoDB ensures data integrity by using an on-disk journal that is created for every write. In case of a server crash, the journal can be used to track the writes that were not written to the disk or data files.

41 . What are the different index types in MongoDB?

  • Default: this is the _id that it creates
  • Single field: for indexing and sorting on a single field
  • Compound: for multiple fields
  • Multi-key: for indexing array data
  • Hashed: indexes the hashes of a field value
  • Geospatial: to query geospatial(location) data

42 . What is the difference between updateOne() and replaceOne()?

The updateOne() method updates the content of the matched document while the replaceOne() method replaces the entire document that matched with the query. 

43 . How does concurrency affect the primary replica set?

When the collection changes are written to primary, it writes the same to a special collection in the local database, called the primary’s oplog. Hence, both the collection’s database and local database are locked.

43 . Explain the purpose of the map-reduce command.

Map-reduce is a way to perform aggregation.

  • The Map function emits the key-value pair specified.
  • The Reduce function combines the key value pair and returns the aggregation result.

Syntax:

db.collection.mapReduce( 

function() {emit(key,value);}, 

function(key, values) {return aggregatedResult}, { out: collection } 

</pre.

 )

44 . Explain the working mechanism of Journaling work in MongoDB?

Journaling is used to recover information after the last checkpoint when it exits unexpectedly. The storage engine (WiredTiger) creates a journal record for each of the clients that initiated the write operation. 

If there is an update, a single journal record records the update operation as well as index modifications. Journal records are stored using in-memory buffering. Journal files are stored under the ‘journal’ directory created by it. 

45 . What is GridFS?

GridFS stores and retrieves large files like images, audio and video files, etc. Although the limit to store a file is 16MB, GridFS can store files with sizes greater than that. GridFS breaks the file into chunks and stores each chunk as a different document of a maximum size of 255k. It uses two collections, fs.chunks, and fs.files for storing chunks and metadata, respectively.

46 . Is MongoDB the best NoSQL Database? If yes, why?

MongoDB is the most suitable NoSQL database for data analytics as well as web application development. It helps developers and data scientists gain insights from stored data, unlike Hadoop, which requires experts to analyze data.

It allows for efficient data manipulation and administration capabilities. The support for multiple JavaScript operations and Javascript-based MEAN stack add to the popularity of it. Sharding for horizontal scaling and aggregation framework to build pipelines made MongoDB fast and efficient and hence the best database to use.

47 . Explain the process of Transaction/Locking in MongoDB?

It supports multi-granular locking with read and write locks.

There are three types of locking mechanisms possible:

  • Global level
  • Database level
  • Collection level

The implementation also depends on the individual storage engine. There are four modes of locking:

  • R(shared lock),
  • W(exclusive lock),
  • r(intent shared lock),
  • w(intent exclusive lock).

48 . Explain the procedure of starting the MongoDB server/instance.

To start a MongoDB instance, follow the steps below:

First, open the command prompt and run mongod.exe.Alternatively, you can move to the path where MongoDB is installed, for example, “C: MongoDB”Navigate to the bin folder, locate the mongod.exe and double click the same to execute it.You can also navigate to the required folder, for example, “C: MongoDB/bin” and type mongo to connect MongoDB through the shell.

49 . What is the return value of the deleteMany() method?

The deleteMany() method returns an object containing two properties:

acknowledged: A boolean value representing if the operation was successful or not.

deletedCount: Total number of documents deleted during the operation.