<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    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 閱讀(346) 評論(0)  編輯  收藏 所屬分類: DB

    主站蜘蛛池模板: 成全高清视频免费观看| 中文字幕在亚洲第一在线| 特级做a爰片毛片免费看| 亚洲欧洲成人精品香蕉网| 久久免费视频精品| 亚洲精品永久在线观看| 亚洲精品成人片在线播放| 青青青免费国产在线视频小草| 美女一级毛片免费观看| 久久精品国产亚洲av成人| 免费看美女让人桶尿口| 免费人成在线观看视频高潮| 亚洲AV一二三区成人影片| 爱情岛论坛网亚洲品质自拍| 精品免费人成视频app| 九一在线完整视频免费观看| 亚洲女人影院想要爱| 亚洲色偷偷综合亚洲AV伊人| 99在线精品视频观看免费| 国产精品青草视频免费播放| 亚洲1区1区3区4区产品乱码芒果 | 中文字幕亚洲码在线| 精品亚洲一区二区三区在线观看| 99精品热线在线观看免费视频| 亚洲av乱码中文一区二区三区| 久久噜噜噜久久亚洲va久| 免费一级毛片正在播放| 国产乱子精品免费视观看片| a毛片在线还看免费网站| 老子影院午夜伦不卡亚洲| 亚洲欧洲国产成人精品| 亚洲一区二区三区偷拍女厕| 精品久久洲久久久久护士免费| 特级无码毛片免费视频尤物| 成人片黄网站色大片免费观看cn| 亚洲日韩AV一区二区三区中文| 亚洲色图在线观看| 亚洲精品少妇30p| 国产乱辈通伦影片在线播放亚洲 | 亚洲午夜电影在线观看高清| 亚洲AV中文无码乱人伦下载|