【问题标题】:Convert UUID to String for insert in mongodb将 UUID 转换为字符串以在 mongodb 中插入
【发布时间】:2020-01-16 17:12:47
【问题描述】:

在尝试以下代码时:

db.getCollection('col').find({}).forEach(function(doc){
            var id = new UUID().toString(); // this doesn't work, neither does 'var id = new UUID();'
            db.getCollection('pubCol')
                .update({
                    "uuid" : id,
                    "deleted" : false
                    }
            , {upsert: true});
         });

我最终分别得到以下结果

"uuid" : "UUID(\"4554a991-2b7f-4464-b871-5f4e91332630\")"
"uuid" : UUID("4554a991-2b7f-4464-b871-5f4e91332630")

但我正在寻找

"uuid" : "4554a991-2b7f-4464-b871-5f4e91332630"

【问题讨论】:

    标签: string mongodb shell uuid robo3t


    【解决方案1】:

    UUID().hex() 返回您要查找的字符串,但不包含连字符。

    您可以手动拆分它,例如使用正则表达式:

    UUID().hex().match(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/).slice(1,6).join('-')
    

    【讨论】:

    • 这对我可以测试的结果有效。但是正则表达式部分使它变得复杂。
    • .toString().substring(...) 怎么样?
    • 它可以解决问题,但它不是 toString() 的预期用途。 UUID 有 3 种方法:base64、hex 和 toString。后者返回 JS 表示。你想要十六进制的。正则表达式是缺少连字符的解决方法。我宁愿提出一个功能请求,为 hex 方法添加一个可选的“分隔符”参数。
    猜你喜欢
    • 1970-01-01
    • 2011-12-11
    • 2018-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多