xp-forge / mongodb
MongoDB connectivity for XP Framework
Installs: 8 973
Dependents: 1
Suggesters: 0
Security: 0
Stars: 0
Watchers: 4
Forks: 0
Open Issues: 5
Requires
- php: >=7.0.0
- xp-framework/core: ^12.0 | ^11.0 | ^10.0 | ^9.0 | ^8.0 | ^7.0
- xp-framework/math: ^9.1
- xp-framework/networking: ^10.0 | ^9.0 | ^8.0
Requires (Dev)
- xp-framework/test: ^2.0 | ^1.5
- dev-master
- v2.4.0
- v2.3.1
- v2.3.0
- v2.2.0
- v2.1.0
- v2.0.0
- v1.15.0
- v1.14.0
- v1.13.0
- v1.12.0
- v1.11.0
- v1.10.0
- v1.9.2
- v1.9.1
- v1.9.0
- v1.8.0
- v1.7.0
- v1.6.0
- v1.5.0
- v1.4.0
- v1.3.0
- v1.2.0
- v1.1.1
- v1.1.0
- v1.0.0
- v0.11.0
- v0.10.0
- v0.9.1
- v0.9.0
- v0.8.0
- v0.7.2
- v0.7.1
- v0.7.0
- v0.6.0
- v0.5.3
- v0.5.2
- v0.5.1
- v0.5.0
- v0.4.0
- v0.3.1
- v0.3.0
- v0.2.0
- v0.1.0
- dev-feature/quicker-reconnect
- dev-one
This package is auto-updated.
Last update: 2024-10-29 07:28:12 UTC
README
This library implements MongoDB connectivity via its binary protocol. It has no dependencies on the PHP extension.
Examples
Finding documents inside a collection:
use com\mongodb\{MongoConnection, ObjectId}; use util\cmd\Console; $c= new MongoConnection('mongodb://localhost'); $id= new ObjectId(...); // Find all documents $cursor= $c->collection('test.products')->find(); // Find document with the specified ID $cursor= $c->collection('test.products')->find($id); // Find all documents with a name of "Test" $cursor= $c->collection('test.products')->find(['name' => 'Test']); foreach ($cursor as $document) { Console::writeLine('>> ', $document); }
Inserting a document into a collection:
use com\mongodb\{MongoConnection, Document}; use util\cmd\Console; $c= new MongoConnection('mongodb://localhost'); $result= $c->collection('test.products')->insert(new Document([ 'name' => 'Test', 'qty' => 10, 'tags' => ['new', 'tested'], ])); Console::writeLine('>> ', $result);
Updating documents:
use com\mongodb\{MongoConnection, ObjectId}; use util\cmd\Console; $c= new MongoConnection('mongodb://localhost'); $id= new ObjectId(...); // Select a single document for updating by its ID $result= $c->collection('test.products')->update($id, ['$inc' => ['qty' => 1]]); // Apply to all documents matchig a given filter $result= $c->collection('test.products')->update(['name' => 'Test'], ['$inc' => ['qty' => 1]]); Console::writeLine('>> ', $result);
Upserting documents:
use com\mongodb\MongoConnection; use util\cmd\Console; $c= new MongoConnection('mongodb://localhost'); $result= $c->collection('test.products')->upsert(['slug' => 'test'], new Document([ 'slug' => 'test', 'name' => 'Test', 'qty' => 10, 'tags' => ['new', 'tested'], ])); Console::writeLine('>> ', $result);
Deleting documents:
use com\mongodb\{MongoConnection, ObjectId}; use util\cmd\Console; $c= new MongoConnection('mongodb://localhost'); $id= new ObjectId(...); // Select a single document to be removed $result= $c->collection('test.products')->delete($id); // Remove all documents matchig a given filter $result= $c->collection('test.products')->delete(['name' => 'Test']); Console::writeLine('>> ', $result);
Note: All of the above have used the collection()
shortcut which is equivalent to chaining database('test')->collection('products')
.
Authentication
To authenticate, pass username and password via the connection string, e.g. mongodb://user:pass@localhost
. The authentication source defaults to admin but can be set by supplying a path, e.g. mongodb://user:pass@localhost/test
.
Both SCRAM-SHA-256 and SCRAM-SHA-1 are supported as authentication mechanisms. Which one is used is negotiated upon connecting with the server / cluster. To explicitely select the authentication mechanism, pass it as part of the connection string, e.g. mongodb://user:pass@localhost?authMechanism=SCRAM-SHA-256
.
SSL / TLS
To connect via SSL / TLS, pass ssl=true
as connection string parameters, e.g.:
use com\mongodb\MongoConnection; $c= new MongoConnection('mongodb://localhost?ssl=true'); // Explicit call to connect, can be omitted when using collection() $c->connect();
Aggregation
The Collection
class also features aggregation methods:
count($filter= [])
distinct($key, $filter= [])
aggregate($pipeline)
See https://docs.mongodb.com/manual/reference/command/nav-aggregation/
Commands
To run commands on a given collection, use the run() method:
use com\mongodb\MongoConnection; $c= new MongoConnection('mongodb+srv://server.example.com'); // A simple connection-wide command without arguments $result= $c->run('ping')->value(); // A command might return a cursor $indexes= $c->collection('app.sessions')->run('listIndexes', [], 'read'); foreach ($indexes->cursor() as $index) { // ... }
See https://www.mongodb.com/docs/manual/reference/command/ for a list of commands.
DNS Seed List Connection
Adding in DNS to specify clusters adds another level of flexibility to deployment. Given the following DNS entries:
Record TTL Class Priority Weight Port Target
_mongodb._tcp.server.example.com. 86400 IN SRV 0 5 27317 mongodb1.example.com.
_mongodb._tcp.server.example.com. 86400 IN SRV 0 5 27017 mongodb2.example.com.
...the following code will connect to one of the above:
use com\mongodb\MongoConnection; $c= new MongoConnection('mongodb+srv://server.example.com'); $c->connect();
Sessions
Using a causally consistent session, an application can read its own writes and is guaranteed monotonic reads, even when reading from replica set secondaries.
use com\mongodb\{MongoConnection, ObjectId}; use util\cmd\Console; $c= new MongoConnection('mongodb+srv://server.example.com?readPreference=secondary'); $session= $c->session(); $id= new ObjectId('...'); // Will write to primary $collection= $c->collection('test.products'); $collection->update($id, ['$set' => ['qty' => 1]], $session); // Will read the updated document $updated= $collection->find($id, $session); $session->close();
Handling errors
All operations raise instances of the com.mongodb.Error
class. Connection and authentication errors can be handled by checking for CannotConnect:
use com\mongodb\{MongoConnection, Error, CannotConnect}; use util\cmd\Console; $c= new MongoConnection('mongodb+srv://user:pass@mongo.example.com'); try { $c->connect(); } catch (CannotConnect $e) { // Error during authentication phase, e.g.: // - DNS errors // - None of the replica set members is reachable // - Authentication failed } catch (Error $e) { // Any other error }
Type mapping
All builtin types are mapped to their BSON equivalents. In addition, the following type mappings are used:
util.Date
=> UTC datetimeutil.Bytes
=> Binary datautil.UUID
=> UUID binary datacom.mongodb.Int64
=> 64-bit integercom.mongodb.Decimal128
=> 128-bit decimalcom.mongodb.ObjectId
=> Object IDcom.mongodb.Timestamp
=> Timestampcom.mongodb.Regex
=> Regular expression
The deprecated types of the BSON spec are not supported, see http://bsonspec.org/spec.html