How to interact with MongoDB in Python

Last updated on Dec 13 2021
Amarnath Garg

Table of Contents

How to interact with MongoDB in Python

As more and more data become available as unstructured or semi-structured, the necessity of managing them through NoSql database increases. Python also can interact with NoSQL databases during a similar way as is interacts with Relational databases. during this blog we’ll use python to interact with MongoDB as a NoSQL database.

In order to attach to MongoDB, python uses a library referred to as pymongo. you’ll add this library to your python environment, using the below command from the Anaconda environment.

conda install pymongo

This library enables python to attach to MOngoDB employing a db client. Once connected we select the db name to be used for various operations.

Inserting Data

To insert data into MongoDB we use the insert() method which is out there within the database environment. First we hook up with the db using python code shown below then we offer the document details in sort of a series of key-value pairs.

# Import the python libraries
from pymongo import MongoClient
from pprint import pprint
# Choose the acceptable client
client = MongoClient()
# hook up with the test db
db=client.test
# Use the worker collection
employee = db.employee
employee_details = {
 'Name': 'Raj Kumar',
 'Address': 'Sears Streer, NZ',
 'Age': '42'
}
# Use the insert method
result = employee.insert_one(employee_details)
# Query for the inserted document.
Queryresult = employee.find_one({'Age': '42'})
pprint(Queryresult)
When we execute the above code, it produces the subsequent result.
{u'Address': u'Sears Streer, NZ',
 u'Age': u'42',
 u'Name': u'Raj Kumar',
 u'_id': ObjectId('5adc5a9f84e7cd3940399f93')}

Updating Data

Updating an existing MongoDB data is analogous to inserting. We use the update() method which is native to mongoDB. within the below code we are replacing the prevailing record with new key-value pairs. Please note how we are using the condition criteria to make a decision which record to update.

# Import the python libraries
from pymongo import MongoClient
from pprint import pprint
# Choose the acceptable client
client = MongoClient()
# hook up with db
db=client.test
employee = db.employee
# Use the condition to settle on the record
# and use the update method
db.employee.update_one(
 {"Age":'42'},
 {
 "$set": {
 "Name":"Srinidhi",
 "Age":'35',
 "Address":"New Omsk, WC"
 }
 }
 )

Queryresult = employee.find_one({'Age':'35'})
pprint(Queryresult)

When we execute the above code, it produces the subsequent result.

{u'Address': u'New Omsk, WC',
 u'Age': u'35',
 u'Name': u'Srinidhi',
 u'_id': ObjectId('5adc5a9f84e7cd3940399f93')}

Deleting Data

Deleting a record is additionally simple where we use the delete method. Here also we mention the condition which is employed to settle on the record to be deleted.

# Import the python libraries
from pymongo import MongoClient
from pprint import pprint
# Choose the acceptable client
client = MongoClient()
# hook up with db
db=client.test
employee = db.employee
# Use the condition to settle on the record
# and use the delete method
db.employee.delete_one({"Age":'35'})
Queryresult = employee.find_one({'Age':'35'})
pprint(Queryresult)

When we execute the above code, it produces the subsequent result.

None

So we see the actual record doesn’t exist within the db any longer .

So, this brings us to the end of blog. This Tecklearn ‘How to interact with MongoDB in Python’ blog helps you with commonly asked questions if you are looking out for a job in Python Programming. If you wish to learn Python and build a career in Data Science domain, then check out our interactive, Python with Data Science Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

https://www.tecklearn.com/course/python-with-data-science/

Python with Data Science Training

About the Course

Python with Data Science training lets you master the concepts of the widely used and powerful programming language, Python. This Python Course will also help you master important Python programming concepts such as data operations, file operations, object-oriented programming and various Python libraries such as Pandas, NumPy, Matplotlib which are essential for Data Science. You will work on real-world projects in the domain of Python and apply it for various domains of Big Data, Data Science and Machine Learning.

Why Should you take Python with Data Science Training?

  • Python is the preferred language for new technologies such as Data Science and Machine Learning.
  • Average salary of Python Certified Developer is $123,656 per annum – Indeed.com
  • Python is by far the most popular language for data science. Python held 65.6% of the data science market.

What you will Learn in this Course?

Introduction to Python

  • Define Python
  • Understand the need for Programming
  • Know why to choose Python over other languages
  • Setup Python environment
  • Understand Various Python concepts – Variables, Data Types Operators, Conditional Statements and Loops
  • Illustrate String formatting
  • Understand Command Line Parameters and Flow control

Python Environment Setup and Essentials

  • Python installation
  • Windows, Mac & Linux distribution for Anaconda Python
  • Deploying Python IDE
  • Basic Python commands, data types, variables, keywords and more

Python language Basic Constructs

  • Looping in Python
  • Data Structures: List, Tuple, Dictionary, Set
  • First Python program
  • Write a Python Function (with and without parameters)
  • Create a member function and a variable
  • Tuple
  • Dictionary
  • Set and Frozen Set
  • Lambda function

OOP (Object Oriented Programming) in Python

  • Object-Oriented Concepts

Working with Modules, Handling Exceptions and File Handling

  • Standard Libraries
  • Modules Used in Python (OS, Sys, Date and Time etc.)
  • The Import statements
  • Module search path
  • Package installation ways
  • Errors and Exception Handling
  • Handling multiple exceptions

Introduction to NumPy

  • Introduction to arrays and matrices
  • Indexing of array, datatypes, broadcasting of array math
  • Standard deviation, Conditional probability
  • Correlation and covariance
  • NumPy Exercise Solution

Introduction to Pandas

  • Pandas for data analysis and machine learning
  • Pandas for data analysis and machine learning Continued
  • Time series analysis
  • Linear regression
  • Logistic Regression
  • ROC Curve
  • Neural Network Implementation
  • K Means Clustering Method

Data Visualisation

  • Matplotlib library
  • Grids, axes, plots
  • Markers, colours, fonts and styling
  • Types of plots – bar graphs, pie charts, histograms
  • Contour plots

Data Manipulation

  • Perform function manipulations on Data objects
  • Perform Concatenation, Merging and Joining on DataFrames
  • Iterate through DataFrames
  • Explore Datasets and extract insights from it

Scikit-Learn for Natural Language Processing

  • What is natural language processing, working with NLP on text data
  • Scikit-Learn for Natural Language Processing
  • The Scikit-Learn machine learning algorithms
  • Sentimental Analysis – Twitter

Introduction to Python for Hadoop

  • Deploying Python coding for MapReduce jobs on Hadoop framework.
  • Python for Apache Spark coding
  • Deploying Spark code with Python
  • Machine learning library of Spark MLlib
  • Deploying Spark MLlib for Classification, Clustering and Regression

Got a question for us? Please mention it in the comments section and we will get back to you.

 

0 responses on "How to interact with MongoDB in Python"

Leave a Message

Your email address will not be published. Required fields are marked *