从旧版UUID迁移到标准UUID

时间:2018-01-23 13:22:59

标签: c# .net mongodb mongodb-.net-driver

我有一个简单的mongo迁移框架,它正在执行一些传递的脚本。

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

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");

然后我运行它:

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中运行此脚本时,它按预期工作。

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

1 个答案:

答案 0 :(得分:1)

这个人为我工作:

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");

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