0% found this document useful (0 votes)
6 views40 pages

Mongodb

NoSQL, which stands for 'Not Only SQL', is a type of database that allows for storing and retrieving data without the constraints of traditional relational databases, making it suitable for big data and real-time applications. It includes various types such as key-value, document, graph, and wide-column stores, each with its own advantages and disadvantages. MongoDB is highlighted as a prominent NoSQL database known for its document-oriented structure, scalability, and flexibility.

Uploaded by

harshadshukla23
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views40 pages

Mongodb

NoSQL, which stands for 'Not Only SQL', is a type of database that allows for storing and retrieving data without the constraints of traditional relational databases, making it suitable for big data and real-time applications. It includes various types such as key-value, document, graph, and wide-column stores, each with its own advantages and disadvantages. MongoDB is highlighted as a prominent NoSQL database known for its document-oriented structure, scalability, and flexibility.

Uploaded by

harshadshukla23
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

NoSQL DATABASE: MONGODB

Question1: Define NOSQL.

Answer:

 NoSQL Stands for “Not Only SQL”.


 NoSQL is a database that provides mechanism to store & retrieve data other than relational database.
 It is a class of DBMS that does not follow all of the rules of a RDBMS and cannot use traditional SQL to query
data.
 It doesn’t required a fixed schema and have simple API.
 There are no needs to design a table to store data inside it.
 NoSQL is used for big data and real-time web apps.
 For Example companies like Twitter, Facebook, and Google that collect terabytes of user data every single day.
 The primary objective of NoSQL database are:
1. Design Simplicity
2. Horizontal Scaling
3. High Availability
4. Replication
 NoSQL database uses different data structure as compared to relational dataset.
 This are the list of some NoSQL database:
1. MongoDB
2. Redis
3. Couch db
4. Cassandra
5. Voldemort
6. Infogrid
7. Hbase
8. Neo4j

Question 2: Write A Short Note On history of NoSQL.

Answer:

 Relational database are invented in 1970s to that make possible to store data in the form of table which is
combination of row and columns.
 To communicate with relational database a language called SQL was introduced & almost all relational database
system use SQL.
 SQL is more rigid to work with unstructured data.

Evolution of NOSQL:

 To acronym NoSQL was first used in 1998 by Carlo Strozziwhile naming his lightweight, open-source “relational”
database that did not use SQL.
 Carlo Strozzi suggests that ,because the current NoSQL movement “departs from the relational model
altogether, it should therefore have been called more appropriately ‘NoREL’—referring to ‘No Relational’.
 The name came up again in 2009 when Eric Evans and Johan Oskarsson used it to describe non-relational
database.
 Johan Oskarsson, then a developer at Last.fm, reintroduced the term NoSQL in early 2009 when he organized an
event to discuss “open Source distributed, non-relational database”.

Plazma Institute Page 1


NoSQL DATABASE: MONGODB
 Based on 2014 revenue, the NoSQL market leaders are MarkLogic, MongoDB, and Datastax.
 Based on 2015 popularity ranking, the most popular NoSQL database are MongoDB, Apache Cassandra, and
Redis.

Question 3:Explain Difference Between NoSQL And SQL database..

Answer:

No. SQL NoSQL

1. SQL Stands for Structure Query Language. NOSQL Stands for Not Only SQL.

2. SQL is a query language that used to There is no declarative query language to communicate with
communicate with relational database. database.

3. SQL database are primarily called RDBMS or NoSQL database are primarily called as non-relational or
relational database. distributed database.

4. SQL or relational database stores structure NOSQL database deals with semi-structure & unstructured
oriented data. data.

5. Traditional RDBMS uses SQL syntax and queries NoSQL database system consists of various kind of database
to analyze and get the data for further use. technologies that developed in response to the demand
presented for the development of the modern application.

6. SQL database are Table based database. NoSQL database can be document based, key-value pairs,
graph database.

7. SQL database Have a predefined schema. NoSQL database use dynamic schema for unstructured data.

8. SQL database are vertically scalable. NoSQL databases use dynamic schema for unstructured data.

9. An ideal choice for the complex query intensive It is not good fit complex queries.
environment.

10. SQL database are not suitable for hierarchical More suitable for the hierarchical data store as it supports
data storage. key-value pair method.

11. It was developed in the 1970s to deal with issues Developed in the late 2000s to overcome issues and
with flat file storage. limitation of SQL database.

12. Most of RDBMS systems are proprietary. Most of NoSQL systems open-source.

13. It should be used when data validity is super Use when it’s more important to have fast data than correct
important. data.

14. Examples: Oracle, Postgres And MS-SQL. Example: MongoDB, Redis, Neo4j, Cassandra, Hbase.

Question 4:Write down Advantages & Disadvantages of NoSQL Database.

Answer:

Plazma Institute Page 2


NoSQL DATABASE: MONGODB
Characteristics of NoSQL (Advantages)

1. Structured & Unstructured data:


- NoSQL system database can store structure data, semi structured data unstructured data so that data can
be managed easily.
2. Multi-format data.
- NoSQL system store and retrieve data from many formats like key-value stores, graph database, column-
family(big table) stores, document stores, and even rows in tables.

3. Open source
- NoSQL is an open source so its software’s are easily available on internet.
4. Free of joins
- NoSQL system allows you to extract your data using simple interfaces without joins.
5. Schema-free
- In NoSQL system user do not need to define schema for data because it is schema free.
6. Work on many processors
- NoSQL system allows you to store your database on multiple processors and maintain high-speed
performance.
7. Less cost
- NoSQL database is less expensive for storage and transactions.
8. Linear scalability
- Huge amount of data can store on NoSQL database.
- When you add more processors, you get a consistent increase in performance.
9. Innovative
- NoSQL offers option to a single way of storing, retrieving, and manipulating data.
10. Highly distributable
- NoSQL uses the powerful, efficient architecture instead of the expensive single architecture that make
possible to distribute data very fast & efficiently.
11. Continues availability
- A database server can stay online as well as offline.
- Users can also use server 24*7 so server may continues available.
12. Non-relational
- The information in NoSQL is stored in the form aggregate.
- A single record stores every information about the transaction, including the delivery address.

Disadvantages:

- NoSQL is open-source database, so there is no reliable standard for NoSQL yet.


- GUI mode tools to access the database is not flexibly available in the market.
- Some database system like MongoDB and CochDB store data in JSON format which means the document
are quite large.
- Relational database are a better choice in the field of Transaction management than NoSQL.
- Backup is a great weak point for some NoSQL database. There is no approach for the backup of data in a
consistent manner.

Question 5: Write down External benefit of NoSQL.

Answer:

Plazma Institute Page 3


NoSQL DATABASE: MONGODB
1. Database administration:
- NoSQL database require less administrative task because it has automatic management with data.
2. Schema-free:
- In NoSQL system user do not need to define schema for data because it is schema free.
3. Distributable:
- NoSQL database can be distributed among multiple servers, so it can be easily available to, multiple users.
4. Easy Structure:
- Users can easily store the data in NoSQL database.
- Users can also retrieve the data easily from the server.
5. Object Oriented:
- NoSQL also Support object oriented programming.

6. Own access language:


- NoSQL database has is own access language.
- There is no common language for all NoSQL databases like SQL.
7. Automatic management:
- In NoSQL when user insert record it will automatically create the table in database as well as when you
insert record a database will create unique id for new record automatically.
8. Multiple data structure:
- NoSQL database supports different data structure like key-value, column list, parent-child structure etc.

Question 6: Write down type of NoSQL with advantage and disadvantage.

Answer:

- NoSQL provides different type of database technology.


- According to type of data storage there are four type of NoSQL database:
1. Key value type
2. Document type
3. Graph type
4. Wide-column stores type
1. Key Value Type:
- Key-value types are the simplest NoSQL type.
- In this type of database all data are stored with key & its associated value.
- It is also known as associative arrays, organized into rows.

Advantages:

- Simple data format.


- Support any value like text, number, images or any long code.
- No need to maintain index.
- It is used when data is not related.
- Basic operation are managed easily
- Fast in data retrieval

Disadvantages:

Plazma Institute Page 4


NoSQL DATABASE: MONGODB
- Only one way to look up values by key.
- Not supports range queries.
- No any standard for queries.
- Poor performance in related data.
2. Document Value Type
- As like name document store database store data in document format.
- A document database is a type of non-relational database that is designed to store query data as JSON-Like
document.
- Document store NoSQL database is similar to key-value database in that there’s a key and a value.
- In this type data is stored as a value while its associated key is the unique identifiers for that value.

Advantages:

- Simple data format.


- Flexible schema.
- Store mixed of structured as well as semi structured data.
- All operation can manage easily.
- Use key: value pair to manage queries.
- Easy to write queries.

Disadvantages:

- Difficult to perform transaction over multiple documents.


- Not suitable for aggregation.
- Size of documents becomes larger.
3. Graph Type
- A graph database views data in terms of graph.
- It consists of entities & their relationship that is mot mapped in table.
- Using graph model users can deal with the data by its entities & relationship directly.
- Graph database provides index free architecture so every element in graph contain direct pointer to adjust
elements.
- This type of database is suitable for relational based data.

Advantages:

- Easy to understand.
- Easy to represents highly connected data.
- Provide index free architecture
- Flexible schema
- Suitable for real-time update big data
- Support relational data

Disadvantage:

- Difficult to modify each node


- Difficult to remove nodes
- Not suitable for disported data
- Not suitable transactional application.
4. Wide column store

Plazma Institute Page 5


NoSQL DATABASE: MONGODB
- It is also known as column family, wide column family, columnar family database.
- This database allows you to store single column or group of columns in a disk blocks.
- A column store database is a type of database that store data in the form of column oriented model instead
of row form.
- Each column contains a tuple of name & value ordered and comma separator.

Advantage:

- Fast to loaded data


- Efficient for data compression
- Fast data retrieval for aggregation queries
- Distributed data storage
- Suitable for large amount of data.

Disadvantages:

- Increase disk seek time


- Do not suitable for different type of values.

Question 7: Explain Locally Hosted Database.

Answer:

- When a database is stored in a local pc or stand-alone pc then it is called local hosted database.
- This type of database is local to your application only, so that it is stored on the pc where application is
resides.
- This type of database uses SDF file format (Single Data File).
- If you want to publish your database over the internet then locally hosted database will be used.
- It’s limited for authorized users only. A user doesn’t know where the data is physically located users can
access it.
- It is basically maintain by system administrator.
- A database can be accessed over different network.
- The main advantage of this system is you have complete control over data because data is stored on local
server.

Advantage:

- Data is easily accessible.


- High speed in data retrieval
- No need of internet connection to access data.
- More secure than other system
- You have entire control on your data.

Disadvantages:

- If server dies than lose your data.


- Setup of all system & server become costly.
- It increases network traffic.
- Continues backup is needed.
- Deadlock detection & management become difficult.

Plazma Institute Page 6


NoSQL DATABASE: MONGODB
- When organization grows needs to upgrade system that becomes costly.
- Continues administration is needed.

Question 8: Write a note on Database as a service.

Answer:

1. When a database stored on server then it is called service based database.


2. This type of database uses MDF-multiple data format.
3. Database as a service – DBaaS is a concept of cloud computing that allows you to store database on a cloud
storage server.
4. The DBaaS provides the equipment, software, and infrastructure needed for business to run their database on
the DBaaS.
5. It removes the worry about the key factors for managing a database like database administration, license,
backup, security etc..
6. DBaaS is a managed service offering assessment to a database along with the application and their related
database.
7. The service provider responsible for installing, updating and ensuring for performance of the database.
8. DBaaS provide service on “pay as you go” model.
9. It allowing the users to pay for the usage instead of a fixed cost paid for licenses and investments on purchasing
and maintaining the physical machine.
10. When you required more facility u have to pay for additional services.
11. Database services take care of scalability and high availability of the database.

Question 9: What is MongoDB?

Answer:

- MongoDB is a document-oriented NoSQL database used for high volume data storage.
- MongoDB is an open source document based NoSQL database that can install on different platform like
windows, Linux etc.
- MongoDB is a non-relational database.
- It is a cross-platform, document oriented database that provides, high performance and easy scalability.
- Relational database have a fixed data structure while MongoDB is a schema free.
- In MongoDB data is stored in the form of JSON style document.
- Main purpose to build MongoDB is:
1. Scalability
2. Performance
3. High Availability
- MongoDB is suitable for the following application:
1. Big Data
2. Content management and delivery
3. Mobile and social infrastructure
4. User data management
5. Data Hub
- MongoDB works on concept of
1. Database
2. Collection

Plazma Institute Page 7


NoSQL DATABASE: MONGODB
3. Document

Question 10: Explain Advantages of MongoDB.

Answer:

1. Document based database:


- MongoDB stores data in document format like JSON, BSON etc. so it is known as document storage
database.
2. Schema-free:
- Unlike RDBS MongoDB do not contain any fixed schema.
- MongoDB contain different type of document & there are no needs to define schema or structure.
- Each document contains different number of field size.
3. No complex join:
- MongoDB provides simple query structure that make possible to access data easily.
- It’s a non-relational database so no needs to perform complex join operation to retrieve data.
4. Ad hoc queries:
- MongoDB supports searching by field, range queries, and regular expression searches.
- Queries can be made to return specific fields within document.
5. Automatic primary key:
- MongoDB creates unique key for each document store inside it.
- When you store data it automatically gives unique key for each document which is known as objected.
6. Fast and alternative development:
- It has dynamic schema so it is fast for developer to build application against RDBMS.
7. Load balancing:
- MongoDB uses the concept of sharding to scale horizontally by splitting data across multiple MongoDB
instance.
8. Scalability:
- A system that scales well will be able to maintain and increase its level of performance under larger
operational demands.
- MongoDB supports horizontal scaling through sharding, distributing data across several machines and
facilitating high throughput operations with large set of data.

9. Indexing:
- Indexes can be created to improve the performances of searches with in MongoDB.
10. Replication:
- MongoDB supports master slave replication.
- A master can perform reads and writes and s slave copies data from the master and can only be used for
reads or backup.
11. Duplication of Data:
- MonogoDB can run over multiple servers.
- The data is duplicated to keep the system up and also keep its running condition in case of hardware failure.

Question 11: Explain The basic concept of MongoDB.

OR

Explain Database, Document & Collection.

Plazma Institute Page 8


NoSQL DATABASE: MONGODB
Answer:

1. Database:
- Database is a physical container for collection.
- Each database gets its own set of files on the system.
- A single MongoDB server typically has multiple databases.
- In MongoDB, database holds collection of documents.
- A MongoDB, server can store multiple databases.
2. Collection:
- Collection is a group of MongoDB document.
- It is equivalent of an RDBMS table.
- The data records are BSON document stored in collection inside a database.
- BSON stand for Binary JSON.
- Collections stores document.
- Documents are the unit of data stored in collection.
- A collection exists within a single database.
- Documents within a collection can have different fields.
- All documents in a collection are of similar or related purpose.

3. Document:
- A record in a MongoDB collection is basically called a document.
- Documents are the unit of data stored in collections.
- Documents have a dynamic schema.
- MongoDB document are composed of field-and-value pairs and have the following structure:
{
Field1: value1,
Field2: value2,
Field3: value3,
………
Fieldn: valuen,
}

Question 12: Write down installation step of MongoDB

Answer:

- First check the operating system architecture by placing following command in cmd

C :>wmidos get osarchitecture

- It will show operating system architecture either 32bit or 64bit.


- Download the MongoDBmsi installer package from www.MongoDB.org
- Install MongoDB with the installation wixard.
- Run MongoDB-win32-x86_64-2008plus-ssl-3.0.5-signed in your download directory
- It will start wizard.
- First screen shows welcome screen of MongoDBclik on next button
- Accept license agreement & click on next button.
- Next dialog box shows choose set type: select complete & click on next.

Plazma Institute Page 9


NoSQL DATABASE: MONGODB
- Now click on install button.
- After the setup has been finished, you can check in you c:\program files a MongoDB folder must have been
created.

Now set up MongoDB Environment:

- MongoDB require a data directory to store all data; MongoDB’s default data directory path is \data\db.
- To configure this go to your c:drive and create data\db folder (“db” folder inside “data” folder)
So now full path of db folder will be-C:\data\db
- Now open cmd& type go to MongoDB directory.
C:\users\stud\ cd C:\program files (x86)\MongoDB\server\3.0\bin
- Now run MongoDB method MongoDB server has been started on port – 27017
- Now open another cmd prompt and type mongo.
- This shows that you have been connected with MongoDB server.
- Now you can perform all MongoDB commands.

Question 13: Explain Data model of MongoDB?

Answer:

- MongoDB contains flexible schema or schema-less, which means there is no need of defining a structure for
the data before insertion.
- MongoDB is a document based database, in which any document stored in collection.
- Collection in MongoDB doesn’t enforce the document structure.
- In general, the documents in a collection of MongoDB will always share the same data structure
(recommended for best performance, not mandatory)
- The dynamic schema required high data balancing of application and performance characteristics of
database engine.
- During designing of data model always consider the application usage of data such as queries, update and
processing of data as well as structure of data itself.
- There are two tools in MongoDB that represent the relationship between data.
1. Reference Document
2. Embedded Document

Question 14: What is Query? What are the types of Query document in MongoDB?

Answer:

- Query is a request which is used to retrieve data from the database.


- By using query we can instructdatabase engine to perform some specific task.
- Query make possible to interact with database.
- MongoDB use document database to store data.
- It provides many different type of queries to perform some specific operation.

MongoDB provides following type of queries:

1. Key value queries:


- It is basically used to retrieve the document according to specified keys/fields and its value.
- For ex: Display all documents where stream is mca
>db.stud.find({stream:”mca”})

Plazma Institute Page 10


NoSQL DATABASE: MONGODB
2. Range queries:
- It is used to retrieve the document by specifying range of value.
- For ex: Display all document where per between 60 to 80.
>db.stud.find({$per:[{$get:620}},{$per:{$lte:80}}]})
3. Text search queries
- It is used to search text data from documents.
- It uses Boolean operators & return result in text argument.
4. Aggregation queries:
- It is used to produce aggregate result on group of key/fields values rather than a single key.
- You can use aggregate function along with group key/fields.
- For ex: Display stream wise highest percentage from documents.
>db.stud.aggregate([{$group:{_id:streem},highper{$max:”$per}}])
5. Map reduce queries
- Map reduce is function which is used to perform some example queries.
- It allows complex data processing by first combine all the data then arrange it 7 reduce the data & display
document according to query specified by user.

Question 15: How to create database in MongoDB?

OR

Explain Database Handling Commands.

Answer:

1. Create database
- Syntax:
Use <DATABASE_NAME>
- USE command is used to create a database in MongoDB.
- The command will create a new database; if it doesn’t exit otherwise it will return the existing database.
- Example:
>use student
2. Display database
db command
- Syntax:
db
- To check your currently selected database use the command db
Show dbs:
Syntax:
- Show dbs
- This command used to display all database created by user.
3. Delete database
Syntax
- db.dropDatabase()
- To remove database from MongoDB use db.dropDatabase ().
- This will delete the selected database.
- Before delete any database first use database with its name.
- If you have not selected any database, then it will delete default ‘test’ database.

Plazma Institute Page 11


NoSQL DATABASE: MONGODB
- For example:
>use stud
>db.dropDatabase ()

Question 16: Write a note on collection handling commands of MongoDB.

Answer:

1. Create collection In MongoDB


- In MongoDB, the first basic step is to have a database and collection in place.
- The database is used to store all of the collection, and the collection in turn is used to store all of the
documents.
- Collection can be created by using two ways:
1. using CreateCollection() method
2. using insert() to create collection
- db.createCollection():
- Syntax:
db.createCollection(name,option)
Parameter Type Description

Name String Name of the collection to be created

Option Document (optional) Specify options about memory size and indexing

Field Type Description


- (Optional) if true, enables a capped collection.
Capped Boolean
- If you specify true, you need to specify size parameter also.
- (Optional) if true, automatically create index on _id field.
autoindexid Boolean
- Default value false.
- (Optional) Specifies a maximum size in bytes for a capped collection.
Size Number
- If capped is true, then you need to specify this field also.
- (Optional) Specifies a maximum number of document allowed in the
Max Number
capped collection.
- Insert()
Syntax:
db.collection_name.insert()
- Insert () command to insert documents into a collection.
- We can also use db.collection.save() to save document.
EXAMPLE:
> use student
> db.student.insert(
{
"rlno" : 1,
"name": "meghna"
})

Plazma Institute Page 12


NoSQL DATABASE: MONGODB

2.DISPLAY ALL COLLECTION IN MONGODB:

- syntax:
show Collections
- MongoDB allows you to display all collection by using show collection method.
- This method list out all collection created in currently used document.
- EXAMPLE:
> show collections

3. DELETE COLLECTION IN MONGODB:

- syntax:
db.collection_name.drop()
- MongoDB allows you to remove collection.
- To remove collection drop() will be used.
- After delete the collection method will return true, if the selected collection is not delete successfully then
MongoDB return false.
- for example:
> show collections
> db.student.drop()

4. RENAME COLLECTION IN MONGODB:

- syntax:
db.collection.renameCollection(target)
- MongoDB allows you to rename collection by using db.collection.renameCollection method.
- In syntax: Target specifies the new name of collection.
- EXAMPLE:
> db.student.renameCollection(“stud”)

5. COPY COLLECTION IN MONGODB:

- syntax:
db.collection.copyTo(target)
- MongoDB allows you to copy collection by using db.collection.copyTo().
- copyTo() returns the number of documents copied. If the copy fails, it throws an exception.
- In syntax: Target specifies the new name of collection.
- EXAMPLE:
> show collections
student

> db.stud.copyTo(“student”)

6. VIEW STORAGE SIZE OF COLLECTION IN MONGODB:

- syntax:
db.collection.storageSize()

Plazma Institute Page 13


NoSQL DATABASE: MONGODB
- The total amount of storage allocated to this collection for document storage.
- EXAMPLE:
> show collections
student
> db.student.storageSize()
- Output: 32767

7. VIEW SIZE OF COLLECTION IN MONGODB:

- syntax:
db.collection.dataSize()
- MongoDB allows you to view the size of collection by using db.collection.dataSize()
- dataSize() return The size in bytes of the collection.
- EXAMPLE:
> show collections
> db.student.dataSize()
- Output: 336

Question 17: How To Insert Document In MongoDB.

Answer:

- MongoDB provides three ways to insert document.


- 1. insert()
- 2. insertOne()
- 3. insertMany()
1. insert():
- syntax:
db.collection_name.insert()
- insert () command to insert documents into a collection.
- We can also use db.collection.save() to save document.
- EXAMPLE:
> use student
> db.student.insert
(
{
"rlno" : 1,
"name": "meghna"

2. insertOne():
- syntax:
db.collection_name.insertOne()
- insertOne () command to insert a single documents into a collection.
- This method is available with MongoDB version 3.2 or newer version launch after 3.2
- After insert document in collection this method return unique ID of the document.

Plazma Institute Page 14


NoSQL DATABASE: MONGODB
- This ID can be used to find document from collection.
- EXAMPLE :
> use student
> db.stud.insertOne(
{
"rlno" : 1,
"name": "meghna"

})

3. insertMany():
- syntax:
db.collection_name.insertMany(,…..)
- insertMany () command to insert a multiple documents into a collection.
- This method is available with MongoDB version 3.2 or newer version launch after 3.2
- After insert document in collection this method return unique ID of the each document.
- This ID can be used to find document from collection.
- EXAMPLE:
> use student
> db.stud.insertMany(
{
"rlno" : 1,
"name": "meghna"
},
{
“rlno”:2,
“name”:”ekta”
})

Question 18: Explain Quering Document In MongoDB.

Answer:

- MongoDB allows you to display data stored in collection.


- While performing a query operation, one can also use criteria’s or conditions which can be used to retrieve
specific data from the database?
1. DISPLAY ALL DOCUMENTS USING FIND()
- find ()
- syntax: db.collection_name.find({})
- find () allows you to display all document stored in your collection.
- By using this function we can display all documents of currently used database.
- We can specify criteria for retrieval documents with find().
- EXAMPLE:
>use college
>db.stud.find()
- Above example display all records/documents from stud collection.

Plazma Institute Page 15


NoSQL DATABASE: MONGODB
2. DISPLAY ALL DOCUMENTS OF STUD COLLECTION USING FIND()
- EXAMPLE:
>use college
>db.stud.find( {streem :"mscit"})
- Above example display all records/documents from stud collection who are in mscit streem.
3. DISPLAY ALL DOCUMENTS OF STUD IN READABLE FORMAT
- Two functions are used to display output in JSON format.
- pretty ()
- syntax: db.collection_name.find().pretty()
- When we display output with find () the output we get is not in any format and less-readable.
- The pretty command improve the readability, we can format the output in json format.
- EXAMPLE:
>use college
>db.stud.find().pretty()
- print JSON()
- syntax: db.collection_name.find().forEach(printjson);
- This function works same as pretty ().
- It is also used to display output in json format.
- EXAMPLE:
>use college
>db.stud.find().pretty().forEach(printjson)

Question 19: How To Update Document In MongoDB

Answer:

- update ():
- syntax: db.collection_name.update (selection_criteria, updated_data)
- Update () is used to update existing data stored in document.
- We need to specify selection criteria for update a document & then update data using $set keyword.

selection_criteria - Specify key:value of filed for updation

updated_data - Update data use $set keyword

- In this section you have to specify the field along with value

- UPDATE A SINGLE DOCUMENT


- To update document:
1. Issue the update command
2. Choose the condition which you want to use to decide for update document.
3. Use the $set command to modify the Field Name
4. Choose which Field Name you want to modify and enter the new value.
- EXAMPLE:
db.stud.update({rolno:1},{$set :{streem:”mca”}})
- UPDATE MULTIPLE DOCUMENTS:
- We can update multiple documents in MongoDB by using update()
- To update multiple documents in MongoDB use multi option.

Plazma Institute Page 16


NoSQL DATABASE: MONGODB
- Maulti option contains Boolean value either true or false.
- By default multi option set to false; to do multiple update use multi : true
- To update multiple document
1. Issue the update command
2. Choose the condition which you want to use to decide for update document.
3. Use the $set command to modify the Field Name
4. Choose which Field Name you want to modify and enter the new value.
5. Specify {multi:true}
- EXAMPLE:
>db.stud.update({streem:”mscit”},{$set :{streem:”mca”}},{multi:true})

Question 20: Explain Update Operators With Example.

Answer:

- There are several operators used with update command which is divided into two parts:
1. Field update operator
2. Array update operator
 Field update operator
- Field update operators are basically used to update fields.
- Following are field update operators:
1. $set:
- Syntax: { $set: { : , ... } }
- This operator used to set new value in a field/key.
- Parameters:
Name Description

Field1 Specify name of the column or field

Value1 the new value for the field


- EXAMPLE: set design is manager where empno is 1001
> db.emp.update({empno:1001},{$set:design:”manager”}})
2. $unset:
- Syntax: { $unset: { : "", ... } }
- In MongoDB, the $unset operator is used to delete a particular field.
- The $unset has no effect when the field does not exist in the document.
- Parameters:
- field1 - Specify name of the column or field
- EXAMPLE: delete empno field form all documents
> db.emp.update({},{$unset:{empno:””}},{multi:”true”})
3. $inc
- Syntax: { $inc: { : , ... } }
- This operator used to increment values of field in MongoDB.
- Parameters:
Name Description

Field1 Specify name of the column or field

Plazma Institute Page 17


NoSQL DATABASE: MONGODB

amount1 incremental value

- EXAMPLE: increment salaray of each employee by 1000 whose designation is clerk


> db.emp.update({design:”clerk”},{$inc: {sal:1000}},{multi:true})
4. $rename
- syntax:
{<old_name1>:<new_name1>,<old_name2>:<new_name2>,…}}
- The $rename operator is used to updates the name of a field.
- It is required to mention the new field name is different from the existing field name.
Name Description

old_name1,old_name2 old name of the columns or fields

new_name1,new_name2 new name of the columns or fields

- EXAMPLE: rename rlno field as rollnumber of all documents


>db.stud.update({rlno:{$gt:0}},{$rename:{rlno:’roll_number’}},{multi:true})
 ARRAY UPDATE OPERATOR
- Array update operators are basically used to either add, remove single or multiple values form array.
- Following are array update operators:
1. $addToSet :
- Syntax: db.collection.update( {<field>:<value> }, { $addToSet: {<field>:<addition>}})
- This operator used to add element in array
Name Description

field1 Specify name of the column or field

Value The value, specified against a field for an expression, or condition, or matching criteria.

Addition The value of to be added for a field or column into an array if this value not exists.

- EXAMPLE: documents contain 4 subject marks & rlno 5 contain 3 marks want to add marks in array
>db.stud.update({rlno:5},{$addToSet: {marks:55}})
2. $pop
- Syntax: db.collection.update( {field: value }, { $pop: { field: [1 | -1] } } )
- $pop operator removes the first or last element of an array.
- -1 is used to remove the first element of an array
- 1 is used to remove the last element.
3. $pull
- syntax :{ $pull: {<field1> :<value|condition>,<field2>:<value|condition>,…} }
- The $pull operator removes from an existing array all instances of a value or values that match a specified
condition.
- parameters:
Name Description

Field,field1 Name of the column or field to the document..

Plazma Institute Page 18


NoSQL DATABASE: MONGODB

Value, value1, value2, … These are the values to be specified for the fields or columns.

- EXAMPLE
>db.alpha.update({id:111},{$pull:{text: {$in:["aa","e","h"]}}})
4. $pullAll
- syntax:{ $pullAll: { field1: [ value1, value2, value3 ] } } )
- The $pullAll operator is used to remove multiple values specified with $pullAll operator.
- It is similar to $pull operator
- Parameters:
Name Description

Field,field1 Name of the column or field to the document..

Value, value1, value2, … These are the values to be specified for the fields or columns.
- EXAMPLE:
>db.alpha.update({id:111},{$pullAll:{text: ["bb","g"]}})
5. $push
- This operator used to insert element in array. Generally $push insert element at the end of an array.
- by using $push we can
1. push from the start of an array
2. push from the end of an array
3. push multiple elements at once
4. push at any location to an array

Question 21: How To Delete A Document From Collection In MongoDB.

Answer:

1. REMOVE DOCUMENTS
 Remove ()
- syntax:db.COLLECTION_NAME.remove(DELLETION_CRITTERIA, justone)
- Remove () method is used to remove a document from the collection.
- By using this command we can delete a single document or all document stored in collection.
- Remove () method accepts two parameters.
- after performing deletion MongoDB display message along with a number that specify total no of document to
be deleted
Deletion _criteria - Specify criteria for delete document.

justOne - it an Boolean value which is optional


- if it is true then remove only one record from document
- EXAMPLE:
DELETE ALL DOCUMENT FROM STUD COLLECTION
> use college
> db.stud.remove({})
2. DELETE ONE DOCUMENTS
 deleteone()

Plazma Institute Page 19


NoSQL DATABASE: MONGODB
- syntax: db.COLLECTION_NAME.deleteOne(delletion_critteria,writeConcern)
Deletion _criteria - Specify criteria for delete document.

writeConcern - it an Boolean value which is optional


- if it is false then will not display default write concern

- MongoDB's deleteOne() method is used to remove a single document from the collection.
- by using this command we can delete a single document that match specific criteria.
- EXAMPLE:
- DELETE ONE DOCUMENT FROM STUD COLLECTION WHO ARE IN MCA.
> use college
> db.stud.deleteOne({streem:"MCA"})
3. DELETE MULTIPLE DOCUMENTS deleteMany ()
- syntax: db.collection_name.deletemany(delletion_critteria,writeconcern)
Deletion _criteria - Specify criteria for delete document.

writeConcern - it an Boolean value which is optional


- if it is false then will not display default write concern

- MongoDB's deleteMany () method is used to remove a more than one document from the collection.
- by using this command we can delete multiple documents that match specific criteria
- EXAMPLE:
- DELETE DOCUMENTS FROM STUD COLLECTION WHO ARE IN MCA.
> use college
> db.stud.deleteMany({streem:"msc.it"})

Question 22: Explain MongoDB Datatypes.

Answer:

- MongoDB stores data in BSON - Binary-encoded format of JSON.


- This data type is almost similar to java script type.
- MongoDB assigns each data type of an integer ID number from 1 to 255 when querying by type.

MongoDB Data type ALIAS Number Description

Double “double” 1 This type is used to store floating point value.

String “string” 2 This is most commonly used MongoDB datatype


BSON string are utf-8

Object “object” 3 Object data type stores embedded documents.

Array “array” 4 It is used to store an array.

Binary Data “bindata” 5 These MongoDB data types store the binary data in
it.

Plazma Institute Page 20


NoSQL DATABASE: MONGODB

Undefined “undefines” 6 This MongoDB data type stores the undefined


values.

Object id “objected” 7 This data type in MongoDB stores the unique key Id
of documents stored

Boolean “bool” 9 This type is used to store a boolean (true/ false)


value

Date “date” 10 Date data type stores current date or time

Null “null” 11 This MongoDB data types stores a null value in it

Regular Expression “regex” 12 These MongoDB data types stores regular


expressions in MongoDB.

Javascript “javascript” 13 These MongoDB data types store the JavaScript data
without a scope.

Symbol “symbol” 14 These MongoDB data types similar to the string data
type.

Javascript with scope “javascriptwithScop” 15 These MongoDB data types store JavaScript data
with a scope.

Integer “int” 16 to 18 It is used store numerical value.

Timestamp “timestamp” 10 This data type is used to store a timestamp.

Min key “minkey” 255 Min key compares the value of the lowest BSON
element.

Max key “maxkey” 127 Max key compares the value against the highest
BSON element.

Question 23: Explain Operator In MongoDB.

Answer:

- Operators are symbols that used to perform operations on documents.


- MongoDB provides various types of operators:
1. COMPARISION OPERATOR:
- This operators are used to compare the values & display document that match specified criteria.

Name Usage Syntax

$eq Matches values that are equal to a specified value. { key :{ $eq :value } }

$gt Matches values that are greater than a specified value. { key :{ $gt :value } }

$lt Matches values that are less than a specified value. { key :{ $lt :value } }

Plazma Institute Page 21


NoSQL DATABASE: MONGODB

$gte Matches values that are greater than or equal to a specified value. { key :{ $gte :value } }

$lte Matches values that are less than or equal to a specified value. { key :{ $lte :value } }

$ne Matches values that are not equal to a specified value. { key :{ $ne :value } }

$in Matches any of the values specified in array. { key :{ $in :value } }

$nin Matches none of the values specified in an array. { key :{ $nin :value } }

2. LOGICAL OPERATOR:
- This operators are used to compare the values & display document that match specified criteria.

Name Usage Syntax

$and returns all documents that match the conditions of both { $and: [ {<exp1> }, {<exp2> } , ... , {<expN } ] }
expression becomes true

$not Returns documents that do not match the query {field: {$not: [ {operator-expression> }}}
expression.

$or returns all documents that match any one or all the { $or: [ {<exp1> }, {<exp2> } , ... , {<expN } ] }
conditions of both expression becomes true

$nor returns all documents that fail to match both clauses. { $nor: [ {<exp1> }, {<exp2> } , ... , {<expN } ] }

3. ELEMENT QUERY OPERATOR:


- There are two operators are used as element query operator:
1. $exists
- Syntax: { field: { $exists: } }
- This operator matches the documents that contain the field, including documents where the field value is null.
- Pass either true or false as a Boolean value.
- EXAMPLE:
>db.stud.find({rlno :{$exists : true, $in: [2,5]}})
- Above example check that whether rollno field is available if available then it will shows document of rollno 2 & 5
2. $type
- Syntax: { field: { $type: } }
- This operator returns the data type of value which is stored inside field.
- As we know than MongoDB stores unstructured data & data type are not predefined.
- Sometime it is necessary to know the type of value then $type will be used.
- In syntax BSON type can be double, int, decimal, long, string, array, date, time, null, object etc.
- EXAMPLE:
>db.stud.find({rlno :{$type : “string”}})
- Above example display all record in which we entered string value in rollno field.
4. ARRAY QUERY OPERATOR:
- There are two operators are used as element query operator:
1. $all

Plazma Institute Page 22


NoSQL DATABASE: MONGODB
- Syntax: { <field>: { $all: [<value1>,<value2>... ] } }
- The $all operator selects the documents where the value of a field is an array that contains all the specified
elements.
- The elements might be any order.
- EXAMPLE:
>use skills
> db.createCollection(“sdata”)
>db.sdata.insert( [{ "Name" : "Balaji", "skills" : [ "Dancing", "Cooking", "Singing" ] },
{ "Name" : "Ramesh", "skills" : [ "Cooking", "Singing" ] },
{ "Name" : "Suresh", "skills" : [ "Dancing", "Singing" ] }])
>db.s.find({skills:{$all:["Cooking","Dancing"]}})
2. $elemMatch
- Syntax: {<field>: {$elemmatch: {<query1>,<query2> , … } } }
- This operator matches documents that contain an array field with at least one element that matches all the
specified query criteria.
- EXAMPLE:
>use user
>db.udata.find({hobbis:{$elemMatch:{nm:"sports",score:{$gte:10}}}})
3. $size:
- Syntax: {<field> : { $size:<element> } }
- It’s an array operator that Counts and returns the total the number of items in an array .
- The $size operator used to display the documents according to elements.
- EXAMPLE:
>use skills
> db.createCollection(“sdata”)
>db.sdata.insert( [{ "Name" : "Balaji", "skills" : [ "Dancing", "Cooking", "Singing" ] },
{ "Name" : "Ramesh", "skills" : [ "Cooking", "Singing" ] },
{ "Name" : "Suresh", "skills" : [ "Dancing", "Singing" ] }])
>db.s.find({skills:{$size:2}})

Question 24: What Is Query Modification? Explain Commands

Answer:

- In Mongo DB we got query modifiers such as the 'limit' and 'Orders' clause to provide more flexibility when
executing queries.
- This modifier allows users to perform external functionality to retrieve data.
- MongoDB provides three modifiers:
1. Limit()
- Syntax: db.collection_name.find().limit(number_of_documents)
- Limit () provides the limitations of documents to be displayed in MongoDB.
- This method specifies that how many number of documents that you want to display in output.
- Using limit() method to limit the documents in the result
- It is used with find () command.
- In syntax Number of documents specifies number of document to be display as an argument of limit ().
- EXAMPLE:
>db.stud.find().limit(3).pretty()

Plazma Institute Page 23


NoSQL DATABASE: MONGODB
>db.stud.find({rlno: {$gt:3}}).limit(2).pretty()
2. Skip()
- Syntax: db.collection_name.find().skip(number_of_documents)
- Skip () methods provides a facility to skip the documents from total documents.
- This method skips the given number of documents in the Query result.
- You can also used it with limit() Number of documents specify number of document to be skip.
- EXAMPLE:
>db.stud.find().skip(3).pretty()
>db.stud.find({rlno: {$gt:3}}).limit(5).skip(2).pretty()
3. Sort()
- Syntax: db.collection_name.find().sort( {key: value : [-1/1]})
- Sort () methods used to arrange document either in ascending or descending order.
- When we want to display document that arrange in specific order than sort () will be used.
- This method contain 2 parameters
- 1 ➔ used 1 for ascending order
- -1➔ used -1 for descending order

Question 25: What Is Index? How To Create Index In MongoDB.

Answer:

- Indexing is used to increase performance.


- When your database is too large & has lots of documents inside it; it is difficult for MongoDB to search
document from it.
- To retrieve data MongoDB examine each document according to search criteria.
- These make speed of execution fall down.
- To improve execution of query index will be used.

CREATE INDEX

 ensureIndex():
- syntax: db.collection_name.ensureIndex({key : 1 })
- This command used to create index in MongoDB.
- Specify a fieldname on which you want to create index as a key.
- You can create index on one or field in MongoDB.
- Use 1 to arrange index field in ascending order & -1 for descending order.
- EXAMPLE:
>db.m.ensureIndex({no:1})

 createIndex():
- syntax: db.collection_name.createIndex({key : 1 })
- This command used to create index in MongoDB.
- It works similar to ensureIndex command.
- You can create index on one or field in MongoDB.
- Use 1 to arrange index field in ascending order & -1 for descending order.
- EXAMPLE:
>db.m.createIndex({no:1})

Plazma Institute Page 24


NoSQL DATABASE: MONGODB
HOW / DISPLAY INDEXES

- getIndexes():
- syntax: db.collection_name.getIndexes()
- This command used to display index generated by users in MongoDB.
- EXAMPLE:
>db.stud.ensureIndex({per:1})
>db.stud.getIndexes()

REMOVE INDEXES

- dropIndex():
- syntax: db.collection_name.dropIndex({key:1})
- This command used to remove index generated by users in MongoDB.
- EXAMPLE: >db.stud.dropIndex({per:1})

SHOW EXECUTION STATUS

- Execute ()
- By using execute () method we can show execution states.
- To show how many documents are examine by MongoDB to find any document use executeStatus()
- EXAMPLE:
- Want to display all documents where per > 50 & see how many documents examine by MongoDB to perform this
query.
>db.stud.ensureIndex({per:{:$gt:50}}). Explain (“executionStats”)

Question 26: How to Manage Relationship between Documents In MongoDB.

Answer:

- Relationship means connect documents logically.


- MongoDB does not provide a relationship concept as we define in RDBMS but it provide different model to
establish relationship between documents.
- During designing of data model always consider the application usage of data such as queries, update and
processing of data as well as structure of data itself.
- There are two tools in MongoDB that represents the relationship between data.
1. EMBEDDED DOCUMENTS:
- It is also known as De-Normalized data.
- This type of data model provides single document structure.
- In this, one collection will be embedded into another collection.
- It means that you can store related information in same document in the form of embedded documents.
- Main advantage of embedded document is that it allows application to retrieve and manipulate related data
within a single query.
- So the execution of query becomes fast.
- Embedded documents model contain two types of relationship
1. one to one relationship
2. One to many relationships

2. REFERENCES DOCUMENTS:

Plazma Institute Page 25


NoSQL DATABASE: MONGODB
- It is also known as Normalized data model.
- In this approach, the documents are maintained separately.
- We can create relationship between data stored in different collections by using reference Id.
- MongoDB or application can use these references Id to retrieve the related data.
- Embedded documents contain duplicate data but references don’t contain duplicate data.
- References implement only one relationship: one To many relationship.

Question 27: Explain: Http Session

Answer:

 Establishing a Connection Section


- In client-server protocols, it is the client which establishes the connection.
- Opening a connection in HTTP means initiating a connection in the underlying transport layer TCP.
- With TCP the default port is 80.
 Sending a client request section
- Once the connection is established, the user-agent can send the request A client request consists of text
directives divided into three blocks:
- The first line contains a request method followed by its parameters:
1. the path of the document
2. the HTTP protocol version
- The second line represent an HTTP header, giving the server information about what type of data is appropriate
(e.g., what language, what MIME types)

Question 28: Explain Session In Php

Answer:

- Session support in PHP consists of a way to preserve certain data across subsequent accesses.
- A visitor accessing your web site is assigned a unique id, the so-called session id.
Session_start() Start session

Session_id () Generate unique id for user.

Session_destroy () It destroy session

Session_name () User can get or set the name of session

Sesssion_status () Return status information about session

session_get_cookie_params Get the session cookie parameters

Session_unset Free all session variables

Session_write_close Write session data & end session

Session_reset Re-initialize session array with original values

- Start a PHP Session


- EXAMPLE:

Plazma Institute Page 26


NoSQL DATABASE: MONGODB
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>

Question 29: Explain Session Manager in MongoDB

Answer:

- Session Management implements the exchange mechanism between the user and the application.
- The session id is used for remember the user in application or in web application.
- There are many different frameworks which provide their own session management features like J2EE, Asp.Net,
and PHP etc.
- There are different frameworks available for session management which have its own advantages and
disadvantages.
- MongoDB Atlas provides all the features that have made the monogodb as NO SQL database.
- It provides data model flexibility, scalability & combine them with optimizations
- Session Manager is a simple powerful extension that makes it quick and easy to save, update, remove, and
restore sets of tabs in any browser.
- In PHP session management will be performed by different functions.
- A session is a way to store information (in variables) to be used across multiple pages.
- Session variables remains until the user closes the browser.
- A session is started with the session_start() function.
- Session variables are set with the PHP global variable: $_SESSION.
- The session_set_save_handler() function allows us to define our own functions for storing and retrieving session
data.

Question 30: Explain Count In MongoDB?

Answer:

- Count is method that used to count elements.


- In MongoDB there is various use of count.
- It can work with any other methods or individual also; By using count
1. We can count total number or documents.
2. We can count documents that match specific query criteria
3. We can count documents than match multiple query criteria
4. We can use count with find() to count documents that match query criteria
5. We can count the document that you skip or limit during the condition

Plazma Institute Page 27


NoSQL DATABASE: MONGODB
6. We can used is as aggregation command
 COUNT TOTAL NUMBER OF DOCUMENTS
- Syntax:
db.collection_name.count()
- The db.collection.count() method is used to return the count of documents.
- EXAMPLE:
> db.stud.count()
 COUNT WITH FIND() WITH SINGLE QUERY CONDITION
- Syntax: db.collection_name.find().count()
- The db.collection.find().count() method can also used to count documents that match specified criteria.
- In syntax is specify the selection criteria for counting documents.
- We can also produce same output with db.collection.count()
- EXAMPLE:
> db.stud.find({streem:”mba”}).count()
 COUNT WITH SKIP() or LIMIT()
- Skip () used to skip number of documents & return remaining documents while limit () display specific number
of documents.
- We need to specify how many documents are skip in output by MongoDB as an argument of skip() and limit().
- To get number of document after skip() we have to specify ‘true’ parameter as an argument of count()
- EXAMPLE:
> db.stud.find({streem:”mba”}).limit(3).count(true)
 COUNT WITH AGGREGATION:
- We can use count with aggregation queries also.
- Syntax: db.collection_name.aggregation({$group: {<key>, count:(criteria)}})
- When we want to count documents of group of field.
- EXAMPLE: COUNT ALL DOCUMENT
> db.stud.aggregate([]).count()
> db.stud.aggregate([{$group:{_id:"$class",count:{$sum:1}}}])

Question 31: Explain Distinct Method Of MongoDB.

Answer:

- Distinct method is used to retrieve unique values from documents.


- This method is similar to distinct parameter of SQL that used with SELECT clause to retrieve unique records.
- To retrieve non repeated values form document we can use distinct method.
- We can also use distinct method to retrieve unique values from embedded documents also
- Syntax: db.collection_name.distinct({field , query})
- Example:
- RETRIEVE UNIQUE VALUES FROM CLASS FIELD
> db.stud.distinct(“class”)

Question 32: What Aggregation In MongoDB?

Answer:

- Aggregation basically groups the data from multiple documents and returns one combined result.
- When we want to perform operation in group of field then aggregation will be use.

Plazma Institute Page 28


NoSQL DATABASE: MONGODB
- It is similar to group by clause of SQL.
- Aggregation can be performed on single or more group of fields.
- MongoDB provides Aggregate () to perform such operations which is aggregation pipelines.
- Syntax: db.collection_name.aggregate(Aggregate_operation)
 AGGREGATION PIPELINES:
- MongoDB's aggregation framework is based on the concept of data processing in a sequence.
- Aggregation pipeline is similar to the UNIX word pipelines.

 TAGES OF AGGREGATION PIPELINE

- Various stages in pipeline are:


1. $project – select, reshape data
2. $match – filter data
3. $group – aggregate data
4. $sort – sorts data
5. $skip – skips data
6. $limit – limit data
7. $unwind – normalizes data
- Each stage always begin with $

Question 33: Explain $Group or Grouping in MongoDB.

Answer:

- Grouping is method that is used to find out aggregate result.


- When we want to perform operation on group of field then $group will be used.
- It is similar to group by option of SQL.
- It is used to produced aggregate result based on $group key
- Syntax: db.collection_name.aggregate( {$group: {_id: <expression>,<field>: {accumulator : <expression }}})
- In syntax accumulators specify functions that you want to produced aggregate result
- Here is a list of accumulators that we can used with $group.
accumulator Description

$Sum Sum or count total number of documents in aggregation

$avg It calculates the average values from all the documents in the collection.

$min It is used to find out minimum values from all documents

Plazma Institute Page 29


NoSQL DATABASE: MONGODB

$max It is used to find out maximum values from all documents

$addToSet It is used to Insert values to an array but no duplicates in the resulting document.

$push Insert values to an array in the resulting document.

$first Return the first document from the source document that match group field

$last Return the last document from the source document that match group field.

Question 34: Explain String Aggregation Operator Of MongoDB?

Answer:

- String expression are use to perform operation on textual data stored in field.
- We can use string expression with $project stage of aggregation pipeline.
- Some string aggregation operators are:
1. $concat
- This operator is used to merge two or more string
- Syntax: { $concat: [<expression1>,<expression2> , ... ] }
2. $substr
- This operator is used to retrieve string from existing string.
- When we want to retrieve some specific part of string then $substr will be used.
- Syntax: { $substr: [ “expression”,<start> <end>, ] }
3. $toUpper
- $toUpper operator used to convert fields values in uppercase & $lower is used to convert fields value in lower
vase
- Syntax: { $toUpper| $toLower:<”expression”> }
4. $toLower
- This operator is used to find out length of string in bytes
- Syntax: { $strLenBytes:<expression> }
5. $strLenBytes
- This operator is used to compare two string & return a number either 1 , 0 or -1
- if string1 > string2 then return 1
- if string1 < string 2 then return -1
- if string1 and string 2 are equal then return 0
- Syntax: { $strcasecmp:[$str1,$str2] }
6. $strcasecmp
- This operator is used to split a string according to specified delimiter
- Delimiter is any character or symbol
- Syntax: { $split: [<string expression>,<delimiter> ] }

Question 35: Explain Arithmetic Aggregation Operator Of MongoDB?

Answer:

- Arithmetic expressions perform mathematic operations on numberic values

Plazma Institute Page 30


NoSQL DATABASE: MONGODB
- We can use following arithmetic aggregation operators in MongoDB
1. $abs
- This operator is used to convert negative number into positive.
- If the fields value is null then this function return null
- Syntax: { $abs: <number>}
2. $sqrt
- This operator is finding out square root of positive number & return answer in double datatype.
- Syntax: { $sqrt:<number> }
3. $floor
- This operator Returns the lowest integer less than or equal to the specified number.
- Syntax: { $floor:<number> }
4. $ceil
- This operator Returns the smallest integer greater than or equal to the specified number.
- Syntax: { $ceil:<number> }
5. $trunc
- This operator return integer portion from fractional numbers
- Syntax: { $trunc:<number> }
6. $add
- This operator is used to add two numbers.
- Syntax: { $add:[<number1> ,<number2>]}
7. $subtract
- This operator is used to subtract two numbers.
- Syntax: { $subtract:[<number1> ,<number2>]}
8. $multiply
- This operator is used to multiply two numbers.
- Syntax: { $multiply:[<number1> ,<number2>]}
9. $divide
- This operator is used to divide two numbers.
- Syntax: { $divide:[<number1> ,<number2>]}
10. $mod
- This operator is used to divide two numbers & return reminder.
- Syntax: { $mod:[<number1> ,<number2>]}
11. $pow
- This operator is used to return a number that specified a raise to number of expression.
- Syntax: { $pow:[<expression>,<exponent>]}

Question 36: Explain Map Reducing

Answer:

- Map-Reduce are a data processing paradigm.


- Map-Reduce provide mechanism that focus on large volumes of data into useful aggregated results.
- MongoDB uses Map-Reduce command for map and reduce operations.
- Map-Reduce is used for processing large data sets.
- Map-Reduce command takes two functions as an input
1. Map function
- It is also called mapper because it collects and arranges data.

Plazma Institute Page 31


NoSQL DATABASE: MONGODB
- This function start collects data and build map.
- It required key and values with emit()
- This function groups data and stores value in an array
2. Reduce function
- It is also called reducer because it eliminates extra data to generate aggregate results.
- Reduce function is used to process on data and generate aggregate result.
 mapReduce()
- mapReduce() is used to perform map reduce task in MongoDB.

- Syntax:
db.collection.mapReduce(
function() {emit(key,value);}, //map function
function(key,values) {return reduceFunction},
{
out: collection,
query: document,
sort: document,
limit: number
})

Question 37: Explain Extracting Analysis Of Data With Map - Reduce.

Answer:

- Analzing data is the process where we filter out result from external data & produce a proper result.
- Any business contain large amount of data then MongoDB provides a solution that fulfill the needs of users.
- Monogdb provides an ideal operational database that provides high performance, storage & retrieval of large
scale data.
- There are three categories to extract analysing data
1. Using aggregation
2. Using Map-Reduce
3. Using shared collections
 Aggregation / aggregation pipeline
- The aggregation pipeline is a framework for data aggregation which is formed on the concept of data processing
pipelines.
- Documents enter a multi-stage pipeline that transforms the documents into aggregated results.
- There are various stage of aggregation pipeline like $project, $match, $group, $sort , $limit and $unwind
 Using map reducing
- Map-reduce is a data processing paradigm for condensing large volumes of data into useful aggregated results.
- Map reduce performed by two functions: o Mapper o reducer
- In map reduce MongoDB extract all from database using Map function & then merge the data which has same
key.
- The map function emits key-value pairs.
- Then it reduce the external data by using reduce function.
 Shared collections
- Sharding is a method for distributing data across multiple machines.
- MongoDB uses sharding to support deployments with very large data sets and high throughput operations.

Plazma Institute Page 32


NoSQL DATABASE: MONGODB
- Database systems with large data sets or high throughput applications can challenge the capacity of a single
server.
- There are two methods for addressing system growth: vertical and horizontal scaling.
- MongoDB supports horizontal scaling through sharding.

Question 38: Explain Logging.

Answer:

- MongoDB provides a mechanism to send the data in logfile in a particular location.


- Any RDBMS maintain logfile to record the query processing data so that during system crash we can find out the
reason.
 --logpath
- By default MongoDB send its log to stdout directory.
- Most init scripts use the --logpath option to send logs to a file.
- If you have multiple MongoDB instances on a single machine thenlogs are stored in separate files.
- This will create the file if it does not exist, assuming you have write permissions to the directory.
 --logLevel
- MongoDB provides db.setLogLevel() to set loglevel in a single server system
Log Level Description

0 No logging

1 Logs for slow queries

2 Logs for all queries

3,4,5 According to different task maintain log


- Example:
>db.setlogLevel(3)
 --logMessage
- MongoDB includes the severity level and the component for each log message when output to the console or a
logfile.
- logMessage conatin following format:
- <timestamp> <severity> <component> [<context>] <message>
- Where
1. timestamp is iso8601-local
2. security is specify security levels

Log Level Description

F Fatal

E Error

Plazma Institute Page 33


NoSQL DATABASE: MONGODB

W Warning

I Informational

D[1-5] Debug have level between 1 to 5

3. components specify functional categorization of the messages.

Question 39: Explain Real Time Analyzing Data In MongoDB.

Answer:

- MongoDB provides facility to analyze data at any place with fast real time & an less money.
- Most of companies use analytics on real time so analytics must be support simple and faster query retrieval.
- Companies use many applications for complex and long running analysis of data but these applications have
slower response time and lower requirements.
- Real time analytics is hard for Relational databases that aren’t capable of handling unstructured and semi-
structured data.
- Batch processes are the right approach for some jobs.
- MongoDB can incorporate any kind of data – any structure, any format, any source – no matter how often it
changes.
- MongoDB is built to scale out on commodity hardware.
- MongoDB can analyze data of any structure directly within the database.
- MongoDB is used for realtime analytics data in an area such as financial service, government services, high tech
& retail sevices.
1. Financial Service:
- It includes area like risk analytics & reports, Reference Data Management, Market Data Management
2. Government:
- Many government service providers use MongoDB including City municipal services, National defense and
intelligence agencies, Civilian agencies in healthcare, finance, energy, and more.
3. High tech Service:
- In the most competitive industry of all, tech innovators are using MongoDB to do things they could never do
before. Faster. With Less Money.

Question 40: What Is Gridfs?

Answer:

- GridFS is the file system which is use to storing and retrieving files.
- GridFS is a way through which we can store and retrieve large files such as audio files, video files, images, etc. in
MongoDB.
- GridFS is a file system of MongoDB but the data of files are stored within MongoDB collections.
- MongoDB GridFS is used to store and retrieve files that go above the BSON document size limit of 16 MB.
- GridFS divides the file into small parts called as chunks.
- Each chunk is stored as a separate document.
- The default size for a chunk is 255kb for all chunks except the last one, which can be as large as necessary.
- MongoDB GridFS uses two collections to store files.
- One is used to store the file chunks and the second one to store file metadata.

Plazma Institute Page 34


NoSQL DATABASE: MONGODB
- When we query GridFS for a file, the driver reassemble the chunks.
- With MongoDB GridFS, we can perform a range of queries on files stored.
- GridFS is also for storing files that you want to access without loading the entire file into memory.
 GridFS Storage Fashion
- MongoDB, GridFS uses two collections to store files; One is used to store the file chunks and the second one to
store file metadata.

- Collections are:
1. File collection fs.files
2. Chunks collectionfs.chunks
 The files collection
- This collection is used to store only metadata information of file.
- It represents information about file along with id, length, name & Metadata.
- Use db.fs.files.find() to access files collections.
 The chunks collection
- Chunk is small part of file. Chunks collection stores all documents in small parts.
- Default size of each chunk is 255kb so it is possible that one file will divide into multiple chunks.
- db.fs.chunks.find() used to display chunks detail.
 ADVANTAGES GRIDFS:
- Allows you to storing large number of files.
- Support many types of format in storing files.
- Provides metadata information of every file
 DISADVANTAGES OF GRIDFS:
- Not allowed to update the content of entire file.
- GridFS does not provide a way to do an atomic update of a file.
- The file serving performance will be slower than natively serving the file from your web server and file system.

Question 41: Explain Mongofiles Command.

Answer:

- mongoFiles is a command which is used to store, delete , update & display files stored in GridFS objects.
- Using this command GridFS can store any type of file.
- This command serves as an interface between objects stored in your file system and GridFS.
- SYNTAX:
Mongofiles <options> <commands> <filename>
 Options:
- Specify option to connect with MongoDB database. You can use following options:

--help It provides help of mongofiles command

--port It Provides a port number of server.

--host It provides host number.By default mongofiles attempts to connect to a MongoDB


process running on the localhost port number 27017

--version It provides the mongofiles release number.

Plazma Institute Page 35


NoSQL DATABASE: MONGODB

--username It provides Specify username for authentication

--password It provides Specify username for authentication

--local It Specifies the local filesystem name of a file for put and get operations.

--replace Alters the behavior of mongofiles put to replace existing GridFS objects with the
specified local file

--db or -d Specify name of database

 Commands:
- Specify command to perform operations. We can use commands like:

Put <filename> Copy the specified file from the local file system into GridFS storage.

Get <filename> Copy the specified file from GridFS storage to the local file system.

List Lists the files in the GridFS store.

Delete Delete the specified file from GridFS storage.


<filename>

Search <string Lists the files in the GridFS store with names that match any portion of <string>

Question 42: How To Storing, Serving & Reading File With Gridfs?

Answer:

- Mongofiles command is used to perform different operation with grideFS like storing and retrieving files from
local system to grideFS.
- To use GridFS we have to open separate commander window & execute mongofiles command.
- Mongofiles include following commands.
 list
- SYNTAX: mongofiles –d <dbname> list
- It will display the file list of mongo connected to local host.
- It also display the size of file.
- EXAMPLE:
mongofiles –d STUD list
 Put
- SYNTAX: mongofiles –d <dbname> put <filename>
- If you want to add or store the file into gridefs then put command is used.
- You can store different types of files like text files, image file, mp3, etc…
- EXAMPLE:
mongofiles –d STUD put myfile.txt
 get
- SYNTAX: mongofiles –d <dbname> get <filename>
- The get command is used to retrieve the file from grideFS to the local system
Plazma Institute Page 36
NoSQL DATABASE: MONGODB
- This command can't display content of file directly.
- EXAMPLE:
mongofiles –d STUD get myfile.txt
 delete
- SYNTAX: mongofiles -d <dbname> delete<filename>
- If you want to delete a file of grideFS then you have to use the delete command in the mongofiles command
prompt.
- EXAMPLE:
mongofiles –d STUD delete myfile.txt
 Search
- SYNTAX: mongofiles -d <dbname> search <string>
- Lists the files in the GridFS store with names that match any portion of.
- EXAMPLE:
mongofiles –d STUD search xyz

Question 43: Write A Detail Note On Replication In MongoDB.

Answer:

- Replication is a process or method to synchronize the data across multiple servers.


- The replication process always protects a MongoDB database from the loss of a server due to hardware failure
or any other reason.
- In MongoDB replication is performed by using replicaset.
- In MongoDB, a replica set contains two or more MongoDB server.
 Replica set
- MongoDB peform replication using replica set.
- A replica set contains two types of MongoDB instances.
- Primary Instance: The primary instance receives all write operations.
- Secondary Instance: The secondary instance applies operations from the primary so that they have the same
data set.
- In a replica set only one primary instance is allowed and all other instances are secondary instances

- Above figure shows 3 members replica set that contain 1 primary instance and 2 secondary instances.
- When a primary instance receives a write operation from a user then it updates its oplog (operation log).

Plazma Institute Page 37


NoSQL DATABASE: MONGODB

 ADVANTAGES:
- We can keep the data safe.
- Ensure the high availability of data
- We can take care of disaster recovery
- No downtimes required for maintenance
- Replica set is always transparent to the application.

Question 44: How to Deploy Replication in MongoDB.

Answer:

- Perform following steps to deploy replication.


Step-1
- Create 3 directory in data directory : i created mydata1, mydata2, mydata3
Step-2
- Start mongod instance in new cmd & peform following command:
- This command create replicaset r (r is name of my replicaset)
Step-3
- start mongod instance in new cmd & peform following command to start secondary server 1:
Step-4
- start mongod instance in new cmd & peform following command to start secondary server 2 & same for
secondary server 3:
Step-5
- now start a new mongo instance in new cmd & configure replication
Step-6
- Open mongo from port 27017 & set configuration
>mongo –port 27017
- Now we add the remaining two mongod instances in the replica set using the “rs.add()” method
>rs.add(“MEGHNA-PC:27018”);
>rs.add(“MEGHNA-PC:27019”)
- To view status use rs.status()
Step-7
- now create a new database & insert record which can be access from secondary port.
Step-8
- Now connect with port 27018
- Place rs.slaveok ()
- & then you can see replica copy of your database

Question 45: What Is Sharding? How to Perform Sharding.

Answer:

- Sharding is the process of storing data records across multiple machines.


- As the size of the data increases, a single machine can’t store all the data and is unable to provide an acceptable
read and write throughput.

Plazma Institute Page 38


NoSQL DATABASE: MONGODB
- To overcome this issue, database systems have two basic approaches:
1. Vertical scaling
2. Horizontal scaling
- MongoDB perform horizontal scaling by using sharding
- Shard divides the data set and distributes the data over multiple servers.
- These multiple server is known as shards.
- Each shard is an independent database and collectively, the shards make up a single logical database.
- Sharding distributes data over multiple shards so it reduces the number of operations for each shard.
 A sharded cluster contain 3 components. The following describes these components.
1. Shards:
- Shards are used to store the data.
- Each shard contains a replica set. Shards provide high data availability and data consistency.
2. Config Servers:
- Config servers are used to store the metadata of clusters.
- A sharded cluster has exactly 3 config servers.
3. Query Routers:
- Query routers are the Mongo's instance that interfaces with the client applications and does the operations of
the appropriate shards.

Question 46: Write A Note On Optimization In MongoDB.

Answer:

- Optimization is an act or process to make something is fully perfect.


- It is a simple method to perform a design or a system as effective as possible.
- There are many factors which affects the database performance and responsiveness.
- Optimization is used to analyze the db its performance, indexing, query structure, data model, application
design, operational factor, architecture, system configuration etc.
- Optimization is used with mongo db including different types of category like.
1. Analyzing
2. To check mongo db performance
3. Check performance of current operation
4. Optimize query performance
5. Optimize different design notes
 Optimize query performance
- The optimization is very use full for faster processing of multiple queries or a query on multiple fields.
- It can allow creating the index for searching operations

Question 47: Explain Database Administration with MongoDB.

Answer:

- Administration include ongoing & maintenance of MongoDB instance & its deployment.
- Administration is used to keep track & control on database & its resources.
- The database administration provides the operation and maintains of MongoDB instance.

 Administration:-

Plazma Institute Page 39


NoSQL DATABASE: MONGODB
- Every database management system support the administration of database.
- It means that hear all the data and different use are managed property.
- The administration task includes:
1. Deployment of the system
2. Starting & stopping database
3. User creation & assign privileges.
4. Backup & recovery.
5. Logging
6. Replication
Deployment:-
- It is a one type of installation or implementation process where user allows writing different script code for your
data and database.
 Starting MongoDB server:-
- Hear you have to start the server first with mongod.exe file.
- There are different command line option used with mongod commands:
--dbpath
- Each mongo instance required one directory called data directory to store data.
--port
- Specify the port number for server to listen request. The default port of MongoDB is 27017.
--fork
- If you start mongo first time, it take few minutes to allocate database file.
--directoryperdb
- This puts each database in its own directory.
--config
- Use this option if you are using file based configuration.
 Stopping MongoDB server:-
- If you want to stop MongoDB server then you have to use the shutdown command called db.shutdownserver()

Plazma Institute Page 40

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy