YouTube Icon

Interview Questions.

MongoDB Interview Questions and Answers - Sep 08, 2021

fluid

MongoDB Interview Questions and Answers

MongoDB is a report-based database created in 2007 by means of 10gen software program. It works at the concept of collections and documents. A MongoDB server can comprise more than one databases and offers high overall performance along with redundancy and easy scalability. Collection in MongoDB may be taken into consideration as a collection of files which could have one of a kind forms of fields. The file is a set of key-cost pairs having a dynamic schema i.E. Commonplace fields may also maintain one-of-a-kind styles of facts and all documents in the equal series want now not have the same structure. If you are new to MongoDB however have worked with RDBMS like SQL before, this small table will assist you correlate the terminologies:

RDBMS MongoDB
Table Collection
Row Document
Column Field
Table join Embedded documents

A few prominent functions of MongoDB are –

Cross-platform

Written in C++.

Secure and scalable

Schema-less database

Document-orientated

Supports high-availability and redundancy

Top MongoDB Interview Questions and Answers

Here you could begin your 

Question: What is Mongo shell?

Answer: Mongo shell is a JavaScript interface to MongoDB that can be used to question and replace statistics. It is interactive and can also be used to do administrative operations.

Question: How does MongoDB store information?

Answer: Being file-based totally, MongoDB shops files in BSON or Binary JavaScript Object notation that is the binary encoded format of JSON.

Question: What type of NoSQL database is MongoDB?

Answer: It is a report database that consists of files having key-value pairs, key-array pairs, and nested documents.

Question: List out the essential features of MongoDB.

Answer: Important functions of MongoDB are –

It is a schema-much less database

No complex joins

Faster access to records due to the presence of the working set (internal reminiscence)

Features like aggregation, sharding, and replication make it clean to apply.

Cross-platform and document-based

Automatic fail-over and excessive-availability

Question: What are the information fashions in MongoDB?

Answer: Data modeling relies upon at the structure of files. In MongoDB,

Related information can be embedded in a unmarried record shape (Embedded statistics version)

Through references from one record to any other, the connection among statistics is saved (Normalized information model)

Question: MongoDB is known as a schema-much less database. Is it proper? How to create the schema in MongoDB?

Answer: It would be more appropriate to mention that MongoDB has dynamically typed schema as it relies on JSON which is a schema-loose statistics structure. To create a schema, create and insert a document. Once a document is inserted, a corresponding collection will be created within the database.

Question: What is a namespace in MongoDB?

Answer: A namespace is the concatenation of the database call and series call. Example – college students.The concern, wherein students are the database and difficulty, is the collection.

Question: How do you carry out CRUD operations in MongoDB?

Answer:

C – Create – db.Series.Insert();

R – Read – db.Series.Discover();

U – Update – db.Series.Update();

D – Delete – db.Series.Eliminate(“fieldname” : ”cost”);

Question: What are the differences among MySQL and MongoDB?

Answer:

MySQL MongoDB
Written in C and C++ Written in C++ and JavaScript
Follows RDBMS database structure Document-based structure
Scaling is done vertically Horizontal scaling
Rigidly defined data-structure, the schema is strict and should be defined in the beginning. Dynamic and flexible schema creation of complex documents.
Uses a Structured Query language The unstructured query language is used.
Uses Join to link data from two or more tables There is no equivalent for JOIN.
Performance is slow with a large database with unstructured data. Handles large unstructured data efficiently thereby giving a good performance.
Less suitable for a cloud-based environment The best option for services that are cloud-based.

Question: How are constraints controlled in MongoDB?

Answer: You can add file validator on the collections starting MongoDB three.2. Unique indexes also can be created using db.Collection.CreateIndex(“key” : 1 , );

Question: What is ObjectId? How is it dependent?

Answer: ObjectId is a category that is the default primary key for the record in MongoDB. It is determined within the _id subject of the inserted file. It is a 12-byte BSON kind generated the usage of a default set of rules. The structure is –

A 4-byte value that represents seconds seeing that Unix epoch

3-byte system identity

2-byte procedure identification

3-bytes counter that starts with a random range

Question: What is BSON?

Answer: BSON or binary JSON is the binary encoded layout of JSON. It extends JSON and gives more statistics sorts and fields.

Question: How does MongoDB do indexing?

Answer: Indexing is accomplished the use of ensureIndex() technique. Syntax –

db.COLLECTION_NAME.ensureIndex()

Question: Name the default index created for a new series.

Answer: Default index created for the new series is _id

Question: What is sharding in MongoDB?

Answer: MongoDB meets the records boom the use of Sharding, this means that sorting information data across diverse machines. Each shard is a replica set.

Question: What is a protected query and why is it crucial?

Answer: In a blanketed query, all of the fields used inside the query have the index created. The effects lower back ought to also be a part of the index. Due to this, MongoDB fetches the results with out certainly looking internal files, therefore saving time and increasing efficiency.

Question: What is replication and what are the number one and secondary duplicate sets?

Answer: Replication means synchronizing the information throughout more than one servers. It increases statistics availability. If a single server is misplaced, records is still intact within the other servers.

Primary reproduction set – MongoDB writes statistics simplest to number one or master replica set.

Secondary reproduction set – secondary or slave nodes can accept simplest reads. They mirror from the primary.

Question: Name the 2 storage engines the use of MongoDB?

Answer: MMAPv1 and WiredTiger are the 2 garage engines used by MongoDB.

Question: How to create and drop a set in MongoDB?

Answer:

Create series – db.CreateCollection();

Drop collection – db.Collection.Drop();

Question: What is journaling and how does it paintings?

Answer: MongoDB guarantees records integrity via the usage of an on-disk magazine this is created for every write. In case of a server crash, the journal can be used to track the writes that had been not written to the disk or records files.

Journal Mechanics in MongoDB

Question: How can you keep snap shots, movies and different massive files in MongoDB?

Answer: Large documents are stored in MongoDB the use of the GridFS specification.

Question: Compare CouchDB and MongoDB.

Answer:

CouchDB MongoDB
The data model is document oriented i.e. JSON Uses BSON which is an extension of JSON
Uses HTTP/REST for querying Uses standard protocol over TCP/IP
Database has documents The database contains collections and collections contain documents
Written in Erlang Written in C++
Uses range queries and map/reduce Uses object-based query language and map/reduce

Question: In what approaches is MongoDB better than MySQL? Explain.

Answer: MongoDB has a bendy statistics version in which the schema can be multiplied based totally on commercial enterprise needs. Also, MongoDB is quicker and may cope with extra records types to control actual-time packages higher.

Question: What are the one of a kind index kinds in MongoDB?

Answer:

Default – that is the _id that MongoDB creates

Single field – for indexing and sorting on a unmarried field

Compound – for multiple fields

Multi-key – for indexing array information

Hashed – indexes the hashes of a field value

Geospatial – to question geospatial(place) data

Question: What is an ACID transaction? Does MongoDB assist it?

Answer: ACID stands for Atomicity, Consistency, Isolation, and Durability. The transaction manager guarantees these attributes are taken care of. Yes, MongoDB version four.0 supports ACID.

Question: Explain the function of profiler in MongoDB.

Answer: A profiler is an in-built tool that reveals out the gradual and resource-intensive queries and presents query-level insights. You as a dba can examine the queries. Profiler stores all the facts in system.Profile collection.

Question: How does MongoDB cope with transactions and locks?

Answer: MongoDB makes use of multi-granularity locking in which operations can be locked at the global, database or series stage. It is up to the storage engines to implement the level of concurrency. For example, in WiredTiger, it's miles at file-level. For reads, there may be a shared locking mode, at the same time as for write there is an exclusive locking mode.

Question: What is the command to listing all the indexes in a set?

Answer: The command is db.Series.GetIndexes();

Question: How does MongoDB do text search?

Answer: Text search may be finished the use of textual content index. Example –

db.collection_name.ensureIndex();

Question: What is the default c programming language to put in writing updates to the disk?

Answer: The default c language is 60 seconds.

Question: Explain aggregation in MongoDB.

Answer: Aggregation corporations values from extraordinary documents and plays operations at the data to return a unmarried result. There are three methods in which MongoDB performs aggregation –

Aggregation pipeline

Map-reduce feature

Single purpose aggregation strategies

Question: State the distinction among locate() and limit() approach.

Answer: discover() – shows most effective selected facts in place of all of the facts of a file. For instance, in case your file has four fields however you need to reveal best one, set the required area as 1 and others as 0.

db.COLLECTION_NAME.find({},);

restriction() – restrict feature limits the quantity of facts fetched. For example, if you have 7 files but want to display simplest the first four files in a group, use limit. Syntax –

db.COLLECTION_NAME.find().limit(NUMBER);

Question: How does concurrency have an effect on number one duplicate set?

Answer: When the collection adjustments are written to number one, MongoDB writes the identical to a unique collection within the nearby database, called the number one’s oplog. Hence, both the collection’s database and neighborhood database are locked.

Question: Give an instance of insert, delete and update assertion in MongoDB.

Insert
db.books.insert({
 _id: ObjectId(7df74fd8902c),
 title: 'All about MongoDB', 
 description: 'Everything you need to know about MongoDB',
 by: 'Author1',
 url: 'http://www.blogsuthor1.com'
})

 

Delete Remove a particular document -
 db.books.remove({'title':'All about MongoDB'})
Remove all the documents –

db.books.remove();

 

Update To update values of an existing document –
db.books.update({'title':'All 
about MongoDB'},{$set:{'title':'MongoDB for dummies'}})
To replace an existing document with a new
one based on ObjectId –

db.books.save(
 {
 "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB for dummies",
 "by":"Author2"
 }
)

 

Question: What have capped collections?

Answer: Capped collections are fixed-size collection and insert and retrieve data primarily based on insertion order. If a group’s area is complete, the oldest records might be overwritten through the new files inside the series.

Question: Explain the cause of map-reduce command in Mongo-DB.

Answer: Map-lessen is a way of acting aggregation.

Map function emits key-value pair designated.

Reduce characteristic combines the key price pair and returns the aggregation result.

Syntax –

db.collection.mapReduce( 
 function() {emit(key,value);}, 
 function(key, values) {return aggregatedResult}, { out: collection } 
</pre.
 ) 

Question: List some of the records kinds supported through MongoDB.

Answer: Some statistics kinds are Numbers, String, Array, Binary facts, Boolean, Date, Regular expressions, ObjectId, etc…

Question: How can applications get entry to real-time data changes in MongoDB?

Answer: Applications can get entry to real-time records modifications the use of Change streams which acts as a subscriber to all of the series operations like insert, delete and replace.

Question: What are the instructions to create a backup of the records and repair the information?

Answer: Use the command mongodump to create a backup.

Use the command mongorestore [backup_path] to restore the facts.

Question: Explain the distinction between MongoDB and Cassandra?

Answer:

Parameters MongoDB Cassandra
Structure of Data Best database to use when there is no clear structure of the data, i.e. data is a mix of structured and unstructured. Works for both unstructured and structured data, especially when the database is expected to grow dynamically.
Data Model Has a rich and expressive data model, which is data-oriented. Any data structure can be easily represented. Traditional model with rows and columns as in a table. Each column is of a specific type, which makes the structure organized.
Number of Master Nodes There is only one master node in the cluster, which controls many slave nodes. There are many master nodes in the cluster.
Secondary Indexes It is easy to index any property because the secondary indexes are first-class constructs. Secondary indexes are limited to single columns and have less flexibility.
Scalability For data to be written in slave nodes, it has to pass through the single master node, so scalability is less. Since there are many master nodes, data is present in multiple nodes. Hence, the scalability is high.
Aggregation Framework Built-in aggregation framework. No built-in aggregation framework.

Question: Can MongoDB Support overseas key constraints?

Answer: No, MongoDB doesn’t assist overseas key constraints. Because of the file shape, MongoDB gives bendy methods to outline relationships.

Question: What are indexes in MongoDB?

Answer: In MongoDB, indexes help to execute the queries effectively. Indexes are unique statistics structures that store a part of the gathering in a form smooth to traverse. By default, MongoDB creates a everlasting specific index on the _id field while a collection is created. It prevents replica files inside the database.

Question: What is a Storage Engine in MongoDB?

Answer: It is a component of the database that manages how records is stored within the reminiscence and disk both. MongoDB presents help for more than one storage engines that facilitates in better overall performance for unique workloads. The default storage engine is WiredTiger (MongoDB3.2), that is properly-ideal for maximum workloads.

Question: Explain the working mechanism Journaling work in MongoDB?

Answer: Journaling is used to get better statistics after the last checkpoint when MongoDB exits suddenly. The garage engine (WiredTiger) creates a journal file for each of the clients that initiated the write operation. If there is an replace, a unmarried journal record facts the replace operation as well as index changes. Journal records are saved the use of in-memory buffering. Journal files are stored below the ‘magazine’ directory created with the aid of MongoDB. Read more information.

Question: Is it possible to configure the cache size for MMAPv1?

Answer: It is not possible to configure the cache size for MMAPv1. MongoDB uses all of the free memory robotically thru reminiscence-mapped files.

Question: Explain GridFS in MongoDB?

Answer: GridFS stores and retrieves huge files like pix, audio and video documents and so forth. Although the limit to shop a document is 16MB, GridFS can store documents with length extra than that. GridFS breaks the record into chunks and stores every chew as a distinct record of most size 255k. It uses  collections, fs.Chunks and fs.Files for storing chunks and metadata, respectively.

Question: Is it feasible to run a couple of Javascript operations in a MongoDB example?

Answer: Yes, we are able to run more than one JS operations in a MongoDB instance. Through the mongo shell example, we will specify the name of the JavaScript report to be run at the server. The file can include any number of JS operations.

Question: MongoDB is the excellent NoSQL Database? How and why?

Answer: MongoDB is the maximum appropriate NoSQL database for records analytics as well as web application improvement. It can assist developers and records scientists get insights from the stored statistics, not like Hadoop, which calls for specialists to investigate facts.

MongoDB lets in for efficient records manipulation and management competencies. The assist for a couple of JavaScript operations and Javascript-based MEAN stack upload to the popularity of MongoDB. Sharding for horizontal scaling and aggregation framework to build pipelines made MongoDB speedy and efficient and consequently the first-class database to apply.

Question: Explain the manner of Transaction/Locking in MongoDB?

Answer: MongoDB supports multi-granular locking with examine and write locks.

There are 3 types of locking mechanisms feasible in MongoDB:

Global stage

Database degree

Collection level

The implementation additionally depends on the man or woman garage engine. There are 4 modes of locking:

R(shared lock),

W(exclusive lock),

r(cause shared lock),

w(motive unique lock).

To examine greater, go to the reliable documentation web page.

Question: Explain how MongoDB isn't like RDBMS?

Answer:

Parameters RDBMS MongoDB
Definition It is a relational database management system. It is a non-relational DB.
Working Works on relationships between tables that use rows and columns. Document oriented system using documents and fields.
Hierarchical Data Storage Difficult to store hierarchical data. In-built provision for storing hierarchical data
Scalability Vertically scalable. Vertically and horizontally scalable.
Performance Performance increases with an increase in RAM capacity. Performance increases with increase in processors.
Schema Schema has to be pre-decided and designed, changes to the schema are difficult. Dynamic creation and management of schema making the design flexible.
Support for Joins Supports complex joins. No support for joins.
Query Language Uses SQL for querying the database. BSON is used for database querying.
Support for Javascript No support for JavaScript-based clients to query the database. Provision for Javascript-based clients to query the database.

Question: Explain the process of starting the MongoDB server/ instance?

Answer: To begin a MongoDB example, follow the steps as under:

First, open the command spark off and run mongod.Exe.

Alternatively, you can move to the course where MongoDB is set up, as an example, “C: MongoDB”

Navigate to the bin folder, find the mongod.Exe and double click on the same to execute it.

You also can navigate to the desired folder, as an instance, “C: MongoDB/bin” and sort mongo to attach MongoDB thru the shell.

Question: How do you confer with the modern database in a announcement? (by using db)

Answer: Current database is referred to as ‘db’. Example – db.Collection.Find();

If you're looking for more no-SQL-database-based totally interview questions, here's a terrific course that will help you put together nicely for MongoDB interviews: MongoDB Interviews Questions and Answers.

Usually, you would be asked many everyday programming questions from the statistics shape and basic programming languages. Here is a terrific direction: Cracking the IT Architect Interview.




CFG