Working with data in MongoDB & The AbA problem

pp70 of the excellent “The Definitive Guide to MongoDB”
MongoDB manual also here

Removing each occurrence of a specified value
Use the $PULL operator to remove each occurrence of a specified value from an array
> ( {“ISBN” : “123456”}, {$pull: {Author : “Hayes, Stuart} } )

Removing Multiple elements from an array
Use the $PULLALL operator
> ( {“ISBN”: “123456”}, {$pullAll : {Author:  [“Griffin, Louis”, “Griffin, Peter”, “Griffin, Mike”] } } )

In this example, the authors are removed from the book with the particular ISBN. If the datatype isn’t an array, you’ll get an error message.

Summary of update operators:

  • $set
  • $unset
  • $inc: increments a particular value by a certain amount
  • $push: Appends a value to an array
  • $pushAll: Appends several values to an array
  • $pull – as above
  • $pullAll – as above

Update ifCurrent

> {tracklist.title” : “Been A Son”}, {$inc:{“Tracklist.$.Track” : 1} } )
This command update the track number (Tracklist.Track) for the particular song title by 1.

To check if it has worked use
> db.$cmd.findOne({getlasterror:1})
It it has worked, you should get back
{ “err: null, “updatedExisting” : true, “n” : 1, “ok” : 1 }

However, be mindful of simultaneous updates, known as the ABA problem, whereby another user (or application) could update the same record using the same method while MongoDB was making the original modification…In that case, the changes, would be overwritten and Track would wrongly be updated to +2, rather than +1.

To avoid this conflict, there are 4 possible methods

  1. Use the entire object in the update’s query expression, instead of just a partial identifier
  2. Use the $SET to set the field of interest, *if other fields have changed they won’t be affected by this*
  3. Put a version variable in the object and increment it with each update (my personal favourite, facilitating an audit log)
  4. When possible, use a $ operator instead of an update-if-current sequence of operations

Renaming a collection


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s