php实现mongodb事务

Centos7 + Mongodb4.2.0 + php7.3

 'test1'];
$mongoConf['server'] = 'mongodb://localhost:27019';
$options = [
    'username' => 'mongo',
    'password' => '7f27cd7ae184274e2ca645f09183fc63',
    'db' => 'admin',
    'replicaSet' => '',
    'socketTimeoutMS' =>  300,
    'connectTimeoutMS' => 300,
];
$mongoConf['options'] = $options;
$config = (array)$mongoConf + array('server' => 'mongodb://localhost:27019', 'optionss' => array('connect' => true));
extract($config);

//连接 mongodb
$manager = new \MongoDB\Driver\Manager($server, $optionss);


//开启session
//causalConsistency  boolean  因果一致性 如果操作依赖先前的操作需要设置为true
$session = $manager->startSession(['causalConsistency'=>true]);

//开启事务
$session->startTransaction();


//下面执行两个写操作

//批量插入/删除/更新操作  
//ordered  有序操作(TRUE)在MongoDB服务器上串行执行,而无序操作(FALSE)以任意顺序发送到服务器,并且可以并行执行。
$bulk1 = new \MongoDB\Driver\BulkWrite(['ordered' => true]);
$bulk1->insert( ['name'=>'insert', 'age'=>44] );
$writeConcern1 = new \MongoDB\Driver\WriteConcern(\MongoDB\Driver\WriteConcern::MAJORITY, 1000);
//执行批量插入/删除/更新操作  
//第一个参数 databaseName.collectionName
//第二个参数 要执行的操作
$manager->executeBulkWrite('front.user', $bulk1, ['session'=>$session, 'writeConcern'=>$writeConcern1]);


$bulk2 = new \MongoDB\Driver\BulkWrite(['ordered' => true]);
$bulk2->insert( ['id'=>2] );
$writeConcern2 = new \MongoDB\Driver\WriteConcern(\MongoDB\Driver\WriteConcern::MAJORITY, 1000);
$manager->executeBulkWrite('front.coin', $bulk2, ['session'=>$session, 'writeConcern'=>writeConcern2]);

//提交事务
$session->commitTransaction();
//事务回滚
$session->abortTransaction();

注意事项

1.使用事务时必须先创建数据库以及集合 Cannot create namespace front.coin in multi-document transaction
2.事务必须使用在mongodb复制集上 Transaction numbers are only allowed on a replica set member
mongodb搭建复制集

你可能感兴趣的:(php实现mongodb事务)