更新数组mongodb

时间:2018-07-11 07:44:45

标签: node.js mongodb mongoose mongoose-schema

当日期大于特定值时,我想将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 }
  }
)

1 个答案:

答案 0 :(得分:1)

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

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