【发布时间】:2020-03-23 08:09:52
【问题描述】:
我是MongoDB 的新手,因为我之前是MySQL 的超级粉丝。我最近搬到了NoSQL 这个东西并喜欢它,但现在我被MongoDB 中的Transactions严重困住了。
我在 SO 上找到了一些相关问题,但没有答案或已过时,这不适用于新的 MongoDB PHP Driver,因为语法/函数有很多变化,我可以看到许多像我这样的新手在 MongoDB Docs 和 PHP 驱动程序之间感到困惑.
我在 MongoDB Docs 中发现了这种提交事务的方式
$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 Docs,用于 MongoDB 的新 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.committransaction.php
我的问题是,如何使用新 PHP 驱动程序的功能更新上述代码?我相信使用
MongoDB\Driver\Manager::startSession
MongoDB\Driver\Session::startTransaction
MongoDB\Driver\Session::commitTransaction
但由于文档不完整且没有示例,我不明白它们的语法或参数等。感谢您期待您的时间和支持。
【问题讨论】:
标签: php mongodb transactions nosql