Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Using MongoDB with PHP

Introduction

MongoDB is a popular NoSQL database, and PHP provides excellent support for working with MongoDB through the MongoDB PHP Library. This tutorial will guide you through the steps to connect to a MongoDB database, perform CRUD operations, and manage data using PHP.

Setting Up

To get started, you need to install the MongoDB PHP Library. You can install it using Composer:

Installing MongoDB PHP Library

composer require mongodb/mongodb

Connecting to MongoDB

To connect to a MongoDB instance, use the following code:

Example: Connecting to MongoDB

require 'vendor/autoload.php';

$client = new MongoDB\Client("mongodb://localhost:27017");
$collection = $client->testdb->users;

echo "Connected to MongoDB!";
            

CRUD Operations

CRUD stands for Create, Read, Update, and Delete. Here are examples of how to perform these operations using the MongoDB PHP Library:

Create

Inserting a Document

$insertResult = $collection->insertOne([
    'name' => 'John Doe',
    'age' => 30
]);

echo "Inserted document with ID: {$insertResult->getInsertedId()}";
            

Read

Finding a Document

$document = $collection->findOne(['name' => 'John Doe']);
echo "Found document: ";
var_dump($document);
            

Update

Updating a Document

$updateResult = $collection->updateOne(
    ['name' => 'John Doe'],
    ['$set' => ['age' => 31]]
);

echo "Matched {$updateResult->getMatchedCount()} documents and modified {$updateResult->getModifiedCount()} documents.";
            

Delete

Deleting a Document

$deleteResult = $collection->deleteOne(['name' => 'John Doe']);
echo "Deleted {$deleteResult->getDeletedCount()} documents.";
            

Conclusion

In this tutorial, you have learned how to use MongoDB with PHP to perform basic CRUD operations. The MongoDB PHP Library provides powerful tools to interact with MongoDB databases, making it easier to integrate MongoDB into your PHP applications.