我是新来的MongoDB
因为我是一个超级粉丝MySQL
前。我最近搬到了这个NoSQL
东西并且喜欢它,但现在我严重陷入困境交易 in MongoDB
.
我在 SO 上发现了一些相关问题,但没有答案或已过时,不适用于新的MongoDB PHP Driver
因为语法/函数有很多变化,我可以看到许多像我这样的新手对 MongoDB 文档和 PHP 驱动程序感到困惑。
我在 MongoDB 文档中发现了这种提交事务的方式
$client = new MongoDB\Driver\Manager("mongodb://127.0.0.1:27017");
$callback = function (\MongoDB\Driver\Session $session) use ($client)
{
$client->selectCollection('mydb1', 'foo')->insertOne(['abc' => 1], ['session' => $session]);
$client->selectCollection('mydb2', 'bar')->insertOne(['xyz' => 999], ['session' => $session]);
};
// Step 2: Start a client session.
$session = $client->startSession();
// Step 3: Use with_transaction to start a transaction, execute the callback, and commit
$transactionOptions =
[
'readConcern' => new \MongoDB\Driver\ReadConcern(\MongoDB\Driver\ReadConcern::LOCAL),
'writeConcern' => new \MongoDB\Driver\WriteConcern(\MongoDB\Driver\WriteConcern::MAJORITY, 1000),
'readPreference' => new \MongoDB\Driver\ReadPreference(\MongoDB\Driver\ReadPreference::RP_PRIMARY),
];
\MongoDB\with_transaction($session, $callback, $transactionOptions);
但此语法/函数对于新的 PHP 驱动程序来说已过时,并且会出现以下错误
Call to undefined function MongoDB\with_transaction()
根据 PHP 文档,新的 MongoDB PHP 驱动程序提供了这些提交事务的选项,但我不明白如何?因为文档中没有给出示例。
https://www.php.net/manual/en/mongodb-driver-manager.startsession.php https://www.php.net/manual/en/mongodb-driver-manager.startsession.php
https://www.php.net/manual/en/mongodb-driver-session.starttransaction.php https://www.php.net/manual/en/mongodb-driver-session.starttransaction.php
https://www.php.net/manual/en/mongodb-driver-session.committransaction.php https://www.php.net/manual/en/mongodb-driver-session.committransaction.php
我的问题是,如何使用新 PHP 驱动程序的功能更新上述代码?我相信使用
MongoDB\Driver\Manager::startSession
MongoDB\Driver\Session::startTransaction
MongoDB\Driver\Session::commitTransaction
但由于文档不完整且没有示例,我不明白它们的语法或参数等是什么。感谢您的宝贵时间和支持。