随笔 - 79  文章 - 58  trackbacks - 0
<2024年3月>
252627282912
3456789
10111213141516
17181920212223
24252627282930
31123456

常用链接

留言簿(9)

随笔分类

随笔档案

文章档案

相册

搜索

  •  

积分与排名

  • 积分 - 291825
  • 排名 - 87

最新评论

阅读排行榜

评论排行榜

1、实现原理

为了实现自增ID,,需要引入专门计算id的Collection。
该collection中存放的记录格式类似如下:
{'_id': 1,  'current_id_value':1} , 
其中current_id_value对应着当前最大id值+1,每次需要获取一个ID时,需要先到该collection查询对应的currentIdValue 值并把这个值+1
mongodb提供了findAndModify接口,并且是线程安全的,做到查询并加1的原子操作。

2、代码如下

int64_t GetID()
{
    int64_t ret = -1;
    
    mongoc_collection_t *pCountCollection = mongoc_client_get_collection(m_pClient, "test_db", "id_generator");
    
    bson_error_t error;
    bson_t *doc = bson_new();

    bson_t child;
    bson_append_document_begin(doc, "$inc", -1, &child);
    BSON_APPEND_INT64(&child, "current_id_value", 1);
    bson_append_document_end(doc, &child);

    bson_t query;
    bson_init(&query);
    BSON_APPEND_INT64(&query, "_id", 1);

    bson_t reply;
    bool r = mongoc_collection_find_and_modify(pCountCollection,
        &query,
        NULL,
        doc,
        NULL,
        false,
        true,
        true,
        &reply,
        &error);
    if (!r)
    {
        cout << "GetID Failure: " << error.message;
    }
    else
    {
        bson_iter_t iter;
        bson_iter_init(&iter, &reply);
        if (bson_iter_find(&iter, "value"))
        {
            const uint8_t *buf;
            uint32_t len;
            bson_iter_document(&iter, &len, &buf);
            bson_t rec;
            bson_init_static(&rec, buf, len);

            bson_iter_init(&iter, &rec);
            if (bson_iter_find(&iter, "current_id_value"))
            {
                ret = bson_iter_int64(&iter);
            }
            bson_destroy(&rec);
        }
    }

    bson_destroy(&query);
    bson_destroy(&reply);
    bson_destroy(doc);

    return ret;
}
posted on 2014-09-27 16:23 merlinfang 阅读(3862) 评论(0)  编辑 收藏 引用 所属分类: mongodb

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理