MongoDB - PHP: A Beginner's Guide
Hello there, future database wizards! ? I'm thrilled to be your guide on this exciting journey into the world of MongoDB and PHP. As someone who's been teaching computer science for years, I've seen countless students light up when they grasp these concepts. So, let's dive in and make some database magic together!
Make a Connection and Select a Database
Before we can do anything fancy, we need to connect to our MongoDB server and select a database. Think of this as knocking on the door of a giant library and asking to be let in.
Here's how we do it:
<?php
// Create a new MongoDB client
$client = new MongoDB\Client("mongodb://localhost:27017");
// Select a database
$database = $client->selectDatabase("myAwesomeDB");
echo "Connected successfully to the database!";
?>
Let's break this down:
- We create a new MongoDB client, telling it where our MongoDB server is (in this case, it's on our local machine).
- We then select a database called "myAwesomeDB". If it doesn't exist, MongoDB will create it for us. Isn't that nice?
Pro tip: Always check if your connection was successful. In a real-world scenario, you'd want to wrap this in a try-catch block to handle any connection errors gracefully.
Create a Collection
Now that we're in our database, we need a place to store our data. In MongoDB, we call these places "collections". Think of a collection like a drawer in a filing cabinet.
Here's how we create one:
<?php
// Create a new collection
$collection = $database->createCollection("myFirstCollection");
echo "Collection created successfully!";
?>
Easy peasy, right? We just told our database to create a new collection called "myFirstCollection". If the collection already exists, MongoDB will simply return the existing collection.
Insert a Document
Time to put something in our shiny new collection! In MongoDB, we store data as "documents". These are a lot like the JSON objects you might have seen before.
Let's add a document about a cute cat:
<?php
$document = [
"name" => "Whiskers",
"age" => 3,
"color" => "orange",
"likes" => ["naps", "fish", "laser pointers"]
];
$insertResult = $collection->insertOne($document);
echo "Inserted document with ID: " . $insertResult->getInsertedId();
?>
Here's what's happening:
- We create an array that represents our document. It has various fields describing our cat.
- We use the
insertOne()
method to add this document to our collection. - MongoDB gives each document a unique ID, which we can retrieve with
getInsertedId()
.
Find All Documents
Now that we have some data, let's fetch it back out. We'll use the find()
method to get all documents in our collection:
<?php
$cursor = $collection->find();
foreach ($cursor as $document) {
echo "Name: " . $document["name"] . ", Age: " . $document["age"] . "\n";
}
?>
This code will print out the name and age of every cat in our collection. The find()
method returns a cursor, which we can iterate over to access each document.
Update a Document
Oops! We just realized Whiskers had a birthday. Let's update his age:
<?php
$updateResult = $collection->updateOne(
["name" => "Whiskers"],
['$set' => ["age" => 4]]
);
echo "Matched " . $updateResult->getMatchedCount() . " document(s)\n";
echo "Modified " . $updateResult->getModifiedCount() . " document(s)";
?>
Here's what's going on:
- We use
updateOne()
to find a document where the name is "Whiskers". - We then use the
$set
operator to change the age to 4. - The method returns information about how many documents were matched and modified.
Delete a Document
Sometimes, we need to remove data. Let's say Whiskers found a new home (don't worry, he's very happy there!). We can remove his document like this:
<?php
$deleteResult = $collection->deleteOne(["name" => "Whiskers"]);
echo "Deleted " . $deleteResult->getDeletedCount() . " document(s)";
?>
This code finds a document where the name is "Whiskers" and deletes it. The getDeletedCount()
method tells us how many documents were removed.
MongoDB PHP Methods
Here's a handy table of the main MongoDB PHP methods we've covered:
Method | Description |
---|---|
new MongoDB\Client() |
Creates a new MongoDB client |
selectDatabase() |
Selects a database |
createCollection() |
Creates a new collection |
insertOne() |
Inserts a single document |
find() |
Retrieves documents from a collection |
updateOne() |
Updates a single document |
deleteOne() |
Deletes a single document |
And there you have it! You've just learned the basics of working with MongoDB using PHP. Remember, practice makes perfect, so don't be afraid to experiment with these methods. Try creating different collections, inserting various types of documents, and playing around with more complex queries.
In my years of teaching, I've found that the students who dive in and get their hands dirty with code are the ones who truly master these concepts. So go forth, young padawan, and may the database be with you! ??
Credits: Image by storyset