gpt4 book ai didi

MongoDB - 更新字段的数据类型

转载 作者:行者123 更新时间:2023-12-05 09:09:19 28 4
gpt4 key购买 nike

数据插入如下。

{“key1”:20.05,“key2”:21.24

本应存储为 Double,但值存储为 String,返回文档时,值为,

{"key1": "20.05", "key2": "21.24"}

有没有办法在不扫描每个文档的情况下将数据类型更新为 double?

最佳答案

注意

默认情况下,所有 numbers 都存储为 MongoDB 中的 double 除非通常过度转换。

引用: https://stackoverflow.com/a/31267615/10861398


MongoDB 4.2以上版本

您可以使用聚合更新字段的类型数据。以下是将 $key2 字段中的数据类型更改为 double 的聚合查询示例。

db.collection.aggregate([
{
$set: {
key2: { $toDouble: '$key2' },
},
},
])

if the data to be converted to double cannot be altered (ex: "4Bn"), an error will occur. To prevent this, you can use an additional operator called $convert.

引用: $toDouble


MongoDB 3.2以上版本

MongoDB 在此版本中尚不支持聚合运算符$set。因此,您必须使用 findforEachupdateOne 手动执行此操作。

使用 mongo shell 的示例:

db.collection.find({}).forEach(function (doc) {
db.collection.updateOne(
{
_id: doc._id,
},
{
$set: {
key2: NumberInt(doc.key2),
},
}
)
})

引用: NumberInt

关于MongoDB - 更新字段的数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62543377/

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