PHP with MongoDB: Examples, CRUD, Aggregation, and Advanced Features

PHP with MongoDB: Examples, CRUD, Aggregation, and Advanced Features

Table of Contents

  1. Introduction
  2. Driver Architecture & Components
  3. Installation & Setup
  4. Connecting to MongoDB
  5. CRUD Operations
  6. Aggregation & Indexing
  7. Advanced Features: Change Streams, GridFS, Monitoring
  8. Best Practices & Common Pitfalls
  9. Integration with Frameworks
  10. Performance & Scaling Considerations
  11. Real‑World Example: Blog App
  12. Troubleshooting
  13. Conclusion & Further Resources

1. Introduction

MongoDB is a widely adopted NoSQL document database, designed for flexibility, horizontal scalability, and schema evolution. PHP, as a dominant web development language, pairs well with MongoDB to build modern applications using JSON‑style document storage rather than traditional relational schemas.

As of mid‑2025, you should prefer using:

  • The C‑based PHP extension, known as the mongodb extension (via PECL)
  • The PHP library (mongodb/mongodb) from Composer, which provides a high‑level, object‑oriented API on top of the extension (MongoDB, FlatCoding, PHP, Stack Overflow, MongoDB, MongoDB)

Using both together gives you low‑level performance and high‑level developer convenience.

2. Driver Architecture & Components

The PHP MongoDB ecosystem is layered:

  • mongodb extension
    • Written in C, built atop libmongoc and libbson
    • Provides minimal, fast APIs for connections, commands, BSON serialization, queries, writes, and monitoring (FlatCoding, PHP)
    • Key class: MongoDB\Driver\Manager
  • PHP library (mongodb/mongodb)
    • Written in PHP
    • Provides a MongoDB\Client, database and collection abstractions, helper methods like insertOne(), find(), etc. Also supports GridFS, codecs, monitoring, and builders (MongoDB)
  • Additional tools & integrations
    • ODMs like Doctrine, Laravel MongoDB, Symfony bundle, Yii2 extensions, Flysystem GridFS adapter, etc. (MongoDB)

This clean separation lets you update the extension for performance while using the library API for ease of development.

3. Installation & Setup

System Requirements

  • PHP 8.1 or newer (extension v1.21+ and library v1.17+)
  • MongoDB server 4.2 or newer, though extension v1.20+ adds support for MongoDB 8.0 (MongoDB, MongoDB, GitHub)

Installing the extension

On Linux/macOS:

sudo pecl install mongodb

Then add to php.ini:

extension = mongodb.so

Restart Apache or PHP‑FPM. Confirm with:

php -m | grep mongodb

On Windows:

Download the appropriate DLL for your PHP version from PECL or GitHub releases (e.g. version 2.1.1 from June 13, 2025) (Stack Overflow, pecl.php.net). Place it in your PHP ext directory and enable in php.ini:

extension = php_mongodb.dll

Then restart the web server.

Installing the PHP library

Use Composer:

composer require mongodb/mongodb

Currently library version 1.17.0+ is recommended—it introduces support for BSON "codec" APIs, Atlas Search index creation methods, logging via PSR‑3 logger, and requires PHP 7.4+ (effectively PHP 8+) (MongoDB).

4. Connecting to MongoDB

a) Low‑level using the extension

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
// Then use executeQuery, executeBulkWrite etc.

You work with raw commands, BSON or arrays. Useful for custom, lightweight needs but quite verbose (MongoDB, MongoDB).

b) High‑level using the PHP library

require 'vendor/autoload.php';

$client = new MongoDB\Client('mongodb://localhost:27017');
// or use an Atlas URI from environment:
$uri = getenv('MONGODB_URI') ?: die('Define MONGODB_URI');
$client = new MongoDB\Client($uri);

$collection = $client->selectDatabase('mydb')->selectCollection('users');

Then use intuitive methods like insertOne(), find(), updateOne() etc. (MongoDB).

5. CRUD Operations with Examples

Create (Insert)

$result = $collection->insertOne([
  'name' => 'Alice',
  'age'  => 29,
  'tags' => ['admin', 'user'],
]);
echo "Inserted with ID: {$result->getInsertedId()}\n";

Read (Find)

$cursor = $collection->find(['age' => ['$gte' => 18]], [
  'sort' => ['name' => 1],
  'limit' => 10
]);
foreach ($cursor as $doc) {
  printf("%s (%d)\n", $doc['name'], $doc['age']);
}

Update

$updateResult = $collection->updateOne(
  ['name' => 'Alice'],
  ['$inc' => ['age' => 1]]
);
printf("Matched %d document(s), modified %d\n",
  $updateResult->getMatchedCount(),
  $updateResult->getModifiedCount());

Replace

$collection->replaceOne(
  ['_id' => $result->getInsertedId()],
  ['name' => 'Alice', 'age' => 31, 'role' => 'manager']
);

Delete

$deleteResult = $collection->deleteOne(['name' => 'Alice']);
printf("Deleted %d document(s)\n", $deleteResult->getDeletedCount());

Bulk operations are also supported via bulkWrite() using BulkWrite class from the extension.

6. Aggregation, Indexing & Search

Aggregation pipelines are powerful. In library v1.21+, there’s a new Aggregation Builder API for constructing pipelines programmatically and type-safely (GitHub, MongoDB):

$pipeline = (new MongoDB\Driver\Command([
  'aggregate' => 'users',
  'pipeline' => [
    ['$match' => ['age' => ['$gte' => 18]]],
    ['$group' => ['_id' => '$role', 'count' => ['$sum' => 1]]]
  ],
  'cursor' => new stdClass,
]));

$res = $client->admin->executeCommand('mydb', $pipeline);

Alternatively, use convenience methods in the high‑level library or ODM frameworks.

For search, you can create Atlas Search indexes and run $search pipeline stages via methods added in v1.17+ and updated builder syntax in v1.21+ (MongoDB, MongoDB).

Index creation:

$collection->createIndexes([
    ['key' => ['username' => 1], 'unique' => true],
]);

7. Advanced Features

Change Streams

Real‑time listening to changes:

$changeStream = $collection->watch([['$match' => ['operationType' => 'insert']]]);
foreach ($changeStream as $change) {
    var_dump($change);
}

GridFS

Use for storing files >16MB:

$bucket = new MongoDB\GridFS\Bucket($client->selectDatabase('files'));
$stream = fopen('photo.jpg', 'rb');
$id = $bucket->uploadFromStream('photo.jpg', $stream);

Monitoring & Logging

Library v1.17+ supports PSR‑3 logging:

use Psr\Log\LoggerInterface;
MongoDB\add_logger($logger);
MongoDB\remove_logger($logger);

This ties into extension’s monitoring API (MongoDB\Driver\Monitoring\LogSubscriber) (MongoDB, MongoDB).

8. Best Practices

  • Always use the PHP library (Client...) for high‑level operations, unless doing batch writes or specialized commands.
  • Use typed arrays/object mapping via codec API (v1.17+) for cleaner data handling.
  • Leverage indexes on query fields, use unique constraints when possible.
  • Use bulkWrite for batched inserts/updates to reduce server round trips.
  • Handle errors/exceptions: catching MongoDB\Driver\Exception\Exception and check for duplicate key, network errors, timeouts, etc.
  • For large documents (>16MB), use GridFS.
  • To stream results use cursorᵢ and pagination with skip/limit or range queries.
  • When using multiple PHP versions, ensure you’re editing the correct php.ini (CLI vs Apache vs FPM) (MongoDB, GitHub, Stack Overflow, MongoDB).

9. Integration with Frameworks & ODMs

Use ecosystem tools for common frameworks:

  • Laravel MongoDB: an Eloquent adapter package that allows working with MongoDB using Laravel style models and query builder (MongoDB).
  • Doctrine MongoDB ODM: Object Document Mapper for Symfony or standalone.
  • Symfony MongoDB Bundle, Yii2 MongoDB extension, Flysystem GridFS, Mongolid, Xenus – all offer higher‑level abstractions tailored to specific frameworks (MongoDB).

10. Performance & Scaling Considerations

  • Connection pooling: reuse MongoDB\Client instance across requests or via persistent connections (in FPM or CLI).
  • Use projection to limit returned fields.
  • Avoid unindexed queries on large collections.
  • Batch writes via bulkWrite for speed.
  • Use Atlas clusters or sharding for horizontal scaling.
  • Enable wiredTiger compression, allow large data sets.
  • Monitor performance using the driver’s built‑in APM events or PSR‑3 logging.

11. Real‑World Example: Blog App

Setting up

require 'vendor/autoload.php';

$client = new MongoDB\Client('mongodb://127.0.0.1:27017');
$coll = $client->blog->posts;

Inserting a post

$post = [
  'title'   => 'Getting Started with PHP & MongoDB',
  'slug'    => 'php-mongodb-guide',
  'body'    => '<p>...</p>',
  'tags'    => ['php', 'mongodb', 'tutorial'],
  'published_at' => new MongoDB\BSON\UTCDateTime(),
];

$coll->insertOne($post);

Fetching paginated posts

$page = 1;
$limit = 10;
$cursor = $coll->find([], [
  'sort' => ['published_at' => -1],
  'skip' => ($page - 1) * $limit,
  'limit' => $limit,
]);

Aggregating posts per tag

$pipeline = [
  ['$unwind' => '$tags'],
  ['$group' => ['_id' => '$tags', 'count' => ['$sum' => 1]]],
  ['$sort' => ['count' => -1]],
];
$agg = $coll->aggregate($pipeline);
foreach ($agg as $doc) {
    echo $doc->_id . ": " . $doc->count . "\n";
}

Change stream to listen new posts

$stream = $coll->watch();
foreach ($stream as $change) {
    if ($change->operationType === 'insert') {
        echo "New post: " . $change->fullDocument->title . "\n";
    }
}

12. Troubleshooting Common Issues

  • Driver not showing in php -m: ensure you edited the right php.ini. Confirm by phpinfo().
  • Header file errors when installing: on Linux, install php-dev or php-devel package so phpize works (MongoDB, FlatCoding, MongoDB).
  • Legacy driver usage: old tutorials use MongoClient class from PHP 5 era; those are deprecated. Use mongodb extension's Manager or higher-level Client package (Stack Overflow, MongoDB).
  • Version mismatches: extension v2.0+ requires PHP 8.1+, drops support for MongoDB 4.0; library version >=1.17 requires PHP 7.4+ and supports newer features (MongoDB, GitHub).

13. Conclusion & Further Resources

You now have a thorough grounding in using PHP with MongoDB—from installation to advanced features. This setup—MongoDB PHP extension + mongodb/mongodb library—provides a performance‑efficient, feature‑rich foundation for building scalable modern applications.

 Key takeaways:

  • Extension = performance; Library = developer friendliness. Use both together.
  • Use modern PHP (8.1+), MongoDB 4.2+ or 8.0 for latest features.
  • Make heavy use of aggregation, indexing, bulk operations, change streams for real use cases.
  • Consider using frameworks and ODMs when building larger applications.

For further reading:

  • The official MongoDB PHP Library manual and driver docs on MongoDB.com (FlatCoding, Stack Overflow, GitHub, MongoDB, MongoDB)
  • Release announcements for library and extension (e.g. v1.17, v1.21, extension 2.1.1) (pecl.php.net)
  • Community forums and Stack Overflow for real‑world problem solving.
#PHP MongoDB #MongoDB with PHP tutorial #PHP MongoDB guide #install MongoDB PHP #PHP MongoDB CRUD #PHP MongoDB aggregation #MongoDB PHP example #GridFS PHP #MongoDB driver PHP

Subscribe to our newsletter

12k+

Subscribers

Weekly

Frequency

Free

Always