dongqian0763 2012-07-10 16:30
浏览 240
已采纳

带有mgo的Go(golang)中的MongoDB:如何更新记录,查找更新是否成功并通过单个原子操作获取数据?

I am using mgo driver for MongoDB under Go.

My application asks for a task (with just a record select in Mongo from a collection called "jobs") and then registers itself as an asignee to complete that task (an update to that same "job" record, setting itself as assignee).

The program will be running on several machines, all talking to the same Mongo. When my program lists the available tasks and then picks one, other instances might have already obtained that assignment, and the current assignment would have failed.

How can I get sure that the record I read and then update does or does not have a certain value (in this case, an assignee) at the time of being updated?

I am trying to get one assignment, no matter wich one, so I think I should first select a pending task and try to assign it, keeping it just in the case the updating was successful.

So, my query should be something like:

"From all records on collection 'jobs', update just one that has asignee=null, setting my ID as the assignee. Then, give me that record so I could run the job."

How could I express that with mgo driver for Go?

  • 写回答

3条回答 默认 最新

  • douan2478 2012-09-10 15:35
    关注

    I hope you saw the comments on the answer you selected, but that approach is incorrect. Doing a select and then update will result in a round trip and two machines and be fetching for the same job before one of them can update the assignee. You need to use the findAndModify method instead: http://www.mongodb.org/display/DOCS/findAndModify+Command

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?