In this post, we are going to develop an interaction between Python and MongoDB. Before beginning this, I am expecting that you should aware of the basics of Python. This article is not covering Python installation and setup
First, open the mongodb Atlas in a browser.
Select cluster from the left panel.
And press the CONNECT button.
You will see a popup with three options. We will explore each option.
Here, we will choose the “Connect to your Application” option
We will get a popup with 2 options:
From drivers, select Python and the latest version after that. Copy the connection string only.
mongodb+srv://admin:@cluster0-kbpys.mongodb.net/test?retryWrites=true&w=majority
Note
You need to replace the actual password with
Now open any Python editor. I am using PyCharm.
Start development
First, open pycharm.
Create an open sample project.
Open a terminal in pycharm.
Now install mongodb dependencies for python from the terminal.
pip3 install pymongo[srv]
Create one sample py file, mongo_atlas_database.py
Here we are going to print all databases and also add one database.
import pymongo
client = pymongo.MongoClient("<the atlas connection string>")
Copy the connection string from Atlas and paste it here.
import pymongo
client = pymongo.MongoClient("mongodb+srv://admin:admin123@cluster0-kbpys.mongodb.net/test?retryWrites=true&w=majority")
for name in client.list_database_names():
print(name)
The output should look like:
Now we try to list the database and respective collections.
import pymongo
client = pymongo.MongoClient("mongodb+srv://admin:admin123@cluster0-kbpys.mongodb.net/test?retryWrites=true&w=majority")
for database_name in client.list_database_names():
print("Database - "+database_name)
for collection_name in client.get_database(database_name).list_collection_names():
print(collection_name)
CRUD Operations
As we know in mongodb provides us database at the top hierarchy. In the database, we store collections and inside the collections, we add documents.
Create document
First, we create a database.
import pymongo
client = pymongo.MongoClient("mongodb+srv://admin:admin123@cluster0-kbpys.mongodb.net/test?retryWrites=true&w=majority")
collection = client.libraryDB.books
booksData = [
{
"id":"01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt"
},
{
"id":"07",
"language": "C++",
"edition": "second",
"author": "E.Balagurusamy"
}
]
collection.insert_many(booksData)
Using collection.insert_many(booksData) we can able add multiple documents in collection.
View document
To verify the documents are added or not, we have two options.
**Option 1 - View documents in MongoDB atlas **
Select cluster from the left panel.
And press the COLLECTIONS button.
Option 2
Write code in Python to retrieve records:
print('Find One document')
print(client.libraryDB.books.find_one())
print('Find all documents')
for x in client.libraryDB.books.find():
print(x)
print('Find documents with condition')
for x in client.libraryDB.books.find({"language": "Java"}):
print(x)
Update document
myquery = {"language": "Advanced Java"}
newvalues = {"$set": {"language": "Java"}}
client.libraryDB.books.update_one(myquery, newvalues)
Delete document
myquery = {"language": "Java"}
client.libraryDB.books.delete_one(myquery)
Indexing
Indexing is used to improve the performance while retrieving the documents
client.libraryDB.books.create_index([('name', 1)])
1: Ascending
-1: Descending
Index Types
Single Field
collection.create_index([('name', 1)])
Compound Index
client.libraryDB.books.createIndex( { <field1>: <type>, <field2>: <type2>, ... } )
Aggregation
Aggregation operations process data records and also return computed results. Aggregation operations group values from multiple documents together and can perform a variety of operations on the grouped data to return a single result. So, complex computations can easily handle by aggregation.
client.libraryDB.books.aggregate([
{ $match: { 'language': 'Java' } },
{ $group: { _id: "$cust_id", total: { "$sum": "$amount" } } }
])
Summary
We have learned some writing with simple CRUD operations, then we learned the concept of indexing and the use of aggregation. If you need more information, then please go through the below links:
Thank you for reading!
#python #mongodb #developer #programming