update multiple elements in array mongodb [duplicate]

半城伤御伤魂 提交于 2019-12-08 07:59:41

问题


I want to update chargeList isDelete property to true when date is greater than a specific value. my schema as follows.

{
   "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

     }
   ]
 }

schema is as follows.

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]


  });

I have tried as following code but it only update the matching first element in chargeList array.

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

回答1:


You need to use $[] all positional operator to update multiple elements in an array

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


来源:https://stackoverflow.com/questions/51279886/update-multiple-elements-in-array-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!