Professional Documents
Culture Documents
BPM7 14
BPM7 14
Practical – 7
AIM: - How to Download, Install & Run MongoDB Server in Windows OS.
(5.0.6 current version)
Go to link and Download MongoDB Community Server. We will install the 64-bit
version for Windows.
DHRUV SOJITRA
(20270106160) Page 2
BPM(1030106407) COMPUTERENGINEERING.
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.
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
DHRUV SOJITRA
(20270106160) Page 5
BPM(1030106407) COMPUTERENGINEERING.
DHRUV SOJITRA
(20270106160) Page 6
BPM(1030106407) COMPUTERENGINEERING.
DHRUV SOJITRA
(20270106160) Page 7
BPM(1030106407) COMPUTERENGINEERING.
Step 10) Click on next
DHRUV SOJITRA
(20270106160) Page 8
BPM(1030106407) COMPUTERENGINEERING.
Configuration: -
Step 1: - Go to the local disk C and get into Program Files.
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
DHRUV SOJITRA
(20270106160) Page 10
BPM(1030106407) COMPUTERENGINEERING.
DHRUV SOJITRA
(20270106160) Page 11
BPM(1030106407) COMPUTERENGINEERING.
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.
DHRUV SOJITRA
(20270106160) Page 13
BPM(1030106407) COMPUTERENGINEERING.
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.
DHRUV SOJITRA
(20270106160) Page 15
BPM(1030106407) COMPUTERENGINEERING.
Practical – 8
AIM: - How to Create Database, collection and insert documents & Drop
database In MongoDB.
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.
Syntax: -
db.createCollection("Table Name")
DHRUV SOJITRA
(20270106160) Page 16
BPM(1030106407) COMPUTERENGINEERING.
Syntax: -
db.TableName. insert (
{ user_name:"mark",
post_text:"This is a sample post",
post_privacy:"public",
post_likes_count:0
}
)
EXAMPLE:-
db.Table Name.drop()
EXAMPLE:-
DHRUV SOJITRA
(20270106160) Page 17
BPM(1030106407) COMPUTERENGINEERING.
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
● 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
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.
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.
Apart from the find() method, there is findOne() method, that returns only one document.
Syntax
db.COLLECTIONNAME.findOne()
EXAMPLE:-
Syntax
db.COLLECTION_NAME.findOneAndUpdate(SELECTIOIN_CRITERIA, UPDATED_DATA)
DHRUV SOJITRA
(20270106160) Page 21
BPM(1030106407) COMPUTERENGINEERING.
EXAMPLE:-
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.
The $eq specifies the equality condition. It matches documents where the value of a field equals the specified
value.
Syntax:
Example:
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:
Example:
$gte
The $gte choose the documents where the field value is greater than or equal to a specified value.
Syntax:
DHRUV SOJITRA
(20270106160) Page 23
BPM(1030106407) COMPUTERENGINEERING.
Example:
$in
The $in operator choose the documents where the value of a field equals any value in the specified array.
Syntax:
Example:
$lt
The $lt operator chooses the documents where the value of the field is less than the specified value.
Syntax:
Example:
$lte
The $lte operator chooses the documents where the field value is less than or equal to a specified value.
Syntax:
Example:
$ne
The $ne operator chooses the documents where the field value is not equal to the specified value.
Syntax:
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:
Example:
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:
Example:
$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:
Example:
$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:
$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:
Example:
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:
Example:
$type
The type operator chooses documents where the value of the field is an instance of the specified BSON type.
Syntax:
Example:
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:
$jsonSchema
Syntax:
$mod
The mod operator selects the document where the value of a field is divided by a divisor has the specified
remainder.
Syntax:
Example:
$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:
$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:
$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:
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:
Example:
$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:
It matches the documents where all the bit positions given by the query are clear infield.
Syntax:
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:
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:
Example:
1. db.inventory.find( { a: { $bitsAnySet: [ 1, 5 ] } } )
The $comment operator associates a comment to any expression taking a query predicate.
Syntax:
Example:
1. db.inventory.find(
2. {
3. x: { $mod: [ 1, 0 ] },
4. $comment: "Find Odd values."
5. }
The $ operator limits the contents of an array from the query results to contain only the first element
matching the query document.
Syntax:
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:
$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
Syntax:
Example:
DHRUV SOJITRA
(20270106160) Page 33
BPM(1030106407) COMPUTERENGINEERING.
"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" whichsatisfying the
condition -
1. gender of student is Female and
"f_name": "Parth",
"gender": "Male",
"class": "VII",
“age": 13,
"grd_point": 29.5904
}
{ <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.
>db.mycol.find({},{"title":1,_id:0}).limit(1).skip(1)
{"title":"NoSQL"}
>
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 descendingorder.
The MongoDB Shell, mongosh, is a fully functional JavaScript and Node.js 14.x REPL
environment for interacting with MongoDBdeployments. 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.
DHRUV SOJITRA
(20270106160) Page 38
BPM(1030106407) COMPUTERENGINEERING.
a collection.
db.collection.totalIndexSize() Reports the total size used by the
DHRUV SOJITRA
(20270106160) Page 39
BPM(1030106407) COMPUTERENGINEERING.
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
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 forascending 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 onmultiple fields.
>db.mycol.createIndex({"title":1,"description":-1})
DHRUV SOJITRA
(20270106160) Page 41
BPM(1030106407) COMPUTERENGINEERING.
Practical 13
Aim: How to Aggregate Data in MongoDB
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([
]).pretty()
{
"_id" : ObjectId("5b7d9d9efbc9884f689cdba9"),
DHRUV SOJITRA
(20270106160) Page 42
BPM(1030106407) COMPUTERENGINEERING.
"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
}
]
}
MongoDB $project
DHRUV SOJITRA
(20270106160) Page 43
BPM(1030106407) COMPUTERENGINEERING.
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.
This stage …
db.universities.aggregate([
]).pretty()
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([
]).pretty()
DHRUV SOJITRA
(20270106160) Page 44
BPM(1030106407) COMPUTERENGINEERING.
Operator Meaning
$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).
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 } } },
{ $out : 'aggResults' }
])
Now, we check the content of the new ‘aggResults’ collection:
DHRUV SOJITRA
(20270106160) Page 45
BPM(1030106407) COMPUTERENGINEERING.
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.
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.
{
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' } },
{ $unwind : '$students' }
]).pretty()
{
DHRUV SOJITRA
(20270106160) Page 46
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
}
}
{
"_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,
17,
40.9607792
]
DHRUV SOJITRA
(20270106160) Page 47
BPM(1030106407) COMPUTERENGINEERING.
},
"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:-
>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.
Restore data:-
DHRUV SOJITRA
(20270106160) Page 50