You are on page 1of 50

BPM(1030106407) COMPUTERENGINEERING.

Practical – 7

AIM: - How to Download, Install & Run MongoDB Server in Windows OS.
(5.0.6 current version)

How to Download & Install MongoDB on Windows


The following steps can be used to download and install MongoDB on Windows 10

Step 1) Download MongoDB Community Server

Go to link and Download MongoDB Community Server. We will install the 64-bit


version for Windows.

Step 2) Click on Setup


DHRUV SOJITRA
(20270106160) Page 1
BPM(1030106407) COMPUTERENGINEERING.

Once download is complete open the msi file.

Step 3) Click on next

Step 4) Accept the End-User License Agreement

DHRUV SOJITRA
(20270106160) Page 2
BPM(1030106407) COMPUTERENGINEERING.
1. Accept the End-User License Agreement
2. Click Next

Step 5) Click on the “complete” button

DHRUV SOJITRA
(20270106160) Page 3
BPM(1030106407) COMPUTERENGINEERING.
Click on the “complete” button to install all of the components. The custom option can
be used to install selective components or if you want to change the location of the
installation.

Step 6) Service Configuration

DHRUV SOJITRA
(20270106160) Page 4
BPM(1030106407) COMPUTERENGINEERING.
1. Select “Run service as Network Service user”. make a note of the data directory,
we’ll need this later.
2. Click Next

Step 7) Click on next

Step 8) Click on install

DHRUV SOJITRA
(20270106160) Page 5
BPM(1030106407) COMPUTERENGINEERING.

DHRUV SOJITRA
(20270106160) Page 6
BPM(1030106407) COMPUTERENGINEERING.

Step 9) Click on Finish

DHRUV SOJITRA
(20270106160) Page 7
BPM(1030106407) COMPUTERENGINEERING.
Step 10) Click on next

Step 11) Click on start using compass

DHRUV SOJITRA
(20270106160) Page 8
BPM(1030106407) COMPUTERENGINEERING.

Configuration: -
Step 1: - Go to the local disk C and get into Program Files.

There you’ll find a folder named “MongoDB “.

Step 2: - Open it and you’ll find a folder named “bin” i.e., binaries folder.

DHRUV SOJITRA
(20270106160) Page 9
BPM(1030106407) COMPUTERENGINEERING.

Step 3: - You will have 5 to 7 files in it. Copy the path, as given in the snippet path i.e.,
C:\Program Files\MongoDB\Server\5.0\bin

Step 4: - Open Settings and search “Edit environment variable”.


The options given below would pop up in front of you:
1. Edit environment variable of your account

DHRUV SOJITRA
(20270106160) Page 10
BPM(1030106407) COMPUTERENGINEERING.

Step 5: - click on path and add a new file

DHRUV SOJITRA
(20270106160) Page 11
BPM(1030106407) COMPUTERENGINEERING.
Step 6: - paste the path of bin folder here. Click on ok

 Step 7: - Open Command prompts and type “mongo-version” to start the service.
You can see a mongo version 5.0.6 here

DHRUV SOJITRA
(20270106160) Page 12
BPM(1030106407) COMPUTERENGINEERING.

HOW TO CONNECT A MONGO DB TO LOCAL


HOST

Step 1: - click on connect button to connect the local host

Step 2: - Now u will connect to local host

DHRUV SOJITRA
(20270106160) Page 13
BPM(1030106407) COMPUTERENGINEERING.

HOW TO CREATE A DATABASE IN MONGODB

Step 1: - click on create database to create new user.

Step 2: - Given a Database name and collection name as shown in the fig. and then
click on create database

DHRUV SOJITRA
(20270106160) Page 14
BPM(1030106407) COMPUTERENGINEERING.

Step 3: - Now you can see your created database here.

DHRUV SOJITRA
(20270106160) Page 15
BPM(1030106407) COMPUTERENGINEERING.

Practical – 8

AIM: - How to Create Database, collection and insert documents & Drop
database In MongoDB.

How to create a Database


Syntax: -

use Database name

for ex: - use bmu

bmu is database name here but database is not show because you cannot create a table in database so you
can create a table in database.

How to create a Table in Database(collection)

Syntax: -
db.createCollection("Table Name")

for ex: - db.createCollection("student data")

you can see Database by using command: - show dbs

DHRUV SOJITRA
(20270106160) Page 16
BPM(1030106407) COMPUTERENGINEERING.
How to insert a data in table (insert documents)

Syntax: -

db.TableName. insert (
{ user_name:"mark",
post_text:"This is a sample post",
post_privacy:"public",
post_likes_count:0
}
)

EXAMPLE:-

How to drop a table


Syntax: -

db.Table Name.drop()

EXAMPLE:-

DHRUV SOJITRA
(20270106160) Page 17
BPM(1030106407) COMPUTERENGINEERING.

How to drop a Database


Syntax: -

db.dropDatabase()

for ex: - db.dropDatabase()

DHRUV SOJITRA
(20270106160) Page 18
BPM(1030106407) COMPUTERENGINEERING.

Practical – 9

AIM:- How to use Data Types in MongoDB, Read |Query Documents from
Collection in MongoDB

Data Types in MONGODB

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 − timestamp. This can be handy for recording when a document has been
modified or added.
● Object − This data type is used for embedded documents.
● Null − This type is used to store a Null value

Mongo DB Query Document Using Find () Method

The find() Method


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

Syntax

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

EXAMPLE:-

DHRUV SOJITRA
(20270106160) Page 19
BPM(1030106407) COMPUTERENGINEERING.

The pretty() Method

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

Syntax
db.COLLECTION_NAME.find().pretty()

EXAMPLE:-

DHRUV SOJITRA
(20270106160) Page 20
BPM(1030106407) COMPUTERENGINEERING.
The findOne() method

Apart from the find() method, there is findOne() method, that returns only one document.

Syntax
db.COLLECTIONNAME.findOne()

EXAMPLE:-

Update document in a collection

MongoDB findOneAndUpdate() method


The findOneAndUpdate() method updates the values in the existing document.

Syntax

db.COLLECTION_NAME.findOneAndUpdate(SELECTIOIN_CRITERIA, UPDATED_DATA)

DHRUV SOJITRA
(20270106160) Page 21
BPM(1030106407) COMPUTERENGINEERING.
EXAMPLE:-

For find and update: -

db.empdetails.findOneAndUpdate(
{First_Name: 'Sagar'},
{ $set: { e_mail: 'sagar_rudra432@gmail.com'}}
)

Following example updates email values of the document with name 'Sagar'.

DHRUV SOJITRA
(20270106160) Page 22
BPM(1030106407) COMPUTERENGINEERING.

Practical: 10
Aim: How to use Projection, Query Operators, Query | Show Documents
using OR & AND Conditions in MongoDB.

The MongoDB query operator includes comparison, logical, element, evaluation, Geospatial, array, bitwise,
and comment operators.

MongoDB Comparison Operators


$eq

The $eq specifies the equality condition. It matches documents where the value of a field equals the
specified value.

Syntax:

1. { <field> : { $eq: <value> } }  

Example:

1. db.books.find ( { price: { $eq: 300 } } )  

The above example queries the books collection to select all documents where the value of the price filed
equals 300.

$gt

The $gt chooses a document where the value of the field is greater than the specified value.

Syntax:

1. { field: { $gt: value } }  

Example:

1. db.books.find ( { price: { $gt: 200 } } )  

$gte

The $gte choose the documents where the field value is greater than or equal to a specified value.

Syntax:

1. { field: { $gte: value } }  

DHRUV SOJITRA
(20270106160) Page 23
BPM(1030106407) COMPUTERENGINEERING.
Example:

1. db.books.find ( { price: { $gte: 250 } } )   

$in

The $in operator choose the documents where the value of a field equals any value in the specified array.

Syntax:

1. { filed: { $in: [ <value1>, <value2>, ……] } }  

Example:

1. db.books.find( { price: { $in: [100, 200] } } )  

$lt

The $lt operator chooses the documents where the value of the field is less than the specified value.

Syntax:

1. { field: { $lt: value } }  

Example:

1. db.books.find ( { price: { $lt: 20 } } )  

$lte

The $lte operator chooses the documents where the field value is less than or equal to a specified value.

Syntax:

1. { field: { $lte: value } }  

Example:

1. db.books.find ( { price: { $lte: 250 } } )  

$ne

The $ne operator chooses the documents where the field value is not equal to the specified value.

Syntax:

1. { <field>: { $ne: <value> } }  

Example:

DHRUV SOJITRA
(20270106160) Page 24
BPM(1030106407) COMPUTERENGINEERING.
1. db.books.find ( { price: { $ne: 500 } } )  

$nin

The $nin operator chooses the documents where the field value is not in the specified array or does not
exist.

Syntax:

1. { field : { $nin: [ <value1>, <value2>, .... ] } }  

Example:

1. db.books.find ( { price: { $nin: [ 50, 150, 200 ] } } )  

MongoDB Logical Operator


$and

The $and operator works as a logical AND operation on an array. The array should be of one or more
expressions and chooses the documents that satisfy all the expressions in the array.

Syntax:

1. { $and: [ { <exp1> }, { <exp2> }, ....]}  

Example:

1. db.books.find ( { $and: [ { price: { $ne: 500 } }, { price: { $exists: true } } ] } )  

$not

The $not operator works as a logical NOT on the specified expression and chooses the documents that are
not related to the expression.

Syntax:

1. { field: { $not: { <operator-expression> } } }  

Example:

1. db.books.find ( { price: { $not: { $gt: 200 } } } )  

$nor

The $nor operator works as logical NOR on an array of one or more query expression and chooses the
documents that fail all the query expression in the array.

Syntax:

DHRUV SOJITRA
(20270106160) Page 25
BPM(1030106407) COMPUTERENGINEERING.
1. { $nor: [ { <expression1> } , { <expresion2> } , ..... ] }  

Example:

1. db.books.find ( { $nor: [ { price: 200 }, { sale: true } ] } )  

$or

It works as a logical OR operation on an array of two or more expressions and chooses documents that
meet the expectation at least one of the expressions.

Syntax:

1. { $or: [ { <exp_1> }, { <exp_2> }, ... , { <exp_n> } ] }  

Example:

1. db.books.find ( { $or: [ { quantity: { $lt: 200 } }, { price: 500 } ] } )   

MongoDB Element Operator


$exists

The exists operator matches the documents that contain the field when Boolean is true. It also matches the
document where the field value is null.

Syntax:

1. { field: { $exists: <boolean> } }  

Example:

1. db.books.find ( { qty: { $exists: true, $nin: [ 5, 15 ] } } )  

$type

The type operator chooses documents where the value of the field is an instance of the specified BSON
type.

Syntax:

1. { field: { $type: <BSON type> } }  

Example:

1. db.books.find ( { "bookid" : { $type : 2 } } );  

MongoDB Evaluation Operator


$expr
DHRUV SOJITRA
(20270106160) Page 26
BPM(1030106407) COMPUTERENGINEERING.
The expr operator allows the use of aggregation expressions within the query language.

Syntax:

1. { $expr: { <expression> } }  

Example:

1. db.store.find( { $expr: {$gt: [ "$product" , "price" ] } } )   

$jsonSchema

It matches the documents that satisfy the specified JSON Schema.

Syntax:

1. { $jsonSchema: <JSON schema object> }  

$mod

The mod operator selects the document where the value of a field is divided by a divisor has the specified
remainder.

Syntax:

1. { field: { $mod: [ divisor, remainder ] } }  

Example:

1. db.books.find ( { qty: { $mod: [ 200, 0] } } )  

$regex

It provides regular expression abilities for pattern matching strings in queries. The MongoDB uses regular
expressions that are compatible with Perl.

Syntax:

1. { <field>: /pattern/<options> }  

Example:

1. db.books.find( { price: { $regex: /789$/ } } )  

$text

The $text operator searches a text on the content of the field, indexed with a text index.

Syntax:

DHRUV SOJITRA
(20270106160) Page 27
BPM(1030106407) COMPUTERENGINEERING.
1.              {  
2.   $text:  
3.     {  
4.       $search: <string>,  
5.       $language: <string>,  
6.       $caseSensitive: <boolean>,  
7.       $diacriticSensitive: <boolean>  
8.     }  
9. }  

Example:

1. db.books.find( { $text: { $search: "Othelo" } } )  

$where

The "where" operator is used for passing either a string containing a JavaScript expression or a full
JavaScript function to the query system.

Example:

1.                 db.books.find( { $where: function() {  
2.    return (hex_md5(this.name)== "9b53e667f30cd329dca1ec9e6a8")  
3. } } );  

MongoDB Geospatial Operator


$geoIntersects

It selects only those documents whose geospatial data intersects with the given GeoJSON object.

Syntax:

1. {  
2.   <location field>: {  
3.      $geoIntersects: {  
4.         $geometry: {  
5.            type: "<object type>" ,  
6.            coordinates: [ <coordinates> ]  
7.         }  
8.      }  
9.   }  
10. }  

Example:

1.              db.places.find(  
2. {  

DHRUV SOJITRA
(20270106160) Page 28
BPM(1030106407) COMPUTERENGINEERING.
3.   loc: {  
4.     $geoIntersects: {  
5.        $geometry: {  
6.           type: "Triangle" ,  
7.           coordinates: [  
8.             [ [ 0, 0 ], [ 3, 6 ], [ 6, 1 ] ]  
9.           ]  
10.        }  
11.     }  
12.   }  
13. }  

$geoWithin

The geoWithin operator chooses the document with geospatial data that exists entirely within a specified
shape.

Syntax:

1.            {  
2. <location field>: {  
3.    $geoWithin: {  
4.       $geometry: {  
5.          type: <"Triangle" or "Rectangle"> ,  
6.          coordinates: [ <coordinates> ]  
7.       }  
8.    }  
9. }  

$near

The near operator defines a point for which a geospatial query returns the documents from close to far.

Syntax:

1.          {  
2. <location field>: {  
3.   $near: {  
4.     $geometry: {  
5.        type: "Point" ,  
6.        coordinates: [ <longitude> , <latitude> ]  
7.     },  
8.     $maxDistance: <distance in meters>,  
9.     $minDistance: <distance in meters>  
10.   }  
11. }  

Example:

DHRUV SOJITRA
(20270106160) Page 29
BPM(1030106407) COMPUTERENGINEERING.
1.              db.places.find(  
2. {  
3.   location:  
4.     { $near :  
5.        {  
6.          $geometry: { type: "Point",  coordinates: [ -73.9667, 40.78 ] },  
7.          $minDistance: 1000,  
8.          $maxDistance: 5000  
9.        }  
10.     }  
11. }  

$nearSphere

The nearsphere operator specifies a point for which the geospatial query returns the document from
nearest to farthest.

Syntax:

1.             {  
2.   $nearSphere: [ <x>, <y> ],  
3.   $minDistance: <distance in radians>,  
4.   $maxDistance: <distance in radians>  
5. }  

Example:

1.                db.legacyPlaces.find(  
2.    { location : { $nearSphere : [ -73.9667, 40.78 ], $maxDistance: 0.10 } }  
3. )  

$all

It chooses the document where the value of a field is an array that contains all the specified elements.

Syntax:

1. { <field>: { $all: [ <value1> , <value2> ... ] } }  

Example:

1. db.books.find( { tags: { $all: [ "Java", "MongoDB", "RDBMS" ] } } )  

$elemMatch

The operator relates documents that contain an array field with at least one element that matches with all
the given query criteria.

Syntax:

DHRUV SOJITRA
(20270106160) Page 30
BPM(1030106407) COMPUTERENGINEERING.
1. { <field>: { $elemMatch: { <query1>, <query2>, ... } } }  

Example:

1. db.books.find(  
2.    { results: { $elemMatch: { $gte: 500, $lt: 400 } } }  
3. )  

$size

It selects any array with the number of the element specified by the argument.

Syntax:

1. db.collection.find( { field: { $size: 2 } } );   

MongoDB Bitwise Operator


$bitsAllClear

It matches the documents where all the bit positions given by the query are clear infield.

Syntax:

1. { <field>: { $bitsAllClear: <numeric bitmask> } }  

Example:

1. db.inventory.find( { a: { $bitsAllClear: [ 1, 5 ] } } )  

$bitsAllSet

The bitallset operator matches the documents where all the bit positions given by the query are set in the
field.

Syntax:

1. { <field>: { $bitsAllSet: <numeric bitmask> } }  

Example:

1. db.inventory.find( { a: { $bitsAllClear: [ 1, 5 ] } } )  

$bitsAnyClear

The bitAnyClear operator matches the document where any bit of positions given by the query is clear in
the field.

Syntax:

DHRUV SOJITRA
(20270106160) Page 31
BPM(1030106407) COMPUTERENGINEERING.
1. { <field>: { $bitsAnyClear: <numeric bitmask> } }  

Example:

1. db.inventory.find( { a: { $bitsAnyClear: [ 5, 10 ] } } )  

$bitsAnySet

It matches the document where any of the bit positions given by the query are set in the field.

Syntax:

1. { <field>: { $bitsAnySet: <numeric bitmask> } }  

Example:

1. db.inventory.find( { a: { $bitsAnySet: [ 1, 5 ] } } )  

MongoDB comments operator


$comment

The $comment operator associates a comment to any expression taking a query predicate.

Syntax:

1. db.inventory.find( { <query>, $comment: <comment> } )  

Example:

1.              db.inventory.find(  
2. {  
3.   x: { $mod: [ 1, 0 ] },  
4.   $comment: "Find Odd values."  
5. }  

MongoDB Projection Operator


$

The $ operator limits the contents of an array from the query results to contain only the first element
matching the query document.

Syntax:

1. db.books.find( { <array>: <value> ... },  
2.      { "<array>.$": 1 } )  
3. db.books.find( { <array.field>: <value> ...},  
4.      { "<array>.$": 1 } )                  

DHRUV SOJITRA
(20270106160) Page 32
BPM(1030106407) COMPUTERENGINEERING.
$elemMatch

The content of the array field made limited using this operator from the query result to contain only the
first element matching the element $elemMatch condition.

Syntax:

1. db.library.find( { bookcode: "63109" },  
2. { students: { $elemMatch: { roll: 102 } } } )   

$meta

The meta operator returns the result for each matching document where the metadata associated with the
query.

Syntax:

1. { $meta: <metaDataKeyword> }  

Example:

1.              db.books.find(  
2. <query>,  
3. { score: { $meta: "textScore" } }  

$slice

It controls the number of values in an array that a query returns.

Syntax:

1. db.books.find( { field: value }, { array: {$slice: count } } );  

Example:

1. db.books.find( {}, { comments: { $slice: [ 200, 100 ] } } )  

DHRUV SOJITRA
(20270106160) Page 33
BPM(1030106407) COMPUTERENGINEERING.

Show Documents-using OR & AND Conditions:

 Logical Operator $and:-


 The MongoDB $and operator performs a logical AND operation on an array of two or
more expressions and retrieves the documents which satisfy all the expressions in
the array.
 The $and operator uses short-circuit evaluation. If the first expression (e.g.
<expression1>) evaluates to false, MongoDB will not evaluate the remaining
expressions.
 Syntax:- { $and: [ { <exp1> }, { <exp2> } , ... , { <expN> } ]}
 Our database name is 'myinfo' and our collection name is 'student'. Here, is the
collection below.
 For Example, we had taken collection “Student”
[

"f_name": "Jenny",
"gender": "Female",
"class": "VI",
"age": 12,
"grd_point": 32.6342rr
},

"f_name": "Parth",
"gender": "Male",
"class": "VII",
"age": 13,
"grd_point": 29.5904
},

"f_name": "Tom",
"gender": "Male",
"class": "VI",
"age": 11,
"grd_point": 30.1257
},

"f_name": "Leena",
"gender": "Female",
"class": "VIII",
"age": 13,
"grd_point": 28.2514
DHRUV SOJITRA
(20270106160) Page 34
BPM(1030106407) COMPUTERENGINEERING.
},

"f_name": "Dhaval",
"gender: "Male",
"class": "VI",
"age": 11,
"grd_point": 31.5201
}

 If we want to select all documents from the collection "student" which satisfying the
condition -
1. gender of student is Female and

2. class of the student is VI and

3. grd_point of the student is greater than equal to 31


 The following Mongodb command can be used: find({$and:[{“gender":"Male"},{"grd_point":{
$gte: 31
}},{"class":”VI"}]}).pretty();

 SQL Equivalent Command:-


SELECT*FROM student
WHERE gender="Male"AND grd_point>=31AND class="VI";
Output:-

"f_name": "Parth",
"gender": "Male",
"class": "VII",
“age": 13,
"grd_point": 29.5904
}

 Logical Opertor $OR :-


 The $or operator is used to search multiple expression in a single query with only one matching
criterion to be needed in a document. More than one keys and values can be used with the $or
operator.
 The $or operator performs a logical OR operation on an array of two or more
<expressions> and selects the documents that satisfy at least one of the
<expressions>.
 Syntax:-
DHRUV SOJITRA
(20270106160) Page 35
BPM(1030106407) COMPUTERENGINEERING.
{ $or: [ { <expression1> }, { <expression2> }, ... ,

{ <expressionN> } ] }

 Example:

DHRUV SOJITRA
(20270106160) Page 36
BPM(1030106407) COMPUTERENGINEERING.

Practical: 11
Aim: How to use Limit, Sort and Skip, shell, Some Useful Collection Methods
in MongoDB.

MongoDB limit() method:-


 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.
 Syntax:- db.COLLECTION_NAME.find().limit(NUMBER)
 Example: Consider the collection mycol has the following data.

{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB "}


{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL "}
{"_id" : ObjectId(5983548781331adf45ec7), "title":" RDBMS"}
 Following example will display only two documents while querying the document.
>db.mycol.find({},{"title":1,_id:0}).limit(2)
{"title":"MongoDB "}
{"title":"NoSQL "}
 If you don't specify the number of argument in limit() method then it will display all
documents from the collection.

MongoDB Skip() method:-


 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.
 Syntax:-
 >db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)
 Example:-

>db.mycol.find({},{"title":1,_id:0}).limit(1).skip(1)
{"title":"NoSQL"}
>

 The default value in skip() method is 0.

MongoDB sort() method:-


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

DHRUV SOJITRA
(20270106160) Page 37
BPM(1030106407) COMPUTERENGINEERING.

Syntax:- >db.COLLECTION_NAME.find().sort({KEY:1})
 For Example: Consider the collection mycol has the following data.
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB "}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL "}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":" RDBMS"}
 This example will display the documents sorted by title in the descending order.
 The MongoDB Shell, mongosh, is a fully functional JavaScript and Node.js 14.x REPL
environment for interacting with MongoDB deployments. You can use the MongoDB Shell
to test queries and operations directly with your database.
 Collection:
Name Description
db.collection.aggregate() Provides access to the
aggregation pipeline.
db.collection.count() Wraps count to return a count of
the number of documents in a
collection or matching a query.
db.collection.createIndex() Builds an index on a collection.
db.collection.dataSize() Returns the size of the
collection. Wraps the size field
in the output of the collStats.
db.collection.distinct() Returns an array of documents
that have distinct values for the
specified field.
db.collection.drop() Removes the specified collection
from the database.

db.collection.dropIndex() Removes a specified index on a


collection.
db.collection.dropIndexes() Removes all indexes on a
collection
db.collection.explain() Returns information on the
query execution of various

DHRUV SOJITRA
(20270106160) Page 38
BPM(1030106407) COMPUTERENGINEERING.

methods.
db.collection.find() Performs a query on a collection and
returns a cursor object.

db.collection.findAndModify() Atomically modifies and returns a single


document.

db.collection.findOne() Performs a query and returns a single


document.

db.collection.getIndexes() Returns an array of documents that describe


the existing indexes on a collection.

db.collection.group() Provides simple data aggregation


function. Groups documents in a collection
by a key, and processes the results. Use
aggregate() for more complex data
aggregation.

db.collection.insert() Creates a new document in a collection.

db.collection.isCapped() Reports if a collection is a


capped collection.

db.collection.reIndex() Rebuilds all existing indexes on a


collection.

db.collection.remove() Deletes documents from a


collection.

db.collection.renameCollection() Changes the name of a


collection.

db.collection.save() Provides a wrapper around an insert() and


update() to insert new documents.

db.collection.stats() Reports on the state of a collection.


Provides a wrapper around the collStats.

db.collection.storageSize() Reports the total size used by the collection


in bytes. Provides a wrapper around the
storageSize field of the collStats output.

db.collection.totalSize() Reports the total size of a collection,


including the size of all documents and all
indexes on

DHRUV SOJITRA
(20270106160) Page 39
BPM(1030106407) COMPUTERENGINEERING.

a collection.
db.collection.totalIndexSize() Reports the total size used by the
indexes on a collection. Provides a
wrapper around the totalIndexSize
field of the collStats output.

db.collection.update() Modifies a document in a


collection.

db.collection.validate() Performs diagnostic operations on a


collection.

 User Management

Name Description
db.auth() Authenticates a user to a database.
db.createUser() Creates a new user.
db.updateUser() Updates user data.
db.changeUserPassword() Changes an existing user’s password.
db.dropAllUsers() Deletes all users associated with a

DHRUV SOJITRA
(20270106160) Page 40
BPM(1030106407) COMPUTERENGINEERING.

Practical: 12
Aim: How to Create Index in MongoDB

 To create an index, you need to use createIndex() method of


MongoDB.

Syntax:- >db.COLLECTION_NAME.createIndex({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.
 Example:-

>db.mycol.createIndex({"title":1})
{

"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
 In createIndex() method you can pass multiple fields, to
create index on multiple fields.
>db.mycol.createIndex({"title":1,"description":-1})

This method also accepts list of options (which are optional).


Following is the list

DHRUV SOJITRA
(20270106160) Page 41
BPM(1030106407) COMPUTERENGINEERING.

Practical 13
Aim: How to Aggregate Data in MongoDB

What is Aggregation in MongoDB?


Aggregation is a way of processing a large number of documents in a collection by means of
passing them through different stages. The stages make up what is known as a pipeline. The
stages in a pipeline can filter, sort, group, reshape and modify documents that pass through the
pipeline.
One of the most common use cases of Aggregation is to calculate aggregate values for groups of
documents. This is similar to the basic aggregation available in SQL with the GROUP BY clause
and COUNT, SUM and AVG functions. MongoDB Aggregation goes further though and can also
perform relational-like joins, reshape documents, create new and update existing collections, and
so on. 
While there are other methods of obtaining aggregate data in MongoDB, the aggregation
framework is the recommended approach for most work.
There are what are called single purpose methods like estimatedDocumentCount(),  count(),
and distinct() which are appended to a find() query making them quick to use but limited in
scope.
The map-reduce framework on MongoDB is a predecessor of the aggregation framework and
much more complex to use. MongoDB have deprecated

MongoDB $match

The $match stage allows us to choose just those documents from a collection that we want to work
with. It does this by filtering out those that do not follow our requirements.

In the following example, we only want to work with those documents which specify that Spain is
the value of the field country, and Salamanca is the value of the field city.

In order to get a readable output, I am going to add .pretty() at the end of all the commands.

db.universities.aggregate([

 { $match : { country : 'Spain', city : 'Salamanca' } }

]).pretty()

The output is…

DHRUV SOJITRA
(20270106160) Page 42
BPM(1030106407) COMPUTERENGINEERING.

"_id" : ObjectId("5b7d9d9efbc9884f689cdba9"),
"country" : "Spain","city" : "Salamanca",
"name" : "USAL",
"location" : {
"type" : "Point",
"coordinates" : [
-5.6722512,
17,
40.9607792
]
},
"students" : [
{
"year" : 2014,
"number" : 24774
},
{
"year" : 2015,
"number" : 23166
},
{
"year" : 2016,
"number" : 21913
},
{
"year" : 2017,
"number" : 21715
}
]
}
{
"_id" : ObjectId("5b7d9d9efbc9884f689cdbaa"),
"country" : "Spain",
"city" : "Salamanca",
"name" : "UPSA",
"location" : {

"type" : "Point",
"coordinates" : [
-5.6691191,
17,
40.9631732
]
},
"students" : [
{
"year" : 2014,
"number" : 4788
},
{
"year" : 2015,
"number" : 4821
},
{
"year" : 2016,
"number" : 6550
},
{
"year" : 2017,
"number" : 6125
}
]
}

DHRUV SOJITRA
(20270106160) Page 43
BPM(1030106407) COMPUTERENGINEERING.

MongoDB $project

It is rare that you ever need to retrieve all the fields in your documents. It is good practice to
return only those fields you need so as to avoid processing more data than is necessary.

The $project stage is used to do this and to add any calculated fields that you need.

In this example, we only need the fields country, city and name.

In the code that follows, please note that:

 We must explicitly write _id : 0 when this field is not required


 Apart from the _id field, it is sufficient to specify only those fields we need to obtain as a result of
the query

This stage …

db.universities.aggregate([

{ $project : { _id : 0, country : 1, city : 1, name : 1 } }

]).pretty()

..will give the result …

{ "country" : "Spain", "city" : "Salamanca", "name" : "USAL" }

{ "country" : "Spain", "city" : "Salamanca", "name" : "UPSA" }

Here’s another example of MongoDB $project.

MongoDB $group

With the $group stage, we can perform all the aggregation or summary queries that we need, such
as finding counts, totals, averages or maximums.

In this example, we want to know the number of documents per university in our ‘ universities’
collection:

The query …

db.universities.aggregate([

{ $group : { _id : '$name', totaldocs : { $sum : 1 } } }

]).pretty()

DHRUV SOJITRA
(20270106160) Page 44
BPM(1030106407) COMPUTERENGINEERING.

..will produce this result …

{ "_id" : "UPSA", "totaldocs" : 1 }

{ "_id" : "USAL", "totaldocs" : 1 }

MongoDB $group aggregation operators


The $group stage supports certain expressions (operators) allowing users to perform arithmetic,
array, boolean and other operations as part of the aggregation pipeline.

Operator Meaning

$count Calculates the quantity of documents in the given group.

$max Displays the maximum value of a document’s field in the collection.

$min Displays the minimum value of a document’s field in the collection.

$avg Displays the average value of a document’s field in the collection.

$sum Sums up the specified values of all documents in the collection.

$push Adds extra values into the array of the resulting document.

Check out to see other MongoDB operators and learn more on this topic.

MongoDB $out

This is an unusual type of stage because it allows you to carry the results of your aggregation
over into a new collection, or into an existing one after dropping it, or even adding them to the
existing documents (new in 4.1.2 version).

The $out stage must be the last stage in the pipeline.

For the first time, we are using an aggregation with more than one stage. We now have two,
a $group and an $out:

db.universities.aggregate([
{ $group : { _id : '$name', totaldocs : { $sum : 1 } } },

DHRUV SOJITRA
(20270106160) Page 45
BPM(1030106407) COMPUTERENGINEERING.

{ $out : 'aggResults' }
])
Now, we check the content of the new ‘aggResults’ collection:
db.aggResults.find().pretty()
{ "_id" : "UPSA", "totaldocs" : 1 }
{ "_id" : "USAL", "totaldocs" : 1 }
>
Here’s how we used the $out stage in this three-part example.

Now we’ve produced a multi-stage aggregation, we can go on to build up a pipeline.

MongoDB $unwind

The $unwind stage in MongoDB is commonly found in a pipeline because it is a means to an end.

You cannot work directly on the elements of an array within a document with stages such
as $group. The $unwind stage enables us to work with the values of the fields within an array.

Where there is an array field within the input documents, you will sometimes need to output the
document several times, once for every element of that array.

Each copy of the document has the array field replaced with the successive element.

In the next example, I am going to apply the stage only to the document whose field name contains
the value USAL.

This is the document:

{
country : 'Spain',
city : 'Salamanca',
name : 'USAL',
location : {
type : 'Point',
coordinates : [ -5.6722512,17, 40.9607792 ]
},
students : [
{ year : 2014, number : 24774 },
{ year : 2015, number : 23166 },
{ year : 2016, number : 21913 },
{ year : 2017, number : 21715 }
]
}
Now, we apply the $unwind stage, over the student’s array, and check that we get a document per
each element of the array.

The first document is made up of the fields in the first element of the array and the rest of the
common fields.

The second document is made up of the fields in the second element of the array and the rest of
the common fields, and so on.

db.universities.aggregate([
{ $match : { name : 'USAL' } },

DHRUV SOJITRA
(20270106160) Page 46
BPM(1030106407) COMPUTERENGINEERING.

{ $unwind : '$students' }
]).pretty()
{
"_id" : ObjectId("5b7d9d9efbc9884f689cdba9"),
"country" : "Spain",
"city" : "Salamanca",
"name" : "USAL",
"location" : {
"type" : "Point",
"coordinates" : [
-5.6722512,
17,
40.9607792
]
},
"students" : {
"year" : 2014,
"number" : 24774
}
}
{
"_id" : ObjectId("5b7d9d9efbc9884f689cdba9"),
"country" : "Spain",
"city" : "Salamanca",
"name" : "USAL",
"location" : {
"type" : "Point",
"coordinates" : [
-5.6722512,
17,
40.9607792
]
},
"students" : {
"year" : 2015,
"number" : 23166
}
}
{
"_id" : ObjectId("5b7d9d9efbc9884f689cdba9"),
"country" : "Spain",
"city" : "Salamanca",
"name" : "USAL",
"location" : {
"type" : "Point",
"coordinates" : [
-5.6722512,
17,
40.9607792
]
},
"students" : {
"year" : 2016,
"number" : 21913
}
}
{
"_id" : ObjectId("5b7d9d9efbc9884f689cdba9"),
"country" : "Spain",
"city" : "Salamanca",
"name" : "USAL",
"location" : {
"type" : "Point",
"coordinates" : [
-5.6722512,

DHRUV SOJITRA
(20270106160) Page 47
BPM(1030106407) COMPUTERENGINEERING.

17,
40.9607792
]
},
"students" : {
"year" : 2017,
"number" : 21715
}
}

MongoDB $sort

You need the $sort stage to sort your results by the value of a specific field.

For example, let’s sort the documents obtained as a result of the $unwind stage by the number of
students in descending order.

In order to get a lesser output, I am going to project only the year and the number of students.

db.universities.aggregate([
{ $match : { name : 'USAL' } },
{ $unwind : '$students' },
{ $project : { _id : 0, 'students.year' : 1, 'students.number' : 1 } },
{ $sort : { 'students.number' : -1 } }
]).pretty()
This gives the result …
{ "students" : { "year" : 2014, "number" : 24774 } }
{ "students" : { "year" : 2015, "number" : 23166 } }
{ "students" : { "year" : 2016, "number" : 21913 } }
{ "students" : { "year" : 2017, "number" : 21715 } }

DHRUV SOJITRA
(20270106160) Page 48
BPM(1030106407) COMPUTERENGINEERING.

Practical 14
Aim: How to Backup and Restore Database in MongoDB
 5.6 Backup & restore database in MONGODB:-
Dump MongoDB Data:-

To create backup of database in MongoDB, you


should use mongodump command. This command will dump the
entire data of your server into the dump directory. There are
many options available by which you can limit the amount of
data or create backup of your remote server.
 Syntax:- >mongodump
 Example:-
 Start your mongod server. Assuming that your mongod
server is running on the localhost and port 27017, open a
command prompt and go to the bin directory of your
mongodb instance and type the command
mongodump
 Consider the mycol collection has the following data.

>mongodump
 The command will connect to the server running at
127.0.0.1 and port 27017 and back all data of the server to
directory /bin/dump/. Following is the output of the
command .

DHRUV SOJITRA
(20270106160) Page 49
BPM(1030106407) COMPUTERENGINEERING.

 Following is a list of available options that can be


with the mongodump command.

Syntax Description Example

mongodump --host This commmand will backup mongodump --host


HOST_NAME --port all databases of specified tpoint.com --port
PORT_NUMBER mongod instance. 27017

mongodump --dbpath This command will backup mongodump --


DB_PATH --out only specified database at dbpath /data/db/ --
BACKUP_DIRECTORY specified path. out /data/backup/

mongodump --collection This command will backup mongodump --


COLLECTION --db only specified collection of collection mycol --
DB_NAME specified database. db test

Restore data:-

 To restore backup data MongoDB's


mongorestore command is used. This command
restores all of the data from the backup directory.
 Syntax:- >mongorestore

DHRUV SOJITRA
(20270106160) Page 50

You might also like