【问题标题】:MongoDB auto increment ID with PHPMongoDB 使用 PHP 自动增加 ID
【发布时间】:2018-12-06 15:34:59
【问题描述】:

目前我正在使用这个 php 代码在 MongoDB 中创建我自己的自动增量 ID。

$mongo = new MongoDB\Driver\Manager("mongodb://10.1.1.111:27017");

$find = [ '_id' => 'campaignid' ];
$query = new MongoDB\Driver\Query($find, [ ]);
$rows = $mongo->executeQuery('testdb.counters', $query);
$arr = $rows->toArray();

$oldId = 0;
if(count($arr) > 0)
{
    $old = array_pop($arr);
    $oldId = intval($old->seq);
}

$nextId = ++$oldId;

$set = [ '_id' => 'campaignid', 'seq' => $nextId ];
$insRec = new MongoDB\Driver\BulkWrite;
$insRec->update($find, ['$set' => $set], ['multi' => false, 'upsert' => true]);
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
$result = $mongo->executeBulkWrite('testdb.counters', $insRec, $writeConcern);

我必须获取旧 ID,递增并写回它。我认为MongoDB\Driver\Manager::executeReadWriteCommand 有更好的方法,但我找不到。

我找到了thisfindAndModify 的解决方案,但它是为 deprecated 的 MongoClient 编写的。

任何想法如何使用executeReadWriteCommand 或者更好的方法?

【问题讨论】:

标签: php mongodb auto-increment


【解决方案1】:

我找到了解决方案。如果有人也在搜索,只想分享。

我使用mongo-php-library 使其与新的 MongoDB 驱动程序一起工作。但不像@malarzm 评论的findAndModify,因为它只是FindOneAndXXXX 的内部函数。

我用findOneAndUpdate:

$mongo = new MongoDB\Client("mongodb://10.1.1.111:27017");
$collection = $mongo->testdb->counters;
$result =  $collection->findOneAndUpdate(
            [ '_id' => 'campaignid' ],
            [ '$inc' => [ 'seq' => 1] ],
            [ 'upsert' => true,
              'projection' => [ 'seq' => 1 ],
              'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER
             ]
);

$nextId = $result['seq'];

【讨论】:

    【解决方案2】:

    这是另一种解决方案。假设您想更新文档并增加 ID。你可以这样做:

    $mongo->testdb->updateOne(
       ['myidfield' => '123'],
       [
         '$set' => ['name' => 'John'],
         '$inc' => ['id' => 1]
       ],
       [
         'upsert' => true
       ]
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-19
      • 2017-04-20
      • 2019-06-06
      • 1970-01-01
      • 2015-07-05
      • 2016-01-13
      • 2016-10-16
      • 2014-05-18
      相关资源
      最近更新 更多