【问题标题】:how to convert 10 digit number field to string field in mongodb如何将10位数字字段转换为mongodb中的字符串字段
【发布时间】:2022-01-19 13:24:17
【问题描述】:

我想将移动字段更新为 mongodb 中的字符串。

{
"_id": "1373b7723",
"firstname": "name1",
"mobile":1000000099
},
{
"_id": "137be30723",
"firstname": "name2",
"mobile":1000000088
}

我需要这样的输出。

{
"_id": "1373b7723",
"firstname": "name1",
"mobile":"1000000099"
},
{
"_id": "137be30723",
"firstname": "name2",
"mobile":"1000000088"
}
db.users.updateMany(
    {}, //To match all documents
    [{ $set: {mobile: { $concat: [ "", "$mobile" ] } } }], 
    {
        new: true, 
        runValidators : true
    });

我尝试了上面的代码,但没有得到想要的输出。

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    我之前做过类似的事情,但不是转换为字符串,而是转换为日期。见this

    您也可以使用$toString,如here 所述。请参阅与您的用例类似的 this 示例

    如果它适合你,试试下面。

    db.users.find({}).forEach(function (doc) {
      db.users.updateOne(
        {
          _id: doc._id,
        },
        {
          $set: {
            mobile: String(doc.mobile)
          },
        }
      )
    })
    

    或修改后的代码版本

    db.users.updateMany(
        {}, //To match all documents
        [{ $set: {mobile: { $toString: {$toLong:"$mobile"}  } } }], 
        {
            new: true, 
            runValidators : true
        });
    

    【讨论】:

    • 从您的代码的修改版本中,我得到这个号码 987653009 的“9.87654e+09”。但我想要“987653009”。谢谢。
    • @saikrishna 我已经更新了解决方案,如果可行,请 - { $toString: {$toLong:"$mobile"} }
    • 这对我有用..{ $toString: {$toLong:"$mobile"} }。谢谢
    猜你喜欢
    • 2021-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-08
    • 1970-01-01
    相关资源
    最近更新 更多