mongodb 更改已经创建的collection中的document的字段的类型,和更改字段的值

如果已经创建好collection(相当于table)在mongodb,
需要更改这个已经创建的collection中的document的字段的类型,和更改字段的值

比如如下,更改字段dateString的数据类型从ISODate到String

  1. 创建collection并插入data
    db.DateTest.insertMany([{“id”:”test”,”dateString”:new Date(“2017-01-02T12:34:56Z”),”type”:”type”,”code”:”1234”}, {“id”:”test2”,”dateString”:new Date(“2017-01-03T12:34:56Z”),”type”:”type2”,”code”:”1234”}])

  2. 更改字段dateString的数据类型为String
    db.DateTest.find({“dateString”:{$type : 9}}).forEach(
    function(x){
    x.dateString = x.dateString.toISOString();
    db.DateTest.save(x);
    }
    );

  3. 截取dateString的长度
    db.DateTest.find({“dateString”:{$type : 2}}).forEach(
    function(x){
    x.dateString = x.dateString.substr(0, 10);
    db.DateTest.save(x);
    }
    );

或者合并2,3步骤:
db.DateTest.find({“dateString”:{$type : 9}}).forEach(
function(x){
x.dateString = x.dateString.toISOString().substr(0, 10);
db.DateTest.save(x);
}
);

学习Mongo资源:
mongoDB 学习笔记纯干货:
http://www.lovebxm.com/2017/07/13/mongodb_primer/#%E6%9B%B4%E6%96%B0

Using JavaScript in the MongoDB Shell:
http://ptgmedia.pearsoncmg.com/imprint_downloads/informit/learninglabs/9780133902990/ch03.html

MongoDB removing white spaces(leading and trailing) from string value:
https://stackoverflow.com/questions/23903785/mongodb-removing-white-spacesleading-and-trailing-from-string-value

相关文章
相关标签/搜索