mongodb 修改字段类型, 现在集合中有一个字段是string,要修改为date类型, 怎么弄 ?
漂亮男人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)}});
});
曾经蜡笔没有小新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.