Insert Python Object in MongoDB



By using pymongo library, we can insert a Python object into MongoDB, which is a widely used MongoDB driver for Python.

To insert a Python object represented as a dictionary, we have to establish the setup for a MongoDB client and connect to a database and collection. Before starting, ensure you have installed Python 3 (along with PIP) and MongoDB.

The following are the steps for inserting a Python object in MongoDB.

  • Install PyMongo

  • Connect to MongoDB

  • Create a Python Object

  • Insert the Object into MongoDB

  • Verify Insertion

Install PyMongo

To install the PyMongo library, open your command line and execute the following command:

pip install pymongo

Verification

To verify the installation, create a new Python file named test.py and add the following line:

import pymongo

Run the Script

If you execute the file (test.py) with no issues, then the pymongo was installed properly.

D:\Python_MongoDB>test.py
D:\Python_MongoDB>

Connect to MongoDB

To connect to a MongoDB database using PyMongo, follow these steps:

1. Import the Library and Create a Client

from pymongo import MongoClient

#pymongo client Creation
client = MongoClient('localhost', 27017)

2. Access a Database

We can also specify the names for port and host('localhost', 27017), while creating a MongoClient and can access the databases in dictionary format.

To create or access a database, use the following code:

# Access the database  
db = client['my_database']  
print("Database Created or Accessed: my_database")

Output

Database Created

Create a Python Object

In general, the MongoDB documents are represented as BSON, which is similar to JSON.

The following code represents creating the Python object and converting the object into a dictionary format, where pymongo automatically handles this conversion.

#Python object creation in dictionary format 
my_object = {
    "id" : "1001",
    "name" : "Robert",
    "age" : "26",
    "city" : "Hyderabad"
    }
}

Insert the Object into MongoDB

By using the insert() method, we can store the documents in MongoDB.This method accepts a JSON document as a parameter.

Syntax

Following is the syntax of the insert() method:

>db.COLLECTION_NAME.insert(DOCUMENT_NAME)

Insert a Single Document

Use the insert_one() method to insert the document:

# To Insert a single document
result = collection.insertone(my_object)

# Print the ID of the inserted document
print("Document ID of Inserted Object:", result.inserted_id)

Output

Document ID of Inserted Object:: 64c67188ab8c8ae00000001

Inserting Multiple Documents

To insert multiple documents at once, use the insert_many() method:

#list of objects
my_objects = [
    {"id" : "1002",
     "name" : "Rahim",
     "age" : 27,
     "city" : "Bangalore"
	},
    {"id" : "1003",
     "name" : "Ram",
     "age" : "26",
     "city" : "Mumbai"
	}
]

# Inserting the multiple documents
result = collection.insert_many(my_objects)

# Print the IDs of the inserted documents
print("Document ID's of Inserted Objects", result.inserted_ids)

Output

Inserts multiple documents into the collection and prints their IDs

Document ID's of Inserted Objects[ObjectId('64c67188abf2c8ae00000002'), ObjectId('64c67188abf2c8ae00000003')]

Verify Insertion

To confirm your data was inserted correctly, you can query the collection:

To Find a Single Document

# Find a document
document = collection.find_one({"name": "Robert"})
print("Document Found:", document)

Output

Finds and prints a single document where the name is "Robert"

Document Found: {'_id': ObjectId('64c67188ab8c8ae00000001'),"id" : "1001", "name" : "Robert", "age" : "26", "city" : "Hyderabad" }

To Find all the Documents

To retrieve all documents in the collection:

all_documents = collection.find()  
for doc in all_documents:  
    print(doc)

Output

Prints all inserted documents in the collection along with their ID's

{'_id': ObjectId('64c67188ab8c8ae00000001'),"id" : "1001", "name" : "Robert", "age" : "26", "city" : "Hyderabad" }
{'_id': ObjectId('64c67188ab8c8ae00000002'),"id" : "1002", "name" : "Rahim", "age" : "27", "city" : "Bangalore" }
{'_id': ObjectId('64c67188ab8c8ae00000003'),"id" : "1003", "name" : "Ram", "age" : "26", "city" : "Mumbai" }
Updated on: 2024-12-18T19:23:27+05:30

754 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements