首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >添加新文档时自动生成ID

添加新文档时自动生成ID
EN

Stack Overflow用户
提问于 2015-03-10 16:00:03
回答 2查看 174关注 0票数 2

我的项目使用ClusterPoint数据库,我想知道是否可以用随机分配的ID将文档插入数据库。

此文档似乎指定了"ID“。,但是如果它已经存在了呢?是否有更好的方法来生成唯一的标识符。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-03-13 07:47:21

您可以通过对序列使用单独的文档来实现自动增量功能,并使用事务来安全地增加它。当然,这可能会影响吞食速度,因为每次插入都需要额外的往返才能成功。

代码语言:javascript
复制
try {          
          // Begin transaction
          $cpsSimple->beginTransaction();
          // Retrieve sequence document with id "sequence"
          $seq_doc = $cpsSimple->retrieveSingle("sequence", DOC_TYPE_ARRAY);
          //in sequence doc we store last id in field 'last_doc_id'
          $new_id = ++$seq_doc['last_doc_id'];
          $cpsSimple->updateSingle("sequence", $seq_doc);
          //commit
          $cpsSimple->commitTransaction();
          //add new document with allocated new id
          $doc = array('field1' => 'value1', 'field2' => 'value2');
          $cpsSimple->insertSingle($new_id, $doc);
    } catch (CPS_Exception $e) {

    }
票数 1
EN

Stack Overflow用户

发布于 2015-03-11 10:11:06

如果原始操作失败,我尝试重新插入数据,从而解决了问题。下面是我在PHP中的方法:

代码语言:javascript
复制
function cpsInsert($cpsSimple, $data){
    for ($i = 0; $i < 3; $i++){
        try {
            $id = uniqid();
            $cpsSimple->insertSingle($id, $data);
            return $id;
        }catch(CPS_Exception $e){
            if($e->getCode() != 2626) throw $e;

            // will go for another attempt
        }
    }
    throw new Exception('Unable to generete unique ID');
}

我不确定这是不是最好的方法,但有效。

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

https://stackoverflow.com/questions/28968402

复制
相关文章

相似问题

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