SlideShare a Scribd company logo
MONGODB WITH PYTHON
MongoDB is a cross-platform, document-oriented database that works on the
concept of collections and documents. MongoDB offers high speed, high availability,
and high scalability.
The next question which arises in the mind of the people is “Why MongoDB”?
Reasons to opt for MongoDB :
It supports hierarchical data structure
(It supports associate arrays like Dictionaries in Python.)
Built-in Python drivers to connect python-application with Database. Example-
PyMongo
It is designed for Big Data.
Deployment of MongoDB is very easy.
Python has a native library for MongoDB. The name of the available library is “PyMongo”. To import this,
execute the following command:
from pymongo import MongoClient
Create a connection :
The very first after importing the module is to create a MongoClient.
from pymongo import MongoClient
client = MongoClient(“mongodb://localhost:27017/”)
Access DataBase Objects : To create a database or switch to an existing database we use:
mydatabase = client[‘name_of_the_database’]
Accessing the Collection : Collections are equivalent to Tables in RDBMS. We access a collection in PyMongo in
the same way as we access the Tables in the RDBMS. To access the table, say table name “myTable” of the
database, say “mydatabase”.
EX: mydb = client[‘mydatabase’]
Check if Database Exists
print(myclient.list_database_names())
CREATING COLLECTIONS
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.
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
INSERT A DOCUMENT
To insert a record, or document as it is called 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.
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
The insert_one() method returns a InsertOneResult object, which has a property, inserted_id, that
holds the id of the inserted document.
mydict = { "name": "Peter", "address": "Lowstreet 27" }
x = mycol.insert_one(mydict)
print(x.inserted_id)
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:
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 RECORDS WITH SPECIFIC 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.
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
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.
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 table 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.
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
for x in mycol.find():
print(x)
RETURN ONLY SOME SPECIFIC FIELD
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.
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)
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)
FILTER BY 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.
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"}:
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
You can also use regular expressions as a modifier.
To find only the documents where the "address" field starts with the letter "S", use the regular
expression {"$regex": "^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).
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
Use the value -1 as the second parameter to sort descending.
sort("name", 1) #ascending
sort("name", -1) #descending
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
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.
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 Many Documents
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:
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
x = mycol.delete_many({})
print(x.deleted_count, " documents deleted.")
DROP COLLECTIONS
You can delete a table, or collection as it is called in MongoDB, by using the drop() method.
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
mycol.drop()
The drop() method returns true if the collection was dropped successfully, and false if the collection
does not exist.
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.
UPDATE
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.
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
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:Customers
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)
Ad

More Related Content

What's hot (20)

Module Architecture of React-Redux Applications
Module Architecture of React-Redux ApplicationsModule Architecture of React-Redux Applications
Module Architecture of React-Redux Applications
Andrii Sliusar
 
Oraclesql
OraclesqlOraclesql
Oraclesql
Priya Goyal
 
MySQL Functions
MySQL FunctionsMySQL Functions
MySQL Functions
Compare Infobase Limited
 
Angular js PPT
Angular js PPTAngular js PPT
Angular js PPT
Imtiyaz Ahmad Khan
 
2 programming.the.microsoft.windows.driver.model.2nd.edition
2   programming.the.microsoft.windows.driver.model.2nd.edition2   programming.the.microsoft.windows.driver.model.2nd.edition
2 programming.the.microsoft.windows.driver.model.2nd.edition
Max Jeison Prass
 
Impact of the New ORM on Your Modules
Impact of the New ORM on Your ModulesImpact of the New ORM on Your Modules
Impact of the New ORM on Your Modules
Odoo
 
Css Text Formatting
Css Text FormattingCss Text Formatting
Css Text Formatting
Dr. Jasmine Beulah Gnanadurai
 
cloud computing and android
cloud computing and androidcloud computing and android
cloud computing and android
Mohit Singh
 
jQuery
jQueryjQuery
jQuery
Dileep Mishra
 
jQuery -Chapter 2 - Selectors and Events
jQuery -Chapter 2 - Selectors and Events jQuery -Chapter 2 - Selectors and Events
jQuery -Chapter 2 - Selectors and Events
WebStackAcademy
 
CPP Language Basics - Reference
CPP Language Basics - ReferenceCPP Language Basics - Reference
CPP Language Basics - Reference
Mohammed Sikander
 
Constructor and Destructor PPT
Constructor and Destructor PPTConstructor and Destructor PPT
Constructor and Destructor PPT
Shubham Mondal
 
Jetpack Navigation Component
Jetpack Navigation ComponentJetpack Navigation Component
Jetpack Navigation Component
James Shvarts
 
Indexing
IndexingIndexing
Indexing
Mike Dirolf
 
React with Redux
React with ReduxReact with Redux
React with Redux
Stanimir Todorov
 
Indexing and Query Optimization
Indexing and Query OptimizationIndexing and Query Optimization
Indexing and Query Optimization
MongoDB
 
JavaScript
JavaScriptJavaScript
JavaScript
Sunil OS
 
Sql joins
Sql joinsSql joins
Sql joins
Gaurav Dhanwant
 
Resource Bundle
Resource BundleResource Bundle
Resource Bundle
Sunil OS
 
4.3 data structures records
4.3 data structures   records4.3 data structures   records
4.3 data structures records
missstevenson01
 
Module Architecture of React-Redux Applications
Module Architecture of React-Redux ApplicationsModule Architecture of React-Redux Applications
Module Architecture of React-Redux Applications
Andrii Sliusar
 
2 programming.the.microsoft.windows.driver.model.2nd.edition
2   programming.the.microsoft.windows.driver.model.2nd.edition2   programming.the.microsoft.windows.driver.model.2nd.edition
2 programming.the.microsoft.windows.driver.model.2nd.edition
Max Jeison Prass
 
Impact of the New ORM on Your Modules
Impact of the New ORM on Your ModulesImpact of the New ORM on Your Modules
Impact of the New ORM on Your Modules
Odoo
 
cloud computing and android
cloud computing and androidcloud computing and android
cloud computing and android
Mohit Singh
 
jQuery -Chapter 2 - Selectors and Events
jQuery -Chapter 2 - Selectors and Events jQuery -Chapter 2 - Selectors and Events
jQuery -Chapter 2 - Selectors and Events
WebStackAcademy
 
CPP Language Basics - Reference
CPP Language Basics - ReferenceCPP Language Basics - Reference
CPP Language Basics - Reference
Mohammed Sikander
 
Constructor and Destructor PPT
Constructor and Destructor PPTConstructor and Destructor PPT
Constructor and Destructor PPT
Shubham Mondal
 
Jetpack Navigation Component
Jetpack Navigation ComponentJetpack Navigation Component
Jetpack Navigation Component
James Shvarts
 
Indexing and Query Optimization
Indexing and Query OptimizationIndexing and Query Optimization
Indexing and Query Optimization
MongoDB
 
JavaScript
JavaScriptJavaScript
JavaScript
Sunil OS
 
Resource Bundle
Resource BundleResource Bundle
Resource Bundle
Sunil OS
 
4.3 data structures records
4.3 data structures   records4.3 data structures   records
4.3 data structures records
missstevenson01
 

Similar to Python With MongoDB in advanced Python.pptx (20)

Mongodatabase with Python for Students.pptx
Mongodatabase with Python for Students.pptxMongodatabase with Python for Students.pptx
Mongodatabase with Python for Students.pptx
Ramakrishna Reddy Bijjam
 
MongoDB, PHP and the cloud - php cloud summit 2011
MongoDB, PHP and the cloud - php cloud summit 2011MongoDB, PHP and the cloud - php cloud summit 2011
MongoDB, PHP and the cloud - php cloud summit 2011
Steven Francia
 
Mongo db basic installation
Mongo db basic installationMongo db basic installation
Mongo db basic installation
Kishor Parkhe
 
Back to Basics, webinar 2: La tua prima applicazione MongoDB
Back to Basics, webinar 2: La tua prima applicazione MongoDBBack to Basics, webinar 2: La tua prima applicazione MongoDB
Back to Basics, webinar 2: La tua prima applicazione MongoDB
MongoDB
 
Sekilas PHP + mongoDB
Sekilas PHP + mongoDBSekilas PHP + mongoDB
Sekilas PHP + mongoDB
Hadi Ariawan
 
MongoDB With Style
MongoDB With StyleMongoDB With Style
MongoDB With Style
Gabriele Lana
 
Practical Google App Engine Applications In Py
Practical Google App Engine Applications In PyPractical Google App Engine Applications In Py
Practical Google App Engine Applications In Py
Eric ShangKuan
 
Dev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBDev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDB
MongoDB
 
San Francisco Java User Group
San Francisco Java User GroupSan Francisco Java User Group
San Francisco Java User Group
kchodorow
 
Morphia, Spring Data & Co.
Morphia, Spring Data & Co.Morphia, Spring Data & Co.
Morphia, Spring Data & Co.
Tobias Trelle
 
MongoDB - Back to Basics - La tua prima Applicazione
MongoDB - Back to Basics - La tua prima ApplicazioneMongoDB - Back to Basics - La tua prima Applicazione
MongoDB - Back to Basics - La tua prima Applicazione
Massimo Brignoli
 
Back to basics Italian webinar 2 Mia prima applicazione MongoDB
Back to basics Italian webinar 2  Mia prima applicazione MongoDBBack to basics Italian webinar 2  Mia prima applicazione MongoDB
Back to basics Italian webinar 2 Mia prima applicazione MongoDB
MongoDB
 
Back to Basics 2017 - Your First MongoDB Application
Back to Basics 2017 - Your First MongoDB ApplicationBack to Basics 2017 - Your First MongoDB Application
Back to Basics 2017 - Your First MongoDB Application
Joe Drumgoole
 
Back to Basics: My First MongoDB Application
Back to Basics: My First MongoDB ApplicationBack to Basics: My First MongoDB Application
Back to Basics: My First MongoDB Application
MongoDB
 
Webinar: General Technical Overview of MongoDB for Dev Teams
Webinar: General Technical Overview of MongoDB for Dev TeamsWebinar: General Technical Overview of MongoDB for Dev Teams
Webinar: General Technical Overview of MongoDB for Dev Teams
MongoDB
 
Schema Design with MongoDB
Schema Design with MongoDBSchema Design with MongoDB
Schema Design with MongoDB
rogerbodamer
 
Aggregation Framework MongoDB Days Munich
Aggregation Framework MongoDB Days MunichAggregation Framework MongoDB Days Munich
Aggregation Framework MongoDB Days Munich
Norberto Leite
 
Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4
DEVCON
 
Nosql part3
Nosql part3Nosql part3
Nosql part3
Ruru Chowdhury
 
Analytics with MongoDB Aggregation Framework and Hadoop Connector
Analytics with MongoDB Aggregation Framework and Hadoop ConnectorAnalytics with MongoDB Aggregation Framework and Hadoop Connector
Analytics with MongoDB Aggregation Framework and Hadoop Connector
Henrik Ingo
 
Mongodatabase with Python for Students.pptx
Mongodatabase with Python for Students.pptxMongodatabase with Python for Students.pptx
Mongodatabase with Python for Students.pptx
Ramakrishna Reddy Bijjam
 
MongoDB, PHP and the cloud - php cloud summit 2011
MongoDB, PHP and the cloud - php cloud summit 2011MongoDB, PHP and the cloud - php cloud summit 2011
MongoDB, PHP and the cloud - php cloud summit 2011
Steven Francia
 
Mongo db basic installation
Mongo db basic installationMongo db basic installation
Mongo db basic installation
Kishor Parkhe
 
Back to Basics, webinar 2: La tua prima applicazione MongoDB
Back to Basics, webinar 2: La tua prima applicazione MongoDBBack to Basics, webinar 2: La tua prima applicazione MongoDB
Back to Basics, webinar 2: La tua prima applicazione MongoDB
MongoDB
 
Sekilas PHP + mongoDB
Sekilas PHP + mongoDBSekilas PHP + mongoDB
Sekilas PHP + mongoDB
Hadi Ariawan
 
Practical Google App Engine Applications In Py
Practical Google App Engine Applications In PyPractical Google App Engine Applications In Py
Practical Google App Engine Applications In Py
Eric ShangKuan
 
Dev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBDev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDB
MongoDB
 
San Francisco Java User Group
San Francisco Java User GroupSan Francisco Java User Group
San Francisco Java User Group
kchodorow
 
Morphia, Spring Data & Co.
Morphia, Spring Data & Co.Morphia, Spring Data & Co.
Morphia, Spring Data & Co.
Tobias Trelle
 
MongoDB - Back to Basics - La tua prima Applicazione
MongoDB - Back to Basics - La tua prima ApplicazioneMongoDB - Back to Basics - La tua prima Applicazione
MongoDB - Back to Basics - La tua prima Applicazione
Massimo Brignoli
 
Back to basics Italian webinar 2 Mia prima applicazione MongoDB
Back to basics Italian webinar 2  Mia prima applicazione MongoDBBack to basics Italian webinar 2  Mia prima applicazione MongoDB
Back to basics Italian webinar 2 Mia prima applicazione MongoDB
MongoDB
 
Back to Basics 2017 - Your First MongoDB Application
Back to Basics 2017 - Your First MongoDB ApplicationBack to Basics 2017 - Your First MongoDB Application
Back to Basics 2017 - Your First MongoDB Application
Joe Drumgoole
 
Back to Basics: My First MongoDB Application
Back to Basics: My First MongoDB ApplicationBack to Basics: My First MongoDB Application
Back to Basics: My First MongoDB Application
MongoDB
 
Webinar: General Technical Overview of MongoDB for Dev Teams
Webinar: General Technical Overview of MongoDB for Dev TeamsWebinar: General Technical Overview of MongoDB for Dev Teams
Webinar: General Technical Overview of MongoDB for Dev Teams
MongoDB
 
Schema Design with MongoDB
Schema Design with MongoDBSchema Design with MongoDB
Schema Design with MongoDB
rogerbodamer
 
Aggregation Framework MongoDB Days Munich
Aggregation Framework MongoDB Days MunichAggregation Framework MongoDB Days Munich
Aggregation Framework MongoDB Days Munich
Norberto Leite
 
Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4
DEVCON
 
Analytics with MongoDB Aggregation Framework and Hadoop Connector
Analytics with MongoDB Aggregation Framework and Hadoop ConnectorAnalytics with MongoDB Aggregation Framework and Hadoop Connector
Analytics with MongoDB Aggregation Framework and Hadoop Connector
Henrik Ingo
 
Ad

More from Ramakrishna Reddy Bijjam (20)

VBS control structures for if do whilw.docx
VBS control structures for if do whilw.docxVBS control structures for if do whilw.docx
VBS control structures for if do whilw.docx
Ramakrishna Reddy Bijjam
 
Builtinfunctions in vbscript and its types.docx
Builtinfunctions in vbscript and its types.docxBuiltinfunctions in vbscript and its types.docx
Builtinfunctions in vbscript and its types.docx
Ramakrishna Reddy Bijjam
 
VBScript Functions procedures and arrays.docx
VBScript Functions procedures and arrays.docxVBScript Functions procedures and arrays.docx
VBScript Functions procedures and arrays.docx
Ramakrishna Reddy Bijjam
 
VBScript datatypes and control structures.docx
VBScript datatypes and control structures.docxVBScript datatypes and control structures.docx
VBScript datatypes and control structures.docx
Ramakrishna Reddy Bijjam
 
Numbers and global functions conversions .pptx
Numbers and global functions conversions .pptxNumbers and global functions conversions .pptx
Numbers and global functions conversions .pptx
Ramakrishna Reddy Bijjam
 
Structured Graphics in dhtml and active controls.docx
Structured Graphics in dhtml and active controls.docxStructured Graphics in dhtml and active controls.docx
Structured Graphics in dhtml and active controls.docx
Ramakrishna Reddy Bijjam
 
Filters and its types as wave shadow.docx
Filters and its types as wave shadow.docxFilters and its types as wave shadow.docx
Filters and its types as wave shadow.docx
Ramakrishna Reddy Bijjam
 
JavaScript Arrays and its types .pptx
JavaScript  Arrays and its types   .pptxJavaScript  Arrays and its types   .pptx
JavaScript Arrays and its types .pptx
Ramakrishna Reddy Bijjam
 
JS Control Statements and Functions.pptx
JS Control Statements  and Functions.pptxJS Control Statements  and Functions.pptx
JS Control Statements and Functions.pptx
Ramakrishna Reddy Bijjam
 
Code conversions binary to Gray vice versa.pptx
Code conversions binary to Gray vice versa.pptxCode conversions binary to Gray vice versa.pptx
Code conversions binary to Gray vice versa.pptx
Ramakrishna Reddy Bijjam
 
FIXED and FLOATING-POINT-REPRESENTATION.pdf
FIXED and FLOATING-POINT-REPRESENTATION.pdfFIXED and FLOATING-POINT-REPRESENTATION.pdf
FIXED and FLOATING-POINT-REPRESENTATION.pdf
Ramakrishna Reddy Bijjam
 
Handling Missing Data for Data Analysis.pptx
Handling Missing Data for Data Analysis.pptxHandling Missing Data for Data Analysis.pptx
Handling Missing Data for Data Analysis.pptx
Ramakrishna Reddy Bijjam
 
Data Frame Data structure in Python pandas.pptx
Data Frame Data structure in Python pandas.pptxData Frame Data structure in Python pandas.pptx
Data Frame Data structure in Python pandas.pptx
Ramakrishna Reddy Bijjam
 
Series data structure in Python Pandas.pptx
Series data structure in Python Pandas.pptxSeries data structure in Python Pandas.pptx
Series data structure in Python Pandas.pptx
Ramakrishna Reddy Bijjam
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
Ramakrishna Reddy Bijjam
 
Arrays to arrays and pointers with arrays.pptx
Arrays to arrays and pointers with arrays.pptxArrays to arrays and pointers with arrays.pptx
Arrays to arrays and pointers with arrays.pptx
Ramakrishna Reddy Bijjam
 
Pointers and single &multi dimentionalarrays.pptx
Pointers and single &multi dimentionalarrays.pptxPointers and single &multi dimentionalarrays.pptx
Pointers and single &multi dimentionalarrays.pptx
Ramakrishna Reddy Bijjam
 
Certinity Factor and Dempster-shafer theory .pptx
Certinity Factor and Dempster-shafer theory .pptxCertinity Factor and Dempster-shafer theory .pptx
Certinity Factor and Dempster-shafer theory .pptx
Ramakrishna Reddy Bijjam
 
Auxiliary Memory in computer Architecture.pptx
Auxiliary Memory in computer Architecture.pptxAuxiliary Memory in computer Architecture.pptx
Auxiliary Memory in computer Architecture.pptx
Ramakrishna Reddy Bijjam
 
Random Forest Decision Tree.pptx
Random Forest Decision Tree.pptxRandom Forest Decision Tree.pptx
Random Forest Decision Tree.pptx
Ramakrishna Reddy Bijjam
 
VBS control structures for if do whilw.docx
VBS control structures for if do whilw.docxVBS control structures for if do whilw.docx
VBS control structures for if do whilw.docx
Ramakrishna Reddy Bijjam
 
Builtinfunctions in vbscript and its types.docx
Builtinfunctions in vbscript and its types.docxBuiltinfunctions in vbscript and its types.docx
Builtinfunctions in vbscript and its types.docx
Ramakrishna Reddy Bijjam
 
VBScript Functions procedures and arrays.docx
VBScript Functions procedures and arrays.docxVBScript Functions procedures and arrays.docx
VBScript Functions procedures and arrays.docx
Ramakrishna Reddy Bijjam
 
VBScript datatypes and control structures.docx
VBScript datatypes and control structures.docxVBScript datatypes and control structures.docx
VBScript datatypes and control structures.docx
Ramakrishna Reddy Bijjam
 
Numbers and global functions conversions .pptx
Numbers and global functions conversions .pptxNumbers and global functions conversions .pptx
Numbers and global functions conversions .pptx
Ramakrishna Reddy Bijjam
 
Structured Graphics in dhtml and active controls.docx
Structured Graphics in dhtml and active controls.docxStructured Graphics in dhtml and active controls.docx
Structured Graphics in dhtml and active controls.docx
Ramakrishna Reddy Bijjam
 
Code conversions binary to Gray vice versa.pptx
Code conversions binary to Gray vice versa.pptxCode conversions binary to Gray vice versa.pptx
Code conversions binary to Gray vice versa.pptx
Ramakrishna Reddy Bijjam
 
FIXED and FLOATING-POINT-REPRESENTATION.pdf
FIXED and FLOATING-POINT-REPRESENTATION.pdfFIXED and FLOATING-POINT-REPRESENTATION.pdf
FIXED and FLOATING-POINT-REPRESENTATION.pdf
Ramakrishna Reddy Bijjam
 
Handling Missing Data for Data Analysis.pptx
Handling Missing Data for Data Analysis.pptxHandling Missing Data for Data Analysis.pptx
Handling Missing Data for Data Analysis.pptx
Ramakrishna Reddy Bijjam
 
Data Frame Data structure in Python pandas.pptx
Data Frame Data structure in Python pandas.pptxData Frame Data structure in Python pandas.pptx
Data Frame Data structure in Python pandas.pptx
Ramakrishna Reddy Bijjam
 
Series data structure in Python Pandas.pptx
Series data structure in Python Pandas.pptxSeries data structure in Python Pandas.pptx
Series data structure in Python Pandas.pptx
Ramakrishna Reddy Bijjam
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
Ramakrishna Reddy Bijjam
 
Arrays to arrays and pointers with arrays.pptx
Arrays to arrays and pointers with arrays.pptxArrays to arrays and pointers with arrays.pptx
Arrays to arrays and pointers with arrays.pptx
Ramakrishna Reddy Bijjam
 
Pointers and single &multi dimentionalarrays.pptx
Pointers and single &multi dimentionalarrays.pptxPointers and single &multi dimentionalarrays.pptx
Pointers and single &multi dimentionalarrays.pptx
Ramakrishna Reddy Bijjam
 
Certinity Factor and Dempster-shafer theory .pptx
Certinity Factor and Dempster-shafer theory .pptxCertinity Factor and Dempster-shafer theory .pptx
Certinity Factor and Dempster-shafer theory .pptx
Ramakrishna Reddy Bijjam
 
Auxiliary Memory in computer Architecture.pptx
Auxiliary Memory in computer Architecture.pptxAuxiliary Memory in computer Architecture.pptx
Auxiliary Memory in computer Architecture.pptx
Ramakrishna Reddy Bijjam
 
Ad

Recently uploaded (20)

How to Add Customer Note in Odoo 18 POS - Odoo Slides
How to Add Customer Note in Odoo 18 POS - Odoo SlidesHow to Add Customer Note in Odoo 18 POS - Odoo Slides
How to Add Customer Note in Odoo 18 POS - Odoo Slides
Celine George
 
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast BrooklynBridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
i4jd41bk
 
THE STG QUIZ GROUP D.pptx quiz by Ridip Hazarika
THE STG QUIZ GROUP D.pptx   quiz by Ridip HazarikaTHE STG QUIZ GROUP D.pptx   quiz by Ridip Hazarika
THE STG QUIZ GROUP D.pptx quiz by Ridip Hazarika
Ridip Hazarika
 
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and GuestsLDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDM Mia eStudios
 
How to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo SlidesHow to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo Slides
Celine George
 
Operations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdfOperations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdf
Arab Academy for Science, Technology and Maritime Transport
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
Junction Field Effect Transistors (JFET)
Junction Field Effect Transistors (JFET)Junction Field Effect Transistors (JFET)
Junction Field Effect Transistors (JFET)
GS Virdi
 
Grade 2 - Mathematics - Printable Worksheet
Grade 2 - Mathematics - Printable WorksheetGrade 2 - Mathematics - Printable Worksheet
Grade 2 - Mathematics - Printable Worksheet
Sritoma Majumder
 
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living WorkshopLDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDM Mia eStudios
 
How to Manage Purchase Alternatives in Odoo 18
How to Manage Purchase Alternatives in Odoo 18How to Manage Purchase Alternatives in Odoo 18
How to Manage Purchase Alternatives in Odoo 18
Celine George
 
Lecture 1 Introduction history and institutes of entomology_1.pptx
Lecture 1 Introduction history and institutes of entomology_1.pptxLecture 1 Introduction history and institutes of entomology_1.pptx
Lecture 1 Introduction history and institutes of entomology_1.pptx
Arshad Shaikh
 
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
Dr. Nasir Mustafa
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
How to Manage Upselling in Odoo 18 Sales
How to Manage Upselling in Odoo 18 SalesHow to Manage Upselling in Odoo 18 Sales
How to Manage Upselling in Odoo 18 Sales
Celine George
 
"Basics of Heterocyclic Compounds and Their Naming Rules"
"Basics of Heterocyclic Compounds and Their Naming Rules""Basics of Heterocyclic Compounds and Their Naming Rules"
"Basics of Heterocyclic Compounds and Their Naming Rules"
rupalinirmalbpharm
 
Herbs Used in Cosmetic Formulations .pptx
Herbs Used in Cosmetic Formulations .pptxHerbs Used in Cosmetic Formulations .pptx
Herbs Used in Cosmetic Formulations .pptx
RAJU THENGE
 
Exercise Physiology MCQS By DR. NASIR MUSTAFA
Exercise Physiology MCQS By DR. NASIR MUSTAFAExercise Physiology MCQS By DR. NASIR MUSTAFA
Exercise Physiology MCQS By DR. NASIR MUSTAFA
Dr. Nasir Mustafa
 
How to Create A Todo List In Todo of Odoo 18
How to Create A Todo List In Todo of Odoo 18How to Create A Todo List In Todo of Odoo 18
How to Create A Todo List In Todo of Odoo 18
Celine George
 
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdfBiophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
PKLI-Institute of Nursing and Allied Health Sciences Lahore , Pakistan.
 
How to Add Customer Note in Odoo 18 POS - Odoo Slides
How to Add Customer Note in Odoo 18 POS - Odoo SlidesHow to Add Customer Note in Odoo 18 POS - Odoo Slides
How to Add Customer Note in Odoo 18 POS - Odoo Slides
Celine George
 
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast BrooklynBridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
i4jd41bk
 
THE STG QUIZ GROUP D.pptx quiz by Ridip Hazarika
THE STG QUIZ GROUP D.pptx   quiz by Ridip HazarikaTHE STG QUIZ GROUP D.pptx   quiz by Ridip Hazarika
THE STG QUIZ GROUP D.pptx quiz by Ridip Hazarika
Ridip Hazarika
 
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and GuestsLDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDM Mia eStudios
 
How to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo SlidesHow to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo Slides
Celine George
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
Junction Field Effect Transistors (JFET)
Junction Field Effect Transistors (JFET)Junction Field Effect Transistors (JFET)
Junction Field Effect Transistors (JFET)
GS Virdi
 
Grade 2 - Mathematics - Printable Worksheet
Grade 2 - Mathematics - Printable WorksheetGrade 2 - Mathematics - Printable Worksheet
Grade 2 - Mathematics - Printable Worksheet
Sritoma Majumder
 
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living WorkshopLDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDM Mia eStudios
 
How to Manage Purchase Alternatives in Odoo 18
How to Manage Purchase Alternatives in Odoo 18How to Manage Purchase Alternatives in Odoo 18
How to Manage Purchase Alternatives in Odoo 18
Celine George
 
Lecture 1 Introduction history and institutes of entomology_1.pptx
Lecture 1 Introduction history and institutes of entomology_1.pptxLecture 1 Introduction history and institutes of entomology_1.pptx
Lecture 1 Introduction history and institutes of entomology_1.pptx
Arshad Shaikh
 
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
Dr. Nasir Mustafa
 
How to Manage Upselling in Odoo 18 Sales
How to Manage Upselling in Odoo 18 SalesHow to Manage Upselling in Odoo 18 Sales
How to Manage Upselling in Odoo 18 Sales
Celine George
 
"Basics of Heterocyclic Compounds and Their Naming Rules"
"Basics of Heterocyclic Compounds and Their Naming Rules""Basics of Heterocyclic Compounds and Their Naming Rules"
"Basics of Heterocyclic Compounds and Their Naming Rules"
rupalinirmalbpharm
 
Herbs Used in Cosmetic Formulations .pptx
Herbs Used in Cosmetic Formulations .pptxHerbs Used in Cosmetic Formulations .pptx
Herbs Used in Cosmetic Formulations .pptx
RAJU THENGE
 
Exercise Physiology MCQS By DR. NASIR MUSTAFA
Exercise Physiology MCQS By DR. NASIR MUSTAFAExercise Physiology MCQS By DR. NASIR MUSTAFA
Exercise Physiology MCQS By DR. NASIR MUSTAFA
Dr. Nasir Mustafa
 
How to Create A Todo List In Todo of Odoo 18
How to Create A Todo List In Todo of Odoo 18How to Create A Todo List In Todo of Odoo 18
How to Create A Todo List In Todo of Odoo 18
Celine George
 

Python With MongoDB in advanced Python.pptx

  • 1. MONGODB WITH PYTHON MongoDB is a cross-platform, document-oriented database that works on the concept of collections and documents. MongoDB offers high speed, high availability, and high scalability. The next question which arises in the mind of the people is “Why MongoDB”? Reasons to opt for MongoDB : It supports hierarchical data structure (It supports associate arrays like Dictionaries in Python.) Built-in Python drivers to connect python-application with Database. Example- PyMongo It is designed for Big Data. Deployment of MongoDB is very easy.
  • 2. Python has a native library for MongoDB. The name of the available library is “PyMongo”. To import this, execute the following command: from pymongo import MongoClient Create a connection : The very first after importing the module is to create a MongoClient. from pymongo import MongoClient client = MongoClient(“mongodb://localhost:27017/”) Access DataBase Objects : To create a database or switch to an existing database we use: mydatabase = client[‘name_of_the_database’] Accessing the Collection : Collections are equivalent to Tables in RDBMS. We access a collection in PyMongo in the same way as we access the Tables in the RDBMS. To access the table, say table name “myTable” of the database, say “mydatabase”. EX: mydb = client[‘mydatabase’] Check if Database Exists print(myclient.list_database_names())
  • 3. CREATING COLLECTIONS 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. import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["mydatabase"] mycol = mydb["customers"]
  • 4. INSERT A DOCUMENT To insert a record, or document as it is called 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. 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)
  • 5. Return the _id Field The insert_one() method returns a InsertOneResult object, which has a property, inserted_id, that holds the id of the inserted document. mydict = { "name": "Peter", "address": "Lowstreet 27" } x = mycol.insert_one(mydict) print(x.inserted_id) 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:
  • 6. 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)
  • 7. INSERT RECORDS WITH SPECIFIC 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. import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["mydatabase"] mycol = mydb["customers"]
  • 8. 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)
  • 9. FIND 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. import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["mydatabase"] mycol = mydb["customers"] x = mycol.find_one() print(x)
  • 10. FIND ALL To select data from a table 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. import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["mydatabase"] mycol = mydb["customers"] for x in mycol.find(): print(x)
  • 11. RETURN ONLY SOME SPECIFIC FIELD 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. 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) 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)
  • 12. FILTER BY 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. 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"}:
  • 13. 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 You can also use regular expressions as a modifier. To find only the documents where the "address" field starts with the letter "S", use the regular expression {"$regex": "^S"}:
  • 14. 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). 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)
  • 15. SORT DESCENDING Use the value -1 as the second parameter to sort descending. sort("name", 1) #ascending sort("name", -1) #descending 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)
  • 16. DELETE 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. 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.
  • 17. Delete Many Documents 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: import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["mydatabase"] mycol = mydb["customers"] x = mycol.delete_many({}) print(x.deleted_count, " documents deleted.")
  • 18. DROP COLLECTIONS You can delete a table, or collection as it is called in MongoDB, by using the drop() method. import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["mydatabase"] mycol = mydb["customers"] mycol.drop() The drop() method returns true if the collection was dropped successfully, and false if the collection does not exist. 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.
  • 19. UPDATE 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)
  • 20. Update Many To update all documents that meets the criteria of the query, use the update_many() method. 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.")
  • 21. LIMIT 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:Customers 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)