Chan Chen Coding...

          Make Auto Incrementing Field in MongoDB

          Side counter method
          One can keep a counter of the current _id in a side document, in a collection dedicated to counters.
          Then use FindAndModify to atomically obtain an id and increment the counter.

          > db.counters.insert({_id: "userId", c: 0});

          > var o = db.counters.findAndModify(
          ...        {query: {_id: "userId"}, update: {$inc: {c: 1}}});
          { "_id" : "userId", "c" : 0 }
          > db.mycollection.insert({_id:o.c, stuff:"abc"});

          > o = db.counters.findAndModify(
          ...        {query: {_id: "userId"}, update: {$inc: {c: 1}}});
          { "_id" : "userId", "c" : 1 }
          > db.mycollection.insert({_id:o.c, stuff:"another one"});
          Once you obtain the next id in the client, you can use it and be sure no other client has it.

          Optimistic loop method
          One can do it with an optimistic concurrency "insert if not present" loop. The following example, in Mongo shell Javascript syntax, demonstrates.

          // insert incrementing _id values into a collection
          function insertObject(o) {
              x = db.myCollection;
              while( 1 ) {
                  // determine next _id value to try
                  var c = x.find({},{_id:1}).sort({_id:-1}).limit(1);
                  var i = c.hasNext() ? c.next()._id + 1 : 1;
                  o._id = i;
                  x.insert(o);
                  var err = db.getLastErrorObj();
                  if( err && err.code ) {
                      if( err.code == 11000 /* dup key */ )
                          continue;
                      else
                          print("unexpected error inserting data: " + tojson(err));
                  }
                  break;
              }
          }
          The above should work well unless there is an extremely high concurrent insert rate on the collection. In that case, there would be a lot of looping potentially.


          -----------------------------------------------------
          Silence, the way to avoid many problems;
          Smile, the way to solve many problems;

          posted on 2012-04-14 01:11 Chan Chen 閱讀(356) 評論(0)  編輯  收藏 所屬分類: DB

          主站蜘蛛池模板: 漳平市| 莱芜市| 射阳县| 子长县| 项城市| 华宁县| 根河市| 肥西县| 德惠市| 马山县| 营山县| 九龙县| 邵东县| 潜山县| 呼和浩特市| 石泉县| 垫江县| 呼玛县| 正宁县| 乐业县| 仙游县| 娱乐| 衡阳县| 苏尼特右旗| 武强县| 武冈市| 孟连| 微山县| 云龙县| 吉林省| 东兰县| 施秉县| 多伦县| 莱州市| 黑水县| 宝兴县| 泸州市| 永兴县| 荥阳市| 西林县| 江陵县|