MongoDB Interview Questions and Answers 2023
MongoDB is a document-oriented database built on a scale-out architecture such as sorting, secondary indexes, aggregations, etc.
It is popular with developers who are engaged in building scalable applications via agile methodologies. MongoDB is specifically built for creating internet and business applications which need to evolve quickly and scale elegantly with time and requirement.
Some common reasons why MongoDB is the preferred choice by companies:
- The document data model is a powerful way to store and retrieve data, which enables faster development.
- MongoDB’s horizontal, scale-out architecture can support huge volumes of data and traffic.
- MongoDB provides a great user experience to developers where they can just install MongoDB and start writing code immediately.
Beginner MongoDB Interview Questions
- What are the differences between MongoDB and Cassandra?
- What do you understand about a collection in MongoDB?
- What are the different data types in MongoDB?
- How does MongoDB maintain consistency?
- How does scale-out happen in MongoDB?
Intermediate MongoDB Interview Questions
- How to insert a document in MongoDB?
- How to execute queries in MongoDB?
- What is the difference between primary and secondary replica sets?
- What is horizontal and vertical scaling in MongoDB?
- What is sharding in MongoDB?
- What is indexing in MongoDB?
- What are some limitations in using MongoDB?
Advanced MongoDB Interview Questions
- What do you understand about the Aggregation Framework in MongoDB?
- What is meant by transactions in MongoDB?
- What is Map-reduce in MongoDB?
- How to create and restore the backup in MongoDB?
- What is the use of MongoDB charts?
- Explain the limit() method in MongoDB.
Beginner MongoDB Interview Questions and Answers
1. What are the differences between MongoDB and Cassandra?
Feature | MongoDB | Cassandra |
Architecture | Document based | Wide column store |
Server Operating System | Windows, Linux, OS X, Solaris, | Windows, Linux, FreeBSD,OS X |
Supported Programming Language | Java, JavaScript, Perl, C, C#, C++, Erlang, Haskell, PHP, Python, Ruby, Scala | Java, Node.js, Perl, PHP, Python, C#, C++, Clojure, Erlang, Go, Haskell, Ruby, Scala |
Replication | Master-slave | Masterless ring |
Use cases | Content Management Systems(CMS), IoT, Analytics, Operational Intelligence, Data Management | E-commerce applications, Sensor Data, Messaging Systems, Fraud Management for Financial Institutions |
2. What do you understand about a collection in MongoDB?
A collection is a grouping of MongoDB documents. Documents within a collection can have different fields. It is the equivalent of a table in a relational database system and exists within a single database.
3. What are the different data types in MongoDB?
The most popular data types supported by MongoDB are:
String: Most common data type in MongoDB to store strings of characters.
E.g., {“name” : “myname”}
Integer: Used to store integers as 32 and 64-bit signed integers.
E.g., {“phone” : 232342100}
Double: Used to store floating-point numbers.
E.g., {“height” : 165.5}
Boolean: Stores either ‘true’ or ‘false’ boolean values.
E.g., {“professional” : true}
Arrays: Stores a set of similar or different data types.
E.g., {“languages” : [“English”, “Spanish”, “German”]}
Object: Stores embedded/ nested documents
E.g., {"company" : {"first" : "IBM",
“second” : “Apple”
}
}
Object Data: Stores the unique document id of a document.
E.g., {"objectid" : ObjectId()}
Null: Stores null data.
E.g., {“landline” : null}
Binary Data: Stores string of bytes.
E.g., {“binaryData” : “101000100”}
Date: Used to store data.
E.g., {“todaysDate” : new Date()}
Read more here.
4. How does MongoDB maintain consistency?
Consistency is maintained by default in MongoDB since the reads and writes are sent to the primary member in a replica set. However, there is an option to read from the secondary member in a replica set as well. These secondary members are eventually consistent by default.
5. How does scale-out happen in MongoDB?
MongoDB has been designed for scaling-out since it has a document-based architecture. The data in the document is split and spread across several servers.
- MongoDB takes care of the below activities:
- Loading data
- Balancing data
- Redistribution of data
- Mongos in the architecture act as a router between the application and the sharded cluster.
- Config servers store the configuration settings.
- Each sharded cluster has its config server.
Intermediate MongoDB Interview Questions and Answers
6. How to insert a document in MongoDB?
There are two ways to insert a document into MongoDB.
- Insert a single document: db.collection.insertOne() is used to insert a single document into a collection. In the below example a new document is getting inserted into a ‘rawmaterial’ collection.
Example: db.rawmaterial.insertOne( { item: "leather", qty: 80, tags: ["brown"], size: { h: 30, w: 40, uom: "cm" } } )
- Insert multiple documents: db.collection.insertMany() is used to insert multiple documents into a collection as an array of documents. In the below example multiple documents are getting inserted into a ‘rawmaterial’ collection.
Example: db.rawmaterial.insertMany([ { item: "notebooks", qty: 25, tags: ["blank", "red"], size: { h: 14, w: 21, uom: "cm" } }, { item: "drawingsheets", qty: 85, tags: ["white"], size: { h: 27.9, w: 35.5, uom: "cm" } }, { item: "pen", qty: 25, tags: ["gel", "blue"], size: { h: 19, w: 22.85, uom: "cm" } } ])
7. How to execute queries in MongoDB?
To execute queries we can use find() method in MongoDB.
Syntax:
db.COLLECTION_NAME.find()
Example:
The below example finds the document with status - ‘D’, and returns the cursor to the document.
myCursor = db.inventory.find( { status: "D" } )
8. What is the difference between primary and secondary replica sets?
Primary replica set | Secondary replica set |
Only one primary is possible. | Can be more than one. |
Only primary receives write operations. | Do not receive write operations, they replicate log from the primary. |
By default, primary accepts the read operations. | Can accept read operations, if the default setting changed. |
9. What is horizontal and vertical scaling in MongoDB?
To distribute the concurrent client requests (read/write), load balancing is used by MongoDB. There are two ways to do it.
Vertical scaling:
It means that we are adding more resources to the server to distribute the load balance across them.
Examples are increasing RAM, disk, CPU capacity, throughput(I/O operations), etc. By doing so the database can handle multiple client requests gracefully and fast.
However, there is a limit to adding hardware to the system which becomes the limitation of such a scaling process. Additionally, in a case of system failure, there is no other point of disaster management. If the system fails, it fails therefore, we use horizontal scaling in MongoDB.
Horizontal scaling:
Here, we divide the database into small parts and distribute them on many servers. Horizontal scaling is accomplished by sharding. Each shard(server) can be thought of as an individual database, and the whole database system is made up of many shards.
Through sharding, the write load is split across multiple servers. The chunks of data are distributed by a balancer on these servers. Therefore, using horizontal scaling, the throughput (read/write) is increased manifolds.
10. What is sharding in MongoDB?
It distributes the load of write/read requests across multiple servers for load balancing. Below are the components in a sharding process:
- Mongos: It is a query router that helps the application server access the shards by redirecting the commands to the correct server. There can be multiple mongos present in a cluster.
- Config servers: They store the metadata and configuration data of the clusters.
- Shards: It is a MongoDB instance that holds a data subset, containing primary and secondary shards within.
11. What is indexing in MongoDB?
Indexes are special data structures which facilitate quick and easy traversal of documents in MongoDB. They store a data value of a field/fields ordered by that value. A MongoDB index works in a similar fashion as an RDBMS index.
There are few functions which are required for indexing, they are:
- createIndex(): To create index
- dropIndex(): To drop an index
- dropIndexes(): To drop multiple indexes
- getIndexes(): Returns all indexes of a collection
More details about indexes here.
12. What are some limitations in using MongoDB?
- Database joins are not supported, hence they are required to be coded manually.
- It stores key-value pairs and the absence of joins causes data redundancy. These two factors add to higher memory consumption.
- The document size is limited to 16MB.
- The document nesting is limited to 100 levels.
Advanced MongoDB Interview Questions and Answers
13. What do you understand about the Aggregation Framework in MongoDB?
The aggregation framework provides the ability to perform analytics on the documents in two or more collections. These aggregation operations fetch data from more than documents and group them. On this group of data, the operations are performed to return a single result.
The aggregation framework works on the principle of the pipeline as shown below:
The documents are processed through a pipeline consisting of many stages of processing. After passing through all these stages a final and single result is produced.
14. What is meant by transactions in MongoDB?
Transactions ensure consistency in MongoDB. They are a logical group of database reads and writes, in a way that either they should fail together or succeed together. Otherwise, it will result in data inconsistency. If any transaction fails in between, then the database ought to roll back all the changes till that point to bring back the consistency.
In this process, the database has to work extra to keep track of all the changes made to it. Also, the ‘locking’ of resources takes place to maintain database consistency.
15. What is Map-reduce in MongoDB?
Map-reduce provides the aggregation technique to condense large data volume into aggregated data. For this purpose, MongoDB provides a command called: MapReduce.
The below image shows the process of query, map, and reduce in database:
16. How to create and restore the backup in MongoDB?
There could be two methods to create and restore the backup in MongoDB(MongoDB Atlas):
- Continuous backups: Incremental backups are taken and stored. Can be restored either from a point of time or by choosing from stored snapshots.
- Cloud provider snapshots: Cluster’s cloud service provider provides localised backup.
MongoDB provides utilities to create and restore backups, they are:
17. What is the use of MongoDB charts?
It is a tool to provide a visual representation of the MongoDB data. It helps in gaining a correlation between the variables and MongoDB data.
MongoDB Charts is a tool which the developers can use directly, without writing any code themselves.
There are two implementations for this purpose:
- MongoDB Charts PaaS (Platform as a Service)
- MongoDB Charts Server
18. Explain the limit() method in MongoDB.
limit() method is used to specify the limit of the values(documents) returned by a find() function in MongoDB. The argument passed to limit() function is a single numeric value.
If we do not specify any limit to the return values, then all the documents from the collection will be displayed.
Syntax:
db.collection_name.find().limit(int);
Example:
db.collection_name.find().limit(3)
To read in detail about the limit() method in MongoDB, with code snippets read here.
Backend Technology Interview Questions
C Programming Language Interview Questions | PHP Interview Questions | .NET Core Interview Questions | NumPy Interview Questions | API Interview Questions | FastAPI Python Web Framework | Java Exception Handling Interview Questions | OOPs Interview Questions and Answers | Java Collections Interview Questions | System Design Interview Questions | Data Structure Concepts | Node.js Interview Questions | Django Interview Questions | React Interview Questions | Microservices Interview Questions | Key Backend Development Skills | Data Science Interview Questions | Python Interview Questions | Java Spring Framework Interview Questions | Spring Boot Interview Questions.
Frontend Technology Interview Questions
HTML Interview Questions | Angular Interview Questions | JavaScript Interview Questions | CSS Interview Questions
Database Interview Questions
SQL Interview Questions | PostgreSQL Interview Questions | MySQL Interview Questions | DBMS Interview Questions
Cloud Interview Questions
AWS Lambda Interview Questions | Azure Interview Questions | Cloud Computing Interview Questions | AWS Interview Questions
Quality Assurance Interview Questions
Moving from Manual Testing to Automated Testing | Selenium Interview Questions | Automation Testing Interview Questions
DevOps and Cyber Security Interview Questions
DevOps Interview Questions | How to Prevent Cyber Security Attacks | Guide to Ethical Hacking | Network Security Interview Questions
Design Product Interview Questions
Product Manager Interview Questions | UX Designer Interview Questions
Interview Preparation Tips
Strength and Weakness Interview Questions | I Accepted a Job Offer But Got Another Interview | Preparation Tips For the Virtual Technical Interview | 7 Tips to Improve Your GitHub Profile to Land a Job | Software Engineer Career Opportunities in Singapore | What can you expect during a whiteboard interview | How To Write A Resignation Letter | Recommendation Letter Templates and Tips.
Quick Links
Practice Skills | Best Tech Recruitment Agency in Singapore, India | Graduate Hiring | HackerTrail Litmus | Scout - Sourcing Top Tech Talent in ONE Minute | About HackerTrail | Careers | Job Openings.