30+ Top MongoDB Interview Questions and Answers
Tags: career, mongodb, fullstack, tips
Published: 2018-10-29 13:49:23

---
title: 30+ Top MongoDB Interview Questions and Answers
published: true
description: 30+ Top MongoDB Interview Questions and Answers (2018 Update)
tags: #career #mongodb #fullstack #tips
canonical_url: https://www.fullstack.cafe/blog/30-best-mongodb-interview-questions-and-answers
---
![30+ Top MongoDB Interview Questions and Answers (2018 Update)](https://images.pexels.com/photos/1143416/pexels-photo-1143416.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=350)
The NoSQL database movement came about to address the shortcomings of relational databases and the demands of modern software development. MongoDB is the leading NoSQL database, with significant adoption among the Fortune 500 and Global 500. 

> Originally published on [FullStack.Cafe - Never Fail Your Tech Interview Again](https://www.fullstack.cafe)

### Q1: Explain what is MongoDB?
> Topic: **MongoDB**<br/>Difficulty: ⭐

MongoDB is an open-source document database that provides high performance, high availability, and automatic scaling.
It's Key Features are:
* Document Oriented and NoSQL database.
* Supports Aggregation
* Uses BSON format
* Sharding (Helps in Horizontal Scalability)
* Supports Ad Hoc Queries
* Schema Less
* Capped Collection
* Indexing (Any field in MongoDB can be indexed)
* MongoDB Replica Set (Provides high availability)
* Supports Multiple Storage Engines

🔗 **Source:** [mongodb.com](https://docs.mongodb.com/manual/introduction/)
### Q2: How is data stored in MongoDB?
> Topic: **MongoDB**<br/>Difficulty: ⭐⭐

Data in MongoDB is stored in BSON documents – JSON-style data structures. Documents contain one or more fields, and each field contains a value of a specific data type, including arrays, binary data and sub-documents. Documents that tend to share a similar structure are organized as collections. It may be helpful to think of documents as analogous to rows in a relational database, fields as similar to columns, and collections as similar to tables.

The advantages of using documents are:

* Documents (i.e. objects) correspond to native data types in many programming languages.
* Embedded documents and arrays reduce need for expensive joins.
* Dynamic schema supports fluent polymorphism.

🔗 **Source:** [mongodb.com](https://www.mongodb.com/faq)
### Q3: What are Indexes in MongoDB?
> Topic: **MongoDB**<br/>Difficulty: ⭐⭐

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.

🔗 **Source:** [tutorialspoint.com](https://www.tutorialspoint.com/mongodb/mongodb_interview_questions.htm)
### Q4: Can you create an index on an array field in MongoDB? If yes, what happens in this case?
> Topic: **MongoDB**<br/>Difficulty: ⭐⭐

Yes. An array field can be indexed in MongoDB. In this case, MongoDB would index each value of the array so you can query for individual items:

```js
> db.col1.save({'colors': ['red','blue']})
> db.col1.ensureIndex({'colors':1})

> db.col1.find({'colors': 'red'})
{ "_id" : ObjectId("4ccc78f97cf9bdc2a2e54ee9"), "colors" : [ "red", "blue" ] }
> db.col1.find({'colors': 'blue'})
{ "_id" : ObjectId("4ccc78f97cf9bdc2a2e54ee9"), "colors" : [ "red", "blue" ] }
```

🔗 **Source:** [stackoverflow.com](https://stackoverflow.com/questions/4059126/how-does-mongodb-index-arrays)
### Q5: What Is Replication In MongoDB?
> Topic: **MongoDB**<br/>Difficulty: ⭐⭐

**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.

🔗 **Source:** [interviewbubble.com](https://interviewbubble.com/advance-topics/mongodb-interview-questions-and-answers/)
### Q6: What is Aggregation in MongoDB?
> Topic: **MongoDB**<br/>Difficulty: ⭐⭐⭐

*Aggregations* operations process data records and return computed results. Aggregation operations group values from multiple documents together, and can perform a variety of operations on the grouped data to return a single result. MongoDB provides three ways to perform aggregation: 
* the aggregation pipeline,
* the map-reduce function, 
* and single purpose aggregation methods and commands.

🔗 **Source:** [tutorialspoint.com](https://www.tutorialspoint.com/mongodb/mongodb_interview_questions.htm)
### Q7: How to query MongoDB with %like%?
> Topic: **MongoDB**<br/>Difficulty: ⭐⭐⭐

I want to query something as SQL's like query:

```sql
select * 
from users 
where name like '%m%'
```
How to do the same in MongoDB?

---
```js
db.users.find({name: /a/})  //like '%a%'
db.users.find({name: /^pa/}) //like 'pa%'
db.users.find({name: /ro$/}) //like '%ro'
```
Or using Mongoose:
```js
db.users.find({'name': {'$regex': 'sometext'}})
```

🔗 **Source:** [stackoverflow.com](https://stackoverflow.com/questions/3305561/how-to-query-mongodb-with-like)
### Q8: How do I perform the SQL JOIN equivalent in MongoDB?
> Topic: **MongoDB**<br/>Difficulty: ⭐⭐⭐

Mongo is not a relational database, and the devs are being careful to recommend specific use cases for $lookup, but at least as of 3.2 doing join is now possible with MongoDB. The new $lookup operator added to the aggregation pipeline is essentially identical to a left outer join:

```js
{
   $lookup:
     {
       from: <collection to join>,
       localField: <field from the input documents>,
       foreignField: <field from the documents of the "from" collection>,
       as: <output array field>
     }
}
```

🔗 **Source:** [stackoverflow.com](https://stackoverflow.com/questions/2350495/how-do-i-perform-the-sql-join-equivalent-in-mongodb)
### Q9: What is the difference b/w MongoDB and CouchDB?
> Topic: **MongoDB**<br/>Difficulty: ⭐⭐⭐

MongoDB and CouchDB both are the great example of open source NoSQL database. Both are document oriented databases. Although both stores data but there is a lot of difference between them in terms of implementation of their data models, interfaces, object storage and replication methods etc.

🔗 **Source:** [medium.com/@hub4tech](https://medium.com/@hub4tech/list-of-top-10-mongodb-interview-questions-for-beginners-and-professionals-ee385b9c501b)
### Q10: What are NoSQL databases? What are the different types of NoSQL databases?
> Topic: **MongoDB**<br/>Difficulty: ⭐⭐⭐

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

🔗 **Source:** [interviewbubble.com](https://interviewbubble.com/advance-topics/mongodb-interview-questions-and-answers/)
### Q11: Explain the structure of ObjectID in MongoDB
> Topic: **MongoDB**<br/>Difficulty: ⭐⭐⭐

**ObjectIds** are small, likely unique, fast to generate, and ordered. ObjectId values consist of 12 bytes, where the first four bytes are a timestamp that reflect the ObjectId’s creation. Specifically:

* a 4-byte value representing the seconds since the Unix epoch,
* a 5-byte random value, and
* a 3-byte counter, starting with a random value.
In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field.

🔗 **Source:** [mongodb.com](https://docs.mongodb.com/manual/reference/bson-types/)
### Q12: What is a covered query in MongoDB?
> Topic: **MongoDB**<br/>Difficulty: ⭐⭐⭐

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

🔗 **Source:** [tutorialspoint.com](https://www.tutorialspoint.com/mongodb/mongodb_interview_questions.htm)
### Q13: Find objects between two dates MongoDB
> Topic: **MongoDB**<br/>Difficulty: ⭐⭐⭐

```js
db.CollectionName.find({"whenCreated": {
    '$gte': ISODate("2018-03-06T13:10:40.294Z"),
    '$lt': ISODate("2018-05-06T13:10:40.294Z")
}});
```

🔗 **Source:** [stackoverflow.com](https://stackoverflow.com/questions/2943222/find-objects-between-two-dates-mongodb)
### Q14: What is oplog?
> Topic: **MongoDB**<br/>Difficulty: ⭐⭐⭐

The *oplog* (operations log) is a special capped collection that keeps a rolling record of all operations that modify the data stored in your databases. MongoDB applies database operations on the primary and then records the operations on the primary’s oplog. The secondary members then copy and apply these operations in an asynchronous process. 

🔗 **Source:** [tutorialspoint.com](https://www.tutorialspoint.com/mongodb/mongodb_interview_questions.htm)
### Q15: Does MongoDB support ACID transaction management and locking functionalities?
> Topic: **MongoDB**<br/>Difficulty: ⭐⭐⭐

ACID stands that any update is:
* **Atomic**: it either fully completes or it does not
* **Consistent**: no reader will see a "partially applied" update
* **Isolated**: no reader will see a "dirty" read
* **Durable**: (with the appropriate write concern)

Historically MongoDB does not support default multi-document ACID transactions (multiple-document updates that can be rolled back and are ACID-compliant). However, MongoDB provides atomic operation on a single document. MongoDB 4.0 **will add support for multi-document transactions**, making it the only database to combine the speed, flexibility, and power of the document model with ACID data integrity guarantees.

🔗 **Source:** [tutorialspoint.com](https://www.tutorialspoint.com/mongodb/mongodb_interview_questions.htm)
### Q16: What is Sharding in MongoDB? Explain.
> Topic: **MongoDB**<br/>Difficulty: ⭐⭐⭐

*Sharding* is a method for storing data across multiple machines. MongoDB uses sharding to support deployments with very large data sets and high throughput operations.

🔗 **Source:** [tutorialspoint.com](https://www.tutorialspoint.com/mongodb/mongodb_interview_questions.htm)
### Q17: Should I normalize my data before storing it in MongoDB?
> Topic: **MongoDB**<br/>Difficulty: ⭐⭐⭐

It depends from your goals. Normalization will provide an _update efficient data representation_. Denormalization will make data _reading efficient_. 

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

* you have “contains” relationships between entities.
* you have one-to-many relationships between entities. In these relationships the “many” or child documents always appear with or are viewed in the context of the “one” or parent documents.

In general, use normalized data models:

* when embedding would result in duplication of data but would not provide sufficient read performance advantages to outweigh the implications of the duplication.
* to represent more complex many-to-many relationships.
* to model large hierarchical data sets.

Also normalizing your data like you would with a relational database is usually not a good idea in MongoDB. Normalization in relational databases is only feasible under the premise that JOINs between tables are relatively cheap. The $lookup aggregation operator provides some limited JOIN functionality, but it doesn't work with sharded collections. So joins often need to be emulated by the application through multiple subsequent database queries, which is very slow (see question MongoDB and JOINs for more information).

🔗 **Source:** [stackoverflow.com](https://stackoverflow.com/questions/24839147/is-it-needed-to-normalize-your-database-when-you-are-using-mongodb)
### Q18: How does MongoDB ensure high availability?
> Topic: **MongoDB**<br/>Difficulty: ⭐⭐⭐⭐

MongoDB automatically maintains replica sets, multiple copies of data that are distributed across servers, racks and data centers. Replica sets help prevent database downtime using native replication and automatic failover.

A replica set consists of multiple replica set members. At any given time one member acts as the primary member, and the other members act as secondary members. If the primary member fails for any reason (e.g., hardware failure), one of the secondary members is automatically elected to primary and begins to process all reads and writes.

🔗 **Source:** [mongodb.com](https://www.mongodb.com/faq)
### Q19: How does MongoDB provide concurrency?
> Topic: **MongoDB**<br/>Difficulty: ⭐⭐⭐⭐

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.

🔗 **Source:** [tutorialspoint.com](https://www.tutorialspoint.com/mongodb/mongodb_interview_questions.htm)
### Q20: How does Journaling work in MongoDB?
> Topic: **MongoDB**<br/>Difficulty: ⭐⭐⭐⭐

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.

🔗 **Source:** [tutorialspoint.com](https://www.tutorialspoint.com/mongodb/mongodb_interview_questions.htm)
### Q21: When to Redis or MongoDB?
> Topic: **MongoDB**<br/>Difficulty: ⭐⭐⭐⭐

* **Use MongoDB if you don't know yet how you're going to query your data or what schema to stick with.**
MongoDB is suited for Hackathons, startups or every time you don't know how you'll query the data you inserted. MongoDB does not make any assumptions on your underlying schema. While MongoDB is schemaless and non-relational, this does not mean that there is no schema at all. It simply means that your schema needs to be defined in your app (e.g. using Mongoose). Besides that, MongoDB is great for prototyping or trying things out. Its performance is not that great and can't be compared to Redis.

* **Use Redis in order to speed up your existing application.** It is very uncommon to use Redis as a standalone database system (some people prefer referring to it as a "key-value"-store). 

🔗 **Source:** [stackoverflow.com](https://stackoverflow.com/questions/5400163/when-to-redis-when-to-mongodb)
### Q22: MongoDB relationships. What to use - embed or reference?
> Topic: **MongoDB**<br/>Difficulty: ⭐⭐⭐⭐

I want to design a question structure with some comments, but I don't know which relationship to use for comments: embed or reference? Explain me pros and cons of both solutions? 

---
In general, 
* **embed** is good if you have one-to-one or one-to-many relationships between entities, and 
* **reference** is good if you have many-to-many relationships.

Also consider as a general rule, if you have a lot of [child documents] or if they are large, a separate collection might be best. Smaller and/or fewer documents tend to be a natural fit for embedding.

🔗 **Source:** [stackoverflow.com](https://stackoverflow.com/questions/5373198/mongodb-relationships-embed-or-reference)
### Q23: Is MongoDB schema-less?
> Topic: **MongoDB**<br/>Difficulty: ⭐⭐⭐⭐

No. In MongoDB schema design is still important. MongoDB's document model does, however, employ a different schema paradigm than traditional relational databases.

In MongoDB, documents are self-describing; there is no central catalog where schemas are declared and maintained. The schema can vary across documents, and the schema can evolve quickly without requiring the modification of existing data.

MongoDB's dynamic schema also makes it easier to represent semi-structured and polymorphic data, as documents do not all need to have exactly the same fields. For example, a collection of financial trading positions might have positions that are equity positions, and some that are bonds, and some that are cash. All may have some fields in common, but some fields ('ticker', “number_of_shares”) do not apply to all position types.

🔗 **Source:** [mongodb.com](https://www.mongodb.com/faq)
### Q24: What are Primary and Secondary Replica sets?
> Topic: **MongoDB**<br/>Difficulty: ⭐⭐⭐⭐

* **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.

🔗 **Source:** [tutorialspoint.com](https://www.tutorialspoint.com/mongodb/mongodb_interview_questions.htm)
### Q25: How to check if a field contains a substring?
> Topic: **MongoDB**<br/>Difficulty: ⭐⭐⭐⭐

Consider:
```js
db.users.findOne({"username" : {$regex : ".*subsctring.*"}});
```

🔗 **Source:** [stackoverflow.com](https://stackoverflow.com/questions/10610131/checking-if-a-field-contains-a-string)
### Q26: What are alternatives to MongoDB?
> Topic: **MongoDB**<br/>Difficulty: ⭐⭐⭐⭐

Cassandra, CouchDB, Redis, Riak, Hbase are a few good alternatives.

🔗 **Source:** [interviewbubble.com](https://interviewbubble.com/advance-topics/mongodb-interview-questions-and-answers/)
### Q27: How to find document with array that contains a specific value?
> Topic: **MongoDB**<br/>Difficulty: ⭐⭐⭐⭐⭐

You have this schema:
```js
person = {
    name : String,
    favoriteFoods : Array
}
```
where the `favoriteFoods` array is populated with strings. How can I find all persons that have `sushi` as their favorite food using MongoDB?

---
Consider:
```js
PersonModel.find({ favouriteFoods: "sushi" }, ...);
PersonModel.find({ favouriteFoods: { "$in" : ["sushi"]} }, ...);
```

🔗 **Source:** [docs.mongodb.com](https://docs.mongodb.com/manual/tutorial/query-arrays/)
### Q28: Is it possible to update MongoDB field using value of another field?
> Topic: **MongoDB**<br/>Difficulty: ⭐⭐⭐⭐⭐

In SQL we will use:
```sql
UPDATE Person SET Name = FirstName + ' ' + LastName
```
Is it possible with MongoDB?

---
You cannot refer to the document itself in an update (yet). You'll need to iterate through the documents and update each document using a function. 
So consider:
```js
db.person.find().snapshot().forEach(
  function(elem) {
    db.person.update({
      _id: elem._id
    }, {
      $set: {
        name: elem.firstname + ' ' + elem.lastname
      }
    });
  }
);
```

🔗 **Source:** [stackoverflow.com](https://stackoverflow.com/questions/3974985/update-mongodb-field-using-value-of-another-field)
### Q29: Explain what is horizontal scalability?
> Topic: **MongoDB**<br/>Difficulty: ⭐⭐⭐⭐⭐

**Horizontal scalability** is the ability to increase capacity by connecting multiple hardware or software entities so that they work as a single logical unit. MongoDB provides horizontal scalability as part of its core functionality.

🔗 **Source:** [searchcio.techtarget.com](https://searchcio.techtarget.com/definition/horizontal-scalability)
### Q30: What are the differences between MongoDB and MySQL?
> Topic: **MongoDB**<br/>Difficulty: ⭐⭐⭐⭐⭐

The Major Differences between MongoDB and MySQL are:

1. There is a difference in the representation of data in the two databases. In MongoDB, data represents in a collection of JSON documents while in MySQL, data is in tables and rows. JSON documents can compare to associative arrays when using PHP and directory objects when using Python.
2. When it comes to querying, you have to put a string in the query language that the DB system parses. The query language is called Structured Query Language, or SQL,from where MySQL gets its name. This exposes your DB susceptible to SQL injectionattacks. On the other hand, MongoDB’s querying is object-oriented, which means you pass MongoDB a document explaining what you are querying. There is no parsing whatsoever, which will take some time getting used to if you already use SQL.
3. One of the greatest benefits of relational databases like MySQL is the JOIN operation. The operation allows for the querying across several tables. Although MongoDB doesn’t support joints, it supports multi-dimensional data types like other documents and arrays.
4. With MySQL, you can have one document inside another (embedding). You would have to create one table for comments and another for posts if you are using MySQL to create a blog. In MongoDB, you will only have one array of comments and one collection of posts within a post.
5. MySQL supports atomic transactions. You can have several operations within a transaction and you can roll back as if you have a single operation. There is no support for transactions in MongoDB and the single operation is atomic.
6. One of the best things about MongoDB is that you are not responsible for defining the schema. All you need to do is drop in documents. Any 2 documents in a collection need not be in the same field. You have to define the tables and columns before storage in MySQL. All rows in a table share the same columns.
7. MongoDB’s performance is better than that of MySQL and other relational DBs. This is because MongoDB sacrifices JOINS and other things and has excellent performance analysis tools. Note that you still have to index the data and the data in most applications is not enough for them to see a difference. MySQL is criticized for poor performance, especially in ORM application. However, you are unlikely to have an issue if you do proper data indexing and you are using a database wrapper.
8. One advantage of MySQL over NoSQL like MongoDB is that the community in MySQL is much better than NoSQL. This is mostly because NoSQL is relatively new while MySQL has been around for several years.
9. There are no reporting tools with MongoDB, meaning performance testing and analysis is not always possible. With MySQL, you can get several reporting tools that help you rove the validity of your applications.
10. RDBSs function on a paradigm called ACID, which is an acronym for (Atomicity, Consistency, Isolation, and Durability). This is not present in MongoDB database.
11. MongoDB has a Map Reduce feature that allows for easier scalability. This means you can get the full functionality of MongoDB database even if you are using low-cost hardware.
12. You do not have to come up with a detailed DB model with MongoDB because of is non-relational. A DB architect can quickly create a DB without a fine-grained DB model, thereby saving on development time and cost.



🔗 **Source:** [analyticbridge.datasciencecentral.com](https://www.analyticbridge.datasciencecentral.com/profiles/blogs/comparing-mongodb-with-mysql)

> *Thanks 🙌 for reading and good luck on your interview!* <br/>*Please share this article with your fellow devs if you like it!* <br/>*Check more FullStack Interview Questions & Answers on 👉 [www.fullstack.cafe](https://www.fullstack.cafe)*