对于一个文档结构为:
{ "_id" : ObjectId("57133995fb5f8930d0e9b81a"), "taskList" : [{ "taskId" : NumberLong(1), "state" : "ST00", "createTime" : ISODate("2016-04-17T07:21:58.424Z") },{ "taskId" : NumberLong(2), "state" : "ST00", "createTime" : ISODate("2016-04-17T07:21:58.424Z") },{ "taskId" : NumberLong(3), "state" : "ST00", "createTime" : ISODate("2016-04-17T07:21:58.424Z") }] }
taskList 长度不确定
如何批量对数组内容进行修改呢?
例如批量修改 "_id" : ObjectId("57133995fb5f8930d0e9b81a") 的 taskList 内嵌元素 的 state 字段 为 'ST02'
@Mongoing中文社区
MongoDB’s update statement can only update the first matching element in the array at a time. A few ideas:
1) Re-model, put the tasklist into another table, and then use reference to reference it. If you have a lot of needs
2) First do a query to get the length of taskList, and then spell the update statement based on this length:
var length = db.test.aggregate([{$project:{lenOfArray: {$size:"$taskList"}}}]).next().lenOfArray;updateObj["taskList."+ i+".stat"] = "ST02";
var updateObj = {};
for(var i =0;i
}
db.test.update({ }, {$set: updateObj } );
How to put an elephant in the refrigerator? Open the door, put it in, close the door
It’s the same. Get this data, traverse this array, modify it yourself, and save this data~
Generally speaking, it’s like this
Mongodb currently does not support batch modification of embedded data. Currently, it only updates one by one, but you can write a JS method to encapsulate it
Same as above, use js method to modify each doc and save it. The code example is as follows. The subject needs to test it by himself (execute in mongo shell)