MongoDB implements MySQL auto_increment function
Refer to the official documentation (FINDANDMODIFY implementation):
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 ()
Article Source: https://docs.mongodb.com/v3.0/tutorial/create-an-auto-incrementing-field/