MongoDB Interview Questions&Answers

What is MongoDB?
MongoDB is open-source, NoSQL database written in C++. It was introduced in 2009 by 10gen, now known as MongoDB Inc. It is document-oriented database which stores data in JSON/BSON format. It supports dynamic schema i.e. No DDL, No T-SQL.
It supports multiple platform like Windows, Linux, Mac etc.

Why to use MongoDB?
Now-a-days, programmers write code in object oriented fashion using languages like C#, Python, Php, Java etc. Hence, programmers need a database which can store the data in objects. Since, querying and manipulating data objects is easy and it reduces the time of database operations.
And MongoDB stores data in objects. Hence querying MongoDB is easy as compared to RDBMS.

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.

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

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

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

What is Aggregation in MongoDB?
Aggregations are operations that process data records and return computed results.

Define the namespace in mongodb?
It is the concatenation of collection name and database.

What is the use of Index in mongodb?
Indexes provide high performance read operations for frequently used queries.

What is use of GridFS in mongodb?
GridFS is used for storing and retrieving the large files like audio, Images, Video files.

What is the use journaling?
Journaling is used to safe backups in mongodb.

Which command is used to see the connection?
db_adminCommand (“connPoolStats”); is used to see the connection.

What is the use of profiler?
Profiler is used to show the performance characteristics of every operation against the database.

Which type of data mongodb store?
MongoDB stores data in the form of documents, which are JSON-like field and value pairs.

what is embedded documents?
Embedded documents capture relationships between data by storing related data in a single document structure.

Which method is used to create an index?
CreateIndex() method is used to create an index.

What is the use of pretty() method?
Pretty() method is used to show the results in a formatted way.

Which method is used to remove the document form the collection?
Remove() method is used to remove the document form the collection.

Define Mongodb projection.
Projection is used to select only necessary data.It did not select whole data of a document.

What is the use of limit() method?
Limit() method is used to limit the records in database.

What is the syntax of limit() method?
db.COLLECTION_NAME.find().limit(NUMBER) syntax is used.

What is the syntax of sort() method?
db.COLLECTION_NAME.find().sort({KEY:1}) syntax is used for sorting the documents.

Which command is used to create the backup of database?
Mongodump command is used to create the backup of database.

What is collection in monodb?
In monogodb collection is a group of mongodb documents.

What is the use of db command?
Db command gives the name of currently selected database.

Which method is used to update the documents into a collection?
Update() and save() methods are used to update the documents into a collection.

What is the syntax of skip() method?
The syntax of skip methopd is > db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER).

Which command is used to restore the backup?
Mongorestore command is used to restore the backup.

What is the use of save() method?
Save() method is used to replace the existing document to the new document.

What is MongoDB CRUD Operations?
CRUD operations imply to the fundamental operations supported by MongoDB, which are Create, Read, Update, and Delete.

Create operation – Create operation or Insert operation are used to add new documents to the collection and if the collection does not exist, it creates one.
Following command can insert a document on the collection – db.collection.insert()

Read operation – This operation reads the documents from the collection. This process is taken place by executing a query.
The command to read the document is – db.collection.find()

Update operation – Update operation is used to modify an existing document.
The command that updates a document is – db.collection.update()

Delete operation – Delete operation erases the document from the collection.
Following command performs the operations – db.collection.remove()

What is a ‘document’ in MongoDB?
A record in MongoDB is a document which is been described below and a data structure composed of field and value pairs. MongoDB documents are very similar to JSON objects. The values of fields may consist of other such as documents, arrays, and arrays of documents. This is an important differentiation and vital feature devised from RDBMS systems where each field must contain only one value.

MongoDb Commands

Use- MongoDB use DATABASE_NAME is used to create database. The command will create a new database if it doesn't exist, otherwise it will return the existing database.
>use mydb
switched to db mydb
db- To check your currently selected database, use the command db
>db
mydb
show dbsIf you want to check your databases list, use the command show dbs.
>show dbs
local     0.78125GB
test      0.23012GB
Your created database (mydb) is not present in list. To display database, you need to insert at least one document into it.
>db.movie.insert({"name":"tutorials point"})
>show dbs
local      0.78125GB
mydb       0.23012GB
test       0.23012GB
In MongoDB default database is test. If you didn't create any database, then collections will be stored in test database.
dropDatabaseMongoDB db.dropDatabase() command is used to drop a existing database.
db.dropDatabase()
This will delete the selected database. If you have not selected any database, then it will delete default 'test' database.
createCollectionMongoDB db.createCollection(name, options) is used to create collection.
db.createCollection(name, options)
In the command, name is name of collection to be created. Options is a document and is used to specify configuration of collection.
You can check the created collection by using the command show collections.
>show collections
mycollection
system.indexes
The following example shows the syntax of createCollection() method with few important options −
>db.createCollection("mycol", { capped : true, autoIndexId : true, size : 
   6142800, max : 10000 } )
{ "ok" : 1 }
>
In MongoDB, you don't need to create collection. MongoDB creates collection automatically, when you insert some document.
>db.dotnetguru.insert({"name" : "dotnetguru"})
>show collections
mycol
mycollection
system.indexes
dotnetguru
>
drop() collection-  MongoDB's db.collection.drop() is used to drop a collection from the database.
>db.mycollection.drop()
true
>
Data Types- MongoDB supports many datatypes. Some of them are −
  • String − This is the most commonly used datatype to store the data. String in MongoDB must be UTF-8 valid.
  • Integer − This type is used to store a numerical value. Integer can be 32 bit or 64 bit depending upon your server.
  • Boolean − This type is used to store a boolean (true/ false) value.
  • Double − This type is used to store floating point values.
  • Min/ Max keys − This type is used to compare a value against the lowest and highest BSON elements.
  • Arrays − This type is used to store arrays or list or multiple values into one key.
  • Timestamp − ctimestamp. This can be handy for recording when a document has been modified or added.
  • Object − This datatype is used for embedded documents.
  • Null − This type is used to store a Null value.
  • Symbol − This datatype is used identically to a string; however, it's generally reserved for languages that use a specific symbol type.
  • Date − This datatype is used to store the current date or time in UNIX time format. You can specify your own date time by creating object of Date and passing day, month, year into it.
  • Object ID − This datatype is used to store the document’s ID.
  • Binary data − This datatype is used to store binary data.
  • Code − This datatype is used to store JavaScript code into the document.
  • Regular expression − This datatype is used to store regular expression.
insert Data- To insert data into MongoDB collection, you need to use MongoDB's insert()or save() method.


>db.mycol.insert({
   _id: ObjectId(7ae54ah8918c),
   title: 'MongoDB Overview', 
   description: 'MongoDB is no sql database',
   by: 'dotnet gutu',
   url: 'http://www.dotnetguru.com',
   tags: ['mongodb', 'database', 'NoSQL'],
   likes: 200
})

In the inserted document, if we don't specify the _id parameter, then MongoDB assigns a unique ObjectId for this document.
_id is 12 bytes hexadecimal number unique for every document in a collection. 12 bytes are divided as follows −
_id: ObjectId(4 bytes timestamp, 3 bytes machine id, 2 bytes process id, 
   3 bytes incrementer)
To insert multiple documents in a single query, you can pass an array of documents in insert() command.

>db.post.insert([
   {
      title: 'MongoDB Overview', 
      description: 'MongoDB is no sql database',
      by: 'dotnet guru',
      url: 'http://www.dotnetguru.com',
      tags: ['mongodb', 'database', 'NoSQL'],
      likes: 100
   },
 
   {
      title: 'NoSQL Database', 
      description: "NoSQL database doesn't have tables",
      by: 'dotnet guru',
      url: 'http://www.dotnetguru.com',
      tags: ['mongodb', 'database', 'NoSQL'],
      likes: 20, 
      comments: [ 
         {
            user:'user1',
            message: 'My comment',
            dateCreated: new Date(2013,11,10,2,35),
            like: 0 
         }
      ]
   }
])
To insert the document you can use db.post.save(document) also. If you don't specify _id in the document then save() method will work same as insert() method. If you specify _id then it will replace whole data of document containing _id as specified in save() method.

find- To query data from MongoDB collection, you need to use MongoDB's find()method.

>db.COLLECTION_NAME.find()
find() method will display all the documents in a non-structured way.

pretty- To display the results in a formatted way, you can use pretty() method.

>db.mycol.find().pretty()

>db.mycol.find().pretty()
{
   "_id": ObjectId(7df78ad8902c),
   "title": "MongoDB Overview", 
   "description": "MongoDB is no sql database",
   "by": "dotnet guru",
   "url": "http://www.dotnetgru.com",
   "tags": ["mongodb", "database", "NoSQL"],
   "likes": "100"
}
>
Apart from find() method, there is findOne() method, that returns only one document.

RDBMS Where Clause Equivalents in MongoDB
To query the document on the basis of some condition, you can use following operations.

OperationSyntaxExampleRDBMS Equivalent
Equality{<key>:<value>}db.mycol.find({"by":"tutorials point"}).pretty()where by = 'tutorials point'
Less Than{<key>:{$lt:<value>}}db.mycol.find({"likes":{$lt:50}}).pretty()where likes < 50
Less Than Equals{<key>:{$lte:<value>}}db.mycol.find({"likes":{$lte:50}}).pretty()where likes <= 50
Greater Than{<key>:{$gt:<value>}}db.mycol.find({"likes":{$gt:50}}).pretty()where likes > 50
Greater Than Equals{<key>:{$gte:<value>}}db.mycol.find({"likes":{$gte:50}}).pretty()where likes >= 50
Not Equals{<key>:{$ne:<value>}}db.mycol.find({"likes":{$ne:50}}).pretty()where likes != 50
AND in MongoDB
In the find() method, if you pass multiple keys by separating them by ',' then MongoDB treats it as AND condition. Following is the basic syntax of AND −

Syntax:

>db.mycol.find(
   {
      $and: [
         {key1: value1}, {key2:value2}
      ]
   }
).pretty()
Following example will show all the tutorials written by 'dotnet guru' and whose title is 'MongoDB Overview'.
>db.mycol.find({$and:[{"by":"dotnet guru"},{"title": "MongoDB Overview"}]}).pretty() {
   "_id": ObjectId(7df78ad8902c),
   "title": "MongoDB Overview", 
   "description": "MongoDB is no sql database",
   "by": "dotnet guru",
   "url": "http://www.dotnetguru.com",
   "tags": ["mongodb", "database", "NoSQL"],
   "likes": "100"
}
OR in MongoDB
To query documents based on the OR condition, you need to use $or keyword. Following is the basic syntax of OR −

>db.mycol.find(
   {
      $or: [
         {key1: value1}, {key2:value2}
      ]
   }
).pretty()
Following example will show all the tutorials written by 'tutorials point' or whose title is 'MongoDB Overview'.

>db.mycol.find({$or:[{"by":"dotnet guru"},{"title": "MongoDB Overview"}]}).pretty()
{
   "_id": ObjectId(7df78ad8902c),
   "title": "MongoDB Overview", 
   "description": "MongoDB is no sql database",
   "by": "dotnet guru",
   "url": "http://www.dotnetguru.com",
   "tags": ["mongodb", "database", "NoSQL"],
   "likes": "100"
}
>

Using AND and OR Together
The following example will show the documents that have likes greater than 10 and whose title is either 'MongoDB Overview' or by is 'dotnet guru'. Equivalent SQL where clause is 'where likes>10 AND (by = 'dotnet guru' OR title = 'MongoDB Overview')'


>db.mycol.find({"likes": {$gt:10}, $or: [{"by": "dotnet guru"},
   {"title": "MongoDB Overview"}]}).pretty()
{
   "_id": ObjectId(7df78ad8902c),
   "title": "MongoDB Overview", 
   "description": "MongoDB is no sql database",
   "by": "dotnet guru",
   "url": "http://www.dotnetguru.com",
   "tags": ["mongodb", "database", "NoSQL"],
   "likes": "100"
}
>
Update- MongoDB's update() and save() methods are used to update document into a collection. The update() method updates the values in the existing document while the save() method replaces the existing document with the document passed in save() method.

Consider the mycol collection has the following data.
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Dotnet guru Overview"}
Following example will set the new title 'New MongoDB Tutorial' of the documents whose title is 'MongoDB Overview'.
>db.mycol.update({'title':'MongoDB Overview'},{$set:{'title':'New MongoDB Tutorial'}})
>db.mycol.find()
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"New MongoDB Tutorial"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Dotnet guru Overview"}>

By default, MongoDB will update only a single document. To update multiple documents, you need to set a parameter 'multi' to true.
>db.mycol.update({'title':'MongoDB Overview'},
   {$set:{'title':'New MongoDB Tutorial'}},{multi:true})

remove- MongoDB's remove() method is used to remove a document from the collection. remove() method accepts two parameters. One is deletion criteria and second is justOne flag.
  • deletion criteria − (Optional) deletion criteria according to documents will be removed.
  • justOne − (Optional) if set to true or 1, then remove only one document.
Consider the mycol collection has the following data.
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Dotnet guru Overview"}
Following example will remove all the documents whose title is 'MongoDB Overview'.
>db.mycol.remove({'title':'MongoDB Overview'})
>db.mycol.find()
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Dotnet guru Overview"}
>
If there are multiple records and you want to delete only the first record, then set justOne parameter in remove() method.
>db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)
If you don't specify deletion criteria, then MongoDB will delete whole documents from the collection. This is equivalent of SQL's truncate command.
>db.mycol.remove()
>db.mycol.find()
>
find- MongoDB's find() method, explained in MongoDB Query Document accepts second optional parameter that is list of fields that you want to retrieve. In MongoDB, when you execute find() method, then it displays all fields of a document. To limit this, you need to set a list of fields with value 1 or 0. 1 is used to show the field while 0 is used to hide the fields.

Consider the collection mycol has the following data −
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}
Following example will display the title of the document while querying the document.
>db.mycol.find({},{"title":1,_id:0})
{"title":"MongoDB Overview"}
{"title":"NoSQL Overview"}
{"title":"Tutorials Point Overview"}
>
Please note _id field is always displayed while executing find() method, if you don't want this field, then you need to set it as 0.
limit- To limit the records in MongoDB, you need to use limit() method. The method accepts one number type argument, which is the number of documents that you want to be displayed.
Consider the collection myycol has the following data.
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}
Following example will display only two documents while querying the document.
>db.mycol.find({},{"title":1,_id:0}).limit(2)
{"title":"MongoDB Overview"}
{"title":"NoSQL Overview"}
>
Apart from limit() method, there is one more method skip() which also accepts number type argument and is used to skip the number of documents.

Following example will display only the second document.
>db.mycol.find({},{"title":1,_id:0}).limit(1).skip(1)
{"title":"NoSQL Overview"}
>
sort- To sort documents in MongoDB, you need to use sort() method. The method accepts a document containing a list of fields along with their sorting order. To specify sorting order 1 and -1 are used. 1 is used for ascending order while -1 is used for descending order.

Consider the collection myycol has the following data.
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}
Following example will display the documents sorted by title in the descending order.
>db.mycol.find({},{"title":1,_id:0}).sort({"title":-1})
{"title":"Tutorials Point Overview"}
{"title":"NoSQL Overview"}
{"title":"MongoDB Overview"}
>
Please note, if you don't specify the sorting preference, then sort() method will display the documents in ascending order.
ensureIndex- Indexes support the efficient resolution of queries. Without indexes, MongoDB must scan every document of a collection to select those documents that match the query statement. This scan is highly inefficient and require MongoDB to process a large volume of data.
Indexes are special data structures, that store a small portion of the data set in an easy-to-traverse form. The index stores the value of a specific field or set of fields, ordered by the value of the field as specified in the index.
To create an index you need to use ensureIndex() method of MongoDB.

The basic syntax of ensureIndex() method is as follows().

>db.COLLECTION_NAME.ensureIndex({KEY:1})
Here key is the name of the field on which you want to create index and 1 is for ascending order. To create index in descending order you need to use -1.
>db.mycol.ensureIndex({"title":1})
>
In ensureIndex() method you can pass multiple fields, to create index on multiple fields.
>db.mycol.ensureIndex({"title":1,"description":-1})
>

0 comments:

Post a Comment

Topics

ADO .Net (2) Ajax (1) Angular Js (17) Angular2 (24) ASP .Net (14) Azure (1) Breeze.js (1) C# (49) CloudComputing (1) CMS (1) CSS (2) Design_Pattern (3) DI (3) Dotnet (21) Entity Framework (3) ExpressJS (4) Html (3) IIS (1) Javascript (6) Jquery (9) Lamda (3) Linq (11) Mongodb (1) MVC (48) NodeJS (7) RDLC (1) Report (1) Sql Server (29) SSIS (3) SSRS (2) UI (1) WCF (12) Web Api (10) Web Service (1) XMl (1)