Python MongoDB Tutorial

MongoDb is a very popular NoSQL database. Pymongo is the Python client to connect with MongoDb Server. If you want to use MongoDB in your Python project then you must have both a) MongoDB Server and b) Pymongo installed.

MongoDB Server Installation

Step 1: Visit and download the latest MongoDB Server. At the time of making this tutorial the latest version is 4.4.2

Step 2: Follow the installation wizard and the end add C:\Program Files\MongoDB\Server\4.4\bin to environement path.

Pymongo Installation

Use pip to install pymongo. Simply run:

pip install pymongo

Popular MongoDb Queries

  • Create database
  • Create collection
  • Insert record
  • Read record
  • Update record
  • Delete record
  • Drop collection
Note: In MongoDb database tables and called collections and table rows are known as records

To work with MongoDb using python firstly we need to create a mongodb client as follows:

import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017")

Create Database

mydb = myclient['mydb']
['admin', 'config', 'local', 'test', 'test_database']

MongoDB does not create the database or collection unless their is some record inserted in it.

Create Collection

mycol = mydb['customers']

Insert records in collection

d = {'name':'John', 'address':'Mumbai'}
x = mycol.insert_one(d)
mylist = [
    {'name':'Alex', 'address':'Australia'},
    {'name':'Mike', 'address':'Gorgea'}
x = mycol.insert_many(mylist)
[ObjectId('5fca5cb9e4f3b34640803e83'), ObjectId('5fca5cb9e4f3b34640803e84')]
l = [
    {'_id':1, 'name':'Ravi', 'address':'Bhopal'},
    {'_id':2, 'name':'Neha', "address":'Mumbai'}
x = mycol.insert_many(l)
[1, 2]

Find records from collection

x = mycol.find_one()
{'_id': ObjectId('5fca5c0de4f3b34640803e82'), 'name': 'John', 'address': 'Mumbai'}