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 https://www.mongodb.com/try/download/community 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']
print(myclient.list_database_names())
['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']
print(mydb.list_collection_names())
[]
                        

Insert records in collection

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

Find records from collection

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