使用$ addFields将_id设置为新的UUID [英] Set _id to a new UUID using $addFields

查看:61
本文介绍了使用$ addFields将_id设置为新的UUID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,有人把事情弄糟了.不是我,但我可以解决它.我需要做的是用新的UUID替换集合中每个文档的 _id .

Well, someone done goofed. Wasn't me, but I get to fix it. What I need to do, is replace the _id of each and every document in the collection with a new UUID.

我的计划是汇总整个集合,使用 $ addFields 替换 _id ,然后将其合并回自身,替换记录.幸运的是,我可以使用一个辅助(复合)键进行合并,因此在这里很好-我想,因为我还没有到那里.

My plan was aggregating the entire collection, use $addFields to replace the _id, then merge it back into itself, replacing the records. Fortunately, there is a secondary (composite) key I can use for merging, so I'm good there — I think, because I haven't gotten there yet.

我面临的问题是在 $ addFields 阶段生成唯一的UUID.

The problem I face is generating a unique (that's kinda the point of it) UUID during the $addFields stage.

db.foo.agregate([
    {
        $addFields: {
            // I really just need the UUID string itself, hence the split
            '_id': UUID().toString().split('"')[1]
        }
    }
    // here's where the merge would go
])

这里的问题是 UUID()仅被调用一次,所以我得到所有相同的ID.那不是我想要的.

The problem here is that UUID() is called only once, so I get all the same IDs. That's not quite what I want.

现在乏味的方法是从一个循环开始一步一步地完成此操作.但是,有没有办法一口气从聚合管道中做到这一点?

Now the tedious way would be to do this one by one, from a loop. But is there a way to do this from within an aggregation pipeline in one go?

现在我发现了这个问题提出了基本相同的问题,但是通过不使用UUID来解决了,而是使用顺序键,因此它实际上并不是我的问题的答案.

Now I found this question asking basically the same question, but it was solved by not using an UUID, using sequential keys instead, so it really isn't an answer to my question.

推荐答案

因此,此答案仅是生成唯一的 UUID ,但是生成的 UUID 很奇怪.因此,仅在它们有用时才使用它.试试这个:

So this answer is just to generate unique UUIDs, but the generated UUIDs are weird. So use it only if they are useful. Try this:

db.collectionName.aggregate([
    {
        $addFields: {
            _id: {
                $function: {
                    body: function() {
                        return UUID().toString().split('"')[1];
                    },
                    args: [],
                    lang: "js"
                }
            }
        }
    }
])

btw,它仅适用于MongoDB版本> = 4.4.输出:

btw, its only works in MongoDB version >= 4.4. Output:

/* 1 */
{
    "_id" : "5dc9316a-50a8-4013-8090-06fc66cdce9f",
    "dummy" : "data"
},

/* 2 */
{
    "_id" : "062ebc8f-4455-4a81-a9e0-34f6c7132cab",
    "dummy" : "data"
},

/* 3 */
{
    "_id" : "94eef4b8-9c0e-4910-a1cb-58443a63a036",
    "dummy" : "data"
}

这篇关于使用$ addFields将_id设置为新的UUID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆