Mongo DB upserts and _ids
Mongo gives some confusing errors if you upsert incorrectly. The trick is that you need to repeat the id in the update clause if and only if you are not using modifier operations. So you end up with either
1) foo.update({‘_id’: ‘X’}, {‘_id’: ‘X’, ‘bar’: ‘baz’}, true)
or
2) foo.update({‘_id’: ‘X’}, {‘$set’: { ‘bar’: ‘baz’} }, true)
Also, the syntax doesn’t support arrays as much as you’d like. You can’t say, “put this at index X in array foo, creating array foo if needed.” { ‘bar.x’: ‘donuts’ } does not work because bar will be created as dictionary, not an array, if it does not exist.
The best I could come up with is update({‘_id’: ‘X’, ‘bar’: { ‘$exists’: 0 } }, {‘_id’: ‘X’, ‘bar’: []}), waiting for that to complete, and then setting the value at index X .
Alternatively, you can call update({‘_id’: ‘X’, ‘bar’: { ‘$exists’: 0 } }, {‘_id’: ‘X’, ‘bar’: [null,null,null,null,’donuts’]}) and then call update({‘_id’: ‘X’, {‘bar’.X: ‘donuts’}) only if the first call did not produce updatedExisting.