mongodb - 如何将 mongodb 字段数据类型从 NumberLong 更改为 Double?

标签 mongodb double type-conversion

如何将 mongodb 字段数据类型从 NumberLong 更改为 Double?

我试过没有成功:

db.getCollection('mycoll').find({'_id':10150097174480591}).forEach( function (x) { 
    x._id = new Double(x._id);
    db.getCollection('mycoll').save(x);
});

最佳答案

对象的“类型”需要重铸。批量更好,并使用 $type 过滤掉:

var bulk = db.users2.initializeOrderedBulkOp(),
    count = 0;

db.mycoll.find({ "_id": { "$type": 18 } }).forEach(function(doc) {
    doc._id = parseInt(doc._id.valueOf());
    bulk.insert(doc);
    count++;       

    if ( count % 1000 == 0 ) {
        bulk.execute();
        bulk = db.users2.initializeOrderedBulkOp();
    }
});

if ( count % 1000 != 0 )
    bulk.execute();

请注意,因为这是 _id,所以您需要另一个集合。如果您尝试对同一集合中的其他字段进行操作,则需要删除并“重置”文档中的字段才能使更改生效:

var bulk = db.mycoll.initializeOrderedBulkOp(),
    count = 0;

db.mycoll.find({ "a": { "$type": 18 } }).forEach(function(doc) {
    doc.a = parseInt(doc.a.valueOf());
    bulk.find({ "_id": doc._id }).updateOne({
        "$unset": { "a": "" }
    });
    bulk.find({ "_id": doc._id }).updateOne({
        "$set": { "a": doc.a }
    });

    count++;       

    if ( count % 500 == 0 ) {
        bulk.execute();
        bulk = db.mycoll.initializeOrderedBulkOp();
    }
});

if ( count % 500 != 0 )
    bulk.execute();

关于mongodb - 如何将 mongodb 字段数据类型从 NumberLong 更改为 Double?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31938393/

相关文章:

mongodb - 如果存在如何更新,否则插入新文档?

node.js - 如何用 mongoose 区分填充的集合

java - Java 整数类型原始类型是否在转换类型的 MAX_INT 处转换为 "capped"?

swift - swift 中的转换运算符

c# - -1U和-1UL的怪异行为

ruby-on-rails - 无架构数据库 : Indexing dynamically-typed things by their properties?

c# - 预测两个 double 之和

java - Java Integer 和 Double 对象是否有不必要的开销?

c++ - 如何将 int 转换为 QString?

javascript - 从返回的 MongoDB 对象更新 Angular.js $scoped