【问题标题】:$add only supports numeric or date types, not array Error when Incrementing in Mongoose$add 仅支持数字或日期类型,不支持数组在 Mongoose 中递增时出错
【发布时间】:2020-08-20 05:06:15
【问题描述】:

我有一个如下所示的文档:

{ 
  "_id": ObjectId("1111"), 
  "products":[
   {
    _id:'abc',
    quantity:3},
   {
    _id:'xyz',
    quantity:5
   }
 ]
}

我需要将子文档 products.quantity 增加一定数量。

这是我迄今为止尝试过的

Counter.findOneAndUpdate(
 { "_id": ObjectId("1111"), "products._id": 'abc' },

 [{
  $addFields: {
   'products.quantity': { $add: [ "$products.quantity", 7 ] }
  }
 }])

当我运行它时,我希望数量为 10,但我收到一个错误,提示 $add 仅支持数字或日期类型,而不支持数组

现在我该如何实现呢?

【问题讨论】:

  • 是否要更新 products 数组中所有元素的数量?
  • @whoami 不,它只是数组中与过滤器匹配的一个元素,即 "products._id": 'abc' 如我的问题所示

标签: mongodb express mongoose aggregate


【解决方案1】:

您可以使用array filters 按所需位置进行过滤,并使用$inc 来增加值,如下所示:

Counter.findOneAndUpdate({
  _id: "1111",
  "products._id": "abc"
},
{
  $inc: {
    "products.$[element].quantity": 7
  }
},
{
  arrayFilters: [
    {
      "element._id": "abc"
    }
  ]
})

例如here

顺便说一句,你为什么得到$add only supports numeric or date types, not array 的问题是因为"$products.quantity" 都是数组中的值。在您的示例中,值为[{quantity:3},{quantity:5}]。然后你必须过滤你想要得到数字的确切值,而不是数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-12
    • 1970-01-01
    • 2017-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-15
    • 2021-09-26
    相关资源
    最近更新 更多