Episode 16 of 17

MongoDB with PHP

Connect MongoDB with PHP using the official MongoDB PHP library. Learn how to install the PHP driver, perform CRUD operations, use the Builder classes, handle aggregation queries, and integrate MongoDB into PHP frameworks like Laravel.

PHP remains one of the most widely used server-side languages, powering WordPress, Laravel, and millions of web applications. Integrating MongoDB with PHP gives you the flexibility of a document database with PHP's mature web ecosystem. This episode covers installation, CRUD operations, and practical patterns.

Installing the MongoDB PHP Driver

You need two components: the PHP extension (low-level driver) and the PHP library (high-level abstraction).

Step 1: Install the PHP Extension

# Using PECL
pecl install mongodb

# Add to php.ini
extension=mongodb.so

# Verify installation
php -m | grep mongodb
# Output: mongodb

# Check version
php --ri mongodb

Step 2: Install the PHP Library

# Using Composer
composer require mongodb/mongodb

Connecting to MongoDB

<?php
require 'vendor/autoload.php';

use MongoDB\Client;

// Connect to local MongoDB
$client = new Client('mongodb://localhost:27017');

// Connect with authentication
$client = new Client('mongodb://username:password@localhost:27017/admin');

// Get a database
$db = $client->blogApp;

// Get a collection
$collection = $db->posts;

echo "Connected to MongoDB!\n";

Insert Documents

// Insert one document
$result = $collection->insertOne([
    'title' => 'Getting Started with MongoDB and PHP',
    'content' => 'This tutorial covers MongoDB basics...',
    'author' => 'John Doe',
    'tags' => ['mongodb', 'php', 'tutorial'],
    'likes' => 0,
    'published' => true,
    'createdAt' => new MongoDB\BSON\UTCDateTime()
]);

echo "Inserted ID: " . $result->getInsertedId() . "\n";

// Insert many documents
$result = $collection->insertMany([
    [
        'title' => 'PHP Arrays Deep Dive',
        'author' => 'Jane Smith',
        'tags' => ['php', 'arrays'],
        'published' => true,
        'createdAt' => new MongoDB\BSON\UTCDateTime()
    ],
    [
        'title' => 'Docker for PHP Developers',
        'author' => 'Bob Wilson',
        'tags' => ['php', 'docker', 'devops'],
        'published' => false,
        'createdAt' => new MongoDB\BSON\UTCDateTime()
    ]
]);

echo "Inserted " . $result->getInsertedCount() . " documents\n";

Query Documents

// Find one document
$post = $collection->findOne(['author' => 'John Doe']);
echo $post['title'] . "\n";

// Find multiple documents
$cursor = $collection->find(['published' => true]);
foreach ($cursor as $post) {
    echo $post['title'] . " by " . $post['author'] . "\n";
}

// With comparison operators
$cursor = $collection->find([
    'likes' => ['$gte' => 10],
    'published' => true
]);

// With sorting, limit, and projection
$options = [
    'sort' => ['createdAt' => -1],
    'limit' => 10,
    'projection' => ['title' => 1, 'author' => 1, '_id' => 0]
];
$cursor = $collection->find(['published' => true], $options);

// Regex search
$cursor = $collection->find([
    'title' => ['$regex' => 'mongodb', '$options' => 'i']
]);

// Count documents
$count = $collection->countDocuments(['published' => true]);
echo "Published posts: $count\n";

Update Documents

// Update one document
$result = $collection->updateOne(
    ['author' => 'John Doe'],
    ['$set' => ['likes' => 42], '$inc' => ['views' => 1]]
);
echo "Modified: " . $result->getModifiedCount() . "\n";

// Update many documents
$result = $collection->updateMany(
    ['published' => false],
    ['$set' => ['status' => 'draft']]
);

// Upsert
$result = $collection->updateOne(
    ['slug' => 'unique-post'],
    ['$set' => ['title' => 'Unique Post', 'views' => 0]],
    ['upsert' => true]
);

// Find and update (returns the document)
$post = $collection->findOneAndUpdate(
    ['_id' => $postId],
    ['$inc' => ['views' => 1]],
    ['returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER]
);

Delete Documents

// Delete one
$result = $collection->deleteOne(['_id' => $postId]);
echo "Deleted: " . $result->getDeletedCount() . "\n";

// Delete many
$result = $collection->deleteMany([
    'createdAt' => ['$lt' => new MongoDB\BSON\UTCDateTime(strtotime('-1 year') * 1000)]
]);

// Find and delete (returns the deleted document)
$deleted = $collection->findOneAndDelete(['status' => 'pending']);

Aggregation

// Posts per author
$pipeline = [
    ['$match' => ['published' => true]],
    ['$group' => [
        '_id' => '$author',
        'postCount' => ['$sum' => 1],
        'totalLikes' => ['$sum' => '$likes']
    ]],
    ['$sort' => ['totalLikes' => -1]],
    ['$limit' => 5]
];

$cursor = $collection->aggregate($pipeline);
foreach ($cursor as $result) {
    echo $result['_id'] . ": " . $result['postCount'] . " posts, " . $result['totalLikes'] . " likes\n";
}

Laravel Integration

For Laravel projects, use the official MongoDB package:

# Install
composer require mongodb/laravel-mongodb
// config/database.php — add MongoDB connection
'mongodb' => [
    'driver' => 'mongodb',
    'host' => env('MONGO_HOST', 'localhost'),
    'port' => env('MONGO_PORT', 27017),
    'database' => env('MONGO_DATABASE', 'blogApp'),
    'username' => env('MONGO_USERNAME', ''),
    'password' => env('MONGO_PASSWORD', ''),
],
// app/Models/Post.php
use MongoDB\Laravel\Eloquent\Model;

class Post extends Model
{
    protected $connection = 'mongodb';
    protected $collection = 'posts';

    protected $fillable = ['title', 'content', 'author', 'tags', 'published'];
    protected $casts = ['published' => 'boolean', 'tags' => 'array'];
}

// Usage — same Eloquent syntax!
$posts = Post::where('published', true)
    ->orderBy('created_at', 'desc')
    ->take(10)
    ->get();

What's Next

You can now use MongoDB with PHP in both standalone and Laravel applications. In the next and final episode, we'll integrate MongoDB with Go — using the official Go driver for high-performance backend services.

TutorialMongoDBPHP