Top 30 Interview Questions and Answers for MongoDB

Interactive Online Courses: Elevate Skills & Succeed Enroll Now!

Earlier we discussed the part 1 of the MongoDB interview questions and answers. Now we will be looking at some more questions that will help you to prepare for your MongoDB interview.

Let’s explore the best MongoDB interview questions and answers.

Core MongoDB Interview Questions and Answers

Here is the list of frequently asked interview questions for MongoDB.

Q1. How can db.ClockTime.update() convert these text-based values to a date datatype?

Ans. There can be two solutions for the problem given over here:

  • First solution
    > var cursor = db.ClockTime.find()
    > while (cursor.hasNext()) {
    … var doc =;
    … db.ClockTime.update({_id : doc._id}, {$set : {ClockInTime : new Date(doc.ClockInTime)}})
    … }
  • Second solution
    db.ClockTime.find().forEach(function(doc) {
    doc.ClockInTime=new Date(doc.ClockInTime);;


So using any of these you can convert text-based values to date datatype.

Q2. How can you use map-reduce for grouping more than 10000 unique keys?

Ans. For using MapReduce for grouping, use version 2.2. The method’s returned array can contain up to 20,000 elements; that means at up to 20,000 unique groupings.

For the group by operations that are having more than 20,000 unique groupings, MapReduce’s previous versions had a limit of 10,000 elements.

Technology is evolving rapidly!
Stay updated with DataFlair on WhatsApp!!

Q3. In what way will you query live MongoDB data?

Ans. By using the following utilities you can handle live MongoDB data.

  • MongoHub is moved to a native Mac version.
  • This is useful for tree and document views.
  • genghisapp – This is a web-based GUI that is clean, light-weight, straight-forward, offers keyboard shortcuts, and works awesomely well. It also supports GridFS. It’s all a single script.

Q4. How to update a specific key/value of an array field with MongoDB?

Ans. For this let us suppose a collection content, as it contains articles, news, etc. These articles contain another array called the author which contains all the information about the author.

db.content.update({‘’:’xyz’},{$set:{‘authors.$.address’:’Address That I wanted’}},false,true);

It updates all the records properly.

Q.5 How to use the primary key in MongoDB?

Ans. _id field is reserved for the primary key in MongoDB, and that is a unique value. If you don’t set anything to _id it will automatically fill it with “MongoDB Id Object”. But you can put any unique info in that field.

Q6. How to delete everything from the MongoDB database?

Ans. For deleting everything from the MongoDB database, you can use the following code:

use [database];
Ruby code should be pretty similar.
Also, from the command line:
mongo [database] –eval “db.dropDatabase();”
drop collection
use databaseName

Q7. How to use $set in MongoDB?

Ans. For a detailed explanation about how it works dynamically, I’ll give an example in PHP:

$action = array(“columns.$colNum.panels.$panelNum” => $newValue);

Yes there is the positional operator, but it does not appear to be advanced enough to change arrays within arrays, this might have changed in MongoDB 1.7.0

There is an alternative for this. Try to flatten it out. We can make a collection that contains panel & column objects:

column object:
_id: // MongoId
type: ‘column’,
user: ‘username’,
order: 1,
width: 30,
panel object:
_id: //MongoId
type: ‘panel’,
user: ‘username’,
parentColumn: //the columns _id string
top: 125,
left: 100

Then find all columns that belong to a user:

find({ type: ‘column’, user:’username’});

We can detect all panels for a particular column by doing:

find({type: ‘panel’, columnOwner:’ownerID’});

Since each column and panel will contain a unique ID given by MongoDB to it, we can query easily and atomically set options.

update({‘_id’: ObjectId(‘idstring’)}, {$set : { ‘top’ : 125}});

Q8. Using what can you print more than 20 items in MongoDB’s shell?



It will both print out a very expanded view of each document instead of the 1-line version for find():

DBQuery.shellBatchSize = 300

Q9. How to perform join operations in MongoDB?

Ans. From MongoDB 3.2 onwards we can perform join operation. The new $lookup operator added with the aggregation pipeline is essentially similar to a left outer join. This is an example of the same:

from: <collection to join>,
localField: <field from the input documents>,
foreignField: <field from the documents of the "from" collection>,
as: <output array field>

Q10. Explain oplog.

Ans. The operational log(oplog) is a special type of capped collection that keeps a rolling record of all operations that modify the data stored in your databases.

Firstly it applies database operations on the primary and then records these operations on the primary’s oplog. Then, the secondary members copy and implement these operations in an asynchronous process.

Q11. When should the data be normalized in MongoDB?

Ans. It depends on your goals. Normalization will provide an update efficient data representation. Denormalization will make data reading efficiently.

In general, use embedded data models (denormalization) when:

  • When you have “contains” relationships between entities.
  • When you have one-to-many relationships between entities. In these relationships, the “many” or child documents always display with or are seen in the context of the “one” or parent documents.

In general, use normalized data models:

  • When embedding leads to duplication of data but will not give sufficient read performance benefits to outweigh the implications of the duplication.
  • To represent more complex many-to-many relationships.
  • To model large hierarchical data sets.

Q12. Comparison between MongoDB and Cassandra.



  • Data mode are the document
  • Database scalability is read-only
  • Query of the data is multi-index


  • Data mode are a big table like
  • Database scalability is write only
  • Query of the data by using scan or key

Q13. What does ObjectId consist of?

Ans. It consists of the following:

  • Timestamp
  • Client machine ID
  • Client process ID
  • Byte incremented counter

Q14. Explain about replication and when should we use it?

Ans. Replication is the process of synchronizing data across multiple servers so that data is not lost in any condition. It gives redundancy and rises data availability with many copies of data on other database servers.

We can use it for various purposes like for keeping the data safe, for high availability of data, disaster recovery and in no downtime for maintenance.

Q15. When and up to what extent does data get extended to multi-slice?

Ans. The MongoDB scrap stands on a collection. So all substances are kept in a lump or mass.

When there is an additional time slot only then there will be more than a few slice data achievement choices, but at the time, when there is more than 1 lump, data gets extend to many slices and it can further extend to 64 MB.

Q16. Enlist the limitations of the 32-bit version of MongoDB.

Ans. MongoDB uses memory-mapped files. When we run a 32-bit build of MongoDB, the total size of storage for the server, including indexes and data, is 2 gigabytes. Due to this, don’t deploy MongoDB to production on 32-bit machines.

And in the 64-bit build of MongoDB, there’s virtually no limit to storage size. For production deployments, we strongly recommend 64-bit builds and operating systems

Q17. What is the NoSQL database? Is MongoDB a NoSQL database?

Ans. From the advent of social media, the internet is being loaded with big data, big users, big complexity etc. and also becoming more complex day by day.

NoSQL is the answer to all these problems; it is not a traditional database management system, not even a relational database management system (RDBMS). NoSQL stands for “Not Only SQL”.

NoSQL is a kind of database that can handle and segregate all types of messy, unstructured, and complicated data. It is just a new way to describe the database. Yes, MongoDB is a NoSQL database.

Q18. How to find values in the array with multiple criteria?

Ans. Suppose you have the following document:

{_id : 1, numbers : [-1000, 1000]}
{_id : 2, numbers : [5]}

After this, if you write the following command :

db.example.find( { numbers : { $elemMatch : { $gt : -10 , $lt : 10 } } } );

It will return the _id: 2 document.

Q19. How to use select * group by MongoDB aggregation?

Ans. Suppose you want to select all attributes and groups by name across records. Let’s take an example:

{ Name: George, x: 5, y: 3 }
{ Name: George, z: 9 }
{ Name: Rob, x: 12, y: 2 }

And now do the MongoDB aggregation as follows:

{ $group : {
_id : “$Name”,
x: { $addToSet: “$x” },
y: { $addToSet: “$y” },
z: { $addToSet: “$z” },

Q20. How is sorting performed and what is a projection in MongoDB?

Ans. Whenever we have to find any data from MongoDB, find() method is being used. This method will return the documents of the collection on which this is invoked.

Now we can have where clause in MongoDB query so that we can limit the output by MongoDB projection. Whenever we will execute the find() method MongoDB will return all documents related to that specific collection. Below is the syntax for same:

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

Here flag will have two values as 0 or 1. Here 1 indicates that the corresponding values will be displayed and 0 indicates that the corresponding values will not be displayed.

Q21. Is it necessary to call “getLastError” to make a write durable?

Ans. No, it is not necessary to call “getLastError”(Safe Mode). Here the server behaves as if it has been called. The “getLastError” simply allows one to get confirmation that write operation is successfully committed. Here you will want the confirmation, but the safety of write and its durability is independent.

Q22. For how long does the replica set failover take?

Ans. It takes around 10 – 30 seconds for the primary to be dropped down by the other members and a new primary to be elected.

During this time span, the cluster is down for primary operations i.e writes and reads. Eventually, consistent queries can execute to secondaries at any time (in slaveOk mode), including during this window.

Q23. What does the “_v” field correspond to in Mongoose?

Ans. When the mongoose is created for the first time the version key is a property set on each and every document. The value of this key has the internal revision of the document. It is understood that the name of this document is configurable. The default key is __v

Q24. Tell about composition/structure of ObjectId in MongoDB? Explain each composing element.

ObjectId in MongoDB is very special. It associates with _id field, and MongoDB uses objectid as the default value of _id in documents. To generate objectid(), the following is the syntax:


Let’s take an example to understand it better:

obj_id = new ObjectId()

The above query will give us the following output:

There are some methods and details for the same are as follows:

  • str – It provides a string representation of object id.
  • valueOf() – It returns the hexadecimal representation of ObjectId.
  • getTimeStamp() – It returns the creation timestamp of objected.
  • toString() – It returns the string representation of ObjectId in the “ObjectId(haxstring)” .

Q25. Tell about the capped collection. How we create them in MongoDB?

Ans. Capped collection is a special type of collection in MongoDB. That means in this collection we can restrict the size of collection or we can put the limit on the size of the collection, these special type of collection is named as the capped collection. Here is the syntax for creating collections:

db.createCollection(<Collection_Name>, {capped: Boolean, autoIndexId: Boolean, size: Number, max : Number})

Let’s understand the syntax.

  • Collection_Name – Name of the collection that we create as the capped collection.
  • capped – Capped is the Boolean flag, true if the collection is to create as the capped collection, by default the value is false.
  • autoIndexId – The Boolean flag that we use for auto indexing. If true indexes will create automatically, false will say indexes will not create automatically.
  • size – Size parameter depicts the maximum size of documents in bytes. It is a mandatory field in terms of capped collections.
  • max – max parameter depicts the maximum number of documents that allow in a collection. Size gets preference over size.

Here is the syntax for isCapped() method:


Q 26. How can MongoDB simulate join or subquery?

Ans. We are trying to figure out the best way to structure data in Mongo to simulate what would be a simple join or subquery in SQL.

Say we have the classic Users and Posts example, with Users in one collection and Posts in another. We want to find all posts by users who’s city is “Mumbai”.

We have simplified things in this question, in real-world scenario storing posts as an array in the user document won’t work as we have 1,000’s of “posts” per user constantly inserting.

Q27. How can you sort a user-defined function; e.g. suppose x and y are integers, and the difference is (x-y)?

Ans. It is not possible directly.
Server-side sort:

db.eval(function() {
return db.scratch.find().toArray().sort(function(doc1, doc2) {
return doc1.a – doc2.a
Versus the equivalent client-side sort:
db.scratch.find().toArray().sort(function(doc1, doc2) {
return doc1.a – doc2.b

Note that it’s also possible to sort via an aggregation pipeline and by the $orderby operator (i.e. in addition to .sort()) however neither of these ways lets you provide a custom sort function either.

Q28. How to update _id of one MongoDB Document?

Ans. If you want to update _id then you will get something like this:

db.clients.update({‘_id’:ObjectId(“4cc45467c55f4d2d2a000002”)}, {‘$set’:{‘_id’:ObjectId(“4c8a331bda76c559ef000004”)}});

Mod on _id not allowed

And the update of the document is not made. You cannot update it by the given code. You’ll have to save the document using a new _id, and then remove the old document.

Skip code block

// store the document in a variable
doc = db.clients.findOne({_id: ObjectId(“4cc45467c55f4d2d2a000002”)})
// set a new _id on the document
doc._id = ObjectId(“4c8a331bda76c559ef000004”)
// insert the document, using the new _id
// remove the document with the old _id
db.clients.remove({_id: ObjectId(“4cc45467c55f4d2d2a000002”)})

To do it for your whole collection you can also use a loop

db.status.find().forEach(function(doc){ var id=doc._id; doc._id=doc.UserId; db.status.insert(doc); db.status.remove({_id:id}); })

In this case, UserId was the new ID I wanted to use

Q29.  How to get MongoDB database in JavaScript array?

Ans. To get this use the following code:

use admin
dbs = db.runCommand({listDatabases: 1})
dbNames = []
for (var i in dbs.databases) { dbNames.push(dbs.databases[i].name) }
Hopefully this will help.
The below will create an array of the names of the database:
var connection = new Mongo();
var dbNames = connection.getDBNames();

Q30. How to create a database in MongoDB?

Ans. When I was trying to create a database in MongoDB, I got one error:

:~$ mongo
MongoDB shell version: 1.6.5
connecting to: test
Error: couldn’t connect to server (anon):1154
exception: connect failed

A solution to the above issue:

  1. cd /var/lib/mongodb/
  2. Remove mongod.lock file from this folder
  3. Sudo start mongodb (in console)
  4. Mongo (in console)

And it runs fine.

First, you’ll need to run mongod on one terminal. Then fire up another terminal and type mongo. This shall open the mongo shell. You also need to create /data/db/ where mongo will store your databases.

This comes to the end of MongoDB interview questions and answers. We hope you liked our explanation.

Summary – Questions and Answers for MongoDB Interview

Hence, we have seen some questions for the MongoDB interview. These interview questions for MongoDB will surely help you with your interview preparation.

We tried to cover all the questions for MongoDB interview, still, if you have any queries or feedbacks related to MongoDB interview questions and answers article, you can enter in the comment section.

Did you like this article? If Yes, please give DataFlair 5 Stars on Google


Leave a Reply

Your email address will not be published. Required fields are marked *