MongoDB is one of the most popular and widely used NoSQL or non-relational databases which is developed by MongoDB Inc. It is an open-source, documented-oriented database licensed under the Server Side Public License.
Since MongoDB is a non-relational database, it does not store data in the tabular format, like relational databases. Instead, it uses flexible, JSON-like documents to store data. As MongoDB is a document-oriented database, it enables us to store both structured and unstructured data.
In addition, it offers drivers for all major programming languages, including C, C++, Java, Python, Ruby, Scala, PHP, Mongoid, and Node.js. Therefore, developers can immediately start developing applications without spending their time configuring a database.
MongoDB can handle vast amounts of data and scale horizontally and vertically. Moreover, it is available in all major cloud platforms, such as Google Cloud, Amazon Web Services (AWS), and Microsoft Azure, through MongoDB Atlas. Some renowned companies that use MongoDB are Meta, eBay, Google, Adobe, and Nokia.
If you aim to become a MongoDB developer and are preparing for an interview, you are at the right place. This article sheds light on some commonly asked MongoDB interview questions along with their relevant answers. Also, the questions cover all major MongoDB concepts and are thus beneficial for beginners and professionals.
So, without further ado, let us get started with the top MongoDB interview questions!
Top MongoDB Interview Questions and Answers
Here is a curated list of MongoDB interview questions and answers categorized into three levels: beginner, intermediate, and advanced.
MongoDB Basic Interview Questions
1. Explain MongoDB.
MongoDB is an open-source, document-oriented NoSQL database. It is designed to store enormous volumes of structured and unstructured data. As it is a document-oriented database, it makes use of collections and documents to store data. A collection is a set of documents, and a document stores data in the form of the key-value pair .
2. What do you understand about a NoSQL database?
NoSQL is also referred to as ‘Not only SQL’ or ‘non-SQL’. NoSQL databases are non-relational or non-tabular databases that store data in a format other than the one used by relational databases, i.e. relational tables. These databases are available in a variety of types and provide flexible schemas and scale quickly with large volumes of data.
Many NoSQL databases have the following features:
- Horizontal scaling
- Flexible schema
- Fast queries
- Support for structured and unstructured data
3. Explain different types of NoSQL databases.
The four major types of NoSQL databases are document, key-value, wide-column, and graph.
- Document databases: These databases store data in the form of documents analogous to JSON (JavaScript Object Notation) objects. Each document consists of pairs of fields and values.
- Key-value databases: These databases are simple, where each item contains keys and values.
- Wide-column stores: These databases store data in tables, rows, and dynamic columns.
- Graph database: These databases store data in nodes and edges, where nodes store information about people, places, and things, and edges store information about relationships between nodes.
4. What different languages does MongoDB support?
MongoDB provides official drivers for all major programming languages, such as C, C++, Java, Python, Ruby, C#, JavaScript (Node.js), Scala, Erlang, Go, and PHP. We can use any of these languages with MongoDB. Moreover, there are many other community-supported drivers, but the mentioned ones are official and provided by MongoDB.
5. State the features of MongoDB.
The following are the main features of MongoDB:
- Ad-hoc queries: An ad-hoc query is a short-lived command or a loosely typed query whose value depends on a variable. Meaning that when we execute an ad-hoc query, we get different results every time depending upon the variables used in the query. MongoDB supports ad-hoc queries that save system resources since end-users create them at runtime.
- Indexing: MongoDB offers an array of indices and features with language-specific sort orders that collectively supports complex access patterns to datasets. Also, indices in MongoDB can be created on-demand to adapt to ever-changing application requirements and query patterns. We can declare indices on any field of any document.
- Replication: MongoDB creates more than one copy of the same dataset and sends it to multiple MongoDB servers. Therefore, if one server fails, we can retrieve that dataset from another server. Replication ensures the high availability of data.
- Sharding: Sharding is a process of distributing data across multiple hosts or machines. In MongoDB, sharding is achieved by splitting large datasets into small chunks and storing these chunks across multiple MongoDB instances.
- Document oriented: Unlike relational databases, MongoDB does not use tables to store data. It stores data as JSON-like documents.
- Schema-less database: Schema-less database in MongoDB implies one collection can contain different types of documents., i.e., documents can be of any size, any type, and can contain any number of fields. Unlike relational databases, a single collection doesn’t need to contain similar types of documents.
6. What are the advantages of MongoDB?
The following are the significant advantages of MongoDB:
- There is no need to design the schema of a database in MongoDB since it is a schema-less database.
- It supports structured and unstructured data.
- No complex joins are required since data is stored in Binary JSON format, i.e., key-value pairs.
- MongoDB is secure because SQL injection cannot be made since it is a NoSQL database.
- It ensures faster access of data as data is stored in RAM.
- It supports the ACID (Atomicity, Concurrency, Isolation, and Durability) properties for database transactions.
7. What do you understand about a document in MongoDB?
A document in MongoDB consists of data records as BSON documents. BSON stands for Binary representation of JSON documents. Each document is composed of field-value or key-value pairs. The structure of documents in MongoDB is given below:
{
field1: value1;
field2: value2;
field3: value3;
...
fieldN: valueN;
}
Here, the value of the field can be any BSON data type, such as documents, arrays, or arrays of documents.
8. Can you state some restrictions on the field names of documents?
The following are some significant restrictions on the field names of documents:
- The field name _id is preserved to use as a primary key, and its value should be unique.
- If _id contains subfields, the names of subfields cannot begin with the ‘$’ symbol.
- The _id field is immutable and can be of any data type other than an array.
- Field names must not contain the null character.
- The MongoDB server allows storing field names that contain dots (.) and dollar signs ($).
9. What do you understand about a Collection in MongoDB?
A collection in MongoDB is a set of documents, which store data in key-value pairs. It is analogous to tables in relational databases. A single collection can contain different types of documents as a database in MongoDB is schema-less. For example, a collection can contain the below two documents:
{"Company" : "TechAtom", "Product" : TechGeekBuzz"}
{"Author" : "John"}
10. State some restrictions on the collection names in MongoDB.
Following are the restrictions on the collection names in MongoDB:
- A collection name must begin with an underscore (_) or a letter character.
-
It must not:
- Contain ‘$’.
- Be an empty string.
- Contain a null character.
- Begin with the system. prefix.
11. What do you understand about the Collections screen?
The Collections screen displays all the collections and views present in a particular database. For each collection in a database, the Collections screen displays the following information:
- Collection name.
- The number of documents in the collection.
- The average size of documents in the collection.
- Collation properties for the collection.
- The number of indexes on the collection.
- The total size of indexes on the collection.
12. What is a database in MongoDB? State some restrictions on the database names.
In MongoDB, a database is a set of collections, where a collection is a set of documents. We can create multiple databases on the MongoDB server. The restrictions on the database names in MongoDB are:
- For MongoDB deployments running on the Windows systems, the database name cannot contain any of the below characters:
/\. "$*<>:|?<
- For MongoDB deployments running on Linux and Unix systems, the database name cannot contain the following characters:
/\. "$
- The name of a database cannot contain a null character.
- A database cannot be empty and cannot exceed 64 characters.
13. What is Mongo Shell?
Mongo shell is an interactive JavaScript interface that enables us to interact with MongoDB instances via the command line. We can use this shell for database manipulation and administrative operations, such as maintaining database instances.
In short, the Mongo shell is a command-line interface (CLI), where input and output are console-based, and it is the best tool to manipulate small data sets. When we install the MongoDB server, the Mongo shell and the command-line interface (CLI) get installed automatically.
14. Explain Namespace in MongoDB.
In MongoDB, the namespace is a combination of the database name and the name of the collection or index. [database-name].[collection-name or index-name] All documents belong to a namespace.
15. State the difference between MongoDB and MySQL.
The following table highlights the key differences between MongoDB and MySQL databases:
MongoDB | MySQL |
MongoDB is a NoSQL database and stores data records as BSON documents. | MySQL is a relational database that stores data records in rows and columns. |
There is no need to define a schema in MongoDB. | You first have to define the schema of a database before storing the data. |
It is an ideal choice if we have large volumes of unstructured and structured data sets. | It is a good choice if we have structured data sets. |
MongoDB does not support join operations. | MySQL supports join operations. |
It uses JSON query language to query data. | It supports Structured Query Language (SQL) for querying data. |
16. Explain CRUD operations in MongoDB?
CRUD stands for create, read/retrieve, update, and delete.
- Create: The create or insert operation adds new documents to a collection. If a collection does not exist, the insert command will create a new collection.
- Read: The read operation retrieves documents from a collection.
- Update: The update operation updates the existing documents in a collection.
- Delete: The delete operation removes a document from a collection.
MongoDB Intermediate Interview Questions
17. How to create a database in MongoDB?
We can create a database in the MongoDB server using the use DATABASE_NAME statement. This statement creates a new database if the database of the same name does not exist. Otherwise, it will return the existing database. The syntax for the use DATABASE_NAME command is given below:
>use DATABASE_NAME
Let us create a database having the name ‘TechGeekBuzz’.
>use TechGeekBuzz
switched to db TeckGeekBuzz
18. How to create a collection in MongoDB?
We can create a collection in MongoDB using the createCollection() statement. The syntax for creating a collection in MongoDB is given below:
>db.createCollection(name, options)
Here, the name is the name of the collection that we want to create and options is a document. Let us create a collection having the name ‘Learndunia’ in the ‘TeckGeekBuzz’ database.
>use TeckGeekBuzz
switched to db TeckGeekBuzz
>db.createCollection("Learndunia")
{"ok" : 1}
19. How to create a document in MongoDB?
To create a document or insert a document in a collection, we have to use the insert() method. There are two variations of the insert() method to create a document:
- insertOne(): This method allows us to insert only one document in a collection.
The syntax for the insertOne() statement is given below:
>db.collection.insertOne(document)
Let us create one document having an author name, age, and niche in the ‘Learndunia’ collection of the ‘TechGeekBuzz’ database.
>db.Learndunia.insertOne(
{
Author_name: "John",
Author_age: "26",
Niche: "Technology"
}
)
- insertMany(): This method allows us to insert multiple documents in a collection.
The syntax for the insertMany() statement is given below:
>db.collection.insertMany(documents)
Let us use the same above example, but this statement allows us to insert more than one data record in a collection at a time.
>db.Learndunia.insertMany(
[
{
Author_name: "Henry",
Author_age: "34",
Niche: "Travel"
},
{
Author_name: "George",
Author_age: "27",
Niche: "Email Writing"
},
{
Author_name: "Sam",
Author_age: "30",
Niche: "Finance"
}
]
)
20. How to delete a document in MongoDB?
We can delete a document from a collection using the remove() method. This method takes two parameters, namely deletion criteria and justOne flag.
Deletion criteria: It deletes a document depending upon the criteria mentioned.
justOne flag: If it is set to true or 1, it removes only one document. Both the parameters are optional.
- Remove only one document:
If a collection has multiple documents and we want to delete the first document, we will use the below syntax:
>db.COLLECTION_NAME.remove(DELETION_CRITERA, 1)
- Remove all documents:
If we want all the documents from a collection to be deleted, we will use the below syntax:
>db.COLLECTION_NAME.remove({ })
It is equivalent to the truncate command in SQL .
21. How to delete a collection in MongoDB?
Like we use the drop() command in SQL to delete a database, we can use the same command to delete a collection in MongoDB. The syntax for deleting a collection in MongoDB is given below:
>db.COLLECTION_NAME.drop()
Let us take a collection having the name ‘Students’ in the ‘School’ database. Now, we will delete this collection using the drop() command, as shown below:
>use School
switched to db School
>db.Students.drop()
true
If you try to delete a non-existing collection from a database, the output will be false.
22. How to delete a database in MongoDB?
We can delete a database in MongoDB using the dropDatabase() command. The syntax for deleting a database in MongoDB is given below:
>db.dropDatabase()
Consider that we have the ‘Employees’ database, and we need to delete it. The following commands will help us achieve the same
>use Employees
switched to db Employees
>db.dropDatabase()
23. State the differences between MongoDB and Cassandra.
The following table highlights the differences between MongoDB and Cassandra:
MongoDB | Cassandra |
MongoDB is developed using JavaScript, C++, and Python. | Cassandra is developed using only JavaScript. |
Read performance in MongoDB is not as fast as in Cassandra. | Read performance is very high since it takes O(1) time. |
MongoDB supports BSON and JSON data formats. | Cassandra only supports the JSON data format. |
The replication method supported by MongoDB is Master-master Replication. | The replication method supported by Cassandra is the Selectable Replication Factor. |
Renowned companies that use MongoDB are Adobe, Meta, eBay, Google, Lyft, Amadeus, and Craftybase. | Major companies that use Cassandra include Instagram, Netflix, Reddit, and Intuit. |
24. Differentiate between MongoDB and CouchDB.
The following table describes the key differences between MongoDB and CouchDB:
MongoDB | CouchDB |
MongoDB was developed using C++, JavaScript, and Python. | CouchDB was developed using Erlang. |
It supports in-memory capabilities. | It does not support in-memory capabilities. |
MongoDB supports read-only SQL queries via the MongoDB Connector. | CouchDB does not support SQL queries. |
It only supports master-master replication. | It supports master-master and master-slave replication. |
25. What is ObjectID in MongoDB?
Each document in a collection has ‘_id’, which is used to uniquely identify a document in a collection. An ObjectID in MongoDB is a 12-byte field of BSON type. These 12 bytes are:
- The first 4 bytes represent the Unix Timestamp of the document.
- The next 3 bytes are the machine ID on which the MongoDB server is running.
- The next 2 bytes represent the process ID.
- The last 3 bytes are byte counters.
The format of ObjectID is given below:
ObjectID(<Hexadecimal>)
26. What do you know about indexes in MongoDB?
Indexes in MongoDB are used to make query processing fast and more efficient. If no indexes are used, MongoDB has to scan every document in a collection and retrieve only those documents that match the query. This process is time-consuming and inefficient. Indexes in MongoDB are special data structures that enable us to quickly retrieve data stored in documents. They store a small part of a dataset that is easy to access and retrieve.
The syntax for creating an index in MongoDB is given below:
>db.COLLECTION_NAME.createIndex({Key : 1})
Here, Key is the field name on which we want to create an index, and 1 represents an ascending order for index entries, i.e., the indexes will be arranged in ascending order.
27. Can you drop an index in MongoDB? If yes, how?
Yes, we can drop a specific index in MongoDB using the dropIndex() method. The syntax for dropping a particular index is as follows:
>db.COLLECTION_NAME.dropIndex({Key:1})
28. What is the use of the getIndexes() method of MongoDB?
The getIndexes() method is used to retrieve the description of all the indexes of a collection. The syntax of the getIndexes() method is given below:
>db.COLLECTION_NAME.getIndexes()
29. What do you understand about sharding in MongoDB?
Sharding is the process of splitting a large dataset into multiple data chunks and storing them on multiple machines. Querying a very large dataset may sometimes result in more CPU utilization and cause overhead on the MongoDB server. To tackle this problem, MongoDB uses the concept of sharding, where a large volume of data is split into smaller data sets and stored across multiple MongoDB instances.
In MongoDB, we can implement sharding using a cluster of shards or machines. The data record from a collection is distributed across these shards or machines. Here, a cluster is nothing but a MongoDB instance.
30. What do you know about a database profiler?
A database profiler is responsible for collecting detailed information about all the database commands that are being executed against the running MongoDB instance. The database commands include all CRUD operations, administration commands, and configuration commands.
In addition, the database profiler writes all the collected data of the running MongoDB instance to a system.profile collection. The database profiler is off by default. We can enable the database profiler based on per-database or per-instance at any one of the profiling levels. The following are the three profiling levels:
- 0: It is a default profiler level. At this level, the profiler is off and does not collect any data.
- 1: At this level, the profiler collects data for all operations that take longer than the value of slowms.
- 2: The profiler collects data for all operations at this level.
31. State the differences between MongoDB and Redis.
The following table highlights the key differences between MongoDB and Redis:
MongoDB | Redis |
MongoDB is developed with C++, JavaScript, and Python. | Redis is developed with ANSI and C languages. |
It has Document Store as a primary database model. | It has a key-value pair as a primary database model. |
MongoDB supports secondary indexes without any restrictions. | Redis supports secondary indexes only with the RediSearch module. |
It supports only Master-Slave replication. | It supports Master-Master and Master-Slave replication. |
Companies like Craftbase, Lyft, Amadeus, Adobe, etc., use MongoDB. | Companies like Twinkl Educational Publishing, ASOS.com, Merrill Corporation, etc., use Redis. |
32. Explain Replication in MongoDB?
Replication in MongoDB is the process of creating copies of a data set and storing them on several MongoDB servers. It ensures the high availability of data. If the MongoDB server that a user is working on goes down or crashes for some reason, the data present in it will be lost. In such a scenario, replication plays a vital role in safeguarding data. With replication, it becomes possible to retrieve that data from another MongoDB server.
Another purpose of replication is load balancing. If multiple users are connected to a single MongoDB server, it may result in overloading. Since replication ensures that the same data is available on other MongoDB servers, users can connect to multiple servers, which results in an even distribution of load on MongoDB servers.
33. What do you understand about aggregation in MongoDB?
Aggregation in MongoDB is the process of collecting values from different documents and performing different types of operations, like sum, max, min, avg, etc., on the combined data to return a computer result. It is analogous to the aggregate function in SQL.
34. What do you know about the covered query in MongoDB?
Covered queries are essential in querying data faster. A covered query in MongoDB is one in which:
- Fields required by the query are the part of an index that is used in a query. It ensures that the query does not have to examine other documents apart from the indexed ones.
- Fields returned as results are the part of the index used in the query.
It is important to note that covered queries do not work with arrays and sub-documents.
35. Can you state the use of the save() method in MongoDB?
The save() in MongoDB replaces the existing document with a new one. The syntax for the save() method is as follows:
>db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})
MongoDB Advanced Interview Questions
36. List out some utilities provided by MongoDB for data backup and restoration.
The following are the utilities provided by MongoDB for data backup and restore:
- mongoimport
- mongoexport
- mongodump
- mongorestore
37. Explain the terms mongodump and mongorestore.
The term mongodump is defined as the utility to create a binary export of the contents of a database. It can export data from Mongod or Mongos instances. In other words, it can export data from replica sets, standalone, and shared cluster deployments. The term mongorestore is defined as a program that loads data either from a binary database dump created by mongodump or loads the standard input into a Mongod or Mongos instance.
38. Explain mongoimport and mongoexport.
The mongoimport tool is used to import content from an Extended JSON, CSV, or TSV export created by mongoexport. mongoexport is a command-line tool that creates a JSON or CSV export of the data stored in MongoDB instances.
39. Explain vertical scaling in MongoDB.
We can define vertical scaling in MongoDB as increasing the processing power of a single MongoDB server or instance.
40. Explain horizontal scaling in MongoDB.
We can define horizontal scaling in MongoDB as adding or bringing additional shards or machines to a cluster to share the load. We also refer to horizontal scaling as scale-out.
41. What do you know about embedded documents in MongoDB?
Embedded documents are one of the most interesting features of MongoDB and are also referred to as Nested documents. An embedded or nested document is a document inside another document.
In other words, we can define an embedded document as a document nested inside another document within a MongoDB collection. MongoDB supports the nesting of documents only up to 100 levels, and the document size should not exceed 16 MB.
The syntax for an embedded document in MongoDB is given below:
{
...
field: {field1: value1, field2: value2}
...
}
42. Explain different index types in MongoDB.
The following are the different types of indexes in MongoDB:
- Single field index: It is an index on a single field or document. With this index, MongoDB can traverse in ascending and descending order.
- Compound index: It is a single index holding multiple references. We can combine multiple fields for a compound index.
- Multikey index: We use a multikey index to index the values stored in an array. MongoDB created a separate index for every value stored in an array. Using a multikey index, it becomes easier to find a document that contains an array by matching the values.
- Geospatial index: MongoDB provides two geospatial indexes, namely 2d indexes and 2d sphere indexes. We can use these indexes to query geospatial data. If you want to find data stored in a 2D plane, we use the 2d index, whereas to find data stored in spherical geometry, we use the 2d sphere index.
- Text index: A text index allows us to search for string content in a collection.
- Hash index: When we want to distribute data to multiple shards in a cluster evenly, we use the hash index. It indexes the hash of the value of a field.
43. Explain the find() and limit() methods in MongoDB.
find(): This method selects documents in a collection and returns a cursor to the selected documents. Here, the cursor is a pointer pointing to a document. The find() method returns the pointer on the selected documents and returns one by one. The syntax for the find() method in MongoDB is:
>db.COLLECTION_NAME.find(selection_criteria, projection)
limit(): This method limits the number of records to fetch. For example, if a document has 10 records and we want to display only the first four documents in a collection, we can use limit(). The syntax for the limit() method in MongoDB is:
>db.COLLECTION_NAME.find().limit(NUMBER)
44. What do you understand about capped collections?
Capped collections in MongoDB are fixed-size collections. While creating a collection, we need to fix the maximum size of that collection in bytes and the maximum number of documents it can store. Once we create a fixed-size or capped collection, the existing documents will be overwritten if we try to add additional documents more than the specified number.
45. What do you know about GridFS?
GridFS in MongoDB is a specification for storing and retrieving large files, such as images, videos, audio files, etc. In other words, it is a specification for storing and retrieving data that exceeds the BSON-document size, i.e., 16 MB. It divides the large data set into smaller chunks, each chunk of size 255 KB by default, except the last chunk. The last chunk can be as large as we need. It uses two collections to store files, where one stores the file chunks, and the other stores the metadata.
46. What do you understand about storage engines in MongoDB?
The storage engine in MongoDB is a component of a database responsible for managing how the data is stored in memory and on disk. MongoDB uses multiple storage engines, where different engines perform better with different workloads. So, choosing the right storage engine can significantly impact the performance of your application. The default storage engine in MongoDB 3.2 is WiredTiger.
47. State the differences between RDBMS and MongoDB.
The following table highlights the differences between RDBMS and MongoDB:
RDBMS | MongoDB |
RDBMS is a relational database management system. | MongoDB is a type of non-relational database, which is document-oriented. |
Relational database management systems are not ideal for hierarchical data storage. | This non-relational database supports hierarchical data storage. |
Relational databases have a predefined schema. | MongoDB does not have a predefined schema. |
RDBMS only supports SQL for querying data. | MongoDB uses BSON for querying databases. We can use MongoDB Connector for BI to query MongoDB collections with SQL. |
Relational databases are prone to SQL injection attacks . | Non-relational databases are not prone to SQL injection attacks. |
48. List out data types supported by MongoDB.
The following are the data types that MongoDB supports:
- String: It is one of the most common data types in MongoDB to store data. BSON strings are UTF-8.
- Integer: It stores an integer value. MongoDB supports two different forms of integer: 32-bit signed integer and 64-bit signed integer.
- Double: It stores floating-point values.
- Boolean: It stores either true or false.
- Null: It stores null values.
- Array: It is a collection of values, where values can be of any data type.
- Object: It stores embedded documents.
- Object Id: MongoDB creates a unique Object Id for a document immediately after its creation in a collection.
- Undefined: It stores undefined values.
- Binary data: It stores binary data.
- Date: It stores to date, and it is a 64-bit integer.
- JavaScript: It stores JavaScript code into a document without the scope.
- JavaScript with scope: It stores JavaScript into a document with the scope.
- Timestamp: It stores timestamps.
49. What is MongoDB Atlas?
MongoDB Atlas is Database-as-a-Service (DBaaS). DBaaS enables us to set up, deploy, and scale databases without the need to worry about on-premise physical hardware and software updates. In short, MongoDB Atlas is a cloud database that enables us to deploy, run, and scale MongoDB in the cloud.
50. Explain MongoDB Charts.
MongoDB charts provide us with a powerful approach to creating visualizations of data stored in MongoDB Atlas. There are two different implementations of MongoDB Charts, namely:
- MongoDB Charts PaaS.
- MongoDB Charts Server.
Conclusion
MongoDB is one of the most powerful and extensively used NoSQL databases. It offers a wide variety of features, such as indexing, replication, ad-hoc queries support, aggregation, load balancing, sharding, geospatial indexes support, and schemaless database.
This article has covered the most frequently asked MongoDB interview questions and answers. By going through these MongoDB interview questions along with their detailed answers, you will be able to learn and refresh your knowledge of various MongoDB concepts. Consequently, it will help you prepare yourself better for a MongoDB developer job interview.
If you have come across MongoDB interview questions apart from the ones mentioned above, feel free to share them in the comments section below.
People are also reading:
Leave a Comment on this Post