mongodb 内嵌数组 批量修改问题
曾经蜡笔没有小新
曾经蜡笔没有小新 2017-05-02 09:19:52
0
4
954

对于一个文档结构为:

{ "_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中文社区

曾经蜡笔没有小新
曾经蜡笔没有小新

reply all (4)
習慣沉默

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;
var updateObj = {};
for(var i =0;iupdateObj["taskList."+ i+".stat"] = "ST02";
}
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)

        changeState = function(doc){ taskList = doc.taskList; for(var i in taskList){ taskList[i].state = 'ST02'; } db.test.save(doc) } db.test.find({"_id" : ObjectId("57133995fb5f8930d0e9b81a")}).forEach(changeState)
          Latest Downloads
          More>
          Web Effects
          Website Source Code
          Website Materials
          Front End Template
          About us Disclaimer Sitemap
          php.cn:Public welfare online PHP training,Help PHP learners grow quickly!