PYTHON
INTERACTION WITH
MONGODB
Sabitri Pradhan
■ MongoDB, a popular NoSQL
database, offers flexibility and
scalability for modern applications.
Python, a versatile programming
language, provides efficient tools to
interact with MongoDB. This guide
will delve into the essential aspects
Introductio
of using Python to connect, query,
and manipulate data within
MongoDB databases.
n ■ Prerequisites
• Python installation: Ensure
you have Python installed on
your system.
• PyMongo installation: Install
the PyMongo library, a Python
Bashdriver for MongoDB, using pip
pip install pymongo
Connecting to a MongoDB
Database
■ Import the PyMongo library:
Python
import pymongo
■ Establish a connection:
Python
client =
[Link]("mongodb://localhost:27017/")
• Replace the connection string: If your MongoDB instance is hosted
elsewhere, replace the connection string with the appropriate URL.
■ Load a Database:
Python
db = client["mydatabase"]
Basic Operations - CRUD
■ Creating a Collection:
– A collection in MongoDB is analogous to a table in a relational database.
– Use the create_collection() method:
collection = db.create_collection("mycollection")
■ Inserting Documents:
– Documents in MongoDB are similar to rows in a table.
– Use the insert_one() or insert_many() methods:
# Insert a single document
document = {"name": "Alice", "age": 30}
result = collection.insert_one(document)
# Insert multiple documents
documents = [ {"name": "Bob", "age": 25},
{"name": "Charlie", "age": 35} ]
result = collection.insert_many(documents)
Basic Operations - CRUD
■ Querying Documents:
– Use the find() method to retrieve documents:
# Find all documents
results = [Link]()
# Find documents with specific criteria
results = [Link]({"age": {"$gt": 30}})
■ Updating Documents:
– Use the update_one() or update_many() methods:
# Update a single document
result = collection.update_one({"name": "Alice"}, {"$set":
{"age": 31}})
# Update multiple documents
result = collection.update_many({"age": {"$lt": 30}},
{"$inc": {"age": 1}})
Basic Operations - CRUD
■ Deleting Documents:
– Use the delete_one() or delete_many() methods:
# Delete a single document
result = collection.delete_one({"name": "Bob"})
# Delete multiple documents
result = collection.delete_many({"age": {"$gt": 35}})
Example Programs
■ List all collections in a database:
– Use the list_collection_names() method of db object:
import pymongo
# Establish Connection
client =
[Link]("mongodb://localhost:27017/")
# Load the Database
db = client["mydb"]
# choose the collection to work with
mycol = db[“employee”]
print(db.list_collection_names())
Output:
[‘example’, ‘employee’]
By listing the all database in
system
import pymongo
# Establish Connection
client = [Link]("mongodb://localhost:27017/")
Print([Link].database_name())
Output
[‘admin’,local’,’mydatabase’,’mydb’
To check for specific database in
system
Import pymongo
client = [Link]("mongodb://localhost:27017/")
dblist=client.list_database_names()
If “mydb in dblist:
print(”data base axists”)
To check for collection in
database
import pymongo
client = [Link]("mongodb://localhost:27017/")
db = client["mydb"]
collist=db.list_collection_names()
If “employee “ in collist:
Print(“collection exist”)
Example of create or insert a
record
import pymongo
client = [Link]("mongodb://localhost:27017/")
db = client["mydb"]
mycol = db[“employee”]
Mydict={“name”:”Rahul”,”address”:”Mumbai”}
Mycol.insert_one(mydict)
import pymongo
client = [Link]("mongodb://localhost:27017/")
db = client["mydb"]
mycol = db[“employee”]
Mydilist=[
{“name”:”Rahul”,”address”:”Mumbai”},
{“name”:”Rahul”,”address”:”Mumbai”},
{“name”:”Rahul”,”address”:”Mumbai”}
]
X=Mycol.insert_many(mydict)
Print(x.inserted_ids)
Read or find
import pymongo
client = [Link]("mongodb://localhost:27017/")
db = client["mydb"]
mycol = db[“employee”]
For x in [Link]():
print(x)
import pymongo
client = [Link]("mongodb://localhost:27017/")
db = client["mydb"]
mycol = db[“employee”]
For x in [Link]():
print(x)
Update
import pymongo
client = [Link]("mongodb://localhost:27017/")
db = client["mydb"]
mycol = db[“employee”]
Myquery={“address”:”Mumbai”}
Newvalue={“$set”:{“address”:”Navi Mumbai”}}
mycol.update_one(myquery,newvalue)
# print “employee”after update
For x in [Link]():
Print(x)
Update_many()
import pymongo
client = [Link]("mongodb://localhost:27017/")
db = client["mydb"]
mycol = db[“employee”]
Myquery={“address”:{“$regex”:”^N”}}
Newvalue={“$set”:{“name”:”Manisha”}}
x=mycol.update_many(myquery,newvalue)
# print “employee”after update
Print(x.modified_count,”documents updated.”)
Delete
import pymongo
client = [Link]("mongodb://localhost:27017/")
db = client["mydb"]
mycol = db[“employee”]
Myquery={“address”:”Mumbai”}
[Link]-one(myquery)
For x in [Link]():
Print(x)
Delete_many()
import pymongo
client = [Link]("mongodb://localhost:27017/")
db = client["mydb"]
mycol = db[“employee”]
Myquery={“address”:”{“$regex”:”^N”}}
X=[Link]-many(myquery)
Print(x.deleted_count,”ducuments deleted.”)
Delete all the documents
import pymongo
client = [Link]("mongodb://localhost:27017/")
db = client["mydb"]
mycol = db[“employee”]
Myquery={“address”:”Mumbai”}
X=[Link]-one({ })
# print “employee”after delete
For x in [Link]():
Print(x.deleted_count)
Commit,Rollback
From pymongo import MongoClint
From [Link] import ConnectionFaillure
client = [Link]("mongodb://localhost:27017/")
db = client[“shop"]
Order_collection= db[“order”]
payment_collection= db[“payments”]
session=clint.start_session()
session.start_transaction()
try:
order_collection.update_one({‘_id:1},’$set’:{status’:processed}), session=session)
payment_collection.insert_one({‘_id:1},:1,’amount”:100{status’:paid}), session=session)
#commit the transaction
Session.commit_transaction()
print(“transaction committed”)
except Exception as e:
session.abort_transaction()
print(“transaction aborted due to error”)
finally:
session.end_session()
Handling Errors
Types of errors such as
Network errors
Write Errors:
Schema Validation Errors:
Cursor Errors
Network Errors: These errors occur when there are issues with the network
connection between your [Link] application and the MongoDB server. Examples
include connection timeouts, network failures, or server unavailability.
Handling in python: The pyMongo library raises exceptions such
asServerSelectionTimeError, ConnectionFailure or NetworkTimeout
From pymongo import MongoClint ,errors
Try:
client = MongoClient("mongodb://localhost:27017/“, serverSelectionTimeoutMS=5000)
db = [Link]
db.list_collection_name()
[Link] as e:
print(“Network error as {e:}”
[Link] e:
print(f”Connection faild:{e}”)
Write Errors:
These errors occur during write operations such as inserts, updates, or deletes.
Examples include write conflicts, write concern failures, or write operations
exceeding the server's limitations.
From pymongo import MongoClint ,errors
client = MongoClient("mongodb://localhost:27017/")
db = [Link]
Try :
[Link].insert_one({“_id”: 1, “name”: “john”})
[Link].insert_one({“_id”: 1, “name”: “jane”}) # this will cause a
DuplicateKeyError
[Link] e:
print(f”write error: {e}”)
Schema Validation Errors
Schema validation errors occurs when a document fails to meet the
validation criteria specified for a collection. MongoDB allows you to
define JSON schema-based validation rules that documents must adhere.
pyMongo raises OperationFailure when a document violates the schema
validation rules during an insert or update operation.
Example:
From pymongo import MongoClint , errors
client = MongoClient("mongodb://localhost:27017/")
db = client . testdb
Try :
db.create_collection(“contacts”, validator={
“$jsonSchema”: {
“bson type”:””object”,”required”:”object”,
“required”:[“phone”],”
properties”:{“phone”:
{“bsonType”: “string”, ”description”: ,”must be a string and is required
”},
}
},
“validationAction”:”error” })
db,contacts.insert_one({name”: “john” , “phone”: 12345})
[Link] e:
})
Print(f”Scema validation eror:{e}”)
JSON Syntax to store data
•Objects in JSON are collections of key/value pairs enclosed in curly braces {} .
•Each key is a string (enclosed in double quotes " ) followed by a colon : , and the key/value pairs are
separated by commas (,) .
Example: {"firstName": "John", "lastName": "Doe", "age": 30}
But Using 'Arrays'
•Arrays are ordered lists of values, enclosed in square brackets [] .
•Values within an array are separated by commas (,) .
• Example: ["apple", "banana", "cherry"]
"Data Structures": [
{
"Name" : "Trees",
"Course" : "Intoduction of Trees",
"Content" : [ "Binary Tree", "BST",
"Generic Tree"]
},
{
"Name" : "Graphs",
"Topics" : [ "BFS", "DFS", "Topological Sort" ]
}
]
}