MongoDB: cannot upsert if query object and update object contain a same property , 'Cannot apply $addToSet modifier to non-array'

I want to execute a complex upsert, made by the following elements:

  • query on a field f by regex
  • update of the same field f (that is specified in the query object too)

Like this:

db.coll.update({ prop: /valueprop/i } , { $addToSet:{ prop:'a value' }  } , true, false)

My expectation would be that if the document does not exist in the collection it is inserted with prop field equals to 'a value'; in other words it should insert a document with value of prop field that is the one specified in the update object.

Instead it throws Cannot apply $addToSet modifier to non-array , like if it tries to update the field prop with the value specified in the query object (that is a RegExp object) instead of using the value specified in the update object.

Isn't it a bug?


The workaround is using $all keyword in the query object in the following way

db.cancellami.update({prop:{$in:[/regex_value/i]}},{ $addToSet:{prop:'a value'}} ,true,false)

As said in the documentation $addToSet operator adds a value into an array only if the value is not in the array already:

Your prop value is an string so you couldn't use $addToSet. Instead of this you could do the next:

db.collection.update({prop:/valueprop/i},{$set:{prop:['a value']}}, true, false)

Update: In case you need to ensure that are not going to exist duplicates in your arrays, you must first update all your documents to convert them into arrays with something like this:

db.collection.find({ $where : "isString(this.prop)"}).forEach(function (doc) {
       doc.prop = [doc.prop];; 

And then you will be able to execute the next to ensure you'll always update only array fields and no errors will be found:

db.collection.update({ $where : "Array.isArray(this.prop)"},{$addToSet:{prop:'a value'}}, true, false)

Need Your Help

Rails logger level changes to ERROR abruptly

ruby-on-rails ruby ruby-on-rails-3 logging thread-safety

I am experiencing very strange behavior with my Rails logs. Wherein the logger level automatically/abruptly changes to ERROR(:error. logger level code 3) instead of whatever it was supposed to be (...

Accepting Cassandra's Set datatype in golang

go cassandra

I have a column in cassandra which is of type set.