MongoDB 使用 BSON (Binary JSON) 格式存储数据,其中包含多种数值类型:
将 Int32 转换为 Int64 的常见原因:
$convert
操作符(MongoDB 4.0+)db.collection.updateMany(
{ "fieldName": { $type: "int" } },
[
{
$set: {
"fieldName": {
$convert: {
input: "$fieldName",
to: "long",
onError: "Error converting field",
onNull: null
}
}
}
}
]
)
db.collection.updateMany(
{},
[
{
$set: {
"fieldName": { $toLong: "$fieldName" }
}
}
]
)
db.collection.find({ "fieldName": { $type: "int" } }).forEach(function(doc) {
db.collection.updateOne(
{ _id: doc._id },
{ $set: { "fieldName": NumberLong(doc.fieldName) } }
);
});
// 检查转换后的类型
db.collection.find(
{ "fieldName": { $exists: true } },
{ "fieldName": 1, "_id": 0 }
).limit(1)
// 或者使用$type操作符验证
db.collection.find({
"fieldName": { $type: "long" }
}).count()
问题1:转换后查询不返回预期结果
db.collection.find({fieldName: NumberLong(123)})
问题2:转换操作耗时过长
问题3:应用代码无法解析Int64
没有搜到相关的文章