我有一个集合,其中包含一些应该是整数的字段。由于软件错误,其中一些值是字符串。我需要转换它们。这是一个示例文档:
var coll = db.getCollection('info');
coll.find({ id: "985517" });
结果:
{
"_id" : "41cbb4e48284c0612a1c4b3ee5e3e2720c01197a",
"id" : "985517",
"title" : "009_1a.jpg",
"ext" : ".jpg",
"content_type" : "image/jpeg; charset=utf-8",
"sha1" : "41cbb4e48284c0612a1c4b3ee5e3e2720c01197a",
"has_thumb" : true,
"size" : 2917,
"width_px" : "70",
"height_px" : "69"
}
我尝试将 width_px 和 height_px 值转换为整数。我的第一次天真尝试:
var coll = db.getCollection('info');
var bulk = coll.initializeOrderedBulkOp();
var counter = 0;
coll.find({ width_px: { $type: "string" }, id: "985516" }).limit(100).forEach(function(data) {
var updoc = {
"$set": {}
};
updoc["$set"]["width_px"] = parseInt(data.width_px);
// queue the update
bulk.find({
"_id": data._id
}).update(updoc);
counter++;
// Drain and re-initialize every 1000 update statements
if (counter % 1000 == 0) {
bulk.execute();
bulk = coll.initializeOrderedBulkOp();
}
})
// Add the rest in the queue
if (counter % 1000 != 0) bulk.execute();
结果令人失望:
{
"_id" : "41cbb4e48284c0612a1c4b3ee5e3e2720c01197a",
"id" : "985517",
"title" : "009_1a.jpg",
"ext" : ".jpg",
"content_type" : "image/jpeg; charset=utf-8",
"sha1" : "41cbb4e48284c0612a1c4b3ee5e3e2720c01197a",
"has_thumb" : true,
"size" : 2917,
"width_px" : 70.0,
"height_px" : "69"
}
所以它被更新为加倍,而不是 int32。我知道在 JavaScript 中,没有单独的双精度和整数类型,只有“数字”。但我需要更新 100 000 个文档,并且我想高效地完成此操作。
但是怎么做?
解决方案是使用 NumberInt 而不是 parseInt。
它将构造一个特定于 mongodb 的新 NumberInt 对象,并将其序列化为 int32。
根据此处的MongoDB 文档
Documents tab
,MongoDB Compass
您可以查看、插入、克隆、修改和删除文档。首先,您必须连接您的 mongod,
MongoDB Compass
然后您将能够更改 MongoDB 中各自字段的所需数据类型。更改字段类型
您可以使用字段右侧的数据类型选择器更改字段的数据类型。
供您进一步参考
将 str 更改为 int