MongoDB 中 ID 的序列号

发布于 2024-12-08 05:07:42 字数 87 浏览 4 评论 0原文

Mongo DB 中有 findAndModify 命令可以使用自动递增数字而不是默认 ID,但我不知道如何将它用于 PHP 驱动程序(我不确定它是否受支持)。

There is findAndModify command in Mongo DB to use auto increment numbers instead of the default ID, but I do not know how to use it for PHP driver (I am not sure if it is supported at all).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

深海夜未眠 2024-12-15 05:07:42

好的,如果您需要存储增量值,我建议您使用其他字段而不是 mongodb _id 字段 mongodb 使用这些生成的 id 返回一些(我相信很多,如果不是全部)类型的查询,特别是如果您有多集群设置然后它肯定使用 _id 字段来定位数据所在的物理磁盘(我相信使用哈希表或某些此类技术 - 不完全与 mongo 内核的底层操作保持同步)。简而言之,请不要理会它,它被设计为自动生成的参考字段。

Ok, if you need to store incremental values i suggest you do it using some other field not the mongodb _id field mongodb used these generated id's to return some (i believe many if not all) types of queries, especially if you have a multi cluster set up then it definitely uses the _id field to locate the physical disk the data is on (i believe using a hash table or some such technology - not entirely up to date with the under the hood operations of mongo's kernel). In short, please leave this alone its designed to be an auto generated reference field.

酒绊 2024-12-15 05:07:42
<?php
$m = new MongoClient();

// select a database
$db = $m->seq;

// select a collection (analogous to a relational database's table)
$collection = $db->counters;
$user_collection = $db->user;



/**********Function to auto increment seq************/
function getNextSequence($name){
global $collection;

$retval = $collection->findAndModify(
     array('_id' => $name),
     array('$inc' => array("seq" => 1)),
     null,
     array(
        "new" => true,
    )
);
return $retval['seq'];
}

$db_array=array('_id' => getNextSequence("userid"), 'name' => 'debojit');

$user_collection->insert($db_array);
<?php
$m = new MongoClient();

// select a database
$db = $m->seq;

// select a collection (analogous to a relational database's table)
$collection = $db->counters;
$user_collection = $db->user;



/**********Function to auto increment seq************/
function getNextSequence($name){
global $collection;

$retval = $collection->findAndModify(
     array('_id' => $name),
     array('$inc' => array("seq" => 1)),
     null,
     array(
        "new" => true,
    )
);
return $retval['seq'];
}

$db_array=array('_id' => getNextSequence("userid"), 'name' => 'debojit');

$user_collection->insert($db_array);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文