I have multiple publish/subscribe servers that attempt to update a MongoDB database as events occur. Currently I am running into an issue where I need to atomically add entries to a given MongoDB document array, but am running into a race condition when it comes to who adds the entry into the document. I'm attempted to use $addToSet
to accomplish the add. However, since the array entry can get updated once the entry is within the array it makes it difficult for addToSet to work properly since it does a direct comparison to see if the entry is within the array or not. The end result as shown below is I get multiple servers adding in a new entry to the array.
Below is an example of a finished document that I would like:
{
"_id" : ObjectId("522f99a622927d6d65b81dbd"),
"array" : [
{
"type" : "out",
"uuid" : "4f501517-1d10-48c2-91b7-0ca1bda80bd5",
"member_id" : "3847",
"join" : ISODate("2013-09-10T17:13:58.881Z")
}
],
"created" : ISODate("2013-09-10T17:13:58.437Z"),
"name" : "entry"
}
Below is an example of what's happening due to the race condition:
{
"_id" : ObjectId("522f99a622927d6d65b81dbd"),
"array" : [
{
"type" : "out",
"uuid" : "4f501517-1d10-48c2-91b7-0ca1bda80bd5",
"member_id" : "3847",
"join" : ISODate("2013-09-10T17:13:58.881Z")
},
{
"type" : "out",
"uuid" : "4f501517-1d10-48c2-91b7-0ca1bda80bd5",
"member_id" : "3847",
"join" : ISODate("2013-09-10T17:13:58.881Z")
}
],
"created" : ISODate("2013-09-10T17:13:58.437Z"),
"name" : "entry"
}
Has anyone successfully been able to atomically add/modify array entries within a document without having to move the array data out of the collection entirely? I know that by moving it out of the collection it allows me to build a unique constraint against the entry, but I'd rather not have to do that.