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

一笑奈何 提交于 2019-12-11 10:39:26

问题


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?


回答1:


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)



回答2:


As said in the documentation $addToSet operator adds a value into an array only if the value is not in the array already: http://docs.mongodb.org/manual/reference/operator/update/addToSet/#up._S_addToSet

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];
       db.collection.save(doc); 
})

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)


来源:https://stackoverflow.com/questions/22309869/mongodb-cannot-upsert-if-query-object-and-update-object-contain-a-same-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!