<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

    主站蜘蛛池模板: 日本黄页网站免费| 84pao国产成视频免费播放| 免费黄色大片网站| 亚洲色大成网站www| 无码人妻久久一区二区三区免费丨| 久久亚洲中文字幕精品有坂深雪 | 男女一进一出抽搐免费视频 | 91免费在线播放| 亚洲欧洲日本国产| 中文字幕av无码无卡免费| 亚洲人和日本人jizz| 四虎影院免费在线播放| 亚洲AV综合色区无码一二三区 | 日本免费电影一区| 国产区图片区小说区亚洲区| 亚洲人成网站色在线入口| 人人公开免费超级碰碰碰视频| 亚洲一区二区高清| a级毛片无码免费真人久久| 亚洲av不卡一区二区三区| 69天堂人成无码麻豆免费视频| 亚洲色偷精品一区二区三区 | 久久久久亚洲精品影视| 亚洲免费闲人蜜桃| 美女视频黄a视频全免费网站一区| 亚洲色图综合在线| 99久久99久久精品免费观看| 亚洲影视自拍揄拍愉拍| 免费一级做a爰片久久毛片潮喷| aa级毛片毛片免费观看久| 亚洲一区中文字幕久久| 日本免费人成视频播放| 久久成人永久免费播放| 亚洲中文字幕久在线| 亚洲成A人片77777国产| 99久久久国产精品免费牛牛| 亚洲av永久无码精品秋霞电影秋 | 国产亚洲日韩一区二区三区| 131美女爱做免费毛片| 亚洲av无码片vr一区二区三区| 亚洲成A人片777777|