Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to access a collection in MongoDB using Python?
MongoDB is a well-known NoSQL database that offers a scalable and flexible approach to store and retrieve data. Using Python with MongoDB enables developers to interact with database collections effortlessly through the PyMongo library.
This article explains how to access a MongoDB collection using Python, covering the required steps, syntax, and techniques for connecting to, querying, and manipulating data.
Syntax
from pymongo import MongoClient
# Connect to MongoDB
client = MongoClient('mongodb://localhost:27017/')
# Access database and collection
db = client.database_name
collection = db.collection_name
# Perform operations
collection.insert_one(document)
collection.find(query)
collection.update_one(filter, update)
collection.delete_one(filter)
PyMongo Overview
PyMongo is the official Python driver for MongoDB. It provides a straightforward interface to interact with MongoDB databases, allowing developers to leverage MongoDB's document-oriented data model, scalability, and rich query capabilities.
Steps to Access MongoDB Collection
Install PyMongo Install the MongoDB Python driver using
pip install pymongo.Import modules Import
MongoClientfrom thepymongomodule.Establish connection Create a MongoDB client using
MongoClient()with connection details.Access database Specify the database using
client.database_name.Access collection Get the collection using
db.collection_name.Perform operations Use methods like
insert_one(),find(),update_one(),delete_one().Close connection Use
client.close()to terminate the connection.
Example
Below is a complete example demonstrating how to access and manipulate a MongoDB collection using Python ?
from pymongo import MongoClient
# Establish a connection to the MongoDB server
client = MongoClient('mongodb://localhost:27017/')
# Access the desired database
db = client.mydatabase
# Access the collection within the database
collection = db.mycollection
# Insert a document into the collection
document = {"name": "John", "age": 30}
result = collection.insert_one(document)
print("Document inserted successfully.")
# Retrieve documents from the collection
documents = collection.find()
print("Documents in the collection:")
for doc in documents:
print(doc)
# Update a document in the collection
collection.update_one({"name": "John"}, {"$set": {"age": 35}})
print("Document updated successfully.")
# Retrieve the updated document
updated_doc = collection.find_one({"name": "John"})
print("Updated Document:")
print(updated_doc)
# Delete a document from the collection
collection.delete_one({"name": "John"})
print("Document deleted successfully.")
# Verify the deletion
deleted_doc = collection.find_one({"name": "John"})
print("Deleted Document:")
print(deleted_doc)
# Close the MongoDB connection
client.close()
Output
Document inserted successfully.
Documents in the collection:
{'_id': ObjectId('646364820b3f42435e3ad5df'), 'name': 'John', 'age': 30}
Document updated successfully.
Updated Document:
{'_id': ObjectId('646364820b3f42435e3ad5df'), 'name': 'John', 'age': 35}
Document deleted successfully.
Deleted Document:
None
Key Points
-
MongoClient()establishes the connection to MongoDB server (default: localhost:27017). - Access database using
client.database_nameand collection usingdb.collection_name. -
insert_one()adds a single document,find()retrieves documents. -
update_one()modifies documents,delete_one()removes documents. - Always close the connection using
client.close()to release resources.
Conclusion
Accessing MongoDB collections in Python is straightforward using PyMongo. By following the connection pattern and using collection methods, developers can seamlessly integrate MongoDB's powerful features into their Python applications.
