现有集合的增量字段 [英] Incremental field to existing collection

查看:34
本文介绍了现有集合的增量字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含大约 10 万个文档的集合.我想向我的文档添加一个自动递增的custom_id"字段,并从现在开始通过递增该字段来继续添加我的文档.

I have a collection containing around 100k documents. I want to add an auto incrementing "custom_id" field to my documents, and keep adding my documents by incrementing that field from now on.

最好的方法是什么?我在官方文档(http://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/) 但是它们仅用于添加新文档,而不用于更新现有集合.

What's the best approach for this? I've seen some examples in the official document (http://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/) however they're only for adding new documents, not for updating an existing collection.

我根据上面的链接创建的示例代码以增加我的计数器:

Example code I created based on the link above to increment my counter:

function incrementAndGetNext(counter, callback) {
    counters.findAndModify({
        name: counter
    }, [["_id", 1]], {
        $inc: {
            "count": 1
        }
    }, {
        "new": true
    }, function (err, doc) {
        if (err) return console.log(err);
        callback(doc.value);
    })
}

在上面的代码中 countersdb.counters 集合,我在那里有这个文档:

On the above code counters is db.counters collection and I have this document there:

{_id:"...",name:"post",count:"0"}

很想知道.

谢谢.

附言我正在为 js 使用本机 mongojs 驱动程序

P.S. I'm using native mongojs driver for js

推荐答案

好吧,使用您提到的链接,我宁愿使用 计数器收集方法.

Well, using the link you mentionned, I'd rather use the counters collection approach.

计数器集合方法有一些缺点,包括:

The counters collections approach has some drawbacks including :

  • 它总是生成多个请求(两个):一个是获取序列号,另一个是使用您通过序列获得的 id 进行插入,
  • 如果您使用的是 mongodb 的分片功能,则负责存储计数器状态的文档可能会被多次使用,并且每次都会到达同一台服务器.

不过它应该适合大多数用途.

However it should be appropriate for most uses.

你提到的方法("the乐观循环") 不应该破坏 IMO,我不知道您为什么会遇到问题.不过我不推荐它.如果您在多个 mongo 客户端上执行代码,如果一个客户端有很多延迟而其他客户端继续使用 ID,会发生什么情况?我不希望遇到这种问题......此外,每次成功操作至少有两个请求,但成功前没有最多重试......

The approach you mentionned ("the optimistic loop") should not break IMO, and I don't guess why you have a problem with it. However I'd not recommend it. What happens if you execute the code on multiple mongo clients, if one has a lot of latency and others keep taking IDs? I'd not like to encounter this kind of problem... Furthermore, there are at least two request per successful operation, but no maximum of retries before a success...

这篇关于现有集合的增量字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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