Preface: I'm a few days new to mongo and have been creating a MVC
project to interact with mongo. I have been using the
https://github.com/mongodb/mongo-csharp-driver and have been writing
my own layer on top of it.
So I'm trying to do an atomic operation where I add a value to an
array and increment a counter for the array. This is a common scenario
and I do not have trouble doing this. However, I am making certain
that I do not insert a duplicate value. Mongo has built in support for
this feature as I've been able to use 'addtoset' to ensure no
duplicates are placed, however the increment still happens. Which puts
the counter out of synch with the actual amount in the array.
I was hoping to do this in an atomic operation: so I tried to create
the following query:
update( {_id:'123', array: {"$ne": "456"}},
{"$addtoset": { array: "456" } , $inc: { counter : 1 }} )
When 456 does not exist in the array, then the statement works fine.
However, when 456 does exist in the array, then I get the following:
MongoDB.Driver.MongoCommandException : Command 'findAndModify' failed:
No matching object found (response: { "errmsg" : "No matching object
found", "ok" : 0 })
Am I taking the right approach here? Is there a feature, override, or
command I am missing? Is there another way to 'chain' operators on
success?