I need to use transactions on MongoDB in Laravel.
I downloaded the php MongoDB driver 1.6 and copied and pasted php_mongodb.dll into the php/ext folder.
I also installed the php mongo library through
composer require mongodb/mongodb
Now, when I try to use transactions according to this, it doesn't rollback when an error occurs.
$client = new Client($url);
$callback = function (\MongoDB\Driver\Session $session) use ($client) {
$data = [
"name" => "Tommy",
];
$collection = $client->db1->users;
$user = $collection->updateOne(
['mobile' => '*'],
['$set' => $data],
[$session]
);
$data = [
"activate" => 1,
];
$collection = $client->db1->wallets;
$wallet1 = $collection->updateOne(
['_id' => 100],
['set' => $data],
[$session]
);
};
$session = $client->startSession();
$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),
];
try{
\MongoDB\with_transaction($session, $callback, $transactionOptions);
return true;
}catch (\Exception $e)
{
return false;
}
The session class in MongoDB\Driver\Session
is unknown in laravel while this class is for mongodb>=1.4.0. I don't know what is wrong. Can anyone help me?