Top 25+ MongoDB Interview Questions & Answers

Mongo DB 3.2 is 300 times faster than mysql. MongoDB is basically an Open Source cross platform document oriented DB program, often classified as NoSQL DB program. What it means is that instead of the traditional table based RDBMS, the emphasis is on JSON with dynamic schemas.



mongodb


Learning Mongo DB will definitely gives a boost to your career because the demand for Mongo DB in the market is increasing at a tremendous pace.

MongoDB is fast becoming an industry trend and is gaining popularity for its powerful query language and its easy transition from a relational database to NoSQL database. With increasing implementation of Big Data and its technologies, it is a natural progression for the organizations to look for MongoDB skills.

MongoDB is used across several companies in multiple domains (some of them shown below):


mongodb


This blog provides Frequently asked Top 25+ MongoDB interview questions and best answers for freshers and 2-4 year experienced developers.


1. What do you understand by NoSQL databases? Is MongoDB a NoSQL database? explain.

NoSQL is a class of database management systems (DBMS) that do not follow all of the rules of a relational DBMS and cannot use traditional SQL to query data. NoSQL stands for "Not Only SQL". NoSQL is a type of database that can handle and sort all type of unstructured, messy and complicated data. It is just a new way to think about the database.

Yes. MongoDB is a NoSQL database.

2. What are the different types of NoSQL databases? Give some example.

NoSQL database can be classified as 4 basic types:

(i). Key value store NoSQL database
(ii). Document store NoSQL database
(iii). Column store NoSQL database
(iv). Graph base NoSQL databse

There are many NoSQL databases. MongoDB, Cassandra, CouchBD, Hypertable, Redis, Riak, Neo4j, HBASE, Couchbase, MemcacheDB, Voldemort, RevenDB etc. are the examples of NoSQL databases.

3. What type of DBMS is MongoDB?

MongoDB is a document oriented DBMS.

MIND IT !

A record in MongoDB is a document (shown below), which is a data structure composed of field and value pairs. MongoDB documents are similar to JSON objects. The values of fields may include other documents, arrays, and arrays of documents.This is an important differentiation from RDBMS systems where each field must contain only one value.


mongodb


4. What is the difference between MongoDB and MySQL?

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 injection attacks. 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.

5. Why MongoDB is known as best NoSQL database?

MongoDb is the best NoSQL database because, it is:

- Document Oriented
- Rich Query language
- High Performance
- Highly Available
- Easily Scalable

6. What is the difference b/w MongoDB and CouchDB?

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.

CouchDB has some advantages over MongoDB with features like:

- multi master replication which is very helpful when two databases are located in two different datacenters;
- built-in HTTP REST API;
- no database locking, thanks to MVCC.

In the same time some great features from MongoDB are not supported in CouchDB:

- auto sharing which make very easy to scale write operations;
- automatic failover of nodes.
- built-in full text search
- monitoring service like MMS

7. What is a Namespace in MongoDB?

Namespace is a concatenation of the database name and the collection name. Collection, in which MongoDB stores BSON objects.

MIND IT !

BSON : It is a binary form for representing simple data structures, associative arrays (called objects or documents in MongoDB), and various data types of specific interest to MongoDB. The name "BSON" is based on the term JSON and stands for "Binary JSON".

8. Why does Profiler use in MongoDB?

MongoDB uses a database profiler to perform characteristics of each operation against the database. You can use a profiler to find queries and write operations

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

Yes, it be. Remove the attribute and then re-save() the object.

10. In which language MongoDB is written?

MongoDB is written and implemented in C++.

11. Does MongoDB need a lot space of Random Access Memory (RAM)?

No. MongoDB can be run on small free space of RAM.

12. What language you can use with MongoDB?

MongoDB client drivers supports all the popular programming languages so there is no issue of language, you can use any language that you want.

13. Does MongoDB database have tables for storing records?

No. Instead of tables, MongoDB uses "Collections" to store data.

14. Do the MongoDB databases have schema?

Yes. MongoDB databases have dynamic schema. There is no need to define the structure to create collections.

15. What is the method to configure the cache size in MongoDB?

MongoDB's cache is not configurable. Actually MongoDb uses all the free spaces on the system automatically by way of memory mapped files.

16. How to do Transaction/locking in MongoDB?

MongoDB doesn't use traditional locking or complex transaction with Rollback. MongoDB is designed to be light weighted, fast and predictable to its performance. It keeps transaction support simple to enhance performance.

17. Why 32 bit version of MongoDB are not preferred ?

Because MongoDB uses memory mapped files so when you run a 32-bit build of MongoDB, the total storage size of server is 2 GB. But when you run a 64-bit build of MongoDB, this provides virtually unlimited storage size. So 64-bit is preferred over 32-bit.

18. Is it possible to remove old files in the moveChunk directory?

Yes, These files can be deleted once the operations are done because these files are made as backups during normal shard balancing operation. This is a manual cleanup process and necessary to free up space.

19. What will have to do if a shard is down or slow and you do a query?

If a shard is down and you even do query then your query will be returned with an error unless you set a partial query option. But if a shard is slow them Mongos will wait for them till response.

20. What are alternatives to MongoDB?

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

21. Mention what is the basic syntax to use index in MongoDB?

The basic syntax to use in MongoDB is >db.COLLECTION_NAME.ensureIndex ( {KEY:1} ). In here the key is the name of the file on which you want to create an index, where 1 is for ascending order while you use -1 for descending order.

22. Explain what are indexes in MongoDB?

Indexes are special structures in MongoDB, which stores a small portion of the data set in an easy to traverse form. Ordered by the value of the field specified in the index, the index stores the value of a specific field or set of fields.

MIND IT !

The ordering of the index entries supports efficient equality matches and range-based query operations. In addition, MongoDB can return sorted results by using the ordering in the index. The following diagram illustrates a query that selects and orders the matching documents using an index:


mongodb

Indexes are used for better query performance. They are created on fields which appear often in queries(_id) and for operations that return sorted results. MongoDB automatically creates a unique index on the _id field. Indexes have the following properties in MongoDB:

(i). Each index requires at least 8KB of data space.
(ii). Adding an index has some negative performance impact for write operations. For collections with high write-to-read ratio, indexes are expensive since each insert must also update any indexes.
(iii). Collections with high read-to-write ratio often benefit from additional indexes.
(iv). When active, each index consumes disk space and memory. This usage grows over time can becomes significant. Perhaps, for better server space and performance management, it is good practice to track the growth of indexes.

Indexes support the efficient execution of queries. If an appropriate index exists for a query, MongoDB can use the index to limit the number of documents it must inspect.

23. 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'.

24. Define MongoDB?

MongoDB is a cross-platform and open-source document-oriented database, a kind of NoSQL database. As a NoSQL database, MongoDB shuns the relational database’s table-based structure to adapt JSON-like documents that have dynamic schemas which it calls BSON.

mongodb

This makes data integration for certain types of applications faster and easier. MongoDB is built for scalability, high availability and performance from a single server deployment to large and complex multi-site infrastructures.

25. What is the use of MongoDB?

MongoDB is a document-oriented database. Instead of storing your data in tables made out of individual rows, like a relational database does, it stores your data in collections made out of individual documents. In MongoDB, a document is a big JSON blob with no particular format or schema.

(i). MongoDB is typically used as the primary data store for operational applications with real-time requirements (i.e., low-latency, high availability). MongoDB is generally a good fit for 60%-80% of the applications you may be building today. MongoDB is easy to operate and scale in ways that are hard if not impossible with relational databases.

(ii). MongoDB excels in many use cases where relational databases aren't a good fit, like applications with unstructured, semi-structured and polymorphic data, as well as applications with large scalability requirements or multi-data center deployments.

(iii). MongoDB may not be a good fit for some applications. For example, applications that require complex transactions (e.g., a double-entry bookkeeping system) and scan-oriented applications that access large subsets of the data most of the time may not be a good fit for MongoDB. MongoDB is not a drop-in replacement for legacy applications built around the relational data model and SQL.

(iv). Some common use cases include mobile apps, product catalogs, real-time personalization, content management and applications delivering a single view across multiple systems.

26. What kind of database is MongoDB?

MongoDB is an open source database that uses a document-oriented data model. MongoDB is one of several database types to arise in the mid-2000s under the NoSQL banner. Instead of using tables and rows as in relational databases, MongoDB is built on an architecture of collections and documents.

27. Which are the most important features of MongoDB?

1. Flexible data model in form of documents.
2. Agile and highly scalable database.
3. Faster than traditional databases.
4. Expressive query language.

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

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

30. Does MongoDB support foreign key constraints?

No, MongoDB does not support such relationships.

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

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

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


db.products.insert( { item: "card", qty: 15 } )


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

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

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

36. While creating Schema in MongoDB what are the points need to be taken in consideration?

Points need to be taken in consideration are:

(i). Design your schema according to user requirements.
(ii). Combine objects into one document if you use them together. Otherwise, separate them.
(iii). Do joins while write, and not when it is on read.
(iv). For most frequent use cases optimize your schema.
(v). Do complex aggregation in the schema.

37. Explain what is a replica set?

A replica set is a group of mongo instances that host the same data set. In replica set, one node is primary, and another is secondary. From primary to the secondary node all data replicates.

MIND IT !

One mongodb, the primary, receives all write operations. All other instances, secondaries, apply operations from the primary so that they have the same data set (shown below).

The primary accepts all write operations from clients. A replica set can have only one primary. To support replication, the primary records all changes to its data sets in its oplog (operations log).


mongodb


The secondaries 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. If the primary is unavailable, the replica set will elect a secondary to be primary. When a primary does not communicate with the other members of the set for more than 10 seconds, the replica set will attempt to select another member to become the new primary. The first secondary that receives a majority of votes becomes a primary(shown below).


              mongodb


38. How replication works in MongoDB?

Across multiple servers, the process of synchronizing data is known as replication. It provides redundancy and increase data availability with multiple copies of data on different database server. Replication helps in protecting the database from the loss of a single server.

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

40. What is Aggregation in MongoDB?

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.

All the best ....!!

Share This Post:

About The Author

Megha Panwar - I have been helping aspirants to clear different competitive exams. LearnFrenzy as a team gave me an opportunity to do it on a larger level an reach out to more students. Do comment below if you have any questions or feedbacks.