http://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/
Official documents provide two solutions. I only looked at the first one:
function getNextSequence(name) {
var ret = db.counters.findAndModify(
{
query: { _id: name },
update: { $inc: { seq: 1 } },
new: true
}
);
return ret.seq;
}
And
function getNextSequence(name) {
var ret = db.counters.findAndModify(
{
query: { _id: name },
update: { $inc: { seq: 1 } },
new: true,
upsert: true
}
);
return ret.seq;
}
English is a little fuzzy, is it good or bad to have one more upsert?
No, unless you have a unique index, you may insert multiple documents with the same name. There may be more than one
findAndModify
Functions run at the same time, they all find that they cannot find the existing document, so they all decide to insert a new document and repeat it.