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

Mongo Python

Uploaded by

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

Mongo Python

Uploaded by

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

4/30/24, 3:25 PM about:blank

Accessing MongoDB using Python

Estimated time needed: 30 minutes

Objectives
After completing this lab, you will be able to:

Access the MongoDB database from Python with the Pymongo driver
Perform basic operations such as selecting, inserting, and listing using Python
Create a Python program to run the MongoDB operations

About Skills Network Cloud IDE


Skills Network Cloud IDE (based on Theia and Docker) provides an environment for hands-on labs for course and project-related labs. Theia is an open-source IDE
(Integrated Development Environment) for a desktop or cloud. To complete this lab, you will use the Cloud IDE based on Theia and MongoDB running in a Docker
container.

Important notice about this lab environment


Please be aware that sessions for this lab environment do not persist. You will see a new environment every time you connect to this lab. Any data you may have
saved in the earlier session would get lost. Plan to complete these labs in a single session to avoid losing your data.

Working with files in Cloud IDE


If you are new to Cloud IDE, this section will show you how to create and edit files in your project.

To view your files and directories inside Cloud IDE, click the file's icon.

If you have cloned (using the git clone command) boilerplate/starting code, then it will look like the following:

about:blank 1/12
4/30/24, 3:25 PM about:blank

Otherwise, a blank project looks like this:

Create a new file


You can right-click and select New File to create a file in your project.

You can also choose File -> New File to do the same.

It will then prompt you to enter the name of this new file. In the example below, the new file name is sample.html.

about:blank 2/12
4/30/24, 3:25 PM about:blank

Clicking the file name sample.html in the directory structure will open the file in the right pane. You can create all different types of files, for example, FILE_NAME.js
for JavaScript files.

In the following image, we pasted some basic HTML code and then saved the file.

You can save a file with one of the following methods:

Using the menu


Press ⌘ + S on Mac or CTRL + S on Windows
Or it can Autosave it for you, too

about:blank 3/12
4/30/24, 3:25 PM about:blank

Set-up: Start MongoDB


Navigate to Skills Network Toolbox.

You will notice MongoDB is listed there but inactive.

Once you click on it, you will see more details and an icon to start it.

about:blank 4/12
4/30/24, 3:25 PM about:blank

Click Start to run a background process to configure and start your MongoDB server.

Now, your server is ready for use. This deployment has access control enabled, and MongoDB enforces authentication. So, take note of the password, as you will
need it to log in as the root user.

about:blank 5/12
4/30/24, 3:25 PM about:blank

You can now open the terminal and enter details yourself.

This action will open a new terminal at the end of the screen, as in the image below.

about:blank 6/12
4/30/24, 3:25 PM about:blank

Run the following command on the newly opened terminal. (Copy the code by selecting the copy button on the lower right of the code block and then paste it
wherever you wish.)
1. 1

1. mongosh -u root -p PASSWORD --authenticationDatabase admin local

Copied! Executed!

The command contains the username and password to connect to the MongoDB server (the text after the -p option is the password).Your output would be different
from the one shown above. Copy the command given to you, and keep it handy. You will need it in the next step.

Or you can click MongoDB CLI, which does it for you.

about:blank 7/12
4/30/24, 3:25 PM about:blank

In MongoDB CLI (mongo shell), switch the context to the training database.
1. 1

1. use training

Copied!

And create a collection called mycollection


1. 1

1. db.createCollection("mycollection")

Copied!

Exercise 1: Install the Pymongo driver


You need the Pymongo driver installed to access the MongoDB database from Python.

Open a new terminal and run the following command:

1. 1

1. python3 -m pip install pymongo

Copied!

If the above command results in error /usr/bin/python3: No module named pip, you need to install pip (PIP is a package manager for Python packages or modules)
and then install pymongo.
1. 1
2. 2
3. 3

1. curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py


2. python3 get-pip.py
3. python3 -m pip install pymongo

Copied!

This action installs the Python MongoDB driver like in the following image.

Exercise 2: Connect to mongodb server using Python


Open mongo_connect.py in IDE

Copy and paste the below code into this file.

about:blank 8/12
4/30/24, 3:25 PM about:blank
1. 1
2. 2
3. 3
4. 4
5. 5
6. 6
7. 7
8. 8
9. 9
10. 10
11. 11
12. 12
13. 13
14. 14
15. 15
16. 16
17. 17
18. 18
19. 19
20. 20
21. 21
22. 22
23. 23

1. from pymongo import MongoClient


2. user = 'root'
3. password = 'MjQwOTgtcnNhbm5h' # CHANGE THIS TO THE PASSWORD YOU NOTED IN THE EARLIER EXCERCISE - 2
4. host='localhost'
5. #create the connection url
6. connecturl = "mongodb://{}:{}@{}:27017/?authSource=admin".format(user,password,host)
7.
8. # connect to mongodb server
9. print("Connecting to mongodb server")
10. connection = MongoClient(connecturl)
11.
12. # get database list
13. print("Getting list of databases")
14. dbs = connection.list_database_names()
15.
16. # print the database names
17.
18. for db in dbs:
19. print(db)
20. print("Closing the connection to the mongodb server")
21.
22. # close the server connecton
23. connection.close()

Copied!

Note: Please ensure that you have replaced the password value in the file above with the password for your MongoDB server.

Save the code file using the File->Save menu option, like in the following image.

Copy and paste the following code on the terminal to run this file.
1. 1

1. python3 mongo_connect.py

Copied!

You should see an output like the one in the following image.

about:blank 9/12
4/30/24, 3:25 PM about:blank

Exercise 4 - Working with documents


In this exercise, you will make the Python program do the following tasks:

Connect to the MongoDB server


Select a database named training
Select a collection named python
Insert a sample document
Query all the documents in the training database and python collection
Close the connection to the server

Open mongo_connect.py in IDE

Copy and paste the following code into mongo_query.py.

1. 1
2. 2
3. 3
4. 4
5. 5
6. 6
7. 7
8. 8
9. 9
10. 10
11. 11
12. 12
13. 13
14. 14
15. 15
16. 16
17. 17
18. 18
19. 19
20. 20
21. 21
22. 22
23. 23
24. 24
25. 25
26. 26
27. 27
28. 28
29. 29
30. 30
31. 31
32. 32
33. 33
34. 34
35. 35
36. 36
37. 37
38. 38
39. 39
40. 40

1. from pymongo import MongoClient


2. user = 'root'
3. password = 'MjQwOTgtcnNhbm5h' # CHANGE THIS TO THE PASSWORD YOU NOTED IN THE EARLIER EXCERCISE - 2
4. host='localhost'
5. #create the connection url
6. connecturl = "mongodb://{}:{}@{}:27017/?authSource=admin".format(user,password,host)
7.
8. # connect to mongodb server
9. print("Connecting to mongodb server")
10. connection = MongoClient(connecturl)
11.
12. # select the 'training' database
13.
14. db = connection.training
15.
16. # select the 'python' collection
17.
18. collection = db.python
19.
20. # create a sample document
21.
22. doc = {"lab":"Accessing mongodb using python", "Subject":"No SQL Databases"}
23.
24. # insert a sample document
25.
26. print("Inserting a document into collection.")
27. db.collection.insert_one(doc)
28.
29. # query for all documents in 'training' database and 'python' collection
30.
31. docs = db.collection.find()
32.
33. print("Printing the documents in the collection.")
34.

about:blank 10/12
4/30/24, 3:25 PM about:blank
35. for document in docs:
36. print(document)
37.
38. # close the server connecton
39. print("Closing the connection.")
40. connection.close()

Copied!

Note: Please ensure you have replaced the password value in the above file with the password for the MongoDB server you copied.

Save the file.

Run the file using the following command.


1. 1

1. python3 mongo_query.py

Copied!

You should see an output like the one in the following below.

Practice exercise
Write a Python program that can:

Connect to the MongoDB server


Select a database named training
Select a collection named mongodb_glossary
Insert the following documents into the collection mongodb_glossary
1. 1
2. 2
3. 3
1. {"database":"a database contains collections"}
2. {"collection":"a collection stores the documents"}
3. {"document":"a document contains the data in the form of key value pairs."}
Copied!

Query and print all the documents in the training database and mongodb_glossary collection
Close the connection to the server

Solution to practice exercise


1. 1
2. 2
3. 3
4. 4
5. 5
6. 6
7. 7
8. 8
9. 9
10. 10
11. 11
12. 12
13. 13
14. 14
15. 15
16. 16
17. 17
18. 18
19. 19
20. 20
21. 21
22. 22
23. 23
24. 24
25. 25
26. 26
27. 27
28. 28
29. 29
30. 30
31. 31
32. 32
33. 33
34. 34
35. 35
36. 36
37. 37
38. 38
39. 39
40. 40
41. 41
42. 42
43. 43
44. 44

about:blank 11/12
4/30/24, 3:25 PM about:blank
1. from pymongo import MongoClient
2. user = 'root'
3. password = 'MjQwOTgtcnNhbm5h' # CHANGE THIS TO THE PASSWORD YOU NOTED IN THE EARLIER EXCERCISE - 2
4. host='localhost'
5. #create the connection url
6. connecturl = "mongodb://{}:{}@{}:27017/?authSource=admin".format(user,password,host)
7.
8. # connect to mongodb server
9. print("Connecting to mongodb server")
10. connection = MongoClient(connecturl)
11.
12. # select the 'training' database
13.
14. db = connection.training
15.
16. # select the 'python' collection
17.
18. collection = db.mongodb_glossary
19.
20. # create documents
21.
22. doc1 = {"database":"a database contains collections"}
23. doc2 = {"collection":"a collection stores the documents"}
24. doc3 = {"document":"a document contains the data in the form or key value pairs."}
25.
26. # insert documents
27. print("Inserting documents into collection.")
28.
29. db.collection.insert_one(doc1)
30. db.collection.insert_one(doc2)
31. db.collection.insert_one(doc3)
32.
33. # query for all documents in 'training' database and 'python' collection
34.
35. docs = db.collection.find()
36.
37. print("Printing the documents in the collection.")
38.
39. for document in docs:
40. print(document)
41.
42. # close the server connecton
43. print("Closing the connection.")
44. connection.close()

Copied!

Summary
In this lab, you have gained an understanding of working with MongoDB in Python.

Author(s)
Muhammad Yahya

(C) IBM Corporation. All rights reserved.

about:blank 12/12

You might also like