search

Home  >  Q&A  >  body text

mongodb 内嵌数组 批量修改问题

对于一个文档结构为:

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

曾经蜡笔没有小新曾经蜡笔没有小新2822 days ago1037

reply all(4)I'll reply

  • 習慣沉默

    習慣沉默2017-05-02 09:21:52

    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;i<length;i++){
    updateObj["taskList."+ i+".stat"] = "ST02";
    }
    db.test.update({ }, {$set: updateObj } );

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-05-02 09:21:52

    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

    reply
    0
  • 给我你的怀抱

    给我你的怀抱2017-05-02 09:21:52

    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

    reply
    0
  • 習慣沉默

    習慣沉默2017-05-02 09:21:52

    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)
     
     
     

    reply
    0
  • Cancelreply