Installation:
composer require alcaeus/mongo-php-adapter
Ensure ext-mongodb (PHP driver) is installed (php -m | grep mongodb).
Basic Usage:
use MongoDB\Client as MongoClient;
use Alcaeus\MongoClient\Connection;
$client = new MongoClient('mongodb://localhost:27017');
$adapter = new Connection($client);
$collection = $adapter->selectCollection('db', 'collection');
First Use Case:
Replace legacy ext-mongo calls (e.g., mongo_connect()) with the adapter:
// Old (deprecated)
$conn = mongo_connect('localhost');
// New
$client = new MongoClient('mongodb://localhost');
$adapter = new Connection($client);
Connection.php: Core adapter class.Cursor.php: Legacy cursor emulation.Collection.php: Legacy collection wrapper.Wrap MongoDB\Client:
$mongoClient = new MongoClient('mongodb://user:pass@host:port');
$legacyAdapter = new Connection($mongoClient);
Replace mongo_* Functions:
mongo_connect() → new Connection($client)mongo_select_db() → $adapter->selectDB('db')mongo_query() → $collection->find($query)Cursor Handling:
$cursor = $collection->find(['status' => 'active']);
while ($cursor->advance()) {
$doc = $cursor->current();
}
jenssegers/mongodb for seamless ORM integration:
$adapter = new Connection(new MongoClient(env('DB_CONNECTION')));
config(['database.connections.mongodb.adapter' => $adapter]);
$result = $collection
->find()
->limit(10)
->sort(['createdAt' => -1]);
MongoClient transactions via the adapter:
$session = $client->startSession();
$adapter->setSession($session);
Deprecation Warning:
The package is deprecated (last release 2023). Prefer native ext-mongodb or mongodb/mongodb for new projects.
Method Mismatches:
mongo_insert() → Use $collection->insertOne().mongo_find() → Use $collection->find() (returns Cursor).Type Inconsistencies:
mongo_id objects → Convert to MongoDB\BSON\ObjectId:
$id = new MongoDB\BSON\ObjectId($legacyId->__toString());
Session Handling:
$session = $client->startSession();
$adapter->setSession($session); // Critical for transactions
$adapter = new Connection($client, [
'logger' => new \Monolog\Logger('mongo_adapter'),
]);
xdebug to trace Alcaeus\MongoClient method calls in legacy code.Connection to add domain-specific methods:
class CustomAdapter extends Connection {
public function findByEmail($email) {
return $this->selectCollection('users')->find(['email' => $email]);
}
}
Cursor to modify iteration logic (e.g., add caching):
class CachedCursor extends Cursor {
protected $cache = [];
public function current() {
if (!isset($this->cache[$this->key])) {
$this->cache[$this->key] = parent::current();
}
return $this->cache[$this->key];
}
}
$query = ['$query' => ['age' => ['$gt' => 18]], '$orderby' => ['name' => 1]];
$result = $collection->find($query);
How can I help you explore Laravel packages today?