Cannot apply the positional operator without a corresponding query field containing an array.

  • Cannot apply the positional operator without a corresponding query field containing an array.已关闭评论
  • A+
所属分类:mongodb

在用错mongodb $ 操作符时,会报下面的错误信息:

Cannot apply the positional operator without a corresponding query field containing an array.

测试数据:

语句:

db.ttlsa.update({userid:1}, {$set:{"dept.$.deptName":"ttlsa.com"}}, 0, 1)  就会报上没的错误的。

db.ttlsa.update({"dept.deptID":"1"}, {$set:{"dept.$.deptName":"ttlsa.com"}}, 0, 1) 执行正确。

这是为什么呢? 其实就是“$”的使用方法。来看看$ 是啥意思。

update的前两个参数{查询条件}和{更新操作}中,如果在{查询条件}中查询的内容是数组里的内容,{更新操作}中就可以使用"$"来引用前查询中匹配到的元素。

上面的例子中,第一个是查询userid:1的文档,查询条件不包含数组。第二个查询一个数组。

其实就是对更新数组操作符的理解。大家可以看看官方这章内容Array Update Operators

weinxin
微信公众号
扫一扫关注运维生存时间公众号,获取最新技术文章~