MongoDB Basic Interview Questions
1) Is MongoDB a NoSQL database?
Yes, MongoDB is a NoSQL database because it offers all the facilities that a cloud offers without using many commands. It handles complex data easily in varieties of data models like graphs, documents, etc.
2) What are the languages supported by MongoDB?
MongoDB supports the languages C, C++, Java, C#, Python, Node.js, Perl, PHP, Ruby, Go, Erlang, and Scala. It provides the official driver support for these languages.
3) What are the advantages of MongoDB?
MongoDB provides us with many advantages like
- It provides a dynamic database schema.
- It provides inbuilt support for the data partition.
- It uses JavaScript objects.
- It supports field, range-based, string pattern matching type queries.
4) What are the features of MongoDB?
The features provided by MongoDB are
- Indexing
- Aggregation
- File storage
- Sharding
- Special collection
5) What is a Document in MongoDB?
A document in MongoDB is an ordered set of keys with values. It can be represented by a hash, map, or dictionary. It can also be represented as
{“name”: ”coding ninjas”}
6) What is a collection in MongoDB?
In MongoDB, a collection is similar to a table in traditional relational databases. However, unlike tables, collections do not enforce a fixed schema. A collection is a container for storing documents, which are essentially JSON-like objects with key-value pairs. Each document in a collection can have different fields, and data types can vary among different documents within the same collection. This flexibility makes it easier to adapt to evolving data requirements, making collections an integral part of MongoDB's NoSQL architecture.
7) How to add data in MongoDB?
We can add the data to MongoDB using the method insert(). We can use insertOne() to insert a single document and insertMany() to insert multiple documents into a collection.
Example: db.names.insertOne({"name" : "coding ninjas"})
8)How do you Update a Document?
To update a document in MongoDB, you can use methods like `updateOne()`, `updateMany()`, or `findOneAndUpdate()`. These methods take a query to identify the document(s) to update and an update parameter to specify the changes. For example, to update a user's age, you'd execute `db.collection.updateOne({name: "John"}, {$set: {age: 30}})`. This will find the first document where the name is "John" and update the age to 30. Multiple fields can be updated simultaneously.
9) What are the data types supported by MongoDB?
The data types in MongoDB tell us about the type of a variable or any object. The different types are null, boolean, string, number, date, regular expression, array, object, etc.
10) Why is MongoDB known as the best NoSQL database?
MongoDB is known as the best NoSQL database because of its features like
- Document-oriented database
- Rich Query language
- High Performance
- Availability
- Scalability
11)Explain the structure of ObjectID in MongoDB?
In MongoDB, an ObjectID is a 12-byte identifier typically used to uniquely identify documents within a collection. The structure comprises a 4-byte timestamp reflecting the ObjectID's creation time, a 5-byte random value unique to the machine and process, a 2-byte incrementing counter, and a 1-byte machine identifier. This composition ensures global uniqueness and allows some degree of sorting by creation time.
12) What are Indexes in MongoDB?
Indexes in MongoDB enhance query performance by allowing the database engine to search through a smaller subset of data. They work like a table of contents, pointing to the location of specific data in the collection. The most basic type is the single-field index, but MongoDB also supports compound, text, and other specialized index types for more complex queries.
13) How to configure the cache size in MongoDB?
In MongoDB, you can configure the WiredTiger storage engine's cache size using the `--wiredTigerCacheSizeGB` command-line option or by setting the `storage.wiredTiger.engineConfig.cacheSizeGB` parameter in the configuration file. This specifies the maximum amount of RAM in GB that WiredTiger will use for caching data and indexes. Note that the cache size shouldn't exceed the available RAM for optimal performance.
14) Why is the 32-bit version of MongoDB not preferred?
The 32-bit version uses memory-mapped files, so when you run the build, the server can be up to 2GB. But the 64-bit version provides us with unlimited virtual storage, which can be easy to store vast amounts of data.
15) What is sharding in MongoDB?
Sharding in MongoDB is a method for distributing data across multiple servers to manage large datasets and high-throughput operations. By splitting a dataset into smaller "shards," each managed by a separate server, sharding ensures horizontal scalability. This approach allows MongoDB to handle increased data volume and read-write operations, thereby improving performance and availability.
MongoDB Intermediate Interview Questions
16) What is CRUD?
The CRUD operations supported by MongoDB are used to manipulate the data in the collections. They are
17) How to query for data in MongoDB?
The querying in MongoDB can be done using the find() method on collections. It returns the subset or single document in a collection. The fetching of documents is done based on the first argument passed to the method.
Example: db.names.find({"username" : "ninja"})
18) What is the ObjectID composed of?
The ObjectID is composed of
- Timestamp
- Client machine ID
- Client process ID
- 3 byte incremented counter
19) What is a Namespace in MongoDB?
A Namespace in MongoDB is the concatenation of the database name and collection name. Example: db.names, where db is the database and names is the collection in database db.
20) Why is MongoDB better than SQL databases?
MongoDB provides a document-oriented structure with high scalability and flexibility. It can have multiple columns and rooms in the same collection. They are faster than other SQL databases because of indexing.
21) What is a covered query in MongoDB?
A covered query in MongoDB is
- the fields used in the query are part of an index used in the query
- the fields returned in the results are in the same index
22)What is Replication in MongoDB?
Replication in MongoDB involves creating copies of data across multiple servers to ensure high availability and data durability. A replica set consists of one primary node and multiple secondary nodes. The primary node handles all write operations, while secondaries replicate this data asynchronously. In case the primary fails, one of the secondaries can automatically take over, enhancing data resilience.
23) What are the two storage engines used by MongoDB?
The two primary storage engines used by MongoDB are MMAPv1 (deprecated as of MongoDB 4.0) and WiredTiger. WiredTiger is the default and offers better performance, compression, and concurrency.
24) Can you run multiple Javascript operations in a single MongoDB instance?
Yes, you can run multiple JavaScript operations in a single MongoDB instance using the mongo shell or server-side JavaScript execution. However, it's important to note that these operations are single-threaded within each separate connection to the MongoDB server.
25) What are some utilities to backup and restore in MongoDB?
The utilities provided by MongoDB to backup and restore
- mongoimport
- mongoexport
- mongodump
- mongorestore
26) What are the cons of MongoDB?
MongoDB has some drawbacks like limited support for ACID transactions compared to traditional relational databases. This can make complex transactions challenging to handle. Additionally, its schema-less nature can lead to data inconsistency if not carefully managed. Furthermore, MongoDB may require higher storage space due to de-normalization and redundancy, increasing infrastructure costs.
Read about SAP FICO Interview Questions
27) What is Mongo shell?
The Mongo shell is an interactive JavaScript interface to MongoDB, which allows you to interact directly with the database. It serves as a powerful tool for administrative tasks, querying, and updates. You can start the Mongo shell by running the `mongo` command in your terminal, and connecting it to a running MongoDB instance. Within the shell, you can execute MongoDB commands, JavaScript functions, and even scripts to manipulate data, create or drop collections, and perform various operations. The shell is essential for debugging, data manipulation, and administrative tasks.
28) How is data stored in MongoDB?
In MongoDB, data is stored in BSON (Binary JSON) format, which is a binary-encoded serialization of JSON-like documents. Each BSON document contains one or more fields with values that can include various data types, like arrays and other documents. These documents are organized into collections, which function similarly to tables in relational databases. Unlike relational databases, MongoDB allows for a flexible schema, meaning documents within the same collection can have different fields and structures.
29) Why covered query is important?
In a covered query, the indexes are stored in RAM or sequentially on the disk. Thus, the covered queries increase the execution speed of the queries.
In a covered query, all the fields in the query are part of an index. MongoDB checks the query conditions and returns the result using the same index without peeking inside the documents. As the indexes are present in RAM, fetching data from indexes is much faster than fetching data by scanning documents.
30) What factors need to be taken into account when creating a schema in MongoDB?
Points that need to be taken into regard are:
- Design your schema as per the user's needs.
- Merge objects into one document if you use them together; else, separate them.
- Always do joins while write, and not when it is on the read.
- For most frequent use cases, always optimize your schema.
- Do all the complex aggregation in the schema.
MongoDB Advanced Interview Questions
31)How can you implement sharded transactions in MongoDB?
Sharded transactions are available starting MongoDB 4.2. You start a session and then initiate a transaction within that session, which can span multiple shards. Two-phase commit ensures consistency across shards.
32)What are the write concerns in MongoDB and how do they impact data consistency?
Write concerns in MongoDB determine the level of assurance for data writes. By configuring write concerns, you can balance between performance and data consistency. For instance, a majority write concern ensures that data is written to the majority of replica set members.
33)Explain the role of a Config Server in a sharded MongoDB cluster.
Config servers store the metadata that directs traffic for a sharded cluster. They help route the queries to the appropriate shard(s), making them essential for cluster management.
34)How does the Aggregation Framework differ from MapReduce in MongoDB?
The Aggregation Framework is a pipeline for data transformation, optimized for better performance and easier use. MapReduce, although flexible, can be more complex and less performant for certain operations.
35)How do you secure MongoDB against "injection" attacks?
MongoDB can be secured against injection attacks by using input validation, parameterized queries, and native MongoDB drivers which inherently treat data as parameters, not executable code.
36)What are the different types of indexes in MongoDB and how do they differ?
MongoDB supports various types of indexes like Single Field, Compound, Text, Hashed, and Geospatial. Each serves unique query optimization needs, from text searches to geographical data queries.
37)Explain the "Hot Backup" concept in MongoDB.
Hot backups are taken without stopping the database service, generally by snapshotting the underlying volume. This ensures high availability but may need additional considerations for point-in-time consistency.
38)How does journaling work in MongoDB?
Journaling in MongoDB keeps a log of changes not yet written to the database files. If MongoDB unexpectedly stops, you can recover data using the journal.
39)Describe the use of "Projections" in MongoDB queries.
Projections in MongoDB allow you to include or exclude specific fields from query results. This helps optimize the query performance by reducing the amount of data transferred.
40)What is the purpose of the mongostat and mongotop utilities?
Mongostat provides quick statistics about the MongoDB instance, whereas mongotop tracks the read and write operations and shows how much time is spent in each.
41)How do you perform a partial index in MongoDB?
A partial index indexes only the documents that meet a specified filter expression. This optimizes both the storage space and query performance for a specific subset of data.
42)What is the significance of the local database in a MongoDB instance?
The local database is a special database that stores data used in the replication process, and it's not replicated itself. It usually houses the Oplog.
43)What is the role of the _id field in sharding?
The _id field can be crucial for sharding as it could be the shard key or part of a compound shard key. Choosing an appropriate _id field affects the distribution of data across shards.
44)Explain "Eventual Consistency" in MongoDB.
Eventual consistency in MongoDB means that if no new updates are made, eventually all replicas will converge to the same state. This is different from strong consistency models.
45)How do you manage large files in MongoDB?
GridFS can be used to store and manage files larger than the BSON-document size limit of 16MB. It divides the large file into smaller chunks and stores them as separate documents.
MongoDB MCQ
1: What type of database is MongoDB?
a) Relational
b) NoSQL
c) Object-Oriented
d) Graph
Answer: b) NoSQL
2: In MongoDB, what format are documents stored in?
a) XML
b) CSV
c) JSON-like
d) SQL
Answer: c) JSON-like
3: Which of the following is a feature of MongoDB?
a) Fixed Schema
b) Table-based Storage
c) Sharding
d) Triggers
Answer: c) Sharding
4: What is a collection in MongoDB?
a) A table
b) A row
c) A column
d) A group of documents
Answer: d) A group of documents
5: Which command is used to create a collection in MongoDB?
a) CREATE TABLE
b) db.createCollection()
c) CREATE DATABASE
d) db.create()
Answer: b) db.createCollection()
6: What is the default port for MongoDB?
a) 3306
b) 8080
c) 27017
d) 1433
Answer: c) 27017
7: How does MongoDB ensure high availability of data?
a) Indexing
b) Replication
c) Caching
d) Partitioning
Answer: b) Replication
8: Which of the following is NOT a valid data type in MongoDB?
a) String
b) Integer
c) Date
d) ArrayList
Answer: d) ArrayList
9: What is the purpose of MongoDB's aggregation framework?
a) Data Insertion
b) Data Deletion
c) Data Analysis
d) Data Backup
Answer: c) Data Analysis
10: Which method is used to update a document in MongoDB?
a) db.updateOne()
b) db.updateDocument()
c) db.modify()
d) db.alter()
Answer: a) db.updateOne()
Frequently Asked Questions
What do I need to know about MongoDB for an interview?
In order to crack the interview, you should be familiar with MongoDB basics like CRUD operations, BSON format, and collections and documents. Also, the knowledge of data modeling, indexing, replication, and sharding concepts is vital from an interview perspective.
Why to use MongoDB over SQL Interview Questions?
MongoDB is more scalable and faster compared to SQL. The document structure of MongoDB is highly flexible and scalable as well, which makes MongoDB better than SQL. Further, MongoDB supports Agile practices which SQL does not support.
Why MongoDB is best NoSQL database?
MongoDB is viewed to be the best NoSQL database as it provides a flexible and scalable data model, rich query language, replication and higher availability, and better performance compared to most other NoSQL databases. Further, it provides various language support, and it is developer friendly with a large and active community.
Conclusion
In this article, we have discussed MongoDB Interview Questions. MongoDB is a powerful, flexible, and highly scalable NoSQL database that is widely used in modern application development. Understanding MongoDB's core concepts, features, and practical applications is essential for anyone preparing for an interview in roles related to database management, backend development, or data engineering.
The MongoDB interview questions in this blog are designed to help you grasp the fundamental aspects of MongoDB, from basic operations to advanced features.
Also read, Angular interview questions