<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) 評(píng)論(0)  編輯  收藏 所屬分類: DB

    主站蜘蛛池模板: 亚洲熟女www一区二区三区| 亚洲av日韩av高潮潮喷无码| 亚洲va精品中文字幕| 67pao强力打造国产免费| 亚洲AV人无码激艳猛片| 99视频精品全部免费观看| 亚洲视频在线一区| 亚洲精品自产拍在线观看动漫| 国产成人精品免费视频大全| 精品国产亚洲男女在线线电影| 一个人看的www视频免费在线观看 一个人看的免费观看日本视频www | 国产在线精品一区免费香蕉| 亚洲电影日韩精品| a级片免费在线播放| 久久亚洲免费视频| 久久午夜伦鲁片免费无码| 亚洲国产精品免费在线观看| 四虎影视永久在线精品免费| 69式国产真人免费视频| 亚洲午夜久久久久妓女影院| 免费国产污网站在线观看| 妞干网免费视频在线观看| 精品国产综合成人亚洲区| 美国免费高清一级毛片| 国产精彩免费视频| 天堂亚洲国产中文在线| 国产91久久久久久久免费| 一级毛片**免费看试看20分钟 | 99re免费99re在线视频手机版| 亚洲国产成AV人天堂无码| 日韩成人免费在线| 亚洲国产精品成人综合色在线婷婷| 国产情侣激情在线视频免费看| 国产三级免费电影| 久久国产精品免费一区二区三区| 国产成人在线观看免费网站| 亚洲剧场午夜在线观看| 日韩一品在线播放视频一品免费| rh男男车车的车车免费网站| 亚洲高清视频在线播放| 日韩免费无码一区二区三区 |