Top MongoDB Interview Questions and Answers

Last updated on Feb 18 2022
Rajnikanth S

Table of Contents

Top MongoDB Interview Questions and Answers

What is MongoDB?

Mongo-DB is a document database which provides high performance, high availability and easy scalability.

What is “Namespace” in MongoDB?

MongoDB stores BSON (Binary Interchange and Structure Object Notation) objects in the collection. The concatenation of the collection name and database name is called a namespace.

What is sharding in MongoDB?

The procedure of storing data records across multiple machines is referred as Sharding. It is a MongoDB approach to meet the demands of data growth. It is the horizontal partition of data in a database or search engine. Each partition is referred as shard or database shard.

How can you see the connection used by Mongos?

To see the connection used by Mongos use db_adminCommand (“connPoolStats”);

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.

Explain what is the role of profiler in MongoDB?

MongoDB database profiler shows performance characteristics of each operation against the database. You can find queries using the profiler that are slower than they should be.

Explain can you move old files in the moveChunk directory?

Yes, it is possible to move old files in the moveChunk directory, during normal shard balancing operations these files are made as backups and can be deleted once the operations are done.

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

Points need to be taken in consideration are

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

What is the syntax to create a collection and to drop a collection in MongoDB?

  • Syntax to create collection in MongoDB is db.createCollection(name,options)
  • Syntax to drop collection in MongoDB is db.collection.drop()

To do safe backups what is the feature in MongoDB that you can use?

Journaling is the feature in MongoDB that you can use to do safe backups.

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.

Mention what is Objecld composed of?

Objectld is composed of

  • Timestamp
  • Client machine ID
  • Client process ID
  • 3 byte incremented counter

Mention what is the command syntax for inserting a document?

For inserting a document command syntax is database.collection.insert (document).

Mention how you can inspect the source code of a function?

To inspect a source code of a function, without any parentheses, the function must be invoked.

What is the command syntax that tells you whether you are on the master server or not? And how many master does MongoDB allow?

Command syntax Db.isMaster() will tell you whether you are on the master server or not. MongoDB allows only one master server, while couchDB allows multiple masters.

Mention the command syntax that is used to view Mongo is using the link?

The command syntax that is used to view mongo is using the link is db._adminCommand(“connPoolStats.”)

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.

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 the name of the COLUMN (or KEY:VALUE pair) which is present in the documents.

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

NoSQL database can be classified as 4 basic types:

  1. Key value store NoSQL database
  2. Document store NoSQL database
  3. Column store NoSQL database
  4. 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.

Is MongoDB better than other SQL databases? If yes then how?

MongoDB is better than other SQL databases because it allows a highly flexible and scalable document structure.

For example:

  • One data document in MongoDB can have five columns and the other one in the same collection can have ten columns.
  • MongoDB database are faster than SQL databases due to efficient indexing and storage techniques.

What type of DBMS is MongoDB?

MongoDB is a document oriented DBMS

Explain what is GridFS in MongoDB?

For storing and retrieving large files such as images, video files and audio files GridFS is used. By default, it uses two files fs.files and fs.chunks to store the file’s metadata and the chunks.

What are alternatives to MongoDB?

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

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

At the present time, the internet is loaded with big data, big users, big complexity etc. and also becoming more complex day by day. NoSQL is answer of 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 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.

Which are the different languages supported by MongoDB?

MonggoDB provides official driver support for C, C++, C#, Java, Node.js, Perl, PHP, Python, Ruby, Scala, Go and Erlang.

You can use MongoDB with any of the above languages. There are some other community supported drivers too but the above mentioned ones are officially provided by MongoDB.

What is the difference between MongoDB and MySQL?

Although MongoDB and MySQL both are free and open source databases, there is a lot of difference between them in the term of data representation, relationship, transaction, querying data, schema design and definition, performance speed, normalization and many more. To compare MySQL with MongoDB is like a comparison between Relational and Non-relational databases.

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

Does MongoDB support primary-key, foreign-key relationship?

No. By Default, MongoDB doesn’t support primary key-foreign key relationship.

Can you achieve primary key – foreign key relationships in MongoDB?

We can achieve primary key-foreign key relationship by embedding one document inside another. For example: An address document can be embedded inside customer document.

Does MongoDB need a lot of RAM?

No. There is no need a lot of RAM to run MongoDB. It can be run even on a small amount of RAM because it dynamically allocates and de-allocates RAM according to the requirement of the processes.

Explain the structure of ObjectID in MongoDB.

ObjectID is a 12-byte BSON type. These are:

  • 4 bytes value representing seconds
  • 3 byte machine identifier
  • 2 byte process id
  • 3 byte counter

Is it true that MongoDB uses BSON to represent document structure?

Yes.

What are Indexes in MongoDB?

In MondoDB, Indexes are used to execute query efficiently. 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.

By default, which index is created by MongoDB for every collection?

By default, the_id collection is created for every collection by MongoDB.

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.

Can journaling features be used to perform safe hot backups?

Yes.

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.

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.

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.

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.

Explain the covered query in MongoDB.

A query is called covered query if satisfies the following two conditions:

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

What is the importance of covered query?

Covered query makes the execution of the query faster because indexes are stored in RAM or sequentially located on disk. It makes the execution of the query faster.

Covered query makes the fields are covered in the index itself, MongoDB can match the query condition as well as return the result fields using the same index without looking inside the documents.

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

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

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

In which language MongoDB is written?

MongoDB is written and implemented in C++.

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

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

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.

Does MongoDB database have tables for storing records?

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

Do the MongoDB databases have schema?

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

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.

What is sharding in MongoDB?

In MongoDB, Sharding is a procedure of storing data records across multiple machines. It is a MongoDB approach to meet the demands of data growth. It creates horizontal partition of data in a database or search engine. Each partition is referred as shard or database shard.

What is replica set in MongoDB?

A replica can be specified as a group of mongo instances that host the same data set. In a replica set, one node is primary, and another is secondary. All data is replicated from primary to secondary nodes.

What is primary and secondary replica set in MongoDB?

In MongoDB, primary nodes are the node that can accept write. These are also known as master nodes. The replication in MongoDB is single master so, only one node can accept write operations at a time.

Secondary nodes are known as slave nodes. These are read only nodes that replicate from the primary.

By default, which replica sets are used to write data?

By default, MongoDB writes data only to the primary replica set.

What is CRUD in MongoDB?

MongoDB supports following CRUD operations:

  • Create
  • Read
  • Update
  • Delete

In which format MongoDB represents document structure?

MongoDB uses BSON to represent document structures.

What will happen when you remove a document from database in MongoDB? Does MongoDB remove it from disk?

Yes. If you remove a document from database, MongoDB will remove it from disk too.

Why are MongoDB data files large in size?

MongoDB doesn’t follow file system fragmentation and pre allocates data files to reserve space while setting up the server. That’s why MongoDB data files are large in size.

What is a storage engine in MongoDB?

A storage engine is the part of a database that is used to manage how data is stored on disk.

For example: one storage engine might offer better performance for read-heavy workloads, and another might support a higher-throughput for write operations.

Which are the storage engines used by MongoDB?

MMAPv1 and WiredTiger are two storage engine used by MongoDB.

What is the usage of profiler in MongoDB?

A database profiler is used to collect data about MongoDB write operations, cursors, database commands on a running mongod instance. You can enable profiling on a per-database or per-instance basis.

The database profiler writes all the data it collects to the system. profile collection, which is a capped collection.

While creating a schema in MongoDB, what are the points need to be taken into consideration?

While creating a schema in MongoDB, the points need to be taken care of are as follows:

  • Design our schema according to the user requirements
  • Combine objects into one document if we want to use them together; otherwise, separate them
  • Do joins while on write, and not when it is on read
  • For most frequent use cases, optimize the schema
  • Do complex aggregation in the schema

Explain what is MongoDB?

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

What are NoSQL databases? What are the different types of NoSQL databases?

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

it possible to configure the cache size for MMAPv1 in MongoDB?

No. it is not possible to configure the cache size for MMAPv1 because MMAPv1 does not allow configuring the cache size.

How to configure the cache size for WiredTiger in MongoDB?

For the WiredTiger storage engine, you can specify the maximum size of the cache that WiredTiger will use for all data. This can be done using storage.wiredTiger.engineConfig.cacheSizeGB option.

How does MongoDB provide concurrency?

MongoDB uses reader-writer locks for concurrency. Reader-writer locks allow concurrent readers shared access to a resource, such as a database or collection, but give exclusive access to a single write operation.

What is the difference between MongoDB and Redis database?

Difference between MongoDB and Redis:

  • Redis is faster than MongoDB.
  • Redis has a key-value storage whereas MongoDB has a document type storage.
  • Redis is hard to code but MongoDB is easy.

What is the difference between MongoDB and CouchDB?

Difference between MongoDB and CouchDB:

  • MongoDB is faster than CouchDB while CouchDB is safer than MongoDB.
  • Triggers are not available in MongoDB while triggers are available in CouchDB.
  • MongoDB serializes JSON data to BSON while CouchDB doesn’t store data in JSON format.

What is the difference between MongoDB and Cassandra?

Difference between MongoDB and Cassandra:

  • MongoDB is cross-platform document-oriented database system while Cassandra is high performance distributed database system.
  • MongoDB is written in C++ while Cassandra is written in Java.
  • MongoDB is easy to administer in the case of failure while Cassandra provides high availability with no single point of failure.

Is there any need to create database command in MongoDB?

You don’t need to create a database manually in MongoDB because it creates automatically when you save the value into the defined collection at first time.

Compare MongoDB with Cassandra.

ss9

What makes MongoDB the best?

MongoDB is considered to be the best NoSQL database because of its following features:

  • Document-oriented (DO)
  • High performance (HP)
  • High availability (HA)
  • Easy scalability
  • Rich query language

How to do transactions/locking in MongoDB?

MongoDB does not use conventional locking with reduction as it is planned to be light, high-speed, and knowable in its presentation. It can be considered as parallel to the MySQL MyISAM auto entrust sculpt. With the simplest business sustain, performance is enhanced, particularly in a structure with numerous servers.

When do we use a namespace in MongoDB?

During the sequencing of the names of the database and the collection, the namespace is used.

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

Yes, it is deleted. Hence, it is better to eliminate the attribute and then save the object again.

How can we move an old file into the moveChunk directory?

Once the functions are done, the old files are converted to backup files and moved to the moveChunk directory at the time of balancing the slices.

Explain the situation when an index does not fit into RAM.

When an index is too huge to fit into RAM, then MongoDB reads the index, which is faster than reading RAM because the indexes easily fit into RAM if the server has got RAM for indexes, along with the remaining set.

How does MongoDB provide consistency?

MongoDB uses the reader–writer locks, allowing simultaneous readers to access any supply like a database or a collection but always offering private access to single writes.

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

MongoDB scrap stands on a collection. So, an album of all substances is kept in a lump or mass. Only when there is an additional time slot, there will be more than a few slice data achievement choices, but when there is more than one lump, data gets extended to a lot of slices and it can be extended to 64 MB.

Compare MongoDB with Couchbase and Couchbase DB.

Although MongoDB, Couchbase and Couchbase DB are common in many ways, still they are different in the case of necessities for the execution of the model, crossing points, storage, duplications, etc.

Why is MongoDB not chosen for a 32-bit system?

Mongo DB is not considered as a 32-bit system because for running the 32-bit MongoDB, with the server, information and indexes require 2 GB. That is why it is not used in 32-bit devices.

How does Journaling work in MongoDB?

Write operations are saved in memory while journaling is going on. The on-disk journal files are really dependable for the reason that the journal writes are habitual. Inside dbPath, a journal subdirectory is designed by MongoDB.

How can you isolate the cursors from intervening with the write operations?

The snapshot() method is used to isolate the cursors from intervening with writes. This method negotiates the index and makes sure that each query comes to any article only once.

Define MongoDB.

It is a document-oriented database that is used for high availability, easy scalability, and high performance. It supports the dynamic schema design.

Explain the replica set.

It is a group of mongo instances that maintains the same dataset. Replica sets provide redundancy and high availability and are the basis for all production deployments.

What are the key features of MongoDB?

There are three main features of MongoDB:

  • Automatic scaling
  • High performance
  • High availability

What is CRUD?

MongoDB provides CRUD operations:

  • Create
  • Read
  • Update
  • Delete

What is Sharding?

In MongoDB, sharding means to store data on multiple machines.

What is Aggregation in MongoDB?

In MongoDB, aggregations are operations that process data records and return computed results.

Define Namespace in MongoDB.

It is the concatenation of the collection name and the name of the database.

Which syntax is used to create a Collection in MongoDB?

We can create a collection in MongoDB using the following syntax:

db.createCollection(name,options)

Which syntax is used to drop a Collection in MongoDB?

We can use the following syntax to drop a collection in MongoDB:

db.collection.drop()

Explain Replication.

Replication is the process of synchronizing data across multiple servers.

What is the use of an Index in MongoDB?

In MongoDB, indexes provide high-performance read operations for frequently used queries.

Which command is used for inserting a document in MongoDB?

The following command is used for inserting a document in MongoDB:

database.collection.insert (document)

What is the use of GridFS in MongoDB?

GridFS is used for storing and retrieving large files, such as audio, image, and video files.

What is the use of Journaling in MongoDB?

Journaling is used for safe backups in MongoDB.

Which command is used to see a connection?

We can use the following command to see the connection:

db_adminCommand (“connPoolStats”)

Define the primary Replica set.

The primary replica set accepts all write operations from clients.

Define the secondary Replica sets.

The secondaries replicate the primary replica set’s oplog and apply the operations to their datasets such that the secondaries’ datasets reflect the primary’s dataset.

What is the use of Profiler?

Profiler is used to show the performance characteristics of every operation against the database.

What type of data is stored by MongoDB?

MongoDB stores data in the form of documents, which are JSON-like field and value pairs.

What is the purpose of Replication?

Replication provides redundancy, and it increases data availability.

What are Embedded documents?

Embedded documents capture relationships between data by storing related data in a single document structure.

Define the application-level Encryption.

The application-level encryption provides encryption on a per-field or per-document basis within the application layer.

What is Storage Encryption?

Storage encryption encrypts all MongoDB data on storage or on the operating system to ensure that only authorized processes can access the protected data.

Which method is used to remove a document from a collection?

The remove() method is used to remove a document from a collection.

Define MongoDB Projection.

Projection is used to select only the necessary data. It does not select the whole data of a document.

What is the use of the limit() method?

The limit() method is used to limit the records in the database.

What is the syntax of the limit() method?

The syntax of the limit() method is as follows:

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

What is the syntax of the sort() method?

In MongoDB, the following syntax is used for sorting documents:

>db.COLLECTION_NAME.find().sort({KEY:1})

Which command is used to create a backup of the database?

The mongodump command is used to create a backup of the database.

What is a Collection in MongoDB?

In MongoDB, a collection is a group of MongoDB documents.

What is the use of the db command?

The db command gives the name of the currently selected database.

Which method is used to update documents into a collection?

The update() and save() methods are used to update documents into a collection.

What is the syntax of the skip() method?

The syntax of the skip() methopd is as follows:

>db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)

Which command is used to restore the backup?

The mongorestore command is used to restore the backup.

What is the use of the dot notation in MongoDB?

MongoDB uses the dot notation to access the elements of an array and the fields of an embedded document.

Define Auditing.

Auditing provides administrators with the ability to verify that the implemented security policies are controlling the activity in the system.

Define the Aggregation pipeline.

The aggregation pipeline is a framework for performing aggregation tasks. The pipeline is used to transform documents into aggregated results.

Define MapReduce.

MapReduce is a generic multi-phase data aggregation modality that is used for processing quantities of data.

What is Splitting in MongoDB?

Splitting is a background process that is used to keep chunks from growing too large.

Which language is used to write for MongoDB?

C++ is used for writing and implementing MongoDB.

In which format does MongoDB store data?

MongoDB uses collections to store data rather than tables.

What is the use of the save() method?

The save() method is used to replace the existing document with a new document.

What is MongoDB?

MongoDB (from humongous) is a cross-platform document-oriented database. Classified as a NoSQL database, MongoDB eschews the traditional table-based relational database structure in favor of JSON-like documents with dynamic schemas (MongoDB calls the format ‘BSON’), making the integration of data in certain types of applications easier and faster. Released under a combination of the GNU Affero General Public License and the Apache License, MongoDB is open-source.

MongoDB was first developed by the software company 10gen (now, MongoDB Inc.) in October 2007 as a component of a planned platform as a service product. Then, the company shifted to an open-source development model in 2009, with 10gen offering commercial support and other services. Since then, MongoDB has been adopted as backend software by a number of major websites and services, including Craigslist, eBay, Foursquare, SourceForge, Viacom, and the New York Times, among others. Currently, MongoDB is the most popular NoSQL database system.

What is the use of MongoDB?

MongoDB is a relational database management system (RDBMS) replacement for web applications. So, when we have something close to RDBMS, MongoDB could be of good use.

It gives us the additional partition tolerance, which RDMBS doesn’t offer, but it has problems with availability. Nonetheless, if we want more scalability, MongoDB would be the right choice for us. It’s suitable for real-time analytics and high-speed logging, and it’s highly scalable as well. Craigslist uses MongoDB for archived posts.

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

Presently, the Internet is loaded with big data, big users, and so on that are 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’, and it is a type of database that can handle and sort all types of unstructured, messy, and complicated data. It is just a new way to think about databases.

Yes, MongoDB is a NoSQL database.

What type of a DBMS is MongoDB?

MongoDB is a document-oriented DBMS.

What is the difference between MongoDB and MySQL?

Although both MongoDB and MySQL are free and open-source databases, there is a lot of difference between them in terms of data representation, relationships, transaction, querying data, schema design and definition, performance speed, normalization, and many more. To compare MySQL with MongoDB is like a comparison between relational and non-relational databases.

What is the use of MongoDB?

  • MongoDB is typically used as the primary data store for operational applications with real-time requirements (i.e., low latency, high availability, etc.). MongoDB is generally a good fit for 60–80 percent of the applications we build today. MongoDB is easy to operate and scale in the ways that are hard if not impossible with relational databases.
  • MongoDB excels in many use cases where the relational databases aren’t a good fit, like applications with unstructured, semi-structured, and polymorphic data, as well as those with large scalability requirements or multi-datacenter deployments.
  • 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 mostly may not be a good fit for MongoDB. Also, MongoDB is not a drop-in replacement for legacy applications built around the relational data model and SQL.
  • Some common use cases of MongoDB include mobile apps, product catalogs, real-time personalization, content management, and applications delivering a single view across multiple systems.

What kind of a database is MongoDB?

MongoDB is a document-oriented DBMS. We can think of it as MySQL but with JSON-like objects comprising the data model, rather than RDBMS tables. Significantly, MongoDB supports neither joins nor transactions. However, it features secondary indexes, an expressive query language, atomic writes on a per-document level, and fully-consistent reads. Operationally, MongoDB offers the master–slave replication with automated failover and built-in horizontal scaling via automated range-based partitioning.

Which language is MongoDB written in?

MongoDB is implemented in C++. However, drivers and client libraries are typically written in their own respective languages. Although, some drivers use C extensions for better performance.

What are the limitations of the 32-bit versions of MongoDB?

MongoDB uses memory-mapped files. When running a 32-bit build of MongoDB, the total storage size for the server, including data and indexes, is 2 GB. For this reason, we do not deploy MongoDB to production on 32-bit machines.

If we’re running a 64-bit build of MongoDB, there’s virtually no limit to the storage size. For production deployments, 64-bit builds and operating systems are strongly recommended.

What Is Replication In MongoDB?

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.

What are Indexes in MongoDB?

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.

1Can 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 so you can query for individual items:

> 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" ] }

Does MongoDB support ACID transaction management and locking functionalities?

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.

Explain the structure of ObjectID in MongoDB

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.

Find objects between two dates MongoDB

 

db.CollectionName.find({"whenCreated": {

'$gte': ISODate("2018-03-06T13:10:40.294Z"),

'$lt': ISODate("2018-05-06T13:10:40.294Z")

}});


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 (aka subdocuments). Foe e.g. an address document can be embedded inside customer document.

How do I perform the SQL JOIN equivalent in MongoDB?

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:

{

$lookup:

{

from: <collection to join>,

localField: <field from the input documents>,

foreignField: <field from the documents of the "from" collection>,

as: <output array field>

}

}

How is data stored in MongoDB?

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.

How to query MongoDB with %like%?

Problem

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

select *

from users

where name like ‘%m%’

How to do the same in MongoDB?

Answer

db.users.find({name: /a/}) //like ‘%a%’

db.users.find({name: /^pa/}) //like ‘pa%’

db.users.find({name: /ro$/}) //like ‘%ro’

Or using Mongoose:

db.users.find({‘name’: {‘$regex’: ‘sometext’}})

Should I normalize my data before storing it in MongoDB?

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

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.

What is a covered query in MongoDB?

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

What is oplog?

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.

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.

Why MongoDB is not preferred over a 32-bit system?

When running a 32-bit build of MongoDB, the total storage size for the server, including data and indexes, is 2 gigabytes. For this reason, do not deploy MongoDB to production on 32-bit machines.

If you’re running a 64-bit build of MongoDB, there’s virtually no limit to storage size.

Which method is used to create an index?

The createIndex() method is used to create an index.

What is Replica set oplog?

The oplog records all operations that modify the data in the replica set.

What is Vertical Scaling?

Vertical scaling adds more CPU and storage resources to increase capacity.

Define Horizontal Scaling.

Horizontal scaling divides the dataset and distributes data over multiple servers, or shards.

What are the components of the Sharded cluster?

The sharded cluster has the following components:

  • Shards
  • Query routers
  • Config servers

Which command is used to create a database?

To create a database, we can use the Database_Name command.

Which command is used to drop a database?

The db.dropDatabse() command is used to drop a database.

What is the use of the pretty() method?

The pretty() method is used to show the results in a formatted way.

 

So, this brings us to the end of the MongoDB Interview Questions blog.This Tecklearn ‘Top MongoDB Interview Questions and Answers’ helps you with commonly asked questions if you are looking out for a job in MongoDB or Big Data Domain. If you wish to learn MongoDB and build a career in Big Data domain, then check out our interactive, MongoDB Training, that comes with 24*7 support to guide you throughout your learning period.

https://www.tecklearn.com/course/mongodb-training/

MongoDB Training

About the Course

Tecklearn’s MongoDB Training helps you to master the NoSQL database. The course makes you job-ready by letting you comprehend schema design, data modelling, replication, and query with MongoDB through real-time examples. Along with this, you’ll also gain hands-on expertise in installing, configuring, and maintaining the MongoDB environment, including monitoring and operational strategies from this online MongoDB training. Upon completion of this online training, you will hold a solid understanding and hands-on experience with MongoDB.

Why Should you take MongoDB Training?

  • MongoDB – a $36 billion to a $40 billion market growing at 8% to 9% annually – Forbes.com
  • Average salary of a Mongo DB certified professional is $134k – Indeed.com
  • MongoDB has more than 900 customers, including 27 Fortune 100 companies like Cisco, eBay, eHarmony, MetLife & Salesforce.com

What you will Learn in this Course?

Introduction to MongoDB and Importance of NoSQL

  • Understanding the basic concepts of RDBMS
  • What is NoSQL Database and its significance?
  • Challenges of RDBMS and How NoSQL suits Big Data needs
  • Types of NoSQL Database and NoSQL vs. SQL Comparison
  • CAP Theorem and Implementing NoSQL
  • Introduction to MongoDB and its advantages
  • Design Goals for MongoDB Server and Database, MongoDB tools
  • Collection, Documents and Key Value Pair
  • Introduction to JSON and BSON documents
  • MongoDB installation

MongoDB Installation

  • MongoDB Installation
  • Basic MongoDB commands and operations,
  • Mongo Chef (MongoGUI) Installation

Schema Design and Data Modelling

  • Why Data Modelling?
  • Data Modelling Approach
  • Data Modelling Concepts
  • Difference between MongoDB and RDBMS modelling
  • Challenges for Data Modelling
  • Model Relationships between Documents
  • Data Model Examples and Patterns
  • Model Tree Structures

CRUD Operations

  • MongoDB Architecture
  • CRUD Introduction and MongoDB CRUD Concepts
  • MongoDB CRUD Concerns (Read and Write Operations)
  • Cursor Query Optimizations and Query Behavior in MongoDB
  • Distributed Read and Write Queries
  • MongoDB Datatypes

Indexing and Aggregation Framework

  • Concepts of Data aggregation and types and data indexing concepts
  • Introduction to Aggregation
  • Approach to Aggregation
  • Types of Aggregation: Pipeline, MapReduce and Single Purpose
  • Performance Tuning

MongoDB Administration

  • Administration concepts in MongoDB
  • MongoDB Administration activities: Health check, recovery, backup, database sharing and profiling, performance tuning etc.
  • Backup and Recovery Methods for MongoDB
  • Export and Import of Data from MongoDB
  • Run time configuration of MongoDB

MongoDB Security

  • Security Introduction
  • MongoDB security Concepts and security approach
  • MongoDB integration with Java and Robomongo

Got a question for us? Please mention it in the comments section and we will get back to you.

 

0 responses on "Top MongoDB Interview Questions and Answers"

Leave a Message

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