2012-03-29 109 views
1

我想在使用php的MongoDB中的字段中添加自动增量值,而不使用计数记录,下一个数字(count + 1)将作为我的增量值... 或者是否有任何在mongodb,php例如一个客户有多个电子邮件和地址,然后我们可以存储它像email[{1:'[email protected]',2:'[email protected]'},...]address[{1:'Indore',2:'Dewas'},...]也相同因此为了唯一性,我想设置自动增量值从每个电子邮件和地址..如何创建自动增量字段

回答

2

这是可能的,如果你创建了两个collections

首先存储领域whichyou要创建自动增量数

// 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; 
} 

第二要在其中同时使用PHP代码,那么你可以使用find()和/或update()

参考文档create-an-auto-incrementing-field

+0

你怎么用PHP实现上面的? – Slimshadddyyy 2014-09-26 04:09:32

0
使用递增的编号类似

// 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()可能无法正常工作

这是可能的,我们必须得到最大id表格集合

db - > collection - > find() - > sort(array('id'=> -1)) - > limit(1)

它返回最大id数组。添加db ['id'] + 1;

每次都不需要存储mongo中的自动增量id