0% found this document useful (0 votes)
51 views

MongoDBTutorialApril2021 Robo3T

This document provides an introduction to basic MongoDB concepts like collections, documents, and queries. It shows how to connect to a MongoDB database, create collections, insert documents, and run different types of queries.

Uploaded by

Ashim Mahat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views

MongoDBTutorialApril2021 Robo3T

This document provides an introduction to basic MongoDB concepts like collections, documents, and queries. It shows how to connect to a MongoDB database, create collections, insert documents, and run different types of queries.

Uploaded by

Ashim Mahat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

An Introduction to MongoDB

In this tutorial we will explore some of the basic concepts behind using MongoDB. We will
use the freely available GUI Robo3T to run queries against the MongoDB server. There is a
more advanced GUI available called Studio 3T which contains a similar shell (Intellishell) for
entering MongoDB queries, you may also use that if you wish.

Connecting to MongoDB
When you first run MongoDB, you should be presented with the following window.

The first task is to create a connection to your MongoDB database. To do this, you should
follow the instructions in the separate file ‘How to install and run MongoDB with
Robo3T.pdf’ which you can also find on Canvas.

© David Nelson/Trijean Julien, version 2.2, April 2021

Part of this tutorial was written by an exchange student, Trijean Julien, from the University of Bordeaux as part
of a project during the second semester in 2018.
Now run Robo3T and connect following the instructions in the above file.

Click the symbol next to the connection name to list your databases. You should
see the name of your database listed. Move the cursor over the name of your database (in
the example below the database is called test), click the right-hand mouse button and select
the Open Shell option, as shown below.

MongoDB will then open a shell window in which you can enter and run MongoDB
commands.

© David Nelson/Trijean Julien, version 2.2, April 2021

2
Creating Collections and Inserting Data
In MongoDB, we create Collections in which to store and group our data. Collections can loosely be
thought of as similar to tables in a relational database, however as they are schemaless the format
of data instances inside a collection can differ, unlike a relational database where each row is
required to be the same structure. In MongoDB we call each data record a document. Within a
document we have a collection of key-value pairs. For example, in the example below we are
creating a new student document with one key-value pair, the key being name, and the value being
Joe.

The simplest way to create a collection in MongoDB is to insert a document. To do this we use the
db.insert command. Let’s create a simple student document. In your shell, type the following
MongoDB statement.

db.student.insert({name: "Joe"});

Just like in Oracle, don’t forget the semi-colon at the end of the statement.

To execute the command, we use the button which can be found in the menu bar of
MongoDB. Just like in Oracle SQL Developer, this will run all commands in the shell, or highlighted
code if we have highlighted a particular command.

Run the command, and you should see the following result:

© David Nelson/Trijean Julien, version 2.2, April 2021

3
You should see the message:

This means that you MongoDB statement has correctly run. If you get an error message, then
correct the code to ensure it matches as above and run again.

Congratulations! You have just inserted your first MongoDB document into a collection called
student. Now, insert a second student, Sarah. Note that you can type more than one command into
the shell window – then you highlight the command that you want to run with the mouse before

clicking the Run button, which will ensure that only the command you have highlighted will
run (not selecting a command will mean all commands in the window will be run).

Querying
To query, we use the find() operation. As with the insert operation, we use the command

db.student.find();

to return all documents in the student collection, i.e. to return all students. Type and execute this
command and you should get output similar to the example below:

© David Nelson/Trijean Julien, version 2.2, April 2021

4
You probably need to click the icon next to each document to view its contents. You will also
notice that the Object identifier for each document, i.e. the long hexadecimal number, will vary from
the example output above. This is a system generated unique number so will vary from system to
system.

To find a specific document we can specify a query condition to the find operation. For example, to
find “Sarah” we would issue the query:

db.student.find({name: "Sarah"});

Run the query and ensure you take note of the results.

More Complex Documents


MongoDB allows us to create more structured documents that the ones we have seen so far. Say,
for example, that we had a list of students where we want to store their contact details and
information about the modules that they are taking. When we insert a record we can insert a
comma separated list of values, for example run the command below:

db.student.insert({name: "Fred ", phonenos: "0191 1234567 "});

Now, use the command to retrieve all students, and compare the difference between the new
student you have created compared to the previous two students, as shown below:

You will that your new student now has a telephone number value as well as a name.

© David Nelson/Trijean Julien, version 2.2, April 2021

5
Notice a big difference to relational databases, in that we are no longer restricted to all documents
in the same collection having the same attributes. We are using a semi-structured schema, whereby
we do not have a pre-defined schema (i.e. table definition as in Oracle), but our documents in a
collection can have different structure.

Insert the following document.

db.student.insert({name: "William",
phonenos: "01782 294000, 01785 253463",
module1:"CET315 Advanced Databases Tue 9-10",
module2:"CET300 Computing Project Wed 3-4.30"
});

Run a query to retrieve only William, and view the results, which should appear as below.

This is a much more complex document,, however we can improve on this and introduce nesting of
values, similar to the concept of a nested-relation in Oracle. Let’s say, for example, for a module we
want to include a list of assessments as well as the module name and information. Enter and run the
following insert command:

db.student.insert({name: "Jane",

phonenos: "01782 295000",

module1:"Cet201 Information Systems Mon 2-6pm",

© David Nelson/Trijean Julien, version 2.2, April 2021

6
assessments:{

assessment1:"01-06-2012, Information Systems, 50%",

assessment2:"02-06-2012, Networking, 70%"}

});

Run a query to retrieve the new document you have inserted, and you should see the result similar
to the screenshot below:

And in our final example, we can have multiple values within a nested value, e.g.

db.student.insert({name: "Thomas",
phonenos: "01782 294000, 01785 253463",
module1: {code: "CET315",
name: "Advanced Databases",
time: "Tue 9-10"},
module2: {code: "CET300",
name: "Computing Project",
time: "Wed 3-4.30"}
});

Retrieve your newly created document and the result should appear as below:

© David Nelson/Trijean Julien, version 2.2, April 2021

7
If we want to search within an embedded document, we use the nested dot notation similar to
Oracle, however we must also insert the key in quotation marks. For example, to retrieve all
students whose first module is CET315 would require the following query.

db.student.find({"module1.code": "CET315"});

Run this query and you should get the following result:

Other Queries
We can write more expressive queries, i.e. to search for multiple values or to test more than one
condition. Run each of the following queries, and ensure you understand the result by viewing the
resultant output:

1. db.student.find({$or: [{name: "Jane"}, {phonenos:"0191


1234567"}]});
2. db.student.find({$and: [{name: "Fred"}, {phonenos:"0191
1234567"}]});
3. db.student.find({name: {"$in": ["Fred", "Jane"]}});

© David Nelson/Trijean Julien, version 2.2, April 2021

8
Now Your Turn
This was only a very simple tutorial on MongoDB, to give you a taste of one of the more popular
NoSQL systems. We have only considered very simple operations (create, retrieve) and not covered
updates and deletions, nor how to link documents using ObjectIDs. These further operations are
covered in the MongoDB tutorial which can be found at:

http://docs.mongodb.org/manual/tutorial/getting-started/

In this you should look at the sections ‘Getting Started’, and ‘MongoDB CRUD Operations’ which take
you through more of the Create, Retrieve, Insert and Delete (CRUD) operations in MongoDB. The
web site contains a test Mongo shell but of course you can run through the materials using Robo3T
and your Mongo installation.

Learn how to manipulate data set


First of all you need to download a JSON Data set. For the example we will use a world bank data set
which you can download from Canvas.

1. Download the file world_bank.json from Canvas


2. open the file you have just downloaded with Notepad++
2- Select all (Ctrl+a)
3- Copy (Ctrl+c)
4 – Create a new collection in MongoDB – call this “test”. You can do this by typing the command:

db.createCollection(“test”);
© David Nelson/Trijean Julien, version 2.2, April 2021

9
5- right click on the new collection in Robot3T and then select "insert document"

6- Select all the content


7 – remove the existing { and } characters in the insert window
8 - Paste (Ctrl+v)
9 – Validate the code to ensure that the code is error free – if not clear the window and test it again
10 - click on "save"

Then verify that all is well installed by using db.test.find(); into Robo 3T

You should have 50 documents as per the screenshot below:

© David Nelson/Trijean Julien, version 2.2, April 2021

10
Filter and project data
1. Retrieve all data concerning “Kingdom of Morocco” at the date of 2013. You should get 9
documents. Here is a screenshot of the data you have to find:

© David Nelson/Trijean Julien, version 2.2, April 2021

11
2. Try now to keep the same data, but to include one more country like “Hashemite Kingdom
of Jordan” at the same period. You should get 14 documents now. Here is a screenshot of
what you may have:

Now if we want to print out only certain values of the data we must add the key plus a value of 1
into a brace. This is an example with the key “lendprojectcost”:
© David Nelson/Trijean Julien, version 2.2, April 2021

12
(if you don’t want the id value in default you must add {"something":1, _id:0})

3. Print out only the name of their “mjsector_namecode” of the data you have selected just
before. You may obtain something like this:

© David Nelson/Trijean Julien, version 2.2, April 2021

13
Now we must see all the operator we could use to filter the data. We use them like that
"something":{$gt:10}.

Here are some operators:

$gt | $gte $ls | $lse $ne $in | $nin $not $exists $size

Greater Less Than Not Equal in |not in Negation key Exists size of a
Than Equal Equal list

For example:

4. Try to select any data concerning a project which costs more than 500 000 (the key is
“lendprojectcost”).
© David Nelson/Trijean Julien, version 2.2, April 2021

14
Update and delete data

To update your data you must use .update() function and use the operator $set to specify which
values you want to change. For example:

The line containing {"multi":true} is used when you want to update multiple documents.

To delete a document you will use the .remove() function like.update but without needing an
operator, for example :

© David Nelson/Trijean Julien, version 2.2, April 2021

15
© David Nelson/Trijean Julien, version 2.2, April 2021

16
Pattern matching and Indexes
$regex provides regular expression capabilities for pattern matching strings in queries.

For example :

Sort operations that use an index often have better performance than those that do not use an
index. In addition, sort operations that do not use an index will abort when they use 32 megabytes
of memory.

To create an index you must do:

Here I created multiple references in the index

To use one of the references you must do:

© David Nelson/Trijean Julien, version 2.2, April 2021

17
Here I’m doing an ascending sort on “approvalfy” index.

Aggregate queries
The function .aggregate() uses a pipeline (a sequence of data aggregation operations). Here is a
description of the list of the operators that could be used into the aggregate:

{$match:{}} {$project:{}} {$sort:{}} {$group:{}} {$unwind:{}}

use like a filter use like a print use to sort the group documents takes a list of
final result by value, the exit value and
is a new produces for
collection each element of
the list a new
document output
with this element

Here is an example to do a .find() with aggregation:

© David Nelson/Trijean Julien, version 2.2, April 2021

18
Now I will show you an example of the 3 other operators, but to make the example more user-
friendly, I put the operator into variable:

Here the $key like “$peopleRate” is to traverse over the value. So the unwind variable is to select
each values from the list to get an average of them. If you want to sort the result in descending
order you must do like me and use the “-1” value.

1. Try now to retrieve all average of “lendprojectcost” for a country in 2013 in the descending
order.

Map-reduce
Map-reduce is a data processing paradigm for condensing large volumes of data into useful
aggregated results.

For example I want to get the total price per country that the bank lend them:

© David Nelson/Trijean Julien, version 2.2, April 2021

19
1. By use of the Map Reduce example try to retrieve the average percent of the
“majorsector_percent.Name”.

© David Nelson/Trijean Julien, version 2.2, April 2021

20

You might also like