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 the environment path.

Pymongo Installation

Use pip to install pymongo. Simply run:

pip install pymongo

Popular MongoDB Queries

  1. Create database
  2. Create collection
  3. Insert record
  4. Read record
  5. Update record
  6. Delete record
  7. Drop collection

Note: In the 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())

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


Create Collection

mycol = mydb['customers']
print(mydb.list_collection_names())

Insert records in the collection

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

Find records from the collection

x = mycol.find_one()
print(x)

This was a quick CRUD operation on MongoDB with Python.