January 27, 2020

#MongoDB Part 2: Interview Questions And Answers

How to create Database and Collection in MongoDB?
In MongoDB, the database is used to store all of the collections, and the collection in turn is used to store all of the documents. The documents contain the relevant Field name and Field values.

Creating a database: By issuing the 'use' command we can create a database in MongoDB. e.g: when we execute below command it will create CompanyDB and MongoDB will automatically switch to the database once created.

> use EmployeeDB

Creating a Collection/Table: We can use 'insert' statement to create a collection, this will insert a record (which is document with a field names and values) into a collection. While executing 'insert' statement, if the collection does not exist a new one will be created. e.g:

db.Employee.insert
(
   {
     "EmployeeID":9,
"EmployeeName":"David Moore"
   }      
)

How to add MongoDB Array using insert()?
To insert multiple documents into a collection at one time we can use 'insert()' statement. To do this we need to create a JavaScript variable, which will hold the array of documents and then we will use insert command to insert the array of documents into the collection

var employees=
[
   {
     "EmployeeID":9,
"EmployeeName":"David Moore"
   }
   {
     "EmployeeID":10,
"EmployeeName":"martin Spoitte"
   }
];

db.Employee.insert(employees);

To print the employees stored in the MongoDB in JSON format we can use find command.

db.Employee.find().forEach(printjson);

When we execute above command, below result will be printed.
{
   "_id":ObjectId("78687g87ere7687"),
   "EmployeeID":9,
   "EmployeeName":"David Moore"
}
{
   "_id":ObjectId("78687g87er67656"),
   "EmployeeID":10,
   "EmployeeName":"martin Spoitte"
}

What is the primary key in MongoDB?
_id field, which contains a unique ObjectID value act as the primary key for the collection so that each document can be uniquely identified in the collection.

If we don't add a field name with the _id in the field name, then MongoDB will automatically add an Object id field. To query the documents in a collection, we can use the ObjectId for each document in the collection.

-K Himaanshu Shuklaa..

No comments:

Post a Comment