首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从传统UUID迁移到标准UUID

从传统UUID迁移到标准UUID
EN

Stack Overflow用户
提问于 2018-01-23 21:22:59
回答 1查看 3.5K关注 0票数 2

我有一个简单的mongo迁移框架,可以执行其中传递的一些脚本。

现在我想把我的LUUID迁移到UUID。我写了以下内容:

代码语言:javascript
复制
function fixIds(collectionName) {
    function uuidv4() {
        return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });
    }

    var collection = db.getCollection(collectionName);
    var items = collection.find({}).toArray().map(x => Object.assign(x, { _id: UUID(uuidv4()) })); // replace legace UUID with standard UUID
    collection.drop();
    collection.insertMany(items);
}

fixIds("specialoffers");

然后我运行它:

代码语言:javascript
复制
public static async Task<BsonValue> EvalAsync(this IMongoDatabase database, string javascript)
{
    var client = database.Client as MongoClient;

    if (client == null)
        throw new InvalidOperationException("Client is not a MongoClient");

    var function = new BsonJavaScript(javascript);
    var op = new EvalOperation(database.DatabaseNamespace, function, null);

    using (var writeBinding = new WritableServerBinding(client.Cluster, new CoreSessionHandle(new NoCoreSession())))
    {
        return await op.ExecuteAsync(writeBinding, CancellationToken.None).ConfigureAwait(false);
    }
}

它会执行,但会将LUUID值替换为其他LUUID值。但是,当我在我的Robo 3T外壳中运行这个脚本时,它可以正常工作。

这段代码有什么问题?为什么它只能在shell中工作?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-01-23 22:13:56

这家伙为我工作:

代码语言:javascript
复制
function fixIds(collectionName) {
    var collection = db.getCollection(collectionName);
    var items = collection.find({}).toArray().map(x => Object.assign(x, { _id: new BinData(4, x._id.base64()) })); // replace legacy UUID with standard UUID
    collection.drop();
    collection.insertMany(items);
}

fixIds("specialoffers");

我用new BinData(4, x._id.base64()) })替换了UUID(uuidv4()),这是正确更新UUID版本的唯一方法。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48402816

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档