Skip to content


Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Addon for Mongoid to allow optimistic locking (CAS)
branch: master

Fetching latest commit…

Cannot retrieve the latest commit at this time

Failed to load latest commit information.
lib 0.0.4 version with validation fix
spec optimistic locking on a document with validation
.rspec Refactoring with a number of improvements:
.travis.yml remove 1.8.7 as a requirement for mongoid 3 on travis
Gemfile add mongoid 3.0.0rc as a gem requirement and fix a spec
LICENSE Add MIT license (Fixes #2) publish new 0.0.3 version compatible with Mongoid3 after branch merge
Rakefile Refactoring with a number of improvements:
mongoid_optimistic_locking.gemspec add mongoid 3.0.0rc as a gem requirement and fix a spec


This gem helps to abstract the "Update if Current" method which may be used as a replacement for transactions in Mongo.

The gem is an addon over Mongoid ODM and is based on ActiveRecord's Optimistic Locking.


Works with Mongoid 3.

For Mongoid 2 use version 0.0.2

Rails 3 Installation

Add the gem to your Gemfile:

gem 'mongoid_optimistic_locking'


To use it, all you have to do is add include Mongoid::OptimisticLocking:

class Post
  include Mongoid::Document
  include Mongoid::OptimisticLocking
  field :text

This will add a _lock_version field in the document which will be incremented every time a save is called. Be sure to rescue Mongoid::Errors::StaleDocument to handle applicative logic in case the object was changed.

For example:

class PostController < ApplicationController
  ## Adds an "UPDATE: ...some text..." to an existing document
  def add_update
      post = Post.find(params[:id])
      post.text += "---UPDATE---  " + params[:more_text]
    rescue Mongoid::Errors::StaleDocument

That's it!

Embedded Document Caveats

While Mongoid::OptimisticLocking can be used to some degree within embedded documents, there are certain limitations due to Mongoid's document embedding callback structure. Consider the following example:

class Post
  include Mongoid::Document
  field :text
  embeds_many :comments

class Comment
  include Mongoid::Document
  include Mongoid::OptimisticLocking
  embedded_in :post
  field :text

post =
comment = => 'hello') # will use optimistic locking checks # will not use optimistic locking checks

Open sourced by



Mongo Developer FAQ - How do I do transactions/locking?

Mongo Atomic Operations - "Update if Current"

Presentation from "Startup Day" on Mongoid Optimistic Locking

Something went wrong with that request. Please try again.