当前,我正在使用此php代码在MongoDB中创建我自己的自动增量ID.
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);我必须获取旧ID,然后递增并将其写回.我认为 MongoDB \ Driver \ Manager :: executeReadWriteCommand有更好的方法,但我找不到它.
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.
我发现了这,其中 findAndModify ,但是它是为不推荐使用的.
I found this where is a solution with findAndModify, but it is written for MongoClient which is deprecated.
任何想法如何使用 executeReadWriteCommand 或更好的方法?
Any ideas how to use executeReadWriteCommand or maybe a better way?
推荐答案这里是另一种解决方案.假设您要添加文档并增加ID.您可以执行以下操作:
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 ] );更多推荐
使用PHP的MongoDB自动增量ID
发布评论