Python MongoDB

In this tutorial, you will learn about connecting your Python application to a MongoDB database using PyMongo driver and perform CRUD (Create Read Update Delete) operations on the database.

To get started with this tutorial, you must have MongoDB installed on your computer.

Download Free MongoDB here at https://docs.mongodb.com/manual/administration/install-community

Lets create a simple Python project and add dependencies needed for this example:

  1. Create a folder with any project name of your choice. Example: my_project
  2. Open a terminal and navigate your command line to the project folder you just created. Example:
  3. 
        cd my_project
    
  4. Inside the project folder, create a virtualenv with any valid name using the command virtualenv name :
  5. 
        virtualenv env
        
  6. Python requires a MongoDB Driver to connect and interact with the MongoDB database. PyMongo is the official driver for MongoDB published by the MongoDB developers. So, install PyMongo driver using the command pip3 install pymongo:
  7. 
        pip3 install pymongo
    

Connecting to MongoDB

After installing the pymongo driver, create a main.py file inside your project folder and write the following code to connect to your MongoDB:

main.py

import pymongo

try:
    client = pymongo.MongoClient("localhost", 27017)
    #print all existing databases
    print(client.list_database_names())
finally:
    print("Closing mongo client connection")
    client.close()

If the above code runs without any error then your application is ready to interact with the MongoDB.

Creating a Database

The code below connects to the MongoDB and creates a database.

Note: In MondoDB, a database is not created until collections are created in the database.

main.py

import pymongo

try:
    client = pymongo.MongoClient("localhost", 27017)
    print("Existing databases = %s" % (client.list_database_names()))

    #create database
    my_database = client["test_tb"]
finally:
    print("Closing mongo client connection")
    client.close()

If the above code runs without any error then your code is working.

Creating a Collection

Tables are called collections in MongoDB.

The code below connects to the specified MongoDB database and creates a collection in the database:

Note: In MondoDB, a collection is not created until data are saved in the collection.

main.py

import pymongo

try:
    client = pymongo.MongoClient("localhost", 27017)
    #database
    my_database = client["test_tb"]
    #create collection
    customer_my_collection = my_database["customer"]

    print("Existing databases = %s" % (client.list_database_names()))
    print("Existing collections = %s" % (my_database.list_collection_names()))
finally:
    print("Closing mongo client connection")
    client.close()

Insert Into Collection

The code below connects to the specified MongoDB database and inserts data into the specified collection:

main.py

import pymongo

try:
    client = pymongo.MongoClient("localhost", 27017)

    my_database = client["test_tb"]
    customer_my_collection = my_database["customer"]

    print("Existing databases = %s" % (client.list_database_names()))
    print("Existing collections = %s" % (my_database.list_collection_names()))


    customer_data = {"first_name": "Danny",
                     "last_name": "Wright",
                     "email": "danny@tutorialsbuddy.com",
                     "contact_number": "5555555",
                     "country": "United Kingdom"}

    result = customer_my_collection.insert_one(customer_data)
    print("Inserted _id:",result.inserted_id)
finally:
    print("Closing mongo client connection")
    client.close()

Insert Multiple Documents

The code below connects to the specified MongoDB database and inserts multiple documents into the specified collection:

main.py

import pymongo

try:
    client = pymongo.MongoClient("localhost", 27017)

    my_database = client["test_tb"]
    customer_my_collection = my_database["customer"]

    print("Existing databases = %s" % (client.list_database_names()))
    print("Existing collections = %s" % (my_database.list_collection_names()))


    customer_list = [{"first_name": "Peter",
                     "last_name": "A",
                     "email": "peter@tutorialsbuddy.com",
                     "contact_number": "5555555",
                     "country": "United Kingdom"},
                    {"first_name": "Jenny",
                    "last_name": "B",
                    "email": "jenny@tutorialsbuddy.com",
                    "contact_number": "6666666",
                    "country": "United States"},
                    {"first_name": "Maddy",
                    "last_name": "C",
                    "email": "maddy@tutorialsbuddy.com",
                    "contact_number": "7777777",
                    "country": "Australia"},
                    {"first_name": "Jason",
                    "last_name": "D",
                    "email": "jason@tutorialsbuddy.com",
                    "contact_number": "5555555",
                    "country": "South Korea"}]

    result = customer_my_collection.insert_many(customer_list)
    print("Inserted _ids:",result.inserted_ids)
finally:
    print("Closing mongo client connection")
    client.close()

Read Documents From Collection

The code below connects to the specified MongoDB database and reads documents from the specified collection:

main.py

import pymongo

try:
    client = pymongo.MongoClient("localhost", 27117)
    my_database = client["test_tb"]
    customer_my_collection = my_database["customer"]

    print("Existing databases = %s" % (client.list_database_names()))
    print("Existing collections = %s" % (my_database.list_collection_names()))

    # find one document
    customer = customer_my_collection.find_one()
    print(customer)

    # find multiple documents
    customers = customer_my_collection.find()
    for c in customers:
        print(c)

    # get all emails
    customer_email = customer_my_collection.find({}, {"_id": 0, "email": 1})
    for c in customer_email:
        print(c)
finally:
    print("Closing mongo client connection")
    client.close()

Query Collection

The code below connects to the specified MongoDB database and query data from the collection:

main.py

import pymongo

try:
    client = pymongo.MongoClient("localhost", 27117)

    my_database = client["test_tb"]
    customer_my_collection = my_database["customer"]

    print("Existing databases = %s" % (client.list_database_names()))
    print("Existing collections = %s" % (my_database.list_collection_names()))

    my_query = {"email": "maddy@tutorialsbuddy.com"}
    # Query documents by email
    customers = customer_my_collection.find(my_query)
    for c in customers:
        print(c)
finally:
    print("Closing mongo client connection")
    client.close()

Update Documents in Collection

The code below connects to the specified MongoDB database and updates a document by email in the specified collection:

main.py

import pymongo

try:
    client = pymongo.MongoClient("localhost", 27117)

    my_database = client["test_tb"]
    customer_my_collection = my_database["customer"]

    print("Existing databases = %s" % (client.list_database_names()))
    print("Existing collections = %s" % (my_database.list_collection_names()))

    my_query = {"last_name": "C"}
    new_val = {"$set": {"last_name": "D",
                        "country": "Singapore",
                        "contact_number": "9999999"}}
    # update single document
    customer = customer_my_collection.update_one(my_query, new_val)

    # update multiple documents
    my_query = {"last_name": "D"}
    new_val = {"$set": {"last_name": "C", 
                        "country": "Singapore",
                        "contact_number": "9999999"}}

    customers = customer_my_collection.update_many(my_query, new_val)

    print(customers.modified_count, "documents updated.")
finally:
    print("Closing mongo client connection")
    client.close()

Delete Table Data

The code below connects to the specified MongoDB database and deletes documents by last_name in the specified table:

main.py

import pymongo

try:
    client = pymongo.MongoClient("localhost", 27117)

    my_database = client["test_tb"]
    customer_my_collection = my_database["customer"]

    print("Existing databases = %s" % (client.list_database_names()))
    print("Existing collections = %s" % (my_database.list_collection_names()))

    # delete single document
    my_query = {"last_name": "C"}
    customer = customer_my_collection.delete_one(my_query)

    # delete multiple documents
    my_query = {"last_name": "A"}
    customers = customer_my_collection.delete_many(my_query)

    print(customers.deleted_count, "documents deleted.")
finally:
    print("Closing mongo client connection")
    client.close()