Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Python + MongoDB

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

Python + MongoDB

T H E B E G I N N E R S G U I D E

PyMongo Driver

A R U N A R U N I S T O
MongoDB is a popular NoSQL (Not Only SQL)
database management system that provides
a flexible and scalable way to store and
manage data.
MongoDB is widely used in web
development, mobile app development, and
other scenarios where flexible and scalable
data storage is required. It's important to
choose the right database based on the
specific requirements of your application
and the nature of your data.
To connect Python to MongoDB, you can use
the official MongoDB drivers for python.
There are two official Python drivers:
1. PyMongo: For synchronous applications.
2. Motor: For asychronous applications.
For this part of the tutorial we are going to
use the PyMongo driver for synchronous
applications.
PyMongo is a Python driver for MongoDB
that provides a high-level API for interacting
with MongoDB databases.
Installing PyMongo:
You can install PyMongo using pip, the
Python package installer. Open your
terminal or command prompt and run:

pip install 'pymongo[srv]'

Importing PyMongo:
We are going to import the MongoClient
class to create a connection from pymongo.

from pymongo import MongoClient

For connecting the atlas cluster you need to


use the connection string from your atlas
cluster ui. for, that follow the below steps
after login into your cluster account
Click on the connect button shown in the
above figure.

Then click on the drivers option shown in the


above figure. after that select driver of you
installed and copy the connection string like
the below figure, and don’t forget to add
your ip address and change password on
connection string otherwise it will get an
error.
Next, we are going to paste the connection
string on our program, I declared it as an
environment variable for the security
purpose, I declared it on a variable called
MONGODB_URI and call it on our program.

# the connection string i loaded on .env and


# it accessed using os
MONGODB_URI = os.getenv("MONGODB_URI")

# connecting to mongodb client


# using above string
client = MongoClient(MONGODB_URI)

Getting the database names from the cluster.

print("Databases:\n",client.list_database_names())

Selecting the database from the cluster to


work

db = client.test
On the above line of code we select the
database named test.
After connecting to database we are going to
select the collection from the database here
I am going to select my collection named
test_collection.

test_collec = db.test_collection

Finally we connect our db and collection to


the program.next, we are going to do the
CRUD Operations on our program.
Inserting Data:
The sample data we are going to add into our
program

sample_data = {
"name":"arun arunisto",
"age":27,
"tags":["developer", "tech geek"],
"details":{
"job":"full-stack developer",
"organisation":"nic"},
"created_at":datetime.datetime.utcnow()
}
# inserting one data using insert_one() function
result = test_collec.insert_one(sample_data)

#checking the inserted data using refrence_id


document_id = result.inserted_id
print("Inserted _id document:",document_id)

Next, we are going to insert multiple data


using insert_many() function.

sample_data_1 = {
"name":"arun",
"age":27,
"tags":["pythonista", "cyborg"],
"details":{
"job":"AI/ML",
"organisation":"xAI"
},
"created_at":datetime.datetime.utcnow()
}
sample_data_2 = {
"name":"arunisto",
"age":27,
"tags":["backend", "fast api"],
"details":{
"job":"IOT Engineer",
"organisation":"tesla"
},
"created_at":datetime.datetime.utcnow()
}

#using insert_many() function to insert multiple data


result = test_collec.insert_many(
[sample_data_1, sample_data_2])

document_ids = result.inserted_ids
print("No. Documents added:",len(document_ids))
print("_ids of inserted:\n",document_ids)
Accessing Data:
Next, we are going to access data using
find_one() and find() methods. and also we
are going to import two packages for getting
the results in BSON format.
Importing Packages:

from bson.objectid import ObjectId


import pprint

#query to access a data


# for use Object id in your program
# u need to import it from the bson object
id = {"_id":ObjectId('654e604707f115c93d316013')}
result = test_collec.find_one(id)
print("Retrieved data:\n",result)
#pprint using to print in a document form
pprint.pprint(result)
# accessing all data/multiple data
# using find() function
result = test_collec.find()
for document in result:
pprint.pprint(document)

Updating data:

# updating a single data


# using update_one() function

doc_to_update = {'_id':
ObjectId('654e5e80ad5db1b63c82220c')}
field_to_update = {"$inc":{"age":1}}
result = test_collec.update_one(
doc_to_update, field_to_update)
print("Updated Count:",result.modified_count)
# updating multiple document
# using update_many() function

doc_filter = {"age":{"$eq":27}}
add_new_field = {"$inc":{"age":1}}
result = test_collec.update_many(
doc_filter, add_new_field)
print("Document Matched:",result.matched_count)
print("Updated:",result.modified_count)

Deleting Data:

# deleting documents
# using delete_one() method

document_to_delete = {"name":"test1"}
#deleting using delete_one() method
result = test_collec.delete_one(
document_to_delete)
print("No. of deleted documents:",
result.deleted_count)
# deleting multiple elements
# using delete_many() method

doc_to_filter = {"age":{"$eq":28}}
result = test_collec.delete_many(
doc_to_filter)
print("No.of Documents deleted:",
result.deleted_count)

$eq: means equal to its a mongodb operator


$inc: means increment its also a mongodb
operator
After every operation we use close()
function to close the cluster connection.

client.close()

You might also like