search

Home  >  Q&A  >  body text

mongodb id自增问题

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到底是好还是不好?

迷茫迷茫2802 days ago564

reply all(1)I'll reply

  • 黄舟

    黄舟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.

    reply
    0
  • Cancelreply