search

Home  >  Q&A  >  body text

mongodb 修改字段类型, 现在集合中有一个字段是string,要修改为date类型, 怎么弄 ?

mongodb 修改字段类型, 现在集合中有一个字段是string,要修改为date类型, 怎么弄 ?

阿神阿神2834 days ago1077

reply all(3)I'll reply

  • 漂亮男人

    漂亮男人2017-05-02 09:21:22

    MongoDB is "schemaless", and there is no concept of metadata for fields, so there is no way to directly modify field types, because each document's fields have their own types. Based on this situation, you can only traverse all documents and modify the field types one by one. For example, the original document is:

    {_id: ObjectId(...), date: "Fri May 20 2016 17:04:27 GMT+0800 (CST)"}
    

    Then you need to traverse this collection and modify the field types one by one

    db.coll.forEach(function(doc) {
        db.coll.update({_id: doc._id}, {$set: {date: new Date(doc.date)}});
    });

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-02 09:21:22

        db.demo.find({g:{$type:2}}).forEach(function(x){
            
            x.g=new Date();
            db.demo.save(x)
            
            }
    )

    $type: is the type. 2 is string type.

    reply
    0
  • 黄舟

    黄舟2017-05-02 09:21:22

    Refer to this https://zhuanlan.zhihu.com/p/... to solve UTCDatetime

    reply
    0
  • Cancelreply