MONGO DB Lab Manual-1
MONGO DB Lab Manual-1
II B Tech II Sem
MONGO DB LAB
Course Outcomes:
Upon successful completion of the course, the student will be able to: • Installing and
configuring mongoDB in windows
List of Experiments:
4. Creating collection with options before inserting the documents and drop the
collection created.
6. Querying all the documents in json format and Querying based on the criteria.
9. MongoDB Projection
Step 2: Click Next when the MongoDB installation windows pops up.
Step 3: Accept the MongoDB user Agreement and click Next.
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.We are not done
here. There are couple of steps we need to do before we can start using MongoDB.
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.
mongod --directoryperdb --dbpath "C:\Program Files\MongoDB\data\db"
--logpath "C:\Program Files\MongoDB\log\mongo.log" --logappend --rest --install
Step 4: Now you can start MongoDB as a service by typing this command:
net start MongoDB
You should see a message “MongoDB service was started successfully”.
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
In the next tutorials we will learn how to work in the MongoDB shell.
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:
2. Demonstrate how to create and drop a database in MongoDB.
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 “beginnersbook” so the command should be:
use beginnersbook
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
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
Now we are creating a collection user and inserting a document in it.
We will learn how to create collection and document in the next tutorials.
> db.user.insert({name: "Chaitanya", age: 30})
WriteResult({ "nInserted" : 1 })
> show dbs
admin 0.000GB
beginnersbook 0.000GB
local 0.000GB
As you can see that the database “beginnersbook” is not present in the list that means it has
been dropped successfully.
3. Creating the Collection in MongoDB on the fly.
db.beginnersbook.insert({
name: "Chaitanya",
age: 30,
website: "beginnersbook.com"
})
You would see this response in the command prompt.
WriteResult({ "nInserted" : 1 })
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.
> show collections
beginnersbook
4. Creating collection with options before inserting the documents and drop the
collection created.
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.
size: type: number.
This specifies the max size of collection (capped collection) in bytes.
max: type: number.
This specifies the max number of documents a collection can hold.
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.
Lets see an example of capped collection:
db.createCollection("teachers", { capped : true, size : 9232768} )
{ "ok" : 1 }
This command will create a collection named “teachers” with the max size of 9232768 bytes.
Once this collection reaches that limit it will start overwriting old entries.
> db.teachers.drop()
true
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)
So in our case the command would be this:
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.
We can also insert multiple documents using the New Bulk API introduced in MongoDB 2.6.
We will learn that in the Bulk API tutorial.
6. Querying all the documents in json format and Querying based on the criteria.
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.
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.
Here is the screenshot of all the above mentioned steps:
b. Remove only one document matching your criteria.
MongoDB Projection
In the previous tutorials, we learned how to use criteria while Querying document to get the
selected documents from the collection. In this tutorial, 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.
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)
Another way of doing the same thing:
> db.studentdata.find({}, {"_id": 0, "student_name": 0, "student_age": 0})
{ "student_id" : 2002 }
{ "student_id" : 2003 }
{ "student_id" : 2004 }
Important Note:
Some of you may get this error while using Projection in Query:
Error: error: {
"ok" : 0,
"errmsg" : "Projection cannot have a mix of inclusion and exclusion.",
"code" : 2,
"codeName" : "BadValue"
}
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:
db.studentdata.find({}, {"_id": 0, "student_name": 0, "student_age": 1})
This is because we have set student_name to 0 and other field student_age to 1. We can’t mix
these. You either set those fields that you don’t want to display to 0 or set the fields to 1 that
you want to display.
10. limit(), skip(), sort() methods in MongoDB.
Syntax:
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 learn how to specify a criteria while querying documents, read this: MongoDB Query
Document
db.studentdata.find({student_id : {$gt:2002}}).pretty()
Using limit() method to limit the documents in the result:
Lets say I do not want all the documents matching the criteria. I want only selected number of
documents then I can use limit() method to limit the number of documents. For example, if I
want only one document in output then I would do this:
> 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.studentdata.find({student_id : {$gt:2002}}).limit(1).skip(1).pretty()
{
"_id" : ObjectId("59bf63650be1d7770c3982b1"),
"student_name" : "Tim",
"student_id" : 2004,
"student_age" : 23
}
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:
> db.studentdata.find({}, {"student_id": 1, _id:0}).sort({})
{ "student_id" : 2002 }
{ "student_id" : 2003 }
{ "student_id" : 2004 }
You can also sort the documents based on the field that you don’t want to display: For
example, you can sort the documents based on student_id and display the student_age and
student_name fields.
11. MongoDB indexing
a. Create index in MongoDB
Output:
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
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.
b. Finding the indexes in a collection
nIndexesWas: It shows how many indexes were there before this command got executed
ok: 1: This means the command is executed successfully.
d. Drop all the indexes
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.
12. MongoDB with java and PHP
a. Create a simple application that uses MongoDB with Java
Project Structure
Finally, our project structure look like this.
5) Enter into Mongo Shell
Make sure, we have mongoDB installed. After installing, enter into mongo shell by typing the
following command.
1. $ mongo
Databases
We can see available databases by using the following command.
1. > show dbs
Collection
See, the created collection employee.
Record
See the inserted record.
Well, we can see that the Java program is executing fine and we can also perform other
databases operations as well.
b. Create a simple application that uses MongoDB with PHP
Duration 18:10
Loaded: 0.00%
Â
Fullscreen
Backward Skip 10sPlay VideoForward Skip 10s
1. <?php
2. require 'vendor/autoload.php';
3. // Creating Connection
4. $con = new MongoDB\Client("mongodb://localhost:27017");
5. // Creating Database
6. $db = $con->javatpoint;
7. // Creating Document
8. $collection = $db->employee;
9. // Insering Record
10. $collection->insertOne( [ 'name' =>'Peter', 'email' =>'[email protected]' ] );
11. // Fetching Record
12. $record = $collection->find( [ 'name' =>'Peter'] );
13. foreach ($record as $employe) {
14. echo $employe['name'], ': ', $employe['email']."<br>";
15. }
16. ?>
5) Execute Php Script
Execute this script on the localhost server. It will create database and store data into the
mongodb.
1. localhost/php/connect.php
Well all set, this is working fine. We can also perform other database operations as well.