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

Python-MongoDB

Uploaded by

aboobackera839
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)
3 views

Python-MongoDB

Uploaded by

aboobackera839
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/ 36

PYTHON MONGODB

PYTHON MONGODB

• Python can be used in database applications.


• One of the most popular NoSQL database is MongoDB.
• MongoDB stores data in JSON-like documents, which makes the database very
flexible and scalable.
• You can download a free MongoDB database at https://www.mongodb.com
• Install PyMongo Driver - Python needs a PyMongo driver to access the MongoDB
database.
• Download and install " PyMongo"
• pip install pymongo
CREATE DATABASE

• To create a database in MongoDB, start by creating a MongoClient object, then


specify a connection URL with the correct ip address and the name of the database
you want to create.
• MongoDB will create the database if it does not exist, and make a connection to it
CREATE DATABASE

# Create database “mydatabase”


import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")

mydb = myclient["mydatabase"]

• In MongoDB, a database is not created until it gets content!


• MongoDB waits until you have created a collection (table), with at least one
document (record) before it actually creates the database (and collection).
LIST ALL DATABASES

• In MongoDB, a database is not created until it gets content, so if this is your first
time creating a database, you should create collection and create document before
you check if the database exists!
• You can check if a database exist by listing all databases in you system:

import pymongo
myclient = pymongo.MongoClient('mongodb://localhost:27017/')
print(myclient.list_database_names())
CHECK IF DB EXISTS

• Check if "mydatabase" exists:


import pymongo
myclient = pymongo.MongoClient('mongodb://localhost:27017/')
dblist = myclient.list_database_names()
if "mydatabase" in dblist:
print("The database exists.")
else:
print("The database does not exist.")
CREATING A COLLECTION
• A collection in MongoDB is the same as a table in SQL databases
• To create a collection in MongoDB, use database object and specify the name of
the collection you want to create.
• MongoDB will create the collection if it does not exist
• Create a collection called "customers“

import pymongo
myclient = pymongo.MongoClient('mongodb://localhost:27017/')
mydb = myclient['mydatabase']
mycol = mydb["customers"]
CHECK IF COLLECTION EXISTS

• In MongoDB, a collection is not created until it gets content, so if this is your first time
creating a collection, you should create document before you check if the collection exists!
• You can check if a collection exist in a database by listing all collections:
• Return a list of all collections in your database:

import pymongo
myclient = pymongo.MongoClient('mongodb://localhost:27017/')
mydb = myclient['mydatabase']
mycol = mydb["customers"]
print(mydb.list_collection_names())
CHECK IF COLLECTION EXISTS

• You can check a specific collection by name:


• Check if the "customers" collection exists:

collist = mydb.list_collection_names()
if "customers" in collist:
print("The collection exists.")
else:
print("The collection does not exist.")
INSERT DOCUMENT

• A document in MongoDB is the same as a record in SQL databases


• Insert Document Into Collection:
• To insert a document in MongoDB, into a collection, we use the insert_one()
method
• The first parameter of the insert_one() method is a dictionary containing the
name(s) and value(s) of each field in the document you want to insert.
INSERT DOCUMENT

• Insert a document in the "customers" collection:

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

mydict = { "name": "John", "address": "Highway 37" }

x = mycol.insert_one(mydict)
RETURN THE _ID FIELD

• insert_one() method returns a InsertOneResult object, which has a property, inserted_id ,


that holds the id of the inserted document
• Insert another record in the "customers" collection, and return the value of the _id field

import pymongo
myclient = pymongo.MongoClient('mongodb://localhost:27017/')
mydb = myclient['mydatabase']
mycol = mydb["customers"]
mydict = { "name": "Peter", "address": "Lowstreet 27" }
x = mycol.insert_one(mydict)
print(x.inserted_id)
RETURN THE _ID FIELD
• If you do not specify an _id field, then MongoDB will add one for you and
assign a unique id for each document
• In the example above no _id field was specified, so MongoDB assigned a
unique _id for the record (document).
INSERT MULTIPLE DOCUMENTS

• To insert multiple documents INTO a collection in MongoDB, we use the


insert_many() method
• The first parameter of the insert_many() method is a list containing
dictionaries with the data you want to insert
INSERT MULTIPLE DOCUMENTS
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
mylist = [
{ "name": "Amy", "address": "Apple st 652"},
{ "name": "Hannah", "address": "Mountain 21"},
{ "name": "Michael", "address": "Valley 345"},
{ "name": "Sandy", "address": "Ocean blvd 2"},
{ "name": "Betty", "address": "Green Grass 1"},
{ "name": "Richard", "address": "Sky st 331"},
{ "name": "Susan", "address": "One way 98"},
{ "name": "Vicky", "address": "Yellow Garden 2"},
{ "name": "Ben", "address": "Park Lane 38"},
{ "name": "William", "address": "Central st 954"},
{ "name": "Chuck", "address": "Main Road 989"},
{ "name": "Viola", "address": "Sideway 1633"}
]
x = mycol.insert_many(mylist)
#print list of the _id values of the inserted documents:
print(x.inserted_ids)
INSERT MULTIPLE DOCS, WITH SPECIFIED IDS
• If you do not want MongoDB to assign unique ids for you document, you can specify
the _id field when you insert the document(s).
• Remember that the values has to be unique.
• Two documents cannot have the same _id.
INSERT MULTIPLE DOCUMENTS
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
mylist = [
{ "_id": 1, "name": "John", "address": "Highway 37"},
{ "_id": 2, "name": "Peter", "address": "Lowstreet 27"},
{ "_id": 3, "name": "Amy", "address": "Apple st 652"},
{ "_id": 4, "name": "Hannah", "address": "Mountain 21"},
{ "_id": 5, "name": "Michael", "address": "Valley 345"},
{ "_id": 6, "name": "Sandy", "address": "Ocean blvd 2"},
{ "_id": 7, "name": "Betty", "address": "Green Grass 1"},
{ "_id": 8, "name": "Richard", "address": "Sky st 331"},
{ "_id": 9, "name": "Susan", "address": "One way 98"},
{ "_id": 10, "name": "Vicky", "address": "Yellow Garden 2"},
{ "_id": 11, "name": "Ben", "address": "Park Lane 38"},
{ "_id": 12, "name": "William", "address": "Central st 954"},
{ "_id": 13, "name": "Chuck", "address": "Main Road 989"},
{ "_id": 14, "name": "Viola", "address": "Sideway 1633"}
]
x = mycol.insert_many(mylist)
#print list of the _id values of the inserted documents:
print(x.inserted_ids)
FIND ONE
• To select data from a collection in MongoDB, we can use the find_one()
method.
• The find_one() method returns the first occurrence in the selection.
• Find the first document in the customers collection:
import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

x = mycol.find_one()

print(x)
FIND ALL

• To select data from a collection in MongoDB, we can also use the find() method.
• The find() method returns all occurrences in the selection.
• The first parameter of the find() method is a query object.
• In this example we use an empty query object, which selects all documents in the
collection.
• No parameters in the find() method gives you the same result as SELECT * in
MySQL.
FIND ALL

• Return all documents in the "customers" collection, and print each document:

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

for x in mycol.find():
print(x)
RETURN ONLY SOME FIELDS
• The second parameter of the find() method is an object describing which fields to include in
the result.
• This parameter is optional, and if omitted, all fields will be included in the result.
• Return only the names and addresses, not the _ids
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]

for x in mycol.find({},{ "_id": 0, "name": 1, "address": 1 }):


print(x)
RETURN ONLY SOME FIELDS
• You are not allowed to specify both 0 and 1 values in the same object (except if one of the
fields is the _id field). If you specify a field with the value 0, all other fields get the value 1,
and vice versa:
• This example will exclude "address" from the result:

import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
for x in mycol.find({},{ "address": 0 }):
print(x)
RETURN ONLY SOME FIELDS
• You get an error if you specify both 0 and 1 values in the same object (except if one
of the fields is the _id field):

import pymongo
myclient =
pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
for x in mycol.find({},{ "name": 1, "address": 0 }):
print(x)
QUERY
• Filter the Result When finding documents in a collection, you can filter the result by using a
query object.
• The first argument of the find() method is a query object, and is used to limit the search.

# Find document(s) with the address "Park Lane 38":


import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
myquery = { "address": "Park Lane 38" }
mydoc = mycol.find(myquery)
for x in mydoc:
print(x)
ADVANCED QUERY
• To make advanced queries you can use modifiers as values in the query object.
• E.g. to find the documents where the "address" field starts with the letter "S" or higher
(alphabetically), use the greater than modifier: {"$gt": "S"}:

# Find documents where address starts with the letter "S" or higher:
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
myquery = { "address": { "$gt": "S" } }
mydoc = mycol.find(myquery)
for x in mydoc:
print(x)
FILTER WITH REGULAR EXPRESSIONS
• Find documents where the address starts with the letter "S":

import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
myquery = { "address": { "$regex": "^S" } }
mydoc = mycol.find(myquery)

for x in mydoc:
print(x)
SORT THE RESULT
• Use the sort() method to sort the result in ascending or descending order.
• The sort() method takes one parameter for "fieldname" and one parameter for "direction"
(ascending is the default direction).
# Sort the result alphabetically by name:
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
mydoc = mycol.find().sort("name")
for x in mydoc:
print(x)
SORT DESCENDING

• Sort the result reverse alphabetically by name:

import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
mydoc = mycol.find().sort("name", -1)

for x in mydoc:
print(x)
DELETE DOCUMENT

• To delete one document, we use the delete_one() method.


• The first parameter of the delete_one() method is a query object defining which document to
delete.
• Note: If the query finds more than one document, only the first occurrence is deleted.
# Delete the document with the address "Mountain 21":
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
myquery = { "address": "Mountain 21" }
mycol.delete_one(myquery)
DELETE MANY DOCUMENTS

• To delete more than one document, use the delete_many() method.


• The first parameter of the delete_many() method is a query object defining which
documents to delete.
# Delete all documents were the address starts with the letter S:
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
myquery = { "address": {"$regex": "^S"} }
x = mycol.delete_many(myquery)
print(x.deleted_count, " documents deleted.")
DELETE ALL DOCUMENTS IN A COLLECTION

• To delete all documents in a collection, pass an empty query object to the


delete_many() method:
• Delete all documents in the "customers" collection:

import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
x = mycol.delete_many({})
print(x.deleted_count, " documents deleted.")
UPDATE COLLECTION
• You can update a record, or document as it is called in MongoDB, by using the update_one() method.
• The first parameter of the update_one() method is a query object defining which document to update.
• Note: If the query finds more than one record, only the first occurrence is updated. The second
parameter is an object defining the new values of the document.

# Change the address from "Valley 345" to "Canyon 123":


import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
myquery = { "address": "Valley 345" }
newvalues = { "$set": { "address": "Canyon 123" } }
mycol.update_one(myquery, newvalues)
#print "customers" after the update:
for x in mycol.find():
print(x)
UPDATE MANY

• To update all documents that meets the criteria of the query, use the update_many() method.
# Update all documents where the address starts with the letter "S":
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
myquery = { "address": { "$regex": "^S" } }
newvalues = { "$set": { "name": "Minnie" } }
x = mycol.update_many(myquery, newvalues)
print(x.modified_count, "documents updated.")
LIMIT THE RESULT
• To limit the result in MongoDB, we use the limit() method. The limit() method takes one
parameter, a number defining how many documents to return. Consider you have a
"customers" collection:
{'_id': 1, 'name': 'John', 'address': 'Highway37'}
{'_id': 2, 'name': 'Peter', 'address': 'Lowstreet 27'}
{'_id': 3, 'name': 'Amy', 'address': 'Apple st 652'}
{'_id': 4, 'name': 'Hannah', 'address': 'Mountain 21'}
{'_id': 5, 'name': 'Michael', 'address': 'Valley 345'}
{'_id': 6, 'name': 'Sandy', 'address': 'Ocean blvd 2'}
{'_id': 7, 'name': 'Betty', 'address': 'Green Grass 1'}
{'_id': 8, 'name': 'Richard', 'address': 'Sky st 331'}
{'_id': 9, 'name': 'Susan', 'address': 'One way 98'}
{'_id': 10, 'name': 'Vicky', 'address': 'Yellow Garden 2'}
{'_id': 11, 'name': 'Ben', 'address': 'Park Lane 38'}
{'_id': 12, 'name': 'William', 'address': 'Central st 954'}
{'_id': 13, 'name': 'Chuck', 'address': 'Main Road 989'}
{'_id': 14, 'name': 'Viola', 'address': 'Sideway 1633’}
LIMIT THE RESULT

# Limit the result to only return 5 documents:

import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
myresult = mycol.find().limit(5)
#print the result:
for x in myresult:
print(x)
36

THANK YOU!

Dr. Zahid Ahmed Ansari 10/25/2023

You might also like