MongoDB Interview Questions

What is MongoDB?

MongoDB is a free and open-source cross-platform document-oriented database program. Classified as a NoSQLdatabase program, MongoDB uses JSON-like documents with schemas. MongoDB is developed by MongoDB Inc., and is published under a combination of the GNU Affero General Public License and the Apache License.

What makes MongoDB the best?

MongoDB is considered to be best NoSQL database because of :Document-oriented (DO)
High performance (HP)
High availability (HA)
Easy scalability
Rich query language

How to do transactions/locking in MongoDB?

MongoDB does not use conventional locking with reduction, as it is planned to be light, high-speed and knowable in its presentation. It can be considered as parallel to the MySQL MyISAM auto entrust sculpt. With simplest business sustain, performance is enhanced, particularly in a structure with numerous servers.

When and to what extent does Data get extended to Multi-slice?

The MongoDB scrap stands on a collection. So an album of all substances is kept in a lump or mass. Only when there is an additional time slot, there will be more than a few slice data achievement choices, but when there is more than 1 lump, data gets extended to a lot of slices and it can be extended to 64 MB.

Judge against MongoDB with Couchbase and CouchbaseDB?

Although Mongo DB with Couchbase and Couchbase DB are common in many ways, but still they are different in the case of necessities for execution of the model, crossing points, storage, duplications, etc.

When do we use Namespace in MongoDB?

During sequencing of the names of the database and collection name Namespace is used.

If you remove an object attribute, is it deleted from the database?

Yes, it is deleted. So better eliminate the attribute and then save the object again.

How can we move the old file in the moveChunk directory?

Once the functions are done, the old files are converted to backup files and moved to the moveChunk directory at the time of balancing the slices.

Explain the situation when an index does not fit into RAM?

When an index is too huge to fit into RAM, then MongoDB reads the index, which is faster than reading RAM because the indexes easily fit into RAM if the server has got RAM for indexes along with the remaining set.

How does MongoDB provide consistency?

MongoDB uses the reader-writer locks, allowing simultaneous readers to access any supply like a database or any collection. But always offers private access to singles writes.


Why is MongoDB not chosen for a 32-bit system?

Mongo DB is not considered as a 32-bit system because for running the 32-bit MongoDB, with the server, information and indexes require 2 GB. So only it is not used in 32-bit devices.

How does Journaling work in MongoDB?

Write operations are saved in the memory while journaling is going on. The on-disk journal files are really dependable for the reason that the journal writes are habitual. Inside dbPath, a journal subdirectory is designed by MongoDB.

How can you isolate our cursors from intervening with the write operations?

Snapshot () method is used to isolate cursors from intervening with writes. This method negotiates the index and makes sure that each query comes to any article only once.

Define MongoDB.

It is document oriented database which is used to high availability, easy scalability and high performance. It supports the dynamic schema design.

Explain replica set.

It is a group of mongo instances that maintain same data set. Replica sets provide redundancy and high availability, and are the basis for all production deployments.

What are the key features of mongodb?

There are 3 main features of mongodb that are automatic scaling, High performance and high availability.

What is CRUD?

Mongodb provides CRUD operations that are create, Read, Update, Delete.

What is sharding?

Sharding means to store the data on the multiple machines.

What is Aggregation in MongoDB?

Aggregations are operations that process data records and return computed results.

Define the namespace in mongodb?

It is the concatenation of collection name and database.

Which syntax is used to create collection in mongodb?

b.createCollection(name,options) is used to create collection in mongodb.

Which syntax is used to drop collection in mongodb?

db.collection.drop() is used to drop collection in mongodb.

Explain Replication?

Replication is the process of synchronizing data across multiple servers.

What is the use of Index in mongodb?

Indexes provide high performance read operations for frequently used queries.

Which command is used for inserting a document?

database.collection.insert (document) is used for inserting a document.

What is use of GridFS in mongodb?

GridFS is used for storing and retrieving the large files like audio, Images, Video files.

What is the use journaling?

Journaling is used to safe backups in mongodb.

Which command is used to see the connection?

db_adminCommand (“connPoolStats”); is used to see the connection.

Define primary replica sets?

The primary replica set accepts all write operations from clients.

Define secondary replica sets?

The secondaries (page 565) replicate the primary’s oplog and apply the operations to their data sets such that the secondaries’ data sets reflect the primary’s data set.

What is the use of profiler?

Profiler is used to show the performance characteristics of every operation against the database.

Which type of data mongodb store?

MongoDB stores data in the form of documents, which are JSON-like field and value pairs.

What is purpose of replication?

Replication provides redundancy and increases data availability.

what is embedded documents?

Embedded documents capture relationships between data by storing related data in a single document structure.

Define application level encryption?

Application Level Encryption provides encryption on a per-field or per-document basis within the application layer.

What is storage encryption?

Storage Encryption encrypts all MongoDB data on the storage or operating system to ensure that only authorized processes can access protected data.

Which method is used to create an index?

CreateIndex() method is used to create an index.

What is replica set oplog?

The oplog records all operations that modify the data in the replica set.

What is vertical scaling?

Vertical scaling adds more CPU and storage resources to increase capacity.

Define horizontal scaling?

It divides the data set and distributes the data over multiple servers, or shards.

What are the components of shared cluster?

Sharded cluster has the following components: shards, query routers and config servers.

Which command is use to create database?

DATABASE_NAME command is used to create database.

Which command is use to drop database?

db.dropDatabse() command is used to drop the database.

What is the use of pretty() method?

Pretty() method is used to show the results in a formatted way.

Which method is used to remove the document form the collection?

Remove() method is used to remove the document form the collection.

Define Mongodb projection?

Projection is used to select only necessary data.It did not select whole data of a document.

What is the use of limit() method?

Limit() method is used to limit the records in database.

What is the syntax of limit() method?

db.COLLECTION_NAME.find().limit(NUMBER) syntax is used.

What is the syntax of sort() method?

db.COLLECTION_NAME.find().sort({KEY:1}) syntax is used for sorting the documents.

Which command is used to create the backup of database?

Mongodump command is used to create the backup of database.

What are NoSQL databases? What are the different types of NoSQL databases?

A NoSQL database provides a mechanism for storage and retrieval of data that is modeled in means other than the tabular relations used in relational databases (like SQL, Oracle, etc.).

Types of NoSQL databases:

  • Document Oriented
  • Key Value
  • Graph
  • Column Oriented

What kind of NoSQL database MongoDB is?

MongoDB is a document oriented database. It stores data in the form of BSON structure based documents. These documents are stored in a collection.

Which are the most important features of MongoDB?

  • Flexible data model in form of documents
  • Agile and highly scalable database
  • Faster than traditional databases
  • Expressive query language

Which all languages can be used with MongoDB?

Currently, MonggoDB provides official driver support for C, C++, C#, Java, Node.js, Perl, PHP, Python, Ruby, Scala, Go and Erlang. MongoDB can easily be used with any of these languages. There are some other community supported drivers too but the above mentioned ones are officially provided by MongoDB.

Compare SQL databases and MongoDB at a high level?

SQL databases store data in form of tables, rows, columns and records. This data is stored in a pre-defined data model which is not very much flexible for today’s real-world highly growing applications. MongoDB in contrast uses a flexible structure which can be easily modified and extended.

How is MongoDB better than other SQL databases?

MongoDB allows a highly flexible and scalable document structure. For e.g. one data document in MongoDB can have five columns and the other one in the same collection can have ten columns. Also, MongoDB database are faster as compared to SQL databases due to efficient indexing and storage techniques.

Compare MongoDB and CouchDB at high level?

Although both of these databases are document oriented, MongoDB is a better choice for applications which need dynamic queries and good performance on a very big database. On the other side, CouchDB is better used for applications with occasionally changing queries and pre-defined queries.

Does MongoDB support foreign key constraints?

No. MongoDB does not support such relationships.

Does MongoDB support ACID transaction management and locking functionalities?

No. MongoDB does not support default multi-document ACID transactions. However, MongoDB provides atomic operation on a single document.

How can you achieve primary key - foreign key relationships in MongoDB?

By default MongoDB does not support such primary key – foreign key relationships. However, we can achieve this concept by embedding one document inside another. Foe e.g. an address document can be embedded inside customer document.

Does MongoDB need a lot of RAM?

No. MongoDB can be run even on a small amount of RAM. MongoDB dynamically allocates and de-allocates RAM based on the requirements of other processes.

Does MongoDB pushes the writes to disk immediately or lazily?

MongoDB pushes the data to disk lazily. It updates the immediately written to the journal but writing the data from journal to disk happens lazily.

Explain the structure of ObjectID in MongoDB?

ObjectID is a 12-byte BSON type with:

  • 4 bytes value representing seconds
  • 3 byte machine identifier
  • 2 byte process id
  • 3 byte counter

MongoDB uses BSON to represent document structures. True or False?


If you remove a document from database, does MongoDB remove it from disk?

Yes. Removing a document from database removes it from disk too.

Mention the command to insert a document in a database called school and collection called persons?

use school;
db.persons.insert( { name: "kadhir", dept: "CSE" } )

What are Indexes in MongoDB?

Indexes support the efficient execution of queries in MongoDB. Without indexes, MongoDB must perform a collection scan, i.e. scan every document in a collection, to select those documents that match the query statement. If an appropriate index exists for a query, MongoDB can use the index to limit the number of documents it must inspect.

How many indexes does MongoDB create by default for a new collection?

By default, MongoDB created the _id collection for every collection.

Can you create an index on an array field in MongoDB? If yes, what happens in this case?

Yes. An array field can be indexed in MongoDB. In this case, MongoDB would index each value of the array.

What is a covered query in MongoDB?

A covered query is the one in which:

  • fields used in the query are part of an index used in the query, and
  • the fields returned in the results are in the same index

Why is a covered query important?

Since all the fields are covered in the index itself, MongoDB can match the query condition as well as return the result fields using the same index without looking inside the documents. Since indexes are stored in RAM or sequentially located on disk, such access is a lot faster.

Does MongoDB provide a facility to do text searches? How?

Yes. MongoDB supports creating text indexes to support text search inside string content. This was a new feature which can introduced in version 2.6.

What happens if an index does not fit into RAM?

If the indexes do not fit into RAM, MongoDB reads data from disk which is relatively very much slower than reading from RAM.

Mention the command to list all the indexes on a particular collection?


At what interval does MongoDB write updates to the disk?

By default configuration, MongoDB writes updates to the disk every 60 seconds. However, this is configurable with the commitIntervalMs and syncPeriodSecs options.

How can you achieve transaction and locking in MongoDB?

To achieve concepts of transaction and locking in MongoDB, we can use the nesting of documents, also called embedded documents. MongoDB supports atomic operations within a single document.

What is Replication in MongoDB? Explain?

Replication is the process of synchronizing data across multiple servers. Replication provides redundancy and increases data availability. With multiple copies of data on different database servers, replication protects a database from the loss of a single server. Replication also allows you to recover from hardware failure and service interruptions.

What are Primary and Secondary Replica sets?

Primary and master nodes are the nodes that can accept writes. MongoDB’s replication is ‘single-master:’ only one node can accept write operations at a time.

Secondary and slave nodes are read-only nodes that replicate from the primary.

By default, MongoDB writes and reads data from both primary and secondary replica sets. True or False?

False. MongoDB writes data only to the primary replica set.

Why are MongoDB data files large in size?

MongoDB preallocates data files to reserve space and avoid file system fragmentation when you setup the server.

When should we embed one document within another in MongoDB?

You should consider embedding documents for:

  • ‘contains’ relationships between entities
  • One-to-many relationships
  • Performance reasons

Why MongoDB is not preferred over a 32-bit system?

When running a 32-bit build of MongoDB, the total storage size for the server, including data and indexes, is 2 gigabytes. For this reason, do not deploy MongoDB to production on 32-bit machines.

If you’re running a 64-bit build of MongoDB, there’s virtually no limit to storage size.

What is a Storage Engine in MongoDB ?

A storage engine is the part of a database that is responsible for managing how data is stored on disk. For example, one storage engine might offer better performance for read-heavy workloads, and another might support a higher-throughput for write operations.

Which are the two storage engines used by MongoDB?

MongoDB uses MMAPv1 and WiredTiger.

What is the role of a profiler in MongoDB? Where does the writes all the data?

The database profiler collects fine grained data about MongoDB write operations, cursors, database commands on a running mongod instance. You can enable profiling on a per-database or per-instance basis.

The database profiler writes all the data it collects to the system.profile collection, which is a capped collection.

How does Journaling work in MongoDB?

When running with journaling, MongoDB stores and applies write operations in memory and in the on-disk journal before the changes are present in the data files on disk. Writes to the journal are atomic, ensuring the consistency of the on-disk journal files. With journaling enabled, MongoDB creates a journal subdirectory within the directory defined by dbPath, which is /data/db by default.

Mention the command to check whether you are on the master server or not?


Can you configure the cache size for MMAPv1? How?

No. MMAPv1 does not allow configuring the cache size.

Can you configure the cache size for WiredTiger? How?

For the WiredTiger storage engine, you can specify the maximum size of the cache that WiredTiger will use for all data. This can be done using storage.wiredTiger.engineConfig.cacheSizeGB option.

How does MongoDB provide concurrency?

MongoDB uses reader-writer locks that allow concurrent readers shared access to a resource, such as a database or collection, but give exclusive access to a single write operation.

How can you isolate your cursors from intervening with the write operations?

You can use the snapshot() method on a cursor to isolate the operation for a very specific case. snapshot() traverses the index on the _id field and guarantees that the query will return each document no more than once.

Can one MongoDB operation lock more than one databases? If yes, how?

Yes. Operations like copyDatabase(), repairDatabase(), etc. can lock more than onne databases involved.

How can concurrency affect replica sets primary?

In replication, when MongoDB writes to a collection on the primary, MongoDB also writes to the primary’s oplog, which is a special collection in the local database. Therefore, MongoDB must lock both the collection’s database and the local database.

What is GridFS?

GridFS is a specification for storing and retrieving files that exceed the BSON-document size limit of 16MB. Instead of storing a file in a single document, GridFS divides a file into parts, or chunks, and stores each of those chunks as a separate document.

Can you run multiple Javascript operations in a single mongod instance?

Yes. The V8 JavaScript engine added in 2.4 allows multiple JavaScript operations to run at the same time.

Which command can be used to provide various information on the query plans used by a MongoDB query?

The explain() command can be used for this information. The possible modes are: ‘queryPlanner’, ‘executionStats’, and ‘allPlansExecution’.

What is a storage engine in MongoDB?

A storage engine is the part of a database that is used to manage how data is stored on disk.

For example: one storage engine might offer better performance for read-heavy workloads, and another might support a higher-throughput for write operations.

What is the difference between MongoDB and Redis database?

Difference between MongoDB and Redis:

  • Redis is faster than MongoDB.
  • Redis has a key-value storage whereas MongoDB has a document type storage.
  • Redis is hard to code but MongoDB is easy.

What is the difference between MongoDB and Cassandra?

Difference between MongoDB and Cassandra:

  • MongoDB is cross-platform document-oriented database system while Cassandra is high performance distributed database system.
  • MongoDB is written in C++ while Cassandra is written in Java.
  • MongoDB is easy to administer in the case of failure while Cassandra provides high availability with no single point of failure.

Is there any need to create database command in MongoDB?

You don’t need to create a database manually in MongoDB because it creates automaically when you save the value into the defined collection at first time.

In which format MongoDB represents document structure?

MongoDB uses BSON to represent document structures.