【问题标题】:mongodb $ causing error The positional operator did not find the match needed from the querymongodb $ 导致错误位置运算符没有从查询中找到所需的匹配项
【发布时间】:2020-11-09 20:21:45
【问题描述】:

我一直在尝试更新我的 mongoDB 中的数据。 我想用新的 productName 字段更新所有产品。

我的数据看起来像:

{
    "id": "12345",
    "products": [{
        "id": 0
        "productCode": "test",
        "status": "PENDING",
    },
    {
        "id": 1
        "productCode": "test",
        "status": "COMPLETE",
    }],
}

当我尝试以下操作时。我收到此错误位置运算符未从查询中找到所需的匹配项。

db.customers.updateMany(
  { id: "12345" },
  { $set: {
    "products.$.productName": "Name here" } 
  }
)

如果我做 account.0.productName 那就没问题并且可以更新。我不确定为什么 $ 对我不起作用

db.customers.updateMany(
  { id: "12345" },
  { $set: {
    "products.0.productName": "Name here" } 
  }
)

【问题讨论】:

  • productName 是错字吗?应该是productCode?
  • 不,我想为我的所有产品添加一个新的 productName,并且我希望 productCode 保持不变

标签: mongodb


【解决方案1】:

位置运算符不起作用,因为您没有将数组放入find(第一个对象)

如果您尝试this 查询,它将按预期工作,因为您有products.id 的位置查找。

否则,如果你没有更新到数组的位置,你就不能这样使用$操作符。你需要这个查询:

db.collection.update({
  "id": "12345",
  
},
{
  "$set": {
    "products.$[].newField": "test2"
  }
},
{
  "multi": true
})

Mongo 游乐场示例here

使用$[],您可以引用数组并将值添加到每个对象中。

$[] 文档here

上面写着:

所有位置运算符$[]表示更新运算符应该修改指定数组字段中的所有元素。

这正是我们想要的 :)

【讨论】:

  • 非常感谢 J.F !!!这个答案完美!
猜你喜欢
  • 2016-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多