In this section, you'll learn how to perform basic CRUD (Create, Read, Update, Delete) operations with MangaDB. These are the fundamental operations for working with any database.
Note: For all examples in this tutorial, we assume you have already connected to the MangaDB service. If you haven't, refer to the Getting Started section.
Connecting to MangaDB
Before performing any operations, you need to connect to the MangaDB service:
from mongo_db_client import MongoDBClient
# Create a client instance
client = MongoDBClient() # Default: localhost:27020
# Connect to the service
if client.connect():
print("Connected to MangaDB service")
else:
print("Failed to connect to MangaDB service")
1. Create (Insert) Documents
To create a new document in a collection, use the insert
method:
# Insert a document into a collection
document = {
"title": "One Piece",
"author": "Eiichiro Oda",
"year": 1997,
"genres": ["Adventure", "Fantasy", "Comedy"],
"ongoing": True
}
# The collection will be created automatically if it doesn't exist
doc_id = client.insert("mangas", document)
print(f"Inserted document with ID: {doc_id}")
The insert
method returns the ID of the newly created document. MangaDB automatically generates a unique ID for each document and adds it as the _id
field.
2. Read Documents
MangaDB provides two methods for reading documents: find_one
and find
.
Finding a Single Document
To find a single document that matches a query, use the find_one
method:
# Find a document by ID
document = client.find_one("mangas", {"_id": doc_id})
print(document)
# Find a document by other criteria
document = client.find_one("mangas", {"title": "One Piece"})
print(document)
Finding Multiple Documents
To find all documents that match a query, use the find
method:
# Find all documents in a collection
all_mangas = client.find("mangas", {})
print(f"Found {len(all_mangas)} manga(s)")
# Find documents that match specific criteria
ongoing_mangas = client.find("mangas", {"ongoing": True})
print(f"Found {len(ongoing_mangas)} ongoing manga(s)")
3. Update Documents
To update existing documents, use the update
method:
# Update a document by ID
update_count = client.update(
"mangas",
{"_id": doc_id}, # Query to find the document
{"year": 1999} # Fields to update
)
print(f"Updated {update_count} document(s)")
# Update multiple documents
update_count = client.update(
"mangas",
{"ongoing": True}, # Query to find documents
{"last_updated": "2023-08-11"} # Fields to update
)
print(f"Updated {update_count} document(s)")
The update
method returns the number of documents that were updated.
4. Delete Documents
To delete documents, use the delete
method:
# Delete a document by ID
delete_count = client.delete("mangas", {"_id": doc_id})
print(f"Deleted {delete_count} document(s)")
# Delete multiple documents
delete_count = client.delete("mangas", {"ongoing": False})
print(f"Deleted {delete_count} document(s)")
The delete
method returns the number of documents that were deleted.
5. Listing Collections
To get a list of all collections in the database, use the list_collections
method:
# List all collections
collections = client.list_collections()
print(f"Available collections: {collections}")
Disconnecting
When you're done with the database operations, it's good practice to disconnect:
# Disconnect from the service
client.disconnect()
Complete Example
Here's a complete example that demonstrates all the basic operations:
from mongo_db_client import MongoDBClient
# Create a client and connect
client = MongoDBClient()
if not client.connect():
print("Failed to connect to MangaDB service")
exit(1)
try:
# Insert a document
manga = {
"title": "Naruto",
"author": "Masashi Kishimoto",
"year": 1999,
"genres": ["Action", "Adventure", "Fantasy"],
"ongoing": False
}
doc_id = client.insert("mangas", manga)
print(f"Inserted document with ID: {doc_id}")
# Find the document
found_manga = client.find_one("mangas", {"_id": doc_id})
print(f"Found manga: {found_manga}")
# Update the document
update_count = client.update(
"mangas",
{"_id": doc_id},
{"volumes": 72}
)
print(f"Updated {update_count} document(s)")
# Verify the update
updated_manga = client.find_one("mangas", {"_id": doc_id})
print(f"Updated manga: {updated_manga}")
# List collections
collections = client.list_collections()
print(f"Available collections: {collections}")
# Delete the document
delete_count = client.delete("mangas", {"_id": doc_id})
print(f"Deleted {delete_count} document(s)")
finally:
# Always disconnect when done
client.disconnect()
Congratulations! You now know how to perform basic CRUD operations with MangaDB. In the next section, we'll explore more advanced query techniques.