How to Connect MongoDB with Python

To establish a link between the Python programming language and a MongoDB database, the initial step involves installing the pymongo driver. In this example, we will demonstrate how to connect to the database and execute fundamental database operations.

This example includes the following steps:

1) Install Driver

To install the MongoDB Driver, utilize the following command:

Example

$ pip install pymongo

2) Create Python File

// connect.py

Example

from pymongo import MongoClient # import mongo client to connect

import pprint

# Creating instance of mongoclient

client = MongoClient()

# Creating database

db = client.logicpractice

employee = {"id": "101",

"name": "Peter",

"profession": "Software Engineer",

}

# Creating document

employees = db.employees

# Inserting data

employees.insert_one(employee)

# Fetching data

pprint.pprint(employees.find_one())

3) Execute Python Script

This script outputs the newly added record to the console.

4) Enter into Mongo Shell

Next, access the MongoDB database shell to examine the newly established database and its corresponding collection.

The subsequent command can be utilized to access the database.

Example

$ mongo

5) Check Databases

The command provided below is utilized to display the databases that are currently accessible.

Example

> show dbs

6) Check Collection

The command provided below serves the purpose of displaying the collections that are accessible within the database.

Example

> show collections

7) Access Records

The records saved within a specific collection can be viewed. To display the records, the following command is utilized.

Example

> db.employees.find()

Input Required

This code uses input(). Please provide values below: