TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: How to Connect MongoDB with Python
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python AdvancedPython Tutorials

How to Connect MongoDB with Python

Last updated: May 26, 2024 7:18 pm
By Meenakshi Agarwal
Share
9 Min Read
Python MongoDB Programming Tutorial for Beginners
Python MongoDB Programming Tutorial for Beginners
SHARE

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.

Contents
How to connect to MongoDB?Create a database in MongoDBAccess a MongoDB collection in PythonAdd documents to a collectionQuery data in a collectionUpdate data in a collectionRemove data from a collectionPython MongoDB Demo ScriptFinal Word – Python MongoDB Programming

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.

Download the Latest PyMongo Driver

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.

15 Min ReadMySQL vs MongoDB

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

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

How to Use Extent Report in Python

10 Python Tricky Coding Exercises

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Create a Selenium Load Testing Demo Using BrowserMob Proxy BrowserMob Proxy for Selenium Load Testing
Next Article 10 Most Common Selenium Webdriver Howtos Selenium Webdriver Howtos (10) for 2024

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x