mongodb實現mysql AUTO_INCREMENT功能
參照官方文檔(findAndModify實現):
1.Insert into the counters collection, the initial value for the userid:
db.counters.insert( { _id: "userid", seq: 0 })
2.Create a getNextSequence function that accepts a name ofthe sequence. The function uses thefindAndModify() method to atomicallyincrement the seq value and return this new value:
function getNextSequence(name) { var ret = db.counters.findAndModify( { query: { _id: name }, update: { $inc: { seq: 1 } }, new: true } ); return ret.seq;} 3.Use this getNextSequence() function during insert().
db.users.insert( { _id: getNextSequence("userid"), name: "Sarah C." })db.users.insert( { _id: getNextSequence("userid"), name: "Bob D." }) 4.You can verify the results with find():
db.users.find()
文章出處:https://docs.mongodb.com/v3.0/tutorial/create-an-auto-incrementing-field/