首页 > 解决方案 > 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

解决方案


如果您正在运行 MongoDB 4.2,则可以在更新中执行此操作:

db.collection.updateMany( {}, [
        {$set: {uniq: {$convert:{
                              input: "$uniq",
                              to: "int",
                              onError: "valueToUseIfConversionFails"
        }}}}
])

推荐阅读