You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mongo Shell脚本输出ID转换为JUUID格式的方法

将MongoDB Java LUUID(旧版)ID转换为JUUID格式输出

问题说明

MongoDB中存储的_id是Java Legacy UUID(subtype 03),当前查询脚本输出的_id为二进制结构,需要将其转换为JUUID("ACB8AEEA-D247-4C6B-BC20-B8E05C146F30")的格式输出,且不修改存储的UUID subtype,驱动已固定设置为UuidRepresentation.JAVA_LEGACY。

修改后的脚本

var myStringArray = ["string1", "string2"];

// 把Java Legacy UUID(subtype 03)转换为标准带破折号的UUID字符串
function javaLegacyUuidToStr(binaryUuid) {
    if (binaryUuid.subtype() !== 3) return binaryUuid;
    const bytes = binaryUuid.buffer;
    // 调整Java Legacy UUID的字节顺序:前三组字节反转,最后一组保持原顺序
    const adjustedBytes = Buffer.concat([
        bytes.slice(0,4).reverse(),
        bytes.slice(4,6).reverse(),
        bytes.slice(6,8).reverse(),
        bytes.slice(8,16)
    ]);
    // 转换为大写UUID格式字符串
    return adjustedBytes.toString('hex').replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/, '$1-$2-$3-$4-$5').toUpperCase();
}

for (var i = 0; i < myStringArray.length; i++) {
    let outputs = db.getCollection("MyCollection").aggregate([
        { '$match': { "field1": myStringArray[i] } },
        { $project: { _id: 1, "field1": 1 } }
    ]).map(function (el) {
        // 替换_id为JUUID格式
        el._id = `JUUID("${javaLegacyUuidToStr(el._id)}")`;
        return JSON.stringify(el);
    });

    console.log(outputs);
}

关键说明

  • javaLegacyUuidToStr函数:针对subtype 03的Java Legacy UUID调整字节顺序(Java旧版UUID的字节排列和标准UUID不同),转换为符合习惯的带破折号的大写UUID字符串。
  • 聚合操作参数统一放在数组中,保持语法规范。
  • 通过map函数直接替换_id字段格式后再序列化输出。

输出示例

[
  '{"_id":"JUUID(\\"ACB8AEEA-D247-4C6B-BC20-B8E05C146F30\\")","field1":"string1"}'
]
[
  '{"_id":"JUUID(\\"F1D2E3A4-5678-90BC-DEF1-23456789ABC0\\")","field1":"string2"}'
]

如果需要输出时不带转义双引号,可以直接拼接字符串替代JSON.stringify:

return `{"_id": JUUID("${javaLegacyUuidToStr(el._id)}"), "field1": "${el.field1}"}`;

内容的提问来源于stack exchange,提问作者awgtek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 18:52:45