如何创建自动增量字段 [英] How to create auto increment field

查看:110
本文介绍了如何创建自动增量字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用php在mongodb中的一个字段中添加自动增量值,而不使用计数记录,下一个数字(count + 1)将是我的增量值... 或者是否有任何方法可以在mongodbphp中创建自动增量值的数组,例如,一个客户有多个电子邮件和地址,那么我们可以像email[{1:'a@x.com',2:'demo@example.com'},...]一样存储它,对于address[{1:'Indore',2:'Dewas'},...]也一样,所以为了唯一性,我想从每个电子邮件和地址设置自动增量值.

I want to add auto increment value in a field in mongodb using php, without using counting the records and next number(count + 1) will be my increment value... Or Is there any way to create array of autoincrement values in mongodb,php for example A customer having multiple emails and addresses then we can store it like email[{1:'a@x.com',2:'demo@example.com'},...] and also same for address[{1:'Indore',2:'Dewas'},...] So for uniqueness I want to set autoincrement value from each email and address..

推荐答案

如果创建两个收藏

首先存储要为其创建自动递增编号的字段,例如

First to store the field for whichyou want to create autoincrement number like

// Inserting 2 records for which we want to create auto-increment numbers
db.autoincrementcollection.insert({
   field_id: "register_id",
   nextId: 0
},
{
   field_id: "user_id",
   nextId: 0
});

// Function is used to get the next autoincremented value
function getNextId(field)
{
   var ret = db.autoincrementcollection.findAndModify({
        query: { field_id: field },
        update: { $inc: { nextId: 1 } },
        new: true
   });    
   return ret.nextId;
}

第二,您要在其中使用递增的数字,例如

Second in which you want to use the incremented number like

// inserting data in registration collection with register_id auto-increment number
db.registration.insert({
     _id: getNextId("register_id"),
     fname: "Rohan",
     lname:"Kumar"
});
// inserting data in user collection with user_id auto-increment number
db.users.insert({
     _id: getNextId("user_id"),
     name: "Rohan Kumar"
});

findAndModify()可能无法在使用 PHP 的代码中工作,然后可以使用

findAndModify() may not work while code using PHP then you can use find() and/or update()

有关创建的文档 -自动递增字段

Refer Docs for create-an-auto-incrementing-field

这篇关于如何创建自动增量字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆