简体   繁体   English

使用PHP的MongoDB自动增量ID

[英]MongoDB auto increment ID with PHP

currently i'm using this php code to create my own auto increment ID in MongoDB. 目前,我正在使用此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);

I have to fetch the old ID, increment and write it back. 我必须获取旧ID,然后递增并写回。 I think there is a better way with MongoDB\\Driver\\Manager::executeReadWriteCommand , but i was unable to find it. 我认为MongoDB \\ Driver \\ Manager :: executeReadWriteCommand有更好的方法,但是我找不到它。

I found this where is a solution with findAndModify , but it is written for MongoClient which is deprecated . 我发现findAndModify的解决方案,但是它是为不推荐使用的 MongoClient编写的。

Any ideas how to use executeReadWriteCommand or maybe a better way? 有什么想法如何使用executeReadWriteCommand或更好的方法?

I found a solution. 我找到了解决方案。 Just want to share if somebody also is searching for. 只想分享,如果有人也在寻找。

I used mongo-php-library to make it work with new MongoDB driver. 我使用mongo-php-library使它与新的MongoDB驱动程序一起使用。 But not with findAndModify like @malarzm commented because it is only an internal function for FindOneAndXXXX. 但不能与findAndModify像@malarzm评论,因为它仅适用于FindOneAndXXXX的内部函数。

I used findOneAndUpdate : 我用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'];

Here is another solution. 这是另一种解决方案。 Let's say you want to upsert a document and increment ID. 假设您要添加文档并增加ID。 You can do something like this: 您可以执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM