MongoDB Interview Questions and Answers

What is MongoDB?

MongoDB is a document-based database which is highly scalable, and offers better performance.

SQL vs NoSQL

SQL databases are relational, NoSQL are non-relational.
SQL databases use structured query language and have a predefined schema. NoSQL databases have dynamic schemas for unstructured data.
SQL databases are vertically scalable, NoSQL databases are horizontally scalable.
SQL databases are table based, while NoSQL databases are document, key-value, graph or wide-column stores.
SQL databases are better for multi-row transactions, NoSQL are better for unstructured data like documents or JSON.

What is BSON in MongoDB?

MongoDB stores data as BSON documents. BSON is a binary representation of JSON documents, though it contains more data types than JSON. Some of the supported data types are: Double, String, Object, Array, Binary Data, RegEx, Boolean, Date, Null, JavaScript, Timestamp. ObjectId.
Some of the features of BSON:
BSON is lightweight and is an important feature for any data representation format, especially when used over the network.
BSON is designed to be traversed easily.
It is efficient. Encoding data to BSON and decoding from BSON can be performed very quickly in most languages

When do we use a namespace in MongoDB?

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

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.

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)

 

What is the use of Journaling in MongoDB?

Journaling is used for safe backups in MongoDB.

Which programming languages can be used with MongoDB?

MongoDB accepts all the programming languages. The following is a list of a few languages:
C
C++
C#
Java
Node.js
Perl
PHP
Python
Ruby
Scala
Go
Erlang.

What is an embedded document?

Embedded documents specify the relationship between data that is written inside the body. The documents are received while the related data body is small.

Define a replica set?

The group of instances which host similar data set is known as a replica set. Two nodes are present in a replica set, one is secondary and the other is primary, where data is replicated from primary and sent to the secondary node.

What is the role of profiler in MongoDB?

The role of a MongoDB profiler is to show the performance and analyze the characteristics of every operation of the database. By using the profiler, you will find all the queries which are slower than usual.

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

The NoSQL database is classified into four basic types. The following is the classification of NoSQL database:

Column store 
Document store 
Key-value store 
Graph base 
The following are the few examples of NoSQL database

MongoDB
Cassandra
CouchDB
HBASE

What are the key features of MongoDB?

The following are the core features of MongoDB:

High performance
Automatic scaling
Rich query language
High availability

What is the advantage of MongoDB?

The following are a few advantages of MongoDB database:

SchemalesS
Easy to scale-out
No complex joins
Structure of a single object is clear

Do a MongoDB database support foreign-key and primary-key relationship?

No, by default, MongoDB doesn't support foreign key or a primary key relationship.

Define the storage engine in MongoDB with an example.

A storage engine is a part of the database and is used to manage data storage on the disk. For instance, if there are two storage engines, one engine might offer support for read-heavy workloads, and another storage engine might offer higher-throughput for writing operations. 

How to move an old file into the moveChunk directory?

All the old files are converted into backup files and are moved into moveChunk directory at a time once the function is done.

How does MongoDB offer consistency?

To provide consistency, MongoDB makes use of reader-writer locks to allow readers to simultaneously access any collection like a database but it always offers private access to single writers.

What query is used in MongoDB to create and drop a collection?

The following are the queries used to create and drop a collection:

// create a collection
db.createCollection(name,options)
 // drop a collection
db.collection.drop()

 

In MongoDB what is Objecld composed of?

The Objectld is composed of the following parameters:

Client machine ID
Timestamp
3 byte incremented counter
Client process ID

What does sharding mean in MongoDB?

Sharding is a process of storing data records among one or more machines applied by MongoDB to meet the demands of data growth. It forms a horizontal partition in the database and each partition is known as database shard or a shard.

What is CRUD?

Mongodb offers best CRUD operations to perform better database operations. The following are the operations:

Create
Read
Update
Delete

In MongoDB, which command can be used to provide all information of a query plan?

The explain() command is used to provide information of all the query plans. The possible models are as follows:

'queryPlanner',
'executionStats'
'allPlansExecution'.
More information about MongoDB find queries

Define GridFS and its functionality in MongoDB?

In MongoDB, GridFS is a special specification for storing and retrieving files which exceed the BSON-document size limit (16MB). The major functionality of this grid is to divide a file into smaller segments, and stores each of those segments as a separate document instead of storing then into a single document.

what command is used to create a MongoDB collection?

db.createCollection (name, options) is a command used to create collection MongoDB.

What feature in MongoDB is used to do safe backups?

To save backups of the old files “Journaling” feature is used in MongoDB databases.

Mongo complex sorting?

I know how to sort queries in MongoDB by multiple fields, e.g.,

db.coll.find().sort({a:1,b:-1})

 

Create Administrator User in MongoDB

Creating a user administrator in MongoDB is done by using the createUser method. The following example shows how this can be done.

db.createUser(
{	user: "Guru99",
	pwd: "password",

	roles:[{role: "userAdminAnyDatabase" , db:"admin"}]})
// (OR)
db.createUser({ user: "mongoadmin" , pwd: "mongoadmin", roles: ["userAdminAnyDatabase", "dbAdminAnyDatabase", "readWriteAnyDatabase"]})

 

MongoDB Unique records (distinct) aggregation

Distinct and the aggregation framework are not inter-operable.
Instead:

db.users.aggregate([ 
    {$group:{_id:{name:'$name', email:'$email'}, numberOfuserscodes:{$sum:1}}}, 
    {$sort:{numberOfzipcodes:-1}},
]);

 

MongoDB - Fetch Random Records

Below query for fetching random 10 records from database

db.users.aggregate([{ $sample: { size: 10 } }])

 

Get embedded document in MongoDB collection?

Below is the query for fetch embedded record

db.collection.find({ "notes.name" : "nested record MongoDB"});

 

Update embedded document record  in MongoDB collection?

Below is the query for Update embedded document record in MongoDB

db.users.update({"address.id":"1"}, {$set: {'address.$.address1':"test address"});

 

MongoDb joins using Reference and Populate.

Schema Changes:

const UserSchema = new mongoose.Schema({
    username: String
});

const AddressSchema = new mongoose.Schema({
    content: String,
    address: {
      users: mongoose.Schema.Users.ObjectId,
      ref: 'User'
    }
});

Execute Join Query using Populate

User.findOne({ username: username }).populate('address').
    exec((err, address) => {
        console.log("Populated User Address " + address);
    });