mongodb
mongodb
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
import pymongo
■ Establish a connection:
Python
client =
pymongo.MongoClient("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:
■ Updating Documents:
– Use the update_one() or update_many() methods:
import pymongo
# Establish Connection
client =
pymongo.MongoClient("mongodb://localhost:27017/")
print(db.list_collection_names())
Output:
[‘example’, ‘employee’]
By listing the all database in
system
import pymongo
# Establish Connection
client = pymongo.MongoClient("mongodb://localhost:27017/")
Print(clint.list.database_name())
Output
[‘admin’,local’,’mydatabase’,’mydb’
To check for specific database in
system
Import pymongo
client = pymongo.MongoClient("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 = pymongo.MongoClient("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 = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["mydb"]
mycol = db[“employee”]
Mydict={“name”:”Rahul”,”address”:”Mumbai”}
Mycol.insert_one(mydict)
import pymongo
client = pymongo.MongoClient("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 = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["mydb"]
mycol = db[“employee”]
For x in mycol.find():
print(x)
import pymongo
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["mydb"]
mycol = db[“employee”]
For x in mycol.find():
print(x)
Update
import pymongo
client = pymongo.MongoClient("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 mycol.find():
Print(x)
Update_many()
import pymongo
client = pymongo.MongoClient("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 = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["mydb"]
mycol = db[“employee”]
Myquery={“address”:”Mumbai”}
mycol.delete-one(myquery)
For x in mycol.find():
Print(x)
Delete_many()
import pymongo
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["mydb"]
mycol = db[“employee”]
Myquery={“address”:”{“$regex”:”^N”}}
X=mycol.delete-many(myquery)
Print(x.deleted_count,”ducuments deleted.”)
Delete all the documents
import pymongo
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["mydb"]
mycol = db[“employee”]
Myquery={“address”:”Mumbai”}
X=mycol.delete-one({ })
# print “employee”after delete
For x in mycol.find():
Print(x.deleted_count)
Commit,Rollback
From pymongo import MongoClint
From pymongo.errors import ConnectionFaillure
client = pymongo.MongoClient("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)
Network errors
Write Errors:
Schema Validation Errors:
Cursor Errors
Network Errors: These errors occur when there are issues with the network
connection between your Node.js 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
Try:
client = MongoClient("mongodb://localhost:27017/“, serverSelectionTimeoutMS=5000)
db = client.testdb
db.list_collection_name()
excepterrors.ServerSelectionTimeoutError as e:
print(“Network error as {e:}”
excepterrors.ConnectionFailureas 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.
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})
Excepterrors.OperationFailureas e:
})
Print(f”Scema validation eror:{e}”)
JSON Syntax to store data