0% found this document useful (0 votes)
11 views25 pages

Chapter 5

Uploaded by

prashantkori
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)
11 views25 pages

Chapter 5

Uploaded by

prashantkori
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/ 25

Chapter 4: Python Database Interaction Using MongoDB

Mr. Prashant Kori


Assistant Professor
Department of MCA,ASM’s IBMR Pune.
Features of NoSQL

Features of NoSQL
● Schema Flexibility: No fixed schema; easily handles unstructured and semi-structured data.

● Scalability: Scales horizontally by adding more servers.

● High Performance: Optimized for fast data retrieval and handling large volumes.

● Varied Data Models: Supports document, key-value, column-family, and graph databases.

● Distributed Architecture: Data is spread across multiple nodes for reliability and availability.

Mr. Prashant Kori


Assistant Professor
Department of MCA,ASM’s IBMR Pune.
Types of NoSQL

Types of NoSQL Databases:


1. Document-based (e.g., MongoDB): Stores data in documents (JSON, BSON).

2. Key-Value (e.g., Redis): Pairs of keys and values for fast lookups.

3. Column-Family (e.g., Cassandra): Data organized into columns for big data workloads.

4. Graph (e.g., Neo4j): Represents relationships between data points.

Mr. Prashant Kori


Assistant Professor
Department of MCA,ASM’s IBMR Pune.
Types of NoSQL
Types of NoSQL Databases:
1. Document-based (e.g., MongoDB): Stores data in documents (JSON, BSON).
● A document-oriented database stores data in documents similar to JSON (JavaScript Object Notation) objects.
● Each document contains pairs of fields and values.
● The values can typically be a variety of types, including things like strings, numbers, booleans, arrays, or
even other objects.
Examples :MongoDB and Couchbase.
{
"_id": "12345",
"name": "foo bar",
"email": "[email protected]",
"address": {
"street": "123 foo street",
"city": "some city",
"state": "some state",
"zip": "123456"
},
"hobbies": ["music", "guitar", "reading"]
}

Mr. Prashant Kori


Assistant Professor
Department of MCA,ASM’s IBMR Pune.
Types of NoSQL
2. Key-Value (e.g., Redis): Pairs of keys and values for fast lookups.
● A key-value store is a simpler type of database where each item contains keys and values. Each key is unique
and associated with a single value.
● They are used for caching and session management and provide high performance in reads and writes because
they tend to store things in memory.
Examples: Amazon DynamoDB and Redis.

Key: user:12345
Value: {"name": "foo bar", "email": "[email protected]", "designation": "software developer"}

Mr. Prashant Kori


Assistant Professor
Department of MCA,ASM’s IBMR Pune.
Types of NoSQL
3. Column-database (e.g., Cassandra): Data organized into columns for big data workloads.

○ Column database stores data in tables, rows, and dynamic columns.


○ The data is stored in tables. wide-column stores are flexible, where different rows can have different sets
of columns.
○ The wide rows and columns enable efficient retrieval of sparse and wide data.
Examples:Apache Cassandra and HBase.

Mr. Prashant Kori


Assistant Professor
Department of MCA,ASM’s IBMR Pune.
Types of NoSQL
4. Graph (e.g., Neo4j): Represents relationships Examples: Neo4J and Amazon Neptune.
between data points.

○ A graph database stores data in the form of


nodes and edges.
○ Nodes typically store information about
people, places, and things (like nouns),
○ Edges store information about the
relationships between the nodes.

Mr. Prashant Kori


Assistant Professor
Department of MCA,ASM’s IBMR Pune.
Advantages of NoSQL

Mr. Prashant Kori


Assistant Professor
Department of MCA,ASM’s IBMR Pune.
SQL VS NoSQL(Difference between SQL and NoSQL)

Mr. Prashant Kori


Assistant Professor
Department of MCA,ASM’s IBMR Pune.
Introduction to MONGODB with Python

MongoDB (Document based)

● MongoDB stores data in JSON-like documents, which makes the database very flexible and scalable.

PyMongo

● Python needs a MongoDB driver to access the MongoDB database.

● we will use the MongoDB driver "PyMongo".

● We recommend that you use PIP to install "PyMongo".

● PIP is most likely already installed in your Python environment.

Mr. Prashant Kori


Assistant Professor
Department of MCA,ASM’s IBMR Pune.
Installation of MONGODB

PyMongo

● To install PyMongo ,first make sure you have installed python3(along with PIP) an MongoDB properly then
execute following command.
pip install pymongo
● After installation successfully, we now verify weather installation is successful, for the that we open the new
document and write the following code and save as “firstprogram.py”.
import pymongo
● if you execute the firstprogram.py as shown below, you should not get any issues.
C:\User\acer\Desktop\firstprogram.py
C:\>_

Mr. Prashant Kori


Assistant Professor
Department of MCA,ASM’s IBMR Pune.
Exploring Collections and Documents
● MongoDB stores data records as documents which are gathered
together in collections.
● A database stores one or more collections of documents. Check if Database exists
Database
● To create database in MongoDB, start by creating MongoClient import pymongo
object then specify a connection URL with the correct IP address and
the name of the database you want to create. client =
pymongo.MongoClient(“mongo://localhost:27017”)
Example:
print(client.list_database_names())
import pymongo

client = pymongo.MongoClient(“mongo://localhost:27017”)

mydb = client[“mydb”]

● MongoDB database is not created until you have created a


collections(table), with at least one document.
Mr. Prashant Kori
Assistant Professor
Department of MCA,ASM’s IBMR Pune.
Exploring Collections and Documents

Collections:

● A collection in MongoDB is the same as a table in SQL database.

Example:

import pymongo
client = pymongo.MongoClient(“mongo://localhost:27017”)
mydb = client[“mydb”]
mycol = db[“employee”]

Check if Collection exists


import pymongo
client = pymongo.MongoClient(“mongo://localhost:27017”)
print(client.list_collection_names())

Mr. Prashant Kori


Assistant Professor
Department of MCA,ASM’s IBMR Pune.
Exploring Collections and Documents
Documents:

● MongoDB stores data records as JSON document.

Document structure:

{
field1: value1,
field2: value2,
…..
fieldN: value3,
}

Mr. Prashant Kori


Assistant Professor
Department of MCA,ASM’s IBMR Pune.
PERFORMING CRUD OPERATION
C-CREATE
● Mongo stores the data in the form of JSON objects. so every record for a collection in Mongo is called a
document.
● if the collection does not currently exist, insert operations will create the collection.
1. insert_one(): The first parameter of the insert_one() is a dictionary
2. insert_many(): for insert multiple documents.
2.insert_many()
1. insert_one() import pymongo
Example: client =
import pymongo pymongo.MongoClient(“mongo://localhost:2717”)
client = pymongo.MongoClient(“mongo://localhost:27017”) db = client[“mydb”]
db = client[“mydb”] mycol = db[“employee”]
mycol = db[“employee”] mylist=[{“name”:”Rahul”, “address”:”Mumbai”}
mydict={“name”:”Rahul”, “address”:”Mumbai”} {“name”:”Meena”, “address”:”Pune”}
x=mycol.insert_one(mydict) {“name”:”Raj”, “address”:”Delhi”}]
print(x) x=mycol.insert_many(mylist)
print(x)
Mr. Prashant Kori
Assistant Professor
Department of MCA,ASM’s IBMR Pune.
PERFORMING CRUD OPERATION
R-Read
● We can retrieve the documents from a collection using 2 methods
1. find(): method returns all occurrences in the collections. first parameter is query object.
2. find_one(): method returns first occurrences in the selection .

1. find()
Example:
import pymongo
client = pymongo.MongoClient(“mongo://localhost:27017”)
db = client[“mydb”]
mycol = db[“employee”]
for x in mycol.find():
print(x)

Mr. Prashant Kori


Assistant Professor
Department of MCA,ASM’s IBMR Pune.
PERFORMING CRUD OPERATION
U-Update()
● We can update the documents from a collection using 2 methods
1. update_one(): first parameter is query object defining which document to update.
2. update_many(): update all the documents that meets the criteria of the query .
1. update_one()
Example: 2. update_many():
import pymongo
import pymongo
client = pymongo.MongoClient(“mongo://localhost:27017”)
db = client[“mydb”]
client = pymongo.MongoClient(“mongo://localhost:27017”)
mycol = db[“employee”] db = client[“mydb”]
myquery={“address” : “Mumbai”} mycol = db[“employee”]
newvalues={“$set”:{“address”: “Navi Mumbai”}} myquery={“address” : {“$regex”:”^N”}}
mycol.update_one(myquery,newvalues) newvalues={“$set”:{“name”: “Manish”}}
for x in mycol.find(): x=mycol.update_many(myquery,newvalues)
print(x) print(x.modified_count(),”documents updated.”)

Mr. Prashant Kori


Assistant Professor
Department of MCA,ASM’s IBMR Pune.
PERFORMING CRUD OPERATION
D-Delete()
● We can delete the documents from a collection using 2 methods
1. delete_one(): first parameter is query object defining which document to delete.
2. delete_many(): delete all the documents that meets the criteria of the query .
1. delete_one()
Example: 2. delete_many():
import pymongo
import pymongo
client = pymongo.MongoClient(“mongo://localhost:27017”) client = pymongo.MongoClient(“mongo://localhost:27017”)
db = client[“mydb”] db = client[“mydb”]
mycol = db[“employee”] mycol = db[“employee”]
myquery={“address” : “Mumbai”} myquery={“address” : {“$regex”:”^N”}}
mycol.delete_one(myquery) x=mycol.delete_many(myquery)
for x in mycol.find(): print(x.deleted_count,”documents deleted.”)
print(x)

Mr. Prashant Kori


Assistant Professor
Department of MCA,ASM’s IBMR Pune.
PERFORMING CRUD OPERATION
Creating a database using Python in MongoDB
To use Python in MongoDB, we are going to import PyMongo. From that, MongoClient can be imported which is
used to create a client to the database. Using the client, a new database can be created. Example: List of databases
using MongoDB shell (before):
# import MongoClient
from pymongo import MongoClient

# Creating a client
client = MongoClient('localhost', 27017)

# Creating a database name GFG


list_of_db = client.list_database_names() db = client['GFG']
print("Database is created !!")
if "mydbase" in list_of_db:
print("Exists !!")

Mr. Prashant Kori


Assistant Professor
Department of MCA,ASM’s IBMR Pune.
PERFORMING CRUD OPERATION
Method used to Delete Records from NoSQL: delete_one() or delete_many()
● Remove All Documents That Match a Condition : The following operation removes
all documents that match the specified condition.
result = my_collection.delete_many({"name": "Mr.Geek"})
● To see the number of documents deleted :
print(result.deleted_count)
● Remove All Documents :
Method 1 : Remove all documents using delete_many()
result= my_collection.delete_many({})
Method 2 : Delete all documents using collection.remove()
result = my_collection.remove()
Mr. Prashant Kori
Assistant Professor
Department of MCA,ASM’s IBMR Pune.
PERFORMING CRUD OPERATION
What is a MongoDB Query?
● MongoDB query is used to specify the selection filter using query operators while retrieving the data from the

collection by db.find() method.

● We can easily filter the documents using the query object. To apply the filter on the collection,

● we can pass the query specifying the condition for the required documents as a parameter to this method,

which is an optional parameter for db.find() method.

Query Selectors: Following is the list of some operators used in the queries in MongoDB

Mr. Prashant Kori


Assistant Professor
Department of MCA,ASM’s IBMR Pune.
PERFORMING CRUD OPERATION
Query Selectors: Following is the list of some operators used in the queries in MongoDB

Mr. Prashant Kori


Assistant Professor
Department of MCA,ASM’s IBMR Pune.
PERFORMING CRUD OPERATION
Query Selectors: Following is the list of some operators used in the queries in MongoDB

Mr. Prashant Kori


Assistant Professor
Department of MCA,ASM’s IBMR Pune.
PERFORMING CRUD OPERATION
Example on Query Selectors
from pymongo import MongoClient
myclient = MongoClient("mongodb://localhost:27017/")
db = myclient["mydatabase"]
Collection = db["mart"]
cursor = Collection.find({"Quantity":{"$gt":40}})
print("The data having Quantity greater than 40 is:")
for record in cursor:
print(record)
cursor = Collection.find({"Quantity":{"$lt":40}})
print("\nThe data having Quantity less than 40 is:")
for record in cursor:
print(record)
Mr. Prashant Kori
Assistant Professor
Department of MCA,ASM’s IBMR Pune.
PERFORMING CRUD OPERATION
Example on find and replace:
import pymongo

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

db = client["mydatabase"]

col = db["gfg"]

col.find_one_and_replace({'coursename': 'SYSTEM DESIGN'},{'coursename':'PHP'})

for x in col.find({}, {"_id": 0, "coursename": 1, "price": 1}):


print(x)

Mr. Prashant Kori


Assistant Professor
Department of MCA,ASM’s IBMR Pune.

You might also like