Python MongoDB 

Python’s support to MongoDB as a NoSQL database can be enacted through the pymongo library. MongoDB is a document-oriented database that stores data in JSON-like structures called BSON (Binary JSON). This section tends to illuminate some basic ideas and steps concerning the use of MongoDB with Python.

1. Install PyMongo

To work with MongoDB in Python, install the pymongo library:

pip install pymongo

2. Connect to MongoDB

In order to proceed, you must have a running MongoDB server, either locally or hosted (for example, MongoDB Atlas).Use the MongoClient class to connect.

Example: Connect to a Local MongoDB Server

from pymongo import MongoClient

# Connect to the local MongoDB server
client = MongoClient("mongodb://localhost:27017/")

# Access a specific database
db = client["mydatabase"]

# Access a collection (similar to a table in relational databases)
collection = db["mycollection"]

Example: Connect to MongoDB Atlas (Cloud)

client = MongoClient("mongodb+srv://<username>:<password>@cluster0.mongodb.net/test?retryWrites=true&w=majority")
db = client["mydatabase"]
collection = db["mycollection"]

3. MongoDB Design

MongoDB stores data in a hierarchical structure:

  • Database: It is a container for collections (like a database in SQL).
  • Collection: A container for documents (similar to a table in SQL).
  • Document: A JSON-like object with key-value pairs, much like a row in SQL.

4. CRUD Operations

CRUD refers to Create, Read, Update, and Delete operations.

4.1. Create

Insert documents into a collection using insert_one() or insert_many().

Example: Insert a Single Document
document = {"name": "Alice", "age": 25, "city": "New York"}
collection.insert_one(document)
Example: Insert Multiple Documents
documents = [
    {"name": "Bob", "age": 30, "city": "Los Angeles"},
    {"name": "Charlie", "age": 35, "city": "Chicago"}
]
collection.insert_many(documents)

4.2. Read

Retrieve documents using find_one() or find().

Example: Retrieve a Single Document
result = collection.find_one({"name": "Alice"})
print(result)
Example: Retrieve All Documents
for document in collection.find():
    print(document)
Example: Filter Documents
query = {"city": "New York"}
for document in collection.find(query):
    print(document)
Example: Projection (Select Specific Fields)
query = {"city": "New York"}
projection = {"_id": 0, "name": 1}  # Exclude _id, include name
for document in collection.find(query, projection):
    print(document)

4.3. Update

Modify documents using update_one() or update_many().

Example: Update a Single Document
query = {"name": "Alice"}
update = {"$set": {"age": 26}}
collection.update_one(query, update)
Example: Update Multiple Documents
query = {"city": "New York"}
update = {"$set": {"status": "Active"}}
collection.update_many(query, update)

4.4. Delete

Remove documents using delete_one() or delete_many().

Example: Delete a Single Document
query = {"name": "Alice"}
collection.delete_one(query)
Example: Delete Multiple Documents
query = {"city": "New York"}
collection.delete_many(query)

5. Advanced Operations

5.1. Indexing

Indexes improve query performance. Create an index using create_index().

collection.create_index([("name", 1)]) # 1 for ascending, -1 for descending

5.2. Aggregation

Perform complex operations using the aggregation pipeline.

pipeline = [
    {"$match": {"city": "New York"}},
    {"$group": {"_id": "$city", "average_age": {"$avg": "$age"}}}
]
result = collection.aggregate(pipeline)
for doc in result:
    print(doc)

6. Error Handling

Use try-except blocks to handle errors.

from pymongo.errors import ConnectionFailure

try:
    client = MongoClient("mongodb://localhost:27017/")
    print("Connected successfully!")
except ConnectionFailure as e:
    print(f"Could not connect to MongoDB: {e}")

7. Closing the Connection

Close the MongoDB connection after completion.

client.close()

8. Key Points

  • MongoDB’s schema-less nature means that documents in the same collection can have different structures.
  • Use BSON data types like ObjectId for unique identifiers.
  • pymongo handles most MongoDB operations with straightforward methods.