I need to showcase a transaction using mongoDB in PHP. In my example, I have \"accounts\" and \"transfers\". The first operation I am deducting balance from the \"sender account
According to the mongodb docs, the accepted answer leaves out one crucial part - you need to pass the session as parameter to any operations that should be part of the transaction. Otherwise they just behave as normal operations (i.e. won't be rolled back if the transaction is aborted) - it's not like a traditional RDBMS's transaction where it's just start transaction, everything after is by default part of the transaction until COMMIT (or ROLLBACK).
Having said as much, transactions are still quite new in mongo, and at I've not been able to get the been able to get even the sample PHP code working under mongo 4.0.12 w/ PHP MongoDB driver 1.5.5, so it may just be a bit on the bleeding edge still (or maybe just don't use that combination of mongo and driver).
Update: It appears you need a replica set, not a standalone server, in order to use transactions with mongodb.
Update: Accepted answer edited directly to include this information
If you're using the PHP library that wraps the driver, after creating an instance of Client
e.g. called $client
, you can do the following:
$session = $client->startSession();
$session->startTransaction();
try {
// Perform actions.
$session->commitTransaction();
} catch(Exception $e) {
$session->abortTransaction();
}
Unfortunately I couldn't find any relevant documentation in the PHP library reference after a cursory search, but I found examples in the PHP library's issues that suggest that creating a session from the client and using that session to start then either commit or abort the transaction is the appropriate procedure.
A couple of things to be aware of, however:
The $session variable needs to be passed in in a separate parameter. I.e. if you want to execute insertOne(['abc' => 1])
in a session, you'll need insertOne(['abc' => 1], ['session' => $session])
. If you don't do this the operations will still be executed, but won't be part of the session - i.e. if you later roll the session back, they won't be undone.
Transactions are only available if you have configured a replica set. At this stage MongoDB does not support transactions on a standalone server.
If you view the MongoDB docs (as linked above) you'll note that the requirement for a replica set to be in use is not particularly prominently displayed, being in under the third heading, and coming after all of the example code (which, if you're anything like me, will be the first thing you look for).