【问题标题】:update multiple elements in array mongodb [duplicate]更新数组mongodb中的多个元素[重复]
【发布时间】:2018-07-11 07:44:45
【问题描述】:

当日期大于特定值时,我想将chargeList isDelete 属性更新为true。我的架构如下。

{
   "chargeList": [
     { 
         "date": ISODate("2013-06-26T18:57:30.012Z"),
         "price": "123",
         "isDelete": false

     },
     { 
         "date": ISODate("2013-06-27T18:57:30.012Z"),
         "price": "75",
         "isDelete": false

     }
   ]
 }

架构如下。

var ChargeListSchema= new Schema({
    date:  { type: Date , default: Date.now  },
    price: { type: String, required: false },
    isDelete: { type: Boolean, default: false }
});

var ScheduleChargeSchema = new Schema({

  chargeList:[ChargeListSchema]


  });

我尝试了以下代码,但它只更新了chargeList数组中匹配的第一个元素。

 Model.update(
  {
    "_id": 1,
    "chargeList": {
      "$elemMatch": {
        "date": {
           $gt:  ISODate("2013-06-26T18:57:30.012Z")
        }
      }
    }
  },
  {
    "$set": { "chargeList.$.isDelete": true }
  }
)

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-schema


    【解决方案1】:

    您需要使用$[] all positional operator 来更新数组中的多个元素

    Model.update(
      { "_id": 1, "chargeList.date": { "$gt":  ISODate("2013-06-26T18:57:30.012Z") }},
      { "$set": { "chargeList.$[].isDelete": true } }
    )
    

    【讨论】:

    猜你喜欢
    • 2018-12-14
    • 1970-01-01
    • 1970-01-01
    • 2016-11-18
    • 2016-01-16
    • 2018-02-19
    • 1970-01-01
    • 2013-09-07
    • 2020-04-18
    相关资源
    最近更新 更多