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

    主站蜘蛛池模板: 亚洲精品在线免费看| 免费中文字幕不卡视频| 亚洲视频在线免费观看| 国产成人综合亚洲AV第一页| 偷自拍亚洲视频在线观看| 在线观看亚洲免费| 亚洲欧洲日产国码av系列天堂| 一级毛片免费在线| 成年人网站免费视频| 国产一区二区三区在线观看免费 | 岛国片在线免费观看| 亚洲第一永久AV网站久久精品男人的天堂AV| 亚洲一区免费在线观看| 在线观看无码AV网站永久免费| 亚洲久悠悠色悠在线播放| 最近高清国语中文在线观看免费| 亚洲欧美aⅴ在线资源| 中文字幕久精品免费视频| 爽爽日本在线视频免费| 亚洲人成网www| 亚洲人成电影网站免费| 国产亚洲精品免费| 亚洲婷婷五月综合狠狠爱| 少妇人妻偷人精品免费视频| 亚洲第一成人在线| 亚洲视频在线免费观看| 国产精品久久亚洲不卡动漫| 国产jizzjizz免费看jizz| 日韩精品无码免费专区午夜| 亚洲午夜电影在线观看| 四虎永久在线免费观看| 免费污视频在线观看| 亚洲成aⅴ人片久青草影院| 91福利免费网站在线观看| 亚洲综合激情九月婷婷| 日本一道在线日本一道高清不卡免费 | 亚洲一线产区二线产区精华| 免费无遮挡无码永久在线观看视频| 中文字幕永久免费视频| 亚洲伦理中文字幕| 亚洲一区AV无码少妇电影☆|