计数器表
> db.counters.insert({_id: "userid",seq: 0} );
> db.counters.find();
{ "_id" : "userid", "seq" : 0 }
取下个ID的函数
> function getNextSequence(name) {
var ret = db.counters.findAndModify(
{
query: { _id: name },
update: { $inc: { seq: 1 } },
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" }