<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ⅴ亚洲中文字幕| 国产黄色片在线免费观看| 亚洲精品无码久久久久YW| 国产成人免费ā片在线观看| 老司机亚洲精品影院在线观看| 一级毛片直播亚洲| 亚州**色毛片免费观看| 伊人久久亚洲综合| 久久免费线看线看| 亚洲视频在线观看一区| 亚洲成人免费网站| 亚洲人成综合网站7777香蕉| 日本媚薬痉挛在线观看免费| 午夜免费国产体验区免费的| 日本亚洲视频在线| 97碰公开在线观看免费视频| 亚洲精品无码久久久久A片苍井空| 四虎永久免费网站免费观看| 国产黄色免费观看| 久久久无码精品亚洲日韩京东传媒| 久久国内免费视频| 无遮挡免费一区二区三区| 亚洲AV永久无码区成人网站| 91久久成人免费| 国产成人亚洲毛片| 亚洲高清国产拍精品26U| 免费99精品国产自在现线| 免费无码专区毛片高潮喷水| 久久久久亚洲精品无码系列| 无限动漫网在线观看免费| 免费播放国产性色生活片| 西西人体44rt高清亚洲| 日本午夜免费福利视频| 国产va在线观看免费| 久久精品国产亚洲av瑜伽| 亚洲邪恶天堂影院在线观看| 免费高清在线爱做视频|