V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
dupreesun
V2EX  ›  程序员

新手,请教一个 mongodb 并发更新一个 document 的问题

  •  
  •   dupreesun · 2018-10-13 13:03:01 +08:00 · 2350 次点击
    这是一个创建于 2014 天前的主题,其中的信息可能已经有所发展或是发生改变。

    数据库中有这样一个 document:

    {
       _id: 1,
       name: "sue",
       badges: [ "blue", "black" ],
       points: [
          { points: 85, bonus: 20 },
          { points: 85, bonus: 10 }
       ]
     }
    

    两个用户 A/B,同时向 points 插入一个新数据, 譬如 A 插入 {points: 90, bonus: 20}, B 用户插入{ points: 95, bonus: 10 } 如何才能保障一致性?

    findAndModify 能搞定吗?还是一点要加锁?

    3 条回复    2018-10-13 14:25:28 +08:00
    lianyue
        1
    lianyue  
       2018-10-13 13:08:06 +08:00   ❤️ 1
    dupreesun
        2
    dupreesun  
    OP
       2018-10-13 13:17:20 +08:00
    非常感谢!
    menyakun
        3
    menyakun  
       2018-10-13 14:25:28 +08:00
    https://docs.mongodb.com/manual/faq/concurrency/index.html#what-locks-are-taken-by-some-common-client-operations
    按文挡的解释,findOneAndModify 应该也是可以的,这个操作 mongodb 会自动加 Document 级别的锁
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3846 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 05:05 · PVG 13:05 · LAX 22:05 · JFK 01:05
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.