Getting started with MongoDB Python tutorial [Updated]

Simple Python Script to Insert, Read, Update, Delete in MongoDB using PyMongo

Details around setting up MongoDB cluster up and running on AWS. Driver Installation crud operation on MongoDB

Getting Started with MongoDB Python

MongoDB is one of the popular NoSQL databases. It uses a document-oriented, JSON-like approach to represent data, making the integration of semi-structured data fairly easily.

A few days back, I came across the buzzword “DBaaS (Database as a Service)” by Atlas MongoDB offering that provides users with a managed database service.

These services are offered as pay-as-you-go pricing to deploy on Amazon Web Services (AWS), with support to select Microsoft Azure and Google Cloud Platform as an alternative option.

The best part is that you can start working immediately with MongoDB by using a free MongoDB cluster via MongoDB Atlas.

MongoDB Atlas (the free tier ) allows you to create a quick cluster and provide the connection string to try out things!

 

So…In this Blog Post, I will walk through –

  • How to Create a free hosted MongoDB database the free tiering MongoDB Atlas
  • Other Useful setting & command line utility provided by MongoDB
  • Overview of Clusters & Security
  • Installation of Required Python Library PyMongo(the Python Driver)
  • Steps by Step GuideMongoDB Collections and Documents
  • Perform basic Create, Retrieve, Update and Delete (CRUD) operations using PyMongo

Let’s get started!

Start with free tier cluster

Thanks to MongoDB team for providing free tier cluster(Sponsered by AWS) to test things! Creating a free 3-node replica set is easy and quick; You only need to select minimal configuration required to create the cluster.

Its 3 steps process:-

 

Select the Cloud Provider & Region (in Free tier only few Region are Available)

Create Cluster I Atlas_ MongoDB Atlas

Select the Cluster Tier & Cluster Configuration

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Few Settings & Give a real name!

Atlas - Create Cluster

 

 

 

 

 

 

 

 

 

It usually takes few minutes before you see things…meanwhile you can setup user and security group used to connect your cluster from your application.

You can include your current IP to restrict access or provide 0.0.0.0/0 (includes your current IP address) so that this can be accessed everywhere via the internet.

This entirely depends on your need you might need to include your Cloud VM ip to test things from VM network.

LDAP Authentication can be configured if you are using enterprise-level security

if every thing goes well you will see the screen like below that provides an overview of Cluster Created by you.

Atlas Cluster

 

Oh…I forget …did I mention that you didn’t need a credit card to test this 🙂

 

From Cluster overview page navigate to > Command Line tools. You will see detailed instruction like how to import/export data & Connection string.

 

When you Click on Connect instruction …you will see a pop-up with details of all the IP white-listed by the application. You can also add your current IP to the list. make sure to copy them for using them later!

 

If you are using 3.6 or Newer you need to copy and use connection string would be something like below:-

mongodb+srv://mongodb-stitch-techfossguru-qnbdb:<PASSWORD>@techfossguru-go7tu.mongodb.net/test

for older drivers like 3.4 you need to use like below

mongodb://mongodb-stitch-techfossguru-qnbdb:<PASSWORD>
@techfossguru-shard-00-00-go7tu.mongodb.net:27017,
techfossguru-shard-00-01-go7tu.mongodb.net:27017,
techfossguru-shard-00-02-go7tu.mongodb.net:27017/test?ssl=true&replicaSet=techfossguru-shard-0&authSource=admin

**please make sure to use <PASSWORD> as set by you when you created user

That’s all you need to start MongoDB cluster …

let’s go move to next part and write a quick python script to connect and perform required information.

Before that, we need to ensure required prerequisites are met

Setting Required Prerequisites

  • MongoDB Cluster should be up & be running…or if you wish to install locally you can follow [How to install MongoDB] on a local machine
  • Python 2.7 + Installed(  )
  • PyMongo Lib

PyMongo is a Python distribution containing tools for working with MongoDB, and is the recommended way to work with MongoDB from Python.

This documentation attempts to explain everything you need to know to use PyMongo.

Before we start, make sure that you have the PyMongo distribution installed.

In the Python shell, the following should run without raising an exception. (PyMongo can be installed using pip- pip install pymongo)

 techfossguru@techfossguru:~$ pip install pymango
Collecting pymango
  Downloading https://files.pythonhosted.org/packages/33/c0/9f4d142e60119f15ffdba1f8a900745dad904e598ba3802c1cc92c80ee75/pymango-0.1.1.tar.gz
Requirement already satisfied: requests>=2.4.3 in ./anaconda3/lib/python3.6/site-packages (from pymango)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in ./anaconda3/lib/python3.6/site-packages (from requests>=2.4.3->pymango)
Requirement already satisfied: idna<2.7,>=2.5 in ./anaconda3/lib/python3.6/site-packages (from requests>=2.4.3->pymango)
Requirement already satisfied: urllib3<1.23,>=1.21.1 in ./anaconda3/lib/python3.6/site-packages (from requests>=2.4.3->pymango)
Requirement already satisfied: certifi>=2017.4.17 in ./anaconda3/lib/python3.6/site-packages (from requests>=2.4.3->pymango)
Building wheels for collected packages: pymango
  Running setup.py bdist_wheel for pymango ... done
  Stored in directory: /home/techfossguru/.cache/pip/wheels/a3/78/41/cae99ceaf94a0ea75fdd7171afba7762f1aa11c8eefe4f6c62
Successfully built pymango
Installing collected packages: pymango
Successfully installed pymango-0.1.1

 

Simple Python Script to Insert, Read, Update, Delete in MongoDB using PyMongo

Data in MongoDB is represented (and stored) using JSON-style documents.  In PyMongo we use dictionaries to represent documents. In this examples, we will use below fields based document.

{

    "title": "An article about MongoDB and Python",

    "content": "Detailed discussion about MongoDB",

    "publication_date": "2018-04-07 10:00:00",

    "shares": {

        "twitter": 123,

        "facebook" 456,

        "linkedin": 789

    },

    "tags": ["python", "mongodb", "nosql"],

        "name": "Satish",

        "author_id": 1

}
  • Documents are grouped into collections.
  • In comparison with the relational world, if a document is a row/record, a collection would be something similar to a table.
  • A group of collections can be hosted on the same database,
  • Being a JSON-style data store, MongoDB is often referred to as schemaless: as fields can dynamically be added to documents without the need to define an explicit schema.

High-level Steps

  • Import MongoDB client for Accessing a  Mongo Database
  • Establishing a Connection to Atlas MongoDB Cluster
  • Write steps methods to read, insert, update, delete and search
  • Combine them all together

MONGODB CRUD OPERATIONS WITH PYTHON (PYMONGO)

CRUD operations can be mapped directly to database operations:

  • Create matches insert a document in a collection
  • Read matches select/retrive/find documents
  • Update matches update document based on filters
  • Delete matches delete document based on filter

So in our example, we perform steps one by one …!

MongoDB Python Example

Few Points:

  •  If you are using localhost; Mongo DB URI connection method client = MongoClient(‘mongodb://localhost:27017/’)
  • SCRAM-SHA-1 is the default authentication mechanism supported by a cluster configured for authentication with MongoDB 3.0 or later. Authentication is per-database and credentials can be specified through the MongoDB URI or passed to the authenticate() method:
  • >>> uri = “mongodb://user:password@example.com/the_database?authMechanism=SCRAM-SHA-1”
  • >>> client = MongoClient(uri)
  • You can read some advance examples at official documentation site. The examples in this section are intended to give in-depth overviews of how to accomplish specific tasks with MongoDB and PyMongo.
  • You might get an error like pymongo.errors.InvalidURI: Username and password must be escaped according to RFC 3986, use urllib.parse.quote_plus(). This is common if you are using any special character in the password

 

Please feel free to in case more information is required around.

Comments

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More