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

Wk 2 5 Accessing MongoDB Using Python

This document provides a lab guide for accessing MongoDB using Python with the pymongo driver. It includes objectives, prerequisites, and step-by-step exercises for installing pymongo, connecting to the MongoDB server, and performing basic operations like inserting and querying documents. Additionally, it offers a practice exercise to reinforce the concepts learned.

Uploaded by

nguyentluc19
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Wk 2 5 Accessing MongoDB Using Python

This document provides a lab guide for accessing MongoDB using Python with the pymongo driver. It includes objectives, prerequisites, and step-by-step exercises for installing pymongo, connecting to the MongoDB server, and performing basic operations like inserting and querying documents. Additionally, it offers a practice exercise to reinforce the concepts learned.

Uploaded by

nguyentluc19
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

10/4/23, 10:20 AM 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

Prerequisites
Before starting this lab, it’ll be helpful to have knowledge about basic Python and MongoDB operations. If you’re unfamiliar with MongoDB, feel free to take a
look at the Getting Started with MongoDB and MongoDB CRUD labs!

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), that can be run on desktop or on the cloud. to complete this lab, we will be using 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 are not persisted. Every time you connect to this lab, a new environment is created for you. 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.

Exercise 1 - Install the pymongo driver


We need the pymongo driver to be installed in order to access the mongodb database from Python.

Run the below command on the terminal.


1. 1

1. python3 -m pip install pymongo

Copied!

This installs the Python mongodb driver as in the image below.

Exercise 2 - Start the server


1. Problem:

Start the mongodb server.

Click here for Hint


Click here for Solution

Run the below command on the terminal.


1. 1

1. start_mongo

Copied!

Note down the user name and password, that are be displayed in the last line of the output of the start_mongo command.
about:blank 1/6
10/4/23, 10:20 AM about:blank

Exercise 3 - Connect to mongodb server using Python


On the menu, use File->New File to create a new file, as in the image below.

Give the name as mongo_connect.py, as in the figure below, and click on OK.

Copy and paste the below code into the newly opened file.

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

about:blank 2/6
10/4/23, 10:20 AM about:blank
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!

PLEASE ENSURE THAT YOU HAVE REPLACED THE PASSWORD VALUE IN THE FILE ABOVE WITH THE PASSWORD FOR YOUR MONGODB
SERVER THAT YOU COPIED AFTER IT WAS STARTED.

Save the code file using the File->Save menu option as in the image below.

Copy and paste the below code on the terminal to execute this file.

1. 1

1. python3 mongo_connect.py

Copied!

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

Exercise 4 - Working with documents


In this exercise we 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 a new file named mongo_query.py.

about:blank 3/6
10/4/23, 10:20 AM about:blank
Copy and paste the below 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.
35. for document in docs:
36. print(document)
37.
38. # close the server connecton
39. print("Closing the connection.")
40. connection.close()

Copied!

PLEASE ENSURE THAT YOU HAVE REPLACED THE PASSWORD VALUE IN THE FILE ABOVE WITH THE PASSWORD FOR YOUR MONGODB
SERVER THAT YOU COPIED AFTER IT WAS STARTED.

Save the file.

Run the file using the below command.

about:blank 4/6
10/4/23, 10:20 AM about:blank
1. 1

1. python3 mongo_query.py

Copied!

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.

{“database”:”a database contains collections”}

{“collection”:”a collection stores the documents”}

{“document”:”a document contains the data in the form of key value pairs.”}

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

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
about:blank 5/6
10/4/23, 10:20 AM about:blank
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!

Authors
Ramesh Sannareddy

Other Contributors
Rav Ahuja

Change Log
Date (YYYY-MM-DD) Version Changed By Change Description
2022-12-22 0.5 K Sundararajan Updated pip command for pymongo installation
2021-11-17 0.4 Kathy An Updated lab instructions
2021-04-19 0.3 Steve Ryan Review pass
2021-03-19 0.2 Ramesh Sannareddy Added practice exercises.
2021-02-24 0.1 Ramesh Sannareddy Created initial version of the lab

Copyright © 2021 IBM Corporation.

about:blank 6/6

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy