Search code examples
mysqlmongodbinnodbnosql

Atomic in MongoDB with transfer money


I'm new for MongoDB I make a simple application abount account in bank.an account can transfer money to others I design Account collection like that

account
{
         name:A
         age: 24
         money: 100
}

account
{
         name:B
         age: 22
         money: 300
}

assuming that user A transfer 100$ for user B , there are 2 operations : 1) decrease 100$ in user A // update for document A 2) increase 100$ for user B // update with document B It said that atomic only applied for only single document but no mutiple document.

I have a alter desgign

Bank
{
      name:
      address:
      Account[
       {
         name:A
         age: 22
         money: SS
},
{
         name:B
         age: 23
         money: S1S
}
]
} 

I have some question :

  • If I use later way, How can I write transaction query (Can I use findAndModify() function?) ?
  • Does MongoDB support transaction operations like Mysql (InnoDB)?
  • Some pepple tell me that use Mysql for this project is the best way, and just only use MongoDB to save transaction information.(use extra collection named Transaction_money to save them), If I use both MongoDB and Mysql (InnoDB) how can make some operations below are atomic (fail or success whole):
> 1) -100$ with user A 
> 2) +100$ with user B 
> 3) save transaction

information like

transaction
{
   sender: A
   receiver: B
   money : 100
   date: 05/04/2013
}

Thank so much.


Solution

  • I am not sure this is what you are looking for:

    db.bank.update({name : "name"},{ "$inc" : {'Account.0.money' : -100, 'Account.1.money' : 100}})
    
    • update() operation is satisfies ACI properties of ( ACID ). Durability ( D ) depends on the mongo and application configuration while making query.
    • You can prefer to use findAndModify() which won't yield lock on page fault
    • MongoDB provides transactions within a document

    I can't understand, if your application requirement is very simple, then why you are trying to use mongodb. No doubt its a good data-store, but I guess MySql will satisfy all your requirements.

    Just FYI : There is a doc which is exactly the problem you are trying to solve. http://docs.mongodb.org/manual/tutorial/perform-two-phase-commits/ But I won't recommend you to use this because a single query ( transferring money) has been turned into sequence of queries.

    Hope it helped