Python Mongodb Tutorial
Python Mongodb Tutorial
i
Python MongoDB
This tutorial explains how to communicate with MongoDB database in detail, along with
examples.
Audience
This tutorial is designed for python programmers who would like to understand the
pymongo modules in detail.
Prerequisites
Before proceeding with this tutorial, you should have a good understanding of python
programming language. It is also recommended to have basic understanding of the
databases — MongoDB.
All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at contact@tutorialspoint.com
ii
Python MongoDB
Table of Contents
About the Tutorial ........................................................................................................................................... ii
Audience .......................................................................................................................................................... ii
Prerequisites .................................................................................................................................................... ii
Installation ....................................................................................................................................................... 1
iii
1. Python MongoDB — Introduction Python MongoDB
Pymongo is a python distribution which provides tools to work with MongoDB, it is the
most preferred way to communicate with MongoDB database from python.
Installation
To install pymongo first of all make sure you have installed python3 (along with PIP) and
MongoDB properly. Then execute the following command.
Verification
Once you have installed pymongo, open a new text document, paste the following line in
it and, save it as test.py.
import pymongo
If you have installed pymongo properly, if you execute the test.py as shown below, you
should not get any issues.
D:\Python_MongoDB>test.py
D:\Python_MongoDB>
1
2. Python MongoDB ― Create Database Python MongoDB
Unlike other databases, MongoDB does not provide separate command to create a
database.
In general, the use command is used to select/switch to the specific database. This
command initially verifies whether the database we specify exists, if so, it connects to it.
If the database, we specify with the use command doesn’t exist a new database will be
created.
Therefore, you can create a database in MongoDB using the Use command.
Syntax
Basic syntax of use DATABASE statement is as follows:
use DATABASE_NAME
Example
Following command creates a database named in mydb.
>use mydb
switched to db mydb
You can verify your creation by using the db command, this displays the current database.
>db
mydb
Example
Following example creates a database in MangoDB.
2
Python MongoDB
print("Database created........")
#Verification
print("List of databases after creating new one")
print(client.list_database_names())
Output
Database created........
List of databases after creating new one:
['admin', 'config', 'local', 'mydb']
You can also specify the port and host names while creating a MongoClient and can access
the databases in dictionary style.
Example
from pymongo import MongoClient
print("Database created........")
Output
Database created........
3
3. Python MongoDB — Create Collection Python MongoDB
You can create a collection using the createCollection() method. This method accepts a
String value representing the name of the collection to be created and an options (optional)
parameter.
Syntax
Following is the syntax to create a collection in MongoDB.
db.createCollection("CollectionName")
Example
Following method creates a collection named ExampleCollection.
Similarly, following is a query that creates a collection using the options of the
createCollection() method.
4
Python MongoDB
Example
from pymongo import MongoClient
#Creating a collection
collection = db['example']
print("Collection created........")
Output
Collection created........
5
4. Python MongoDB ― Insert Document Python MongoDB
You can store documents into MongoDB using the insert() method. This method accepts a
JSON document as a parameter.
Syntax
Following is the syntax of the insert method.
>db.COLLECTION_NAME.insert(DOCUMENT_NAME)
Example
> use mydb
switched to db mydb
> db.createCollection("sample")
{ "ok" : 1 }
> doc1 = {"name": "Ram", "age": "26", "city": "Hyderabad"}
{ "name" : "Ram", "age" : "26", "city" : "Hyderabad" }
> db.sample.insert(doc1)
WriteResult({ "nInserted" : 1 })
>
Similarly, you can also insert multiple documents using the insert() method.
"_id" : "1002",
"name" : "Rahim",
"age" : 27,
"city" : "Bangalore"
},
{
"_id" : "1003",
"name" : "Robert",
"age" : 28,
"city" : "Mumbai"
}
]
> db.sample.insert(data)
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 3,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
>
Example
Following example inserts a document in the collection named example.
7
Python MongoDB
#Creating a collection
coll = db['example']
print(coll.find_one())
Output
{'_id': ObjectId('5d63ad6ce043e2a93885858b'), 'name': 'Ram', 'age': '26',
'city': 'Hyderabad'}
To insert multiple documents into MongoDB using pymongo, you need to invoke the
insert_many() method.
#Creating a collection
coll = db['example']
res = coll.insert_many(data)
print("Data inserted ......")
print(res.inserted_ids)
8
Python MongoDB
Output
Data inserted ......
['101', '102', '103']
9
5. Python MongoDB — Find Python MongoDB
You can read/retrieve stored documents from MongoDB using the find() method. This
method retrieves and displays all the documents in MongoDB in a non-structured way.
Syntax
Following is the syntax of the find() method.
>db.CollectionName.find()
Example
Assume we have inserted 3 documents into a database named testDB in a collection
named sample using the following queries:
You can retrieve the inserted documents using the find() method as:
You can also retrieve first document in the collection using the findOne() method as:
> db.sample.findOne()
{ "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad" }
10
Python MongoDB
This method comes handy whenever you need to retrieve only one document of a result
or, if you are sure that your query returns only one document.
Example
Following python example retrieve first document of a collection:
#Creating a collection
coll = db['example']
res = coll.insert_many(data)
print("Data inserted ......")
print(res.inserted_ids)
11
Python MongoDB
Output
Data inserted ......
['101', '102', '103']
First record of the collection:
{'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}
Record whose id is 103:
{'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}
To get multiple documents in a single query (single call od find method), you can use the
find() method of the pymongo. If haven’t passed any query, this returns all the
documents of a collection and, if you have passed a query to this method, it returns all
the matched documents.
Example
#Getting the database instance
db = client['myDB']
#Creating a collection
coll = db['example']
res = coll.insert_many(data)
print("Data inserted ......")
#Retrieving records with age greater than 26 using the find() method
print("Record whose age is more than 26: ")
for doc2 in coll.find({"age":{"$gt":"26"}}):
print(doc2)
12
Python MongoDB
Output
Data inserted ......
Records of the collection:
{'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}
{'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}
{'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}
Record whose age is more than 26:
{'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}
{'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}
13
6. Python MongoDB ― Query Python MongoDB
While retrieving using find() method, you can filter the documents using the query object.
You can pass the query specifying the condition for the required documents as a parameter
to this method.
Operators
Following is the list of operators used in the queries in MongoDB.
Example1
Following example retrieves the document in a collection whose name is sarmista.
#Creating a collection
coll = db['example']
14
Python MongoDB
res = coll.insert_many(data)
print("Data inserted ......")
#Retrieving data
print("Documents in the collection: ")
for doc1 in coll.find({"name":"Sarmista"}):
print(doc1)
Output
Data inserted ......
Documents in the collection:
{'_id': '1005', 'name': 'Sarmista', 'age': '23', 'city': 'Delhi'}
Example2
Following example retrieves the document in a collection whose age value is greater than
26.
#Creating a collection
coll = db['example']
15
Python MongoDB
res = coll.insert_many(data)
print("Data inserted ......")
#Retrieving data
print("Documents in the collection: ")
for doc in coll.find({"age":{"$gt":"26"}}):
print(doc)
Output
Data inserted ......
Documents in the collection:
{'_id': '1002', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}
{'_id': '1003', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}
16
7. Python MongoDB — Sort Python MongoDB
While retrieving the contents of a collection, you can sort and arrange them in ascending
or descending orders using the sort() method.
To this method, you can pass the field(s) and the sorting order which is 1 or -1. Where, 1
is for ascending order and -1 is descending order.
Syntax
Following is the syntax of the sort() method.
>db.COLLECTION_NAME.find().sort({KEY:1})
Example
Assume we have created a collection and inserted 5 documents into it as shown below:
> db.sample.insert(data)
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 6,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
17
Python MongoDB
})
Following line retrieves all the documents of the collection which are sorted in ascending
order based on age.
> db.sample.find().sort({age:1})
{ "_id" : "1005", "name" : "Sarmista", "age" : 23, "city" : "Delhi" }
{ "_id" : "1004", "name" : "Romeo", "age" : 25, "city" : "Pune" }
{ "_id" : "1006", "name" : "Rasajna", "age" : 26, "city" : "Chennai" }
{ "_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore" }
{ "_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" }
{ "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad" }
By default, this method sorts the documents in ascending order based on the specified
field. If you need to sort in descending order pass -1 along with the field name:
coll.find().sort("age",-1)
Example
Following example retrieves all the documents of a collection arranged according to the
age values in ascending order:
#Creating a collection
coll = db['myColl']
18
Python MongoDB
res = coll.insert_many(data)
print("Data inserted ......")
Output
Data inserted ......
List of documents (sorted in ascending order based on age):
{'_id': '1005', 'name': 'Sarmista', 'age': 23, 'city': 'Delhi'}
{'_id': '1004', 'name': 'Romeo', 'age': 25, 'city': 'Pune'}
{'_id': '1006', 'name': 'Rasajna', 'age': 26, 'city': 'Chennai'}
{'_id': '1001', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}
{'_id': '1002', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}
{'_id': '1003', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}
19
8. Python MongoDB ― Delete Document Python MongoDB
You can delete documents in a collection using the remove() method of MongoDB. This
method accepts two optional parameters:
just one, if you pass true or 1 as second parameter, then only one document will
be deleted.
Syntax
Following is the syntax of the remove() method:
>db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)
Example
Assume we have created a collection and inserted 5 documents into it as shown below:
})
Following query deletes the document(s) of the collection which have name value as
Sarmista.
> db.sample.find()
{ "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad" }
{ "_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore" }
{ "_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" }
{ "_id" : "1004", "name" : "Romeo", "age" : 25, "city" : "Pune" }
{ "_id" : "1006", "name" : "Rasajna", "age" : 26, "city" : "Chennai" }
If you invoke remove() method without passing deletion criteria, all the documents in the
collection will be deleted.
> db.sample.remove({})
WriteResult({ "nRemoved" : 5 })
> db.sample.find()
These methods accept a query object specifying the condition for deleting documents.
Example
Following python example deletes the document in the collection which has id value as
1006.
#Creating a collection
21
Python MongoDB
coll = db['example']
res = coll.insert_many(data)
print("Data inserted ......")
#Deleting one document
coll.delete_one({"_id" : "1006"})
Output
Data inserted ......
Documents in the collection after update operation:
{'_id': '1001', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}
{'_id': '1002', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}
{'_id': '1003', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}
{'_id': '1004', 'name': 'Romeo', 'age': 25, 'city': 'Pune'}
{'_id': '1005', 'name': 'Sarmista', 'age': 23, 'city': 'Delhi'}
Similarly, the delete_many() method of pymongo deletes all the documents that satisfies
the specified condition.
Example
Following example deletes all the documents in the collection whose age value is greater
than 26:
#Creating a collection
coll = db['example']
res = coll.insert_many(data)
print("Data inserted ......")
Output
Data inserted ......
Documents in the collection after update operation:
{'_id': '1001', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}
{'_id': '1004', 'name': 'Romeo', 'age': '25', 'city': 'Pune'}
{'_id': '1005', 'name': 'Sarmista', 'age': '23', 'city': 'Delhi'}
{'_id': '1006', 'name': 'Rasajna', 'age': '26', 'city': 'Chennai'}
If you invoke the delete_many() method without passing any query, this method deletes
all the documents in the collection.
23
Python MongoDB
coll.delete_many({})
24
9. Python MongoDB — Drop Collection Python MongoDB
Syntax
Following is the syntax of drop() method:
db.COLLECTION_NAME.drop()
Example
Following example drops collection with name sample:
Example
from pymongo import MongoClient
#Creating a collection
col1 = db['collection']
col1.insert_one({"name": "Ram", "age": "26", "city": "Hyderabad"})
col2 = db['coll']
25
Python MongoDB
#List of collections
print("List of collections:")
collections = db.list_collection_names()
for coll in collections:
print(coll)
#Dropping a collection
col1.drop()
col4.drop()
#List of collections
collections = db.list_collection_names()
for coll in collections:
print(coll)
Output
List of collections:
coll
data
collection
myColl
List of collections after dropping two of them:
coll
myColl
26
10. Python MongoDB ― Update Python MongoDB
You can update the contents of an existing documents using the update() method or
save() method.
The update method modifies the existing document whereas the save method replaces the
existing document with the new one.
Syntax
Following is the syntax of the update() and save() methods of MangoDB:
>db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA)
Or,
db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})
Example
Assume we have created a collection in a database and inserted 3 records in it as shown
below:
27
Python MongoDB
{
"_id" : "1003",
"name" : "Robert",
"age" : 28,
"city" : "Mumbai"
}
]
> db.createCollection("sample")
{ "ok" : 1 }
> db.sample.insert(data)
Following method updates the city value of the document with id 1002.
> db.sample.update({"_id":"1002"},{"$set":{"city":"Visakhapatnam"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.sample.find()
{ "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad" }
{ "_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Visakhapatnam" }
{ "_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" }
Similarly you can replace the document with new data by saving it with same id using
the save() method.
This method accepts a query specifying which document to update and the update
operation.
Example
Following python example updates the location value of a document in a collection.
#Creating a collection
coll = db['example']
res = coll.insert_many(data)
print("Data inserted ......")
coll.update_one({"_id":"102"},{"$set":{"city":"Visakhapatnam"}})
Output
Data inserted ......
Documents in the collection:
{'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}
{'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}
{'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}
29
Python MongoDB
Similarly, the update_many() method of pymongo updates all the documents that
satisfies the specified condition.
Example
Following example updates the location value in all the documents in a collection (empty
condition):
#Creating a collection
coll = db['example']
res = coll.insert_many(data)
print("Data inserted ......")
coll.update_many({},{"$set":{"city":"Visakhapatnam"}})
Output
Data inserted ......
Documents in the collection:
{'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}
{'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}
{'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}
Documents in the collection after update operation:
{'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Visakhapatnam'}
{'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Visakhapatnam'}
{'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Visakhapatnam'}
31
11. Python MongoDB — Limit Python MongoDB
While retrieving the contents of a collection you can limit the number of documents in the
result using the limit() method. This method accepts a number value representing the
number of documents you want in the result.
Syntax
Following is the syntax of the limit() method:
>db.COLLECTION_NAME.find().limit(NUMBER)
Example
Assume we have created a collection and inserted 5 documents into it as shown below:
> db.sample.insert(data)
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 6,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
32
Python MongoDB
> db.sample.find().limit(3)
{ "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad" }
{ "_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore" }
{ "_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" }
Example
Following example retrieves first three documents in a collection.
#Creating a collection
coll = db['myColl']
33
Python MongoDB
print(doc1)
Output
Data inserted ......
First 3 documents in the collection:
{'_id': '1001', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}
{'_id': '1002', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}
{'_id': '1003', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}
34