如何使用MongoDB转移资金? [英] How to move money with MongoDB?

查看:96
本文介绍了如何使用MongoDB转移资金?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Account has embedded
  Transactions
    amount (positive for received transactions, negative for outgoing transactions)

用户想汇款.我们需要计算帐户余额以检查是否有足够的钱.用伪代码:

User wants to send money. We need to compute account's balance to check if there is enough money. In pseudocode:

send_money(amount)
  balance = sum(account's all transactions) // Mongo Query 1
  if (amount <= balance)
    add a new transaction to account // Mongo Query 2

但是两个并发的mongo连接是否都可以通过查询1并继续进行查询2,这是不可能的吗?假设用户的余额为1,并且同时通过查询1的两个并发汇款请求(价值1)同时成功添加到交易中.实际上,用户最终的余额为-1.

But isn't it possible that two concurrent mongo connections both pass Query 1 and proceed to make Query 2? Say user's balance is 1 and two concurrent send money requests worth of 1 come at the same time passing Query 1 and are successfully added to transactions. In effect, the user ends up with a balance of -1.

如何预防?

推荐答案

当您的用例需要跨多个文档的事务时,MongoDB通常不适合它,因为当一个以上的实例使用MongoDB时,它不支持原子操作.文档受到影响.

When your use-case requires transactions which span multiple documents, MongoDB is usually a bad fit for it, because it doesn't support atomic operations when more than one document is affected.

可能的解决方法是 two-phase-commit 模型.

A possible workaround is the two-phase-commit model.

基本上,这意味着您首先要向每个文档添加描述,作为其附加字段.然后,您对每个文档执行原子操作,该操作将应用该操作并删除描述.这些步骤中的每一个都通过随后查询文档来确认,并且交易的每个步骤都由第三个文档记录在未决交易的其他集合中.这样,您就可以检查待处理的交易并将其回滚.

It basically means that you first add a description what you want to do to each document as an additional field to it. Then you perform an atomic operation on each document which applies that action and removes the description. Each of these steps is confirmed by querying the document afterwards and each step of the transaction is documented by a 3rd document in an additional collection of pending transactions. This allows you to check for pending transactions and roll them back.

此方法难以实现,并且具有相当大的开销.在执行此操作之前,您应该真正考虑是否确实有理由不使用具有本机事务支持的数据库系统.

This method is hard to implement and has considerable overhead. Before you implement this, you should really consider if there is really a good reason no to use a database system with native transaction support.

这篇关于如何使用MongoDB转移资金?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆