MongoDB is one of the best NoSQL document-oriented databases. If you are working on a project in Python and planning to use MongoDB on the backend, then you are perfectly at the right place. In today’s post, we’ll teach the basics of Python MongoDB. And will also add a few database programming samples. The ready-to-use coding snippets will help you in ramping up quickly. By the way, if you are just beginning to use MongoDB with Python. Then, reading our post on installing & setting up MongoDB would surely help.
In this Python MongoDB programming tutorial, you’ll get to learn where to use MongoDB, and how to create a database. Additionally, we’ll give Python code for selecting, inserting, and deleting records from the tables. We thought to bring every essential element that can quickly get you on board. So enjoy this post and we hope to see you writing better database programming scripts in Python. Let’s read a few words about MongoDB next.
Learn Python MongoDB Programming
Both MySQL and MongoDB are open-source databases. But unlike MySQL, MongoDB is a document-oriented database. It stores all data as documents. There are many benefits of the MongoDB data modeling approach.
- The documents function as independent units. So it’s easier to distribute them which leads to an increase in performance.
- MongoDB programming is easy. No need to do the complex translation of objects between application and SQL queries.
- Flexible schema makes it easier to store unstructured data.
- It uses a document-based query language to create dynamic queries. It’s as powerful as SQL.
While you proceed with the tutorial, we suggest downloading the Python MongoDB driver. It wraps the MongoDB features to use them from a Python script.
To install it, either press the blue button (below) or run the <pip> command given next.
For Linux/Mac OS platforms, issue the below command to add the <PyMongo driver>.
pip install pymongo
In this section, we’ll discuss the essential Python MongoDB commands to connect and access the database. First of all, let’s how to make a connection to MongoDB because after connecting to it only we can perform an access operation on it.
How to connect to MongoDB?
To make a connection to the database we require creating a Mongo Client against the running the <Mongod> instance. For this, we’ll provide the arguments indicating the host and port where the database is running.
If the MongoDB server is running locally <default port for MongoDB is 27017>, then you can proceed with the following command.
from pymongo import MongoClient con = MongoClient('localhost', 27017)
For instance, if you are working in a large hybrid setup where the application server runs on a separate machine. Then, you’ll need to provide the IP address of that machine while creating the Mongo Client.
from pymongo import MongoClient con = MongoClient('192.168.1.2', 27017)
Consequently, if you like to connect on the default <host/port>, then please give the below command.
con = MongoClient()
Once you run through the above steps, you’ll all be set to perform the operations on the database.
Create a database in MongoDB
MongoDB voluntarily creates a database as you start to use it. So for testing purposes, you can execute the below step for DB creation.
db = con.testdb
Another approach is to use dictionary-style access for DB creation. See the below code.
db = client['testdb']
Access a MongoDB collection in Python
A collection is a group of documents stored in the database. It’s the same as a table in RDBMS.
Also, we can access a MongoDB collection in the same way as we did while accessing the database at the last point.
my_coll = db.coll_name #OR do it in the dictonary-style. my_coll = db['coll_name']
Add documents to a collection
MongoDB models data in JSON format. It uses the dictionary to store the records.
emp_rec = {'name':emp_name, 'address':emp_addr, 'id':emp_id}
Also, to work with collections, the Python MongoDB module exposes a set of methods.
For example, the <insert()> method, you may like to call it from your code to add documents to a collection.
rec_id = my_coll.insert(emp_rec)
Since the <insert()> method returns a new record, you can save it to a variable <rec_id> for using it later.
Query data in a collection
The Python MongoDB driver also gives you a method <find()> to query data from any MongoDB collection. Also, on top of it, you can run the <pretty()> method to format the query results.
Here is the code for you to follow.
testdb.coll_name.find()
While we are providing the <pretty()> method example, use it only if required.
testdb.coll_name.find().pretty() { "_id" : ObjectId("7abf53ce1220a0213d"), "name" : emp_name, "address" : emp_addr, "id" : emp_id }
Probably, you’ve taken note that the <_id> is an auto-generated value. Also, it’s unique for a particular document.
Finally, you would have to close the open MongoDB connection after completing the transactions. Call the method as given below.
con.close()
Update data in a collection
To modify a collection, use any of the following Python MongoDB methods.
- <update_one()>,
- <update_many()>.
While you may call any of the above methods to update a collection, you would’ve to use the <$set> macro to change values.
Also, note that we are storing the output into a variable.
ret = db.my_coll.update_one( {"name": "Post"}, { "$set": { "Category": "Programming" }, "$currentDate": {"lastModified": True} } )
Consequently, you can verify the result by issuing the following step.
ret.modified_count
Remove data from a collection
Same as the update, here is a list of methods to delete the documents.
- <delete_one()>,
- <delete_many()>.
Check out the below code snippet for removing more than one document.
ret = db.posts.delete_many({"category": "general"})
Also, you can call the following method to print the number of deleted records.
ret.deleted_count
Python MongoDB Demo Script
Since we promised to give you a full database programming script, here is the Python script to cover the essential Python MongoDB commands.
Also, the script should now be easy for you to understand, as we’ve already explained the individual commands above.
Sample Code: Python MongoDB Script
from pymongo import MongoClient #connect to the MongoDB. conn = MongoClient('localhost',27017) #Access the testdb database and the emp collection. db = conn.testdb.emp #create a dictionary to hold emp details. #create dictionary. emp_rec = {} #set flag variable. flag = True #loop for data input. while (flag): #ask for input. emp_name,emp_addr,emp_id = input("Enter emp name, address and id: ").split(',') #place values in dictionary. emp_rec = {'name':emp_name,'address':emp_addr,'id':emp_id} #insert the record. db.insert(emp_rec) #Ask from user if he wants to continue to insert more documents? flag = input('Enter another record? ') if (flag[0].upper() == 'N'): flag = False #find all documents. ret = db.find() print() print('+-+-+-+-+-+-+-+-+-+-+-+-+-+-') #display documents from collection. for record in ret: #print out the document. print(record['name'] + ',',record['address'] + ',',record['id']) print() #close the conn to MongoDB conn.close()
Final Word – Python MongoDB Programming
While we are at the closing of this blog post after discussing the practical use of Python MongoDB commands, you may ask any query you have about the above tutorial.
MongoDB Database vs MySQL
Check the most important differences between MongoDB and MySQL.
If you want us to continue writing such tutorials, support us by sharing this post on your social media accounts like Facebook / Twitter. This will encourage us and help us reach more people.
All the Best,
TechBeamers