[php]代码库
> db.counters.insert( //计数器表
{
_id: "userid",
seq: 0
}
);
WriteResult({ "nInserted" : 1 })
> db.counters.find();
{ "_id" : "userid", "seq" : 0 }
> function getNextSequence(name) { //取下个ID的函数
var ret = db.counters.findAndModify(
{
query: { _id: name },
update: { $inc: { seq: 1 } }, //这里seq就是上面counters表中的seq字段
new: true,
upsert: true
}
);
return ret.seq;
};
> db.users.insert( //插入数据
{
_id: getNextSequence("userid"),
name: "tank"
}
);
WriteResult({ "nInserted" : 1 })
> db.users.find(); //查看
{ "_id" : 1, "name" : "tank" }
> db.users.insert(
{
_id: getNextSequence("userid"),
name: "test"
}
);
WriteResult({ "nInserted" : 1 })
> db.users.find();
{ "_id" : 1, "name" : "tank" }
{ "_id" : 2, "name" : "test" }