Example of a transaction in MongoDB 4.0 using PHP

前端 未结 2 717
花落未央
花落未央 2021-01-27 04:44

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

2条回答
  •  一生所求
    2021-01-27 05:09

    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).

提交回复
热议问题