gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 10:42:56 27 4
gpt4 key购买 nike

如何将 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com