mongodb id自增问题
迷茫
迷茫 2017-04-22 08:56:12
0
1
563

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

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(1)
黄舟

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template