xp-forge/mongodb

XP Framework 的 MongoDB 连接性

v2.3.1 2024-04-02 13:14 UTC

README

Build status on GitHub XP Framework Module BSD Licence Requires PHP 7.0+ Supports PHP 8.0+ Latest Stable Version

此库通过二进制协议实现 MongoDB 连接。它不依赖于 PHP 扩展。

示例

在集合中查找文档

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);
}

将文档插入到集合中

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);

更新文档

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 文档

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);

删除文档

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);

注意:以上所有操作都使用了 collection() 快捷方式,它等同于链式调用 database('test')->collection('products')

身份验证

要进行身份验证,通过连接字符串传递用户名和密码,例如 mongodb://user:pass@localhost。默认的身份验证来源为 admin,但可以通过提供路径来设置,例如 mongodb://user:pass@localhost/test

支持 SCRAM-SHA-256SCRAM-SHA-1 作为身份验证机制。使用哪个机制是在与服务器/集群连接时协商的。要显式选择身份验证机制,将其作为连接字符串的一部分传递,例如 mongodb://user:pass@localhost?authMechanism=SCRAM-SHA-256

SSL / TLS

要通过 SSL / TLS 连接,将 ssl=true 作为连接字符串参数传递,例如

use com\mongodb\MongoConnection;

$c= new MongoConnection('mongodb://localhost?ssl=true');

// Explicit call to connect, can be omitted when using collection()
$c->connect();

聚合

Collection 类还提供聚合方法

  • count($filter= [])
  • distinct($key, $filter= [])
  • aggregate($pipeline)

有关更多信息,请参阅 https://docs.mongodb.com/manual/reference/command/nav-aggregation/

命令

要在给定的集合上运行命令,请使用 run() 方法

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) {
  // ...
}

有关命令列表,请参阅 https://mongodb.ac.cn/docs/manual/reference/command/

DNS 种子列表连接

在指定集群中添加 DNS 可以为部署增加另一层灵活性。给定以下 DNS 条目

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.

...以下代码将连接到上述之一

use com\mongodb\MongoConnection;

$c= new MongoConnection('mongodb+srv://server.example.com');
$c->connect();

会话

使用因果一致会话,应用程序可以读取自己的写入,并保证从副本集次级读取时的单调读取。

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();

处理错误

所有操作都会引发 com.mongodb.Error 类的实例。可以通过检查 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
}

类型映射

所有内置类型都映射到它们的 BSON 等效类型。此外,还使用了以下类型映射

  • util.Date => UTC datetime
  • util.Bytes => Binary data
  • util.UUID => UUID binary data
  • com.mongodb.Int64 => 64-bit integer
  • com.mongodb.Decimal128 => 128-bit decimal
  • com.mongodb.ObjectId => Object ID
  • com.mongodb.Timestamp => Timestamp
  • com.mongodb.Regex => Regular expression

BSON 规范的已弃用类型不受支持,请参阅 http://bsonspec.org/spec.html