如何重新命名array中的document field?


  • V

    {
        "sender" : "AA",
        "receiver" : "BB",
        "type" : "chat",
        "time" : ISODate("2017-03-08T23:54:33.000+0000"),
        "receives" : [
            {
                "time" : ISODate("2017-03-08T23:54:33.000+0000"),
                "username" : "BB",
                "received" : NumberInt(0)
            }
        ]
    }

    要重新命名 receives 中 received 欄位

  • 註冊用戶

    例如: 將 received 更改為 new_received

    db.log.insert({
     "sender" : "AA",
     "receiver" : "BB",
     "type" : "chat",
     "time" : ISODate("2017-03-08T23:54:33.000+0000"),
     "receives" : [
         {
             "time" : ISODate("2017-03-08T23:54:33.000+0000"),
             "username" : "BB",
             "received" : NumberInt(0)
         }
     ]
    });

    db.log.find().forEach(function(d) {
     var ori_data = d.receives[0].received;
     db.log.update(d, {$set:{"receives.0.new_received":ori_data}, $unset: {"receives.0.received":1} });
    });


  • Lv 1

    @yea

    如果 receives 資料多筆. 這種寫法似乎沒效率

    不如整批代換完再代換


  • 註冊用戶

    @22265

    整批代換完再代換? 有範例嗎?


  • Lv 1

    @yea

    db.log.insert({
     "sender" : "AA", 
     "receiver" : "BB", 
     "type" : "chat", 
     "time" : ISODate("2017-03-08T23:54:33.000+0000"), 
     "receives" : [
         {
             "time" : ISODate("2017-03-08T23:54:33.000+0000"), 
             "username" : "BB", 
             "received" : NumberInt(0)
         },
         {
             "time" : ISODate("2017-04-08T23:54:33.000+0000"), 
             "username" : "BB", 
             "received" : NumberInt(2)
         }
     ]
    });
    db.log.find().forEach(function(d) {
      var d2 = [];
      d.receives.forEach(function(el){
        el.new_received = el.received;
        delete el.received;
        d2.push(el);
      })
      d.receives = d2;
      db.log.save(d);
    });

  • V

    @stlin

    目前採取的解決方式 : 

     db.coll1.find({  "receives.received" : {$exists : true} }).forEach( function(d) {
           var at = d.receives;
           at.forEach(function(att)
           {
              att.new_received = NumberInt(att.received);
              delete att["received"];
           });
           db.coll1.update({_id:d._id},{$set:{receives:at}});
      });



  • 註冊用戶

    看起來幾種方式都可以,說不定以後會用到,收藏~


登录后回复
 

与 萌阔论坛 的连接断开,我们正在尝试重连,请耐心等待