http://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/
官方文档给出了2种解决方法,我只看了第一种的时候:
function getNextSequence(name) {
var ret = db.counters.findAndModify(
{
query: { _id: name },
update: { $inc: { seq: 1 } },
new: true
}
);
return ret.seq;
}
与
function getNextSequence(name) {
var ret = db.counters.findAndModify(
{
query: { _id: name },
update: { $inc: { seq: 1 } },
new: true,
upsert: true
}
);
return ret.seq;
}
英文看得有点模糊,多了一个upsert到底是好还是不好?
黄舟2017-04-22 08:58:12
Not good, unless you have a unique index, you may insert multiple documents with the same name. There may be multiple findAndModify
functions running at the same time. They all find that the existing document cannot be found, so they all decide to insert a new document, so the process repeats.