MongoDB auto increment ID with PHP

倖福魔咒の 提交于 2020-12-15 04:58:42

问题


currently i'm using this php code to create my own auto increment ID in MongoDB.

$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. I think there is a better way with MongoDB\Driver\Manager::executeReadWriteCommand, but i was unable to find it.

I found this where is a solution with findAndModify, but it is written for MongoClient which is deprecated.

Any ideas how to use executeReadWriteCommand or maybe a better way?


回答1:


Here is another solution. Let's say you want to upsert a document and increment ID. You can do something like this:

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



回答2:


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. But not with findAndModify like @malarzm commented because it is only an internal function for FindOneAndXXXX.

I used 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'];


来源:https://stackoverflow.com/questions/51067861/mongodb-auto-increment-id-with-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!