Mongo DB Lab Manual
Mongo DB Lab Manual
LABORATORY MANUAL
B TECH(AI&ML,AI&DS,DS)
(IIYEAR-IISEM)
(2021-2022)
DEPARTMENT OF CSE
PREPARED BY B RANJITH KUMAR
Course Outcomes:
Upon successful completion of the course, the student will be able to:
Installing and configuring mongo DB in windows
Perform all database operations using mongo DB
Develop applications by integrating mongo DB with java/PHP.
LIST OF EXPERIMENTS:
1. Mongo DB installation and configuration in windows.
2. Demonstrate how to create and drop a database in Mongo DB.
3. Creating the Collection in Mongo DB on the fly
4. Creating collection with options before inserting the documents and drop the
collection created.
5. Mongo DB insert document
a. Insert single document
b. Insert multiple documents in collection
6. Querying all the documents in json format and Querying based on the criteria.
9. Mongo DB Projection
DEPARTMENT OF CSE
PREPARED BY B RANJITH KUMAR
DEPARTMENT OF CSE
PREPARED BY B RANJITH KUMAR
Step 2: Click Next when the MongoDB installation windows pops up.
DEPARTMENT OF CSE
PREPARED BY B RANJITH KUMAR
Step 4: When the setup asks you to choose the Setup type, choose Complete.
Step 6: That’s it. Click Finish once the MongoDB installation is complete.
DEPARTMENT OF CSE
PREPARED BY B RANJITH KUMAR
MongoDB Configuration
Step 1: Locate the folder where you have installed MongoDB. If you have followed the above steps
then you can find the folder at this location:
C:\Program Files\MongoDB
Here you need to create couple of folders that we need for MongoDB configuration.
1. Create two folders here, name them data and log.
2. Create another folder inside data and name it as db, that’s where all the data will be stored.
That’s it close the window.
Step 2: Open command prompt (right click and run as administrator). Navigate to the bin folder of
MongoDB as shown in the screenshot. The path to the bin folder may be different in your case
based on where you have installed the MongoDB.
Step 3: Configure the data & log folder and set MongoDB as service by typing this
command. Note: This is a one line command.
DEPARTMENT OF CSE
PREPARED BY B RANJITH KUMAR
Step 4: Now you can start MongoDB as a service by typing this command:
That’s it everything is done. Now we should be working in the MongoDB shell and we can run that
by typing this command within the bin directory.
mongo
DEPARTMENT OF CSE
PREPARED BY B RANJITH KUMAR
If you want to exit the shell, you can do that by typing quit() or use Ctrl-C and then you can stop the
MongoDB service with this command:
DEPARTMENT OF CSE
PREPARED BY B RANJITH KUMAR
Now we should be working in the MongoDB shell. To run the MongoDB shell, type the following
command:
mongo
Once you are in the MongoDB shell, create the database in MongoDB by typing this command:
use database_name
For example I am creating a database “STMARYS” so the command should be:
DEPARTMENT OF CSE
PREPARED BY B RANJITH KUMAR
use STMARYS
Note: If the database name you mentioned is already present then this command will connect you to
the database. However if the database doesn’t exist then this will create the database with the given
name and connect you to it.
At any point if you want to check the currently connected database just type the command db. This
command will show the database name to which you are currently connected. This is really helpful
command when you are working with several databases so that before creating a collection or
inserting a document in database, you may want to ensure that you are in the right database.
db beginnersbook
To list down all the databases, use the command show dbs. This command lists down all the
databases and their size on the disk.
show dbs
admin 0.000GB
local 0.000GB
DEPARTMENT OF CSE
PREPARED BY B RANJITH KUMAR
As you can see that the database “beginnersbook” that we have created is not present in the list of
all the databases. This is because a database is not created until you save a document in it
db.dropDatabase()
We do not specify any database name in this command, because this command deletes the currently
selected database. Lets see the steps to drop a database in MongoDB.
use database_name
For example I want to delete the database “beginnersbook”.
> db.dropDatabase()
{ "dropped" : "beginnersbook", "ok" : 1 }
The command executed successfully and showing the operation “dropped” and status “ok” which
means that the database is dropped.
DEPARTMENT OF CSE
PREPARED BY B RANJITH KUMAR
4. To verify that the database is deleted successfully. Execute the show dbs command again to see
the list of databases after deletion.
As you can see that the database “beginnersbook” is not present in the list that means it has been
dropped successfully.
DEPARTMENT OF CSE
PREPARED BY B RANJITH KUMAR
3.Creating the Collection in Mongo DB on the fly
The cool thing about MongoDB is that you need not to create collection before you insert document
in it. With a single command you can insert a document in the collection and the MongoDB creates
that collection on the fly.
For example:
We don’t have a collection beginnersbook in the database beginnersbookdb. This command
will create the collection named “beginnersbook” on the fly and insert a document in it with the
specified key and value pairs.
db.beginnersbook.insert({
name: "Chaitanya",
age: 30,
website: "beginnersbook.com"
})
WriteResult({ "nInserted" : 1 })
DEPARTMENT OF CSE
PREPARED BY B RANJITH KUMAR
To check whether the document is successfully inserted, type the following command. It shows all
the documents in the given collection.
Syntax: db.collection_name.find()
> db.beginnersbook.find()
{ "_id" : ObjectId("59bcb8c2415346bdc68a0a66"), "name" : "Chaitanya",
"age" : 30, "website" : "beginnersbook.com" }
To check whether the collection is created successfully, use the following command.
show collections
This command shows the list of all the collections in the currently selected database.
DEPARTMENT OF CSE
PREPARED BY B RANJITH KUMAR
Syntax:
db.createCollection(name, options)
name is the collection name
and options is an optional field that we can use to specify certain parameters such as size, max
number of documents etc. in the collection.
First lets see how this command is used for creating collection without any parameters:
> db.createCollection("students")
{ "ok" : 1 }
Lets see the options that we can provide while creating a collection:
capped: type: boolean.
This parameter takes only true and false. This specifies a cap on the max entries a collection can
have. Once the collection reaches that limit, it starts overwriting old entries.
The point to note here is that when you set the capped option to true you also have to specify the
size parameter.
DEPARTMENT OF CSE
PREPARED BY B RANJITH KUMAR
autoIndexId: type: boolean
The default value of this parameter is false. If you set it true then it automatically creates index field
_id for each document. We will learn about index in the MongoDB indexing tutorial.
DEPARTMENT OF CSE
PREPARED BY B RANJITH KUMAR
db.collection_name.insert()
Lets take an example to understand this .
Here we are inserting a document into the collection named “beginnersbook”. The field “course” in
the example below is an array that holds the several key-value pairs.
db.beginnersbook.insert(
{
name: "Chaitanya",
age: 30,
email: "[email protected]",
course: [ { name: "MongoDB", duration: 7 }, { name: "Java", duration:
30 } ]
}
)
WriteResult({ "nInserted" : 1 })
The insert() method creates the collection if it doesn’t exist but if the collection is present then it
inserts the document into it
DEPARTMENT OF CSE
PREPARED BY B RANJITH KUMAR
Verification:
You can also verify whether the document is successfully inserted by typing following command:
db.collection_name.find()
In the above example, we inserted the document in the collection named “beginnersbook” so the
command should be:
> db.beginnersbook.find()
{ "_id" : ObjectId("59bce797668dcce02aaa6fec"), "name" : "Chaitanya", "age"
: 30,
"email" : "[email protected]", "course" : [ { "name" : "MongoDB",
"duration" : 7 }, { "name" : "Java", "duration" : 30 } ] }
DEPARTMENT OF CSE
PREPARED BY B RANJITH KUMAR
var beginners =
[
{
"StudentId" : 1001,
"StudentName" : "Steve",
"age": 30
},
{
"StudentId" : 1002,
"StudentName" : "Negan",
"age": 42
},
{
"StudentId" : 3333,
"StudentName" : "Rick",
"age": 35
},
];
db.students.insert(beginners);
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 3,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
DEPARTMENT OF CSE
PREPARED BY B RANJITH KUMAR
As you can see that it shows number 3 in front of nInserted. This means that the 3 documents have
been inserted by this command.
To verify that the documents are there in collection. Run this command:
db.students.find()
Do you know? You can print the output data in a JSON format so that you can read it easily. To
print the data in JSON format run the command db.collection_name.find().forEach(printjson)
DEPARTMENT OF CSE
PREPARED BY B RANJITH KUMAR
db.students.find().forEach(printjson)
In the screenshot below, you can see the difference. First we have printed the documents using
normal find() method and then we printed the documents of same collection using JSON format.
The documents in JSON format are neat and easy to read.
DEPARTMENT OF CSE
PREPARED BY B RANJITH KUMAR
db.students.find()
However the output we get is not in any format and less-readable. To improve the readability, we
can format the output in JSON format with this command:
db.students.find().forEach(printjson);
db.students.find().pretty()
As you can see in the screenshot below that the documents are in JSON format.
DEPARTMENT OF CSE
PREPARED BY B RANJITH KUMAR
Equality Criteria:
For example: I want to fetch the data of “Steve” from students collection. The command for this
should be:
db.students.find({StudentName : "Steve"}).pretty()
This command returns the document matching the given criteria.
db.collection_name.find({"field_name":{$gt:criteria_value}}).pretty()
For example: I would like to fetch the details of students having age > 32 then the query should be:
db.students.find({"age":{$gt:32}}).pretty()
I got two documents matching the criteria as shown in the screenshot below:
DEPARTMENT OF CSE
PREPARED BY B RANJITH KUMAR
db.collection_name.find({"field_name":{$lt:criteria_value}}).pretty()
Example: Find all the students having id less than 3000. The command for this criteria would be:
db.students.find({"StudentId":{$lt:3000}}).pretty()
Output:
> db.students.find({"StudentId":{$lt:3000}}).pretty()
{
"_id" : ObjectId("59bcecc7668dcce02aaa6fed"),
"StudentId" : 1001,
"StudentName" : "Steve",
"age" : 30
}
{
"_id" : ObjectId("59bcecc7668dcce02aaa6fee"),
"StudentId" : 1002,
"StudentName" : "Negan",
"age" : 42
}
DEPARTMENT OF CSE
PREPARED BY B RANJITH KUMAR
Not Equals Criteria:
Syntax:
db.collection_name.find({"field_name":{$ne:criteria_value}}).pretty()
Example: Find all the students where id is not equal to 1002. The command for this criteria would
be:
db.students.find({"StudentId":{$ne:1002}}).pretty()
Output:
> db.students.find({"StudentId":{$ne:1002}}).pretty()
{
"_id" : ObjectId("59bcecc7668dcce02aaa6fed"),
"StudentId" : 1001,
"StudentName" : "Steve",
"age" : 30
}
{
"_id" : ObjectId("59bcecc7668dcce02aaa6fef"),
"StudentId" : 3333,
"StudentName" : "Rick",
"age" : 35
}
Here are the other two criteria:
db.collection_name.find({"field_name":{$gte:criteria_value}}).pretty()
Less than equals Criteria:
db.collection_name.find({"field_name":{$lte:criteria_value}}).pretty()
The pretty() method that we have added at the end of all the commands is not mandatory. It is just
used for formatting purposes.
DEPARTMENT OF CSE
PREPARED BY B RANJITH KUMAR
Syntax:
db.collection_name.update(criteria, update_data)
Example:
For example: Lets say I have a collection named “got” in the database “beginnersbookdb”. The
documents inside “got” are:
> db.got.find().pretty()
{
"_id" : ObjectId("59bd2e73ce524b733f14dd65"),
"name" : "Jon Snow",
"age" : 32
}
{
"_id" : ObjectId("59bd2e8bce524b733f14dd66"),
"name" : "Khal Drogo",
"age" : 36
}
{
"_id" : ObjectId("59bd2e9fce524b733f14dd67"),
"name" : "Sansa Stark",
"age" : 20
}
{
"_id" : ObjectId("59bd2ec5ce524b733f14dd68"),
"name" : "Lord Varys",
"age" : 42
}
Now suppose if I want to update the name of Jon Snow with the name “Kit Harington”. The
command for this would be:
OUTPUT :
DEPARTMENT OF CSE
PREPARED BY B RANJITH KUMAR
Do you know? By default the update method updates a single document. In the above example we
had only one document matching with the criteria, however if there were more then also only one
document would have been updated. To enable update() method to update multiple documents you
have to set “multi” parameter of this method to true as shown below.
db.got.update({"name":"Jon Snow"},
{$set:{"name":"Kit Harington"}},{multi:true})
DEPARTMENT OF CSE
PREPARED BY B RANJITH KUMAR
db.collection_name.save( {_id:ObjectId(), new_document} )
Lets take the same example that we have seen above. Now we want to update the name of “Kit
Harington” to “Jon Snow”. To work with save() method you should know the unique _id field of
that document.
A very important point to note is that when you do not provide the _id field while using save()
method, it calls insert() method and the passed document is inserted into the collection as a new
document
To get the _id of a document, you can either type this command:
db.got.find().pretty()
Here got is a collection name. This method of finding unique _id is only useful when you have few
documents, otherwise scrolling and searching for that _id in huge number of documents is tedious.
If you have huge number of documents then, to get the _id of a particular document use the criteria
in find() method. For example: To get the _id of the document that we want to update using save()
method, type this command:
Now we know the unique _id field of that document. Lets write the command using save() method.
DEPARTMENT OF CSE
PREPARED BY B RANJITH KUMAR
DEPARTMENT OF CSE
PREPARED BY B RANJITH KUMAR
db.collection_name.remove(delete_criteria)
Lets say I have a collection students in my MongoDB database named beginnersbookdb. The
documents in students collection are:
> db.students.find().pretty()
{
"_id" : ObjectId("59bcecc7668dcce02aaa6fed"),
"StudentId" : 1001,
"StudentName" : "Steve",
"age" : 30
}
{
"_id" : ObjectId("59bcecc7668dcce02aaa6fef"),
"StudentId" : 3333,
"StudentName" : "Rick",
"age" : 35
}
Now I want to remove the student from this collection who has a student id equal to 3333. To do
this I would write a command using remove() method like this:
db.students.remove({"StudentId": 3333})
Output:
WriteResult({ "nRemoved" : 1 })
To verify whether the document is actually deleted. Type the following command:
db.students.find().pretty()
It will list all the documents of students collection.
DEPARTMENT OF CSE
PREPARED BY B RANJITH KUMAR
db.collection_name.remove(delete_criteria, justOne)
DEPARTMENT OF CSE
PREPARED BY B RANJITH KUMAR
Here just One is a Boolean parameter that takes only 1 and 0, if you give 1 then it will limit the
document deletion to only 1 document. This is an optional parameters as we have seen above that we
have used the remove() method without using this parameter.
> db.walkingdead.find().pretty()
{
"_id" : ObjectId("59bf280cb8e797a22c654229"),
"name" : "Rick Grimes",
"age" : 32,
"rname" : "Andrew Lincoln"
}
{
"_id" : ObjectId("59bf2851b8e797a22c65422a"),
"name" : "Negan",
"age" : 35,
"rname" : "Jeffrey Dean Morgan"
}
{
"_id" : ObjectId("59bf28a5b8e797a22c65422b"),
"name" : "Daryl Dixon",
"age" : 32,
"rname" : "Norman Reedus"
}
Lets say I want to remove the document that has age equal to 32. There are two documents in this
collection that are matching this criteria. However to limit the deletion to one we are setting justOne
parameter to true.
db.walkingdead.remove({"age": 32}, 1)
Output: As you can see only one document got deleted.
WriteResult({ "nRemoved" : 1 })
DEPARTMENT OF CSE
PREPARED BY B RANJITH KUMAR
db.collection_name.remove({})
DEPARTMENT OF CSE
PREPARED BY B RANJITH KUMAR
9. Mongo DB Projection
we will learn another interesting topic of MongoDB which is MongoDB Projection. This is
used when we want to get the selected fields of the documents rather than all fields.
For example, we have a collection where we have stored documents that have the fields:
student_name, student_id, student_age but we want to see only the student_id of all the students
then in that case we can use projection to get only the student_id.
Syntax:
db.collection_name.find({},{field_key:1 or 0})
Do not worry about the syntax now, we will see an example to understand this.
> db.studentdata.find().pretty()
{
"_id" : ObjectId("59bf63380be1d7770c3982af"),
"student_name" : "Steve",
"student_id" : 2002,
"student_age" : 22
}
{
"_id" : ObjectId("59bf63500be1d7770c3982b0"),
"student_name" : "Carol",
"student_id" : 2003,
"student_age" : 22
}
{
"_id" : ObjectId("59bf63650be1d7770c3982b1"),
"student_name" : "Tim",
"student_id" : 2004,
"student_age" : 23
}
DEPARTMENT OF CSE
PREPARED BY B RANJITH KUMAR
To get only the student_id for all the documents, we will use the Projection like this:
Value 1 means show that field and 0 means do not show that field. When we set a field to 1 in
Projection other fields are automatically set to 0, except _id, so to avoid the _id we need to
specifically set it to 0 in projection. The vice versa is also true when we set few fields to 0, other
fields set to 1 automatically(see the below example)
Error: error: {
"ok" : 0,
"errmsg" : "Projection cannot have a mix of inclusion and exclusion.",
"code" : 2,
"codeName" : "BadValue"
}
DEPARTMENT OF CSE
PREPARED BY B RANJITH KUMAR
This happens when you set some fields to 0 and other to 1, in other words you mix inclusion and
exclusion, the only exception is the _id field. for example: The following Query would produce this
error:
DEPARTMENT OF CSE
PREPARED BY B RANJITH KUMAR
db.collection_name.find().limit(number_of_documents)
Lets take an example to understand how to use this method. Lets say, I have a
collection studentdata which has following documents:
> db.studentdata.find().pretty()
{
"_id" : ObjectId("59bf63380be1d7770c3982af"),
"student_name" : "Steve",
"student_id" : 2002,
"student_age" : 22
}
{
"_id" : ObjectId("59bf63500be1d7770c3982b0"),
"student_name" : "Carol",
"student_id" : 2003,
"student_age" : 22
}
{
"_id" : ObjectId("59bf63650be1d7770c3982b1"),
"student_name" : "Tim",
"student_id" : 2004,
"student_age" : 23
}
Lets say I want to find out the list of all the students, having the id > 2002. I would write a query
like this using a criteria:
To understand the use of skip() method, lets take the same example that we have seen above. In the
above example we can see that by using limit(1) we managed to get only one document, which is the
first document that matched the given criteria. What if you do not want the first document matching
your criteria. For example we have two documents that have student_id value greater than 2002 but
when we limited the result to 1 by using limit(1), we got the first document, in order to get the second
document matching this criteria we can use skip(1) here which will skip the first document.
DEPARTMENT OF CSE
PREPARED BY B RANJITH KUMAR
> db.studentdata.find({student_id : {$gt:2002}}).limit(1).pretty()
{
"_id" : ObjectId("59bf63500be1d7770c3982b0"),
"student_name" : "Carol",
"student_id" : 2003,
"student_age" : 22
}
Using skip:
db.collecttion_name.find().sort({field_key:1 or -1})
1 is for ascending order and -1 is for descending order. The default value is 1.
> db.studentdata.find().pretty()
{
"_id" : ObjectId("59bf63380be1d7770c3982af"),
"student_name" : "Steve",
"student_id" : 2002,
"student_age" : 22
}
{
"_id" : ObjectId("59bf63500be1d7770c3982b0"),
"student_name" : "Carol",
"student_id" : 2003,
"student_age" : 22
}
{
"_id" : ObjectId("59bf63650be1d7770c3982b1"),
"student_name" : "Tim",
"student_id" : 2004,
DEPARTMENT OF CSE
PREPARED BY B RANJITH KUMAR
"student_age" : 23
}
Lets say I want to display the student_id of all the documents in descending order:
Default: The default is ascending order so If I don’t provide any value in the sort() method then it
will sort the records in ascending order as shown below:
DEPARTMENT OF CSE
PREPARED BY B RANJITH KUMAR
db.collection_name.createIndex({field_name: 1 or -1})
The value 1 is for ascending order and -1 is for descending order.
For example, I have a collection studentdata. The documents inside this collection have
following fields:
student_name, student_id and student_age
Lets say I want to create the index on student_name field in ascending order:
db.studentdata.createIndex({student_name: 1})
Output:
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
DEPARTMENT OF CSE
PREPARED BY B RANJITH KUMAR
We have created the index on student_name which means when someone searches the document
based on the student_name, the search will be faster because the index will be used for this search.
So this is important to create the index on the field that will be frequently searched in a collection.
db.collection_name.getIndexes()
DEPARTMENT OF CSE
PREPARED BY B RANJITH KUMAR
> db.studentdata.getIndexes()
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "test.studentdata"
},
{
"v" : 2,
"key" : {
"student_name" : 1
},
"name" : "student_name_1",
"ns" : "test.studentdata"
}
]
The output shows that we have two indexes in this collection. The default index created on _id and
the index that we have created on student_name field.
Lets drop the index that we have created on student_name field in the collection studentdata.
The command for this:
db.studentdata.dropIndex({student_name: 1})
DEPARTMENT OF CSE
PREPARED BY B RANJITH KUMAR
nIndexesWas: It shows how many indexes were there before this command got executed
ok: 1: This means the command is executed successfully.
Dropping all the indexes:
db.collection_name.dropIndexes()
db.studentdata.dropIndexes()
The message “non-_id indexes dropped for collection” indicates that the default index _id will still
remain and cannot be dropped. This means that using this method we can only drop indexes that we
have created, we can’t drop the default index created on _id field.
DEPARTMENT OF CSE