Mongodb Collection in Python
Working with MongoDB Collections in Python
MongoDB is a NoSQL database that stores data in collections, which are equivalent to tables in relational databases. Collections store documents, which are equivalent to rows in a table, but they are flexible and can have different fields.
To interact with MongoDB in Python, you need to use the pymongo library, which is the official Python driver for MongoDB.
1. Installing pymongo
Before you can use MongoDB with Python, you need to install the pymongo package.
You can install it using pip:
pip install pymongo2. Connecting to MongoDB
First, you need to connect to the MongoDB server. MongoDB runs on a default port 27017 on localhost.
Example: Connecting to MongoDB
import pymongo# Create a MongoClient object to connect to the serverclient = pymongo.MongoClient("mongodb://localhost:27017/")# Access the databasedb = client["mydatabase"]# Access a collection in the databasecollection = db["mycollection"]In this example:
We connect to MongoDB running on the default localhost (
localhost:27017).We access the
mydatabasedatabase.We access the
mycollectioncollection within that database.
3. Inserting Documents into a Collection
MongoDB stores data in documents, which are BSON (binary JSON) objects. You can insert documents into a collection using insert_one() or insert_many() methods.
Inserting a Single Document
# Document to insertdocument = {"name": "Alice", "age": 30, "city": "New York"}# Insert the document into the collectionresult = collection.insert_one(document)print("Inserted document ID:", result.inserted_id)Inserting Multiple Documents
# List of documents to insertdocuments = [ {"name": "Bob", "age": 25, "city": "Los Angeles"}, {"name": "Charlie", "age": 35, "city": "Chicago"}]# Insert the documents into the collectionresult = collection.insert_many(documents)print("Inserted document IDs:", result.inserted_ids)4. Querying Documents from a Collection
You can query documents in MongoDB using find_one() for a single document or find() for multiple documents.
Finding One Document
# Find a single document in the collectionresult = collection.find_one({"name": "Alice"})print(result)Finding Multiple Documents
# Find all documents where the age is greater than 30results = collection.find({"age": {"$gt": 30}})# Loop through the results and print each documentfor document in results: print(document)In the example above:
The
find()method returns a cursor, which can be iterated over to get the documents.The query uses the
$gtoperator to find documents where the age is greater than 30.
5. Updating Documents in a Collection
You can update documents using update_one() or update_many().
Updating a Single Document
# Update the document where name is "Alice"result = collection.update_one( {"name": "Alice"}, # Filter {"$set": {"age": 31}} # Update operation)print(f"Documents matched: {result.matched_count}")print(f"Documents modified: {result.modified_count}")Updating Multiple Documents
# Update all documents where the age is greater than 30result = collection.update_many( {"age": {"$gt": 30}}, # Filter {"$set": {"status": "Senior"}} # Update operation)print(f"Documents matched: {result.matched_count}")print(f"Documents modified: {result.modified_count}")6. Deleting Documents from a Collection
You can delete documents using delete_one() or delete_many().
Deleting a Single Document
# Delete a single document where the name is "Alice"result = collection.delete_one({"name": "Alice"})print(f"Documents deleted: {result.deleted_count}")Deleting Multiple Documents
# Delete all documents where age is greater than 30result = collection.delete_many({"age": {"$gt": 30}})print(f"Documents deleted: {result.deleted_count}")7. Counting Documents in a Collection
You can count the number of documents in a collection using count_documents().
# Count the number of documents in the collectioncount = collection.count_documents({})print(f"Total documents in collection: {count}")8. Indexing in MongoDB
Indexing helps improve the speed of querying operations. You can create indexes on fields to make queries faster.
Creating an Index
# Create an index on the "name" fieldcollection.create_index([("name", pymongo.ASCENDING)])# Create a unique index on the "email" fieldcollection.create_index([("email", pymongo.ASCENDING)], unique=True)9. Aggregation in MongoDB
MongoDB provides an aggregation framework for performing complex queries like grouping, filtering, sorting, and reshaping data.
Example: Aggregation Pipeline
# Group by "city" and count the number of people in each citypipeline = [ {"$group": {"_id": "$city", "count": {"$sum": 1}}}]results = collection.aggregate(pipeline)for result in results: print(result)10. Handling Connections and Closing
You can close the connection when you're done using the MongoDB client.
# Close the connection to MongoDBclient.close()Summary of Common Operations
Insert:
insert_one(document)insert_many(documents)
Query:
find_one(query)find(query)
Update:
update_one(filter, update)update_many(filter, update)
Delete:
delete_one(filter)delete_many(filter)
Count:
count_documents(filter)
Aggregation:
aggregate(pipeline)
Conclusion
pymongois a powerful library for working with MongoDB in Python.You can perform common database operations like insert, query, update, delete, and aggregate with ease.
MongoDB's flexibility with documents and collections makes it a great choice for working with unstructured or semi-structured data.
By using pymongo, you can efficiently interact with MongoDB databases and integrate them into your Python applications!