mongodb/mongo — pull request #298 by cuppett (2012-09-04 00:48:33+00:00)
Title: Add $setIfAbsent modifier

Found myself wanting to set an initial value on *insert only* and/or later if a particular value was not present. I had some trouble identifying how to do it atomically without a couple steps, trips to the server or weird edge cases to handle in-between.

I've implemented a $setIfAbsent modifier for project consideration that works well on update as well findAndModify operations. See simple example below for atomic creation/modified timestamps:

> db.steve.update({"_id" : 17}, { $set : { "modified" : new Date()}, $inc : { "counter" : 1 }, $setIfAbsent : {"created" : new Date()}}, true);

{ "_id" : 17, "counter" : 1, "created" : ISODate("2012-09-04T00:39:54.103Z"), "modified" : ISODate("2012-09-04T00:39:54.103Z") }

> db.steve.update({"_id" : 17}, { $set : { "modified" : new Date()}, $inc : { "counter" : 1 }, $setIfAbsent : {"created" : new Date()}}, true);

{ "_id" : 17, "counter" : 2, "created" : ISODate("2012-09-04T00:39:54.103Z"), "modified" : ISODate("2012-09-04T00:40:41.569Z") }