mongodb - mongo db需要遍历数组中的每个元素并转换底层类型
问题描述
我需要遍历数组中的每个元素并将那里的类型转换为字符串中的数字。我无法将其转换为 Mongo shell。谁能指导我。
{
"_id" : ObjectId("5e9aabb1f9420ce8c8efe282"),
"description" : "base 1"
"title" : "You received a new 3",
"uniq" : [
"12345"
],
"created" : "2020-03-16T11:23:45.172Z"
}
{
"_id" : ObjectId("5e9aabb1f9420ce8c8efe283"),
"description" : "base 1"
"title" : "You received a new 2",
"uniq" : [
"34321"
],
"created" : "2020-03-14T11:23:45.172Z"
}
{
"_id" : ObjectId("5e9aabb1f9420ce8c8efe284"),
"description" : "base 3"
"title" : "You received a new 1",
"uniq" : [
"34328"
],
"created" : "2020-03-15T11:23:45.172Z"
}
我尝试了以下方法。
db.getCollection('noti').find({}).forEach(function(myDoc) {
var val = myDoc._id
db.getCollection('noti').updateOne({
"_id": val},
{"$set": {
"uniq": [ new Number(myDoc.uniq) ]
}
})
})
需要将 uniq ["xxxx"] 转换为 uniq [Int] 并在 Mongo 数据库中更新
解决方案
如果您正在运行 MongoDB 4.2,则可以在更新中执行此操作:
db.collection.updateMany( {}, [
{$set: {uniq: {$convert:{
input: "$uniq",
to: "int",
onError: "valueToUseIfConversionFails"
}}}}
])
推荐阅读
- javascript - 在 Vuejs 中初始化的购物车
- javascript - 如何在 TypeScript 中为全局窗口界面定义“document.documentMode”?
- python - pyspark 流和实用程序导入问题
- r - 每次我尝试安装新版本的 R 时,都会安装旧版本。我应该怎么办?
- r - 使用 R Shiny 中的 bslib 包,情节主题无法正常工作
- spring-boot - Eureka 服务器主机名或 IP
- android - Firebase - 谷歌登录活动,收到这些错误
- r - R创建重复列(批量)
- wordpress - Woocommerce - 删除预定的电子邮件
- javascript - Javascript function continues a step longer than needed