Atomic operation examples

A key goal of MongoDB is to handle a good breadth of use cases, and to handle in a way that is easy for the developer. We found that a good number of use cases require atomic operations / strong consistency; thus that is a feature of the product. Below are some examples (in mongo shell syntax).


// register a new user (atomically)
db.users.insert( { _id : 'joe123' } )
if( db.getLastErrorObj().err ) 
  print("name is use try another")
else 
  print("you are registered")


// decrement y if y > 0 (atomically)
db.stats.update(
  { _id : ‘myid’, y : { $gt : 0 } },
  { $inc : { y : -1 } } 
)


// assure everyone’s email address is unique
db.users.ensureIndex( {email:1} , {unique:true} )


// if joe hasn’t already voted, let him vote (without races)
db.posts.update( 
  { _id : ‘some_post_of_interest’ , voters : { $ne : ‘joe’ } },
  { votes : { $inc : 1 } }
)

Follow @mongodb

MongoDB Pittsburgh - May 15
MongoNYC - May 23
MongoDB Paris - Jun 14
MongoDB UK - Jun 20
MongoDC - June 26


Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.

PLEASE POST QUESTIONS IN THE USER GROUPS FORUM. Post non-question comments and helpful hints here.

blog comments powered by Disqus