它不更新也不显示任何错误

It doesn't update and doesn't show any errors

我的结构如下所示:

{
  _id: 10,
  line_items: [
      { 
        _id: 2,
        name: "name",
        quantity: 2,
      },
      { 
        _id: 3,
        name: "name2",
        quantity: 1,
      }
    ],
    sub_total: 100
  }

我正在尝试进行更新:

query={_id: 10, 'line_items.$._id': 2}
db.orders.update(query, {$push: {$inc: {'line_items.$.quantity': 1}}, $inc: {sub_total: 32}})

但它什么也没做,也没有显示任何错误。怎么了?

您的尝试存在几个问题:

  1. 您需要在为您的案例查询数组字段时使用 $elemMatch
  2. 你的 $push 不正确。你可以简单地使用 $inc

这是一个可行的解决方案:

db.collection.update({
  _id: 10,
  line_items: {
    $elemMatch: {
      _id: 2
    }
  }
},
{
  $inc: {
    "line_items.$.quantity": 1,
    sub_total: 32
  }
})

这里是Mongo playground供您参考。