CRUD operations in Python using MongoDB connector
In this article, you will learn how to perform CRUD operations using mongodb with Python.
MongoDB is a NoSQL (Not only SQL) open-source document-oriented database management system. This is suitable for modern internet applications. It provides dynamic queries, scalability, secondary indexes, and fast atomic updates, and we can easily use more than one database in a project. Like other programming languages, Python can also easily connect with different popular databases, including MongoDB.
Install MongoDB Python
Python requires a MongoDB driver to access the MongoDB database. In this post, we will use the MongoDB driver "PyMongo". The PyMongo distribution contains tools for interacting with the MongoDB database from Python. The installer requires 'python.exe' in your system PATH, otherwise it will fail to install. So make sure to add Python to your system environment.
You can install MongoDB Connector using the pip tool.
(env) c:\python37\Scripts\projects>pip install pymongo
On successful installation, it returns something like this-
Collecting pymongo
Downloading pymongo-3.10.1-cp37-cp37m-win_amd64.whl (354 kB)
|████████████████████████████████| 354 kB 284 kB/s
Installing collected packages: pymongo
Successfully installed pymongo-3.10.1
Start Mongo daemon
We hope you have installed mongodb on your system, and if you do not, please click on 'MongoDB Installation' tutorial.
Once installed, use the following command in a terminal window to start the mongodb daemon.
$ mongod
Create MongoDB client and connect to the host and port
Now we will see how to connect to MongoDB and perform CRUD operations using Python. First, we need to import the MongoDB connector into a Python file to connect to the database. After importing, create an instance of MongoClient and establish a connection to the default host, i.e., localhost and port 27017. The MongoClient method is used to connect to the MongoDB server.
import pymongo
client = pymongo.MongoClient("mongodb://localhost:27017/")
Python Create Database
Here, we have created a new database 'school'. The same pattern is used to create a new database and use an existing one.
mydb = client["school"]
To display the list of databases we can use the list_database_names() method.
mydb.list_database_names()
Create or Access Collection
Here, we have created a collection name 'students'.
mycol = mydb["students"]
Python insert data in collection
To insert a single document into a collection, the insert_one() method is used, and to insert multiple documents, the insert_many() method is used. Here, we have inserted multiple documents in the 'students' collection.
import pymongo
client = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = client["school"]
mycol = mydb["students"]
stu_dict = [
{'name': "Andy Joya", 'age': 10, 'section': '5A'},
{'name': "Mary Soi", 'age': 11, 'section': '5B'},
{'name': "Priska Somya", 'age': 12, 'section':'6A'}
]
x = mycol.insert_many(stu_dict)
Python find collection data
In MongoDB, the find_one() method returns only the first document of a collection that fulfil the specified criteria, and the find() method is used to return the document or documents based on the specified criteria.
import pymongo
client = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = client["school"]
mycol = mydb["students"]
for y in mycol.find():
print(y)
Once you run the above code, it returns the following output-
Python update collection data
The update_one() method is used to update or modify the existing document in a collection, and the update_many() method is used to update the multiple documents in a collection.
import pymongo
client = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = client["school"]
mycol = mydb["students"]
mycol.update_one({'name': "Andy Joya"},{'$set': {'age': 11, 'class': '5B'}})
for y in mycol.find():
print(y)
Once you run the above code, it returns output something like this-
Python delete collection data
The delete_one() method is used to remove a single document, and the delete_many() method is used to remove all documents from a collection that matches the criteria.
import pymongo
client = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = client["school"]
mycol = mydb["students"]
mycol.delete_one({'name': "Mary Soi"})
for y in mycol.find():
print(y)
The above code deleted the specified data and returns the remaining data something like this -
Related Articles
Python requests POST methodDisplay data from MySQL in HTML table using Python
Convert MySQL query result to JSON in Python
Insert XML Data to MySQL Table using Python
Get data from MySQL in Django View with Models
Display image from database in Django
Insert JSON data into MongoDB using Python
Python Converting a CSV File to a MySQL Table
Display data from MongoDB in HTML table using Python
CRUD operations in Python using MYSQL Connector
Django upload image to database
Insert XML data to MongoDB using Python
Python Turtle Graphics Overview
Factorial Program in Python
Convert MongoDB Document to JSON using Python
Django pass variable from view to HTML template
Django ajax GET and POST request
Python get visitor information by IP address
Python snake game code with Pygame
Python JSON Tutorial - Create, Read, Parse JSON file
Python convert xml to dict
Python convert dict to xml