Example of a transaction in MongoDB 4.0 using PHP

前端 未结 2 747
花落未央
花落未央 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:00

    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

提交回复
热议问题