初始化序列:
mongos> db.counters.insert({
_id: "userid",
seq: 0
}
)
写一个函数,用于更新序列值。
function getNextSequence(name){
var result=db.counters.findAndModify({
query:{_id:name},
update:{$inc:{seq:1}},
new: true
}
);
return result.seq;
}
使用函数返回值插入数据,实现序列自增插入:
db.users.insert({
name:"hx",
no:getNextSequence("userid")
}
)
db.users.insert({
name:"lh",
no:getNextSequence("userid")
}
)
mongos> db.users.find()
{ "_id" : ObjectId("533bbad6bbd3bddd62bb1f68"), "name" : "hx", "no" : 1 }
{ "_id" : ObjectId("533bbb00bbd3bddd62bb1f69"), "name" : "lh", "no" : 2 }
由于findAndModify中没有upsert:true,如果插入的语句中name值和初始的不一样,插入会失败:
mongos> db.users.insert({ name:"lz", no:getNextSequence("useri") } )
Wed Apr 2 15:24:26.063 TypeError: Cannot read property 'seq' of null
加上upsert: true,当没有找到符合条件的name时,就插入一条新的,并且初始化seq
function getNextSequence(name){
var result=db.counters.findAndModify({
query:{_id:name},
update:{$inc:{seq:1}},
new: true,
upsert:true
}
);
return result.seq;
}