MongoDB:如果查询对象和更新对象包含相同的属性,则无法向上插入,“无法将$ addToSet修饰符应用于非数组" [英] MongoDB: cannot upsert if query object and update object contain a same property , 'Cannot apply $addToSet modifier to non-array'
问题描述
我要执行由以下元素组成的复杂的upsert:
I want to execute a complex upsert, made by the following elements:
-
通过正则表达式
- 在字段 f 上查询
- 同一字段 f 的更新(也在查询对象中指定)
- query on a field f by regex
- update of the same field f (that is specified in the query object too)
喜欢这个:
db.coll.update({ prop: /valueprop/i } , { $addToSet:{ prop:'a value' } } , true, false)
我的期望是,如果文档不存在于集合中,则将其插入的 prop 字段等于"a value";换句话说,它应该插入一个值为 prop 字段的文档,该字段是更新对象中指定的文档.
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.
相反,它抛出Cannot apply $addToSet modifier to non-array
,就像尝试使用查询对象(即RegExp对象)中指定的值而不是使用update对象中指定的值来更新字段prop一样.
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.
这不是错误吗?
推荐答案
解决方法是通过以下方式在查询对象中使用$all
关键字
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)
这篇关于MongoDB:如果查询对象和更新对象包含相同的属性,则无法向上插入,“无法将$ addToSet修饰符应用于非数组"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!