使用PHP的MongoDB自动增量ID

编程入门 行业动态 更新时间:2024-10-28 11:28:04
本文介绍了使用PHP的MongoDB自动增量ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

当前,我正在使用此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

本文发布于:2023-11-13 09:10:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1583975.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:增量   PHP   MongoDB   ID

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!