Self-growing primary key solution for MongoDB long/int (Long Integer)

Source: Internet
Author: User
Tags mongodb collection

Lucky to taste the mango today, found that there are many types of self-growth ID, but no long/int.

One idea:
1. Self-built a collection (table, assuming named: Identityentity, where Fields: _id, Key, Value, _id you know, key:collection name, need long/ int from the collection name of the growth primary key, the Long/int self-growth maximum value of the collection stored in the Value:key field, which is used to deposit long/int information for the collection self-growing primary key (for convenience example: xlogs)
Structure self-built collection, identityentity as follows:
_id Key Value
New Guid () Xlogs 5

2. Each time the new data is added to the xlogs, the current maximum (5) is taken out, and then 1, we know that the self-growth key is not necessary for us to explicitly insert, of course, it is the same as the entire process by the MONGO itself within the framework of the completion.

3. Since it is done internally, we have to implement a small piece of code that allows the MONGO framework to invoke

Two implementations:

1. Interfaces in the MONGO framework: Iidgenerator

2. Implement the interface, code:

1  Public classLongidgenerator<tdocument, tkey>: IidgeneratorwhereTdocument:class2     {3         Private StaticLongidgenerator<tdocument, tkey> _instance =NewLongidgenerator<tdocument, tkey>();4          Public StaticLongidgenerator<tdocument, tkey> Instance {Get{return_instance;} }5 6          Public ObjectGenerateid (ObjectContainerObjectdocument)7         {8TKey ID =default(TKey);9             varCollection = Container asMongocollection<tdocument>;Ten             if(NULL!=collection) One             { A                 varMongoDB =collection. Database;  -                 varIdcoll = mongodb.getcollection<identityentity<tkey>> ("identityentity"); -                 varKeyName =document. GetType (). Name; theID =Realgenerateid (Idcoll, keyName); -             } -             returnID; -         } +  -         PrivateTKey Realgenerateid (mongocollection<identityentity<tkey>> idcoll,stringkeyName) +         { A TKey ID; at             varIdquery =NewQuerydocument ("Key", Bsonvalue.create (KeyName)); -             varIdbuilder =NewUpdatebuilder (); -Idbuilder.inc ("Value",1); -  -             varargs =NewFindandmodifyargs (); -Args. Query =Idquery; inArgs. Update =Idbuilder; -Args. versionreturned =findandmodifydocumentversion.modified; toArgs. Upsert =true; +  -             varresult =idcoll.findandmodify (args); the             if(!string. IsNullOrEmpty (result. errormessage)) *             { $                 Throw NewException (result. errormessage);Panax Notoginseng             } -id = result. Getmodifieddocumentas<identityentity<tkey>>(). Value; the             returnID; +         }         A  the          Public BOOLIsEmpty (ObjectID) +         { -             if(NULL==ID) $             { $                 return false; -             } -             return true; the         } -}

2.2. From the above code see we know, first to understand the MongoDB collection, change, check and other basic operations, and then understand the "thinking" of the content mentioned. Note Collection identityentity has been written dead in the code, and the first run will automatically add this collection when he does not exist.

Three applications
To this completed code implementation. Now that it is implemented, start talking about applications:
Mode 1.

1   Public classXlogs:baselog, ientity<Long>2     {3         //Application: Add this attribute on the long self-growth key4[Bsonid (Idgenerator =typeof(longidgenerator<xlogs>))]5          Public LongId {Get;Set; }6 7          Public byteStatus {Get;Set; }8       9          Public stringCreatedBy {Get;Set; }Ten        One          PublicSystem.DateTime CreatedDate {Get;Set; } A          -          Public stringRemark {Get;Set; } -          the          Public decimalAmount {Get;Set; } -}

Mode 2. Register the way, before the data into collection xlogs, it is necessary to run it

1 bsonclassmap.registerclassmap<xlogs> (rc =2            {3                RC). Automap (); 4                 Tch Setidmember (RC. Getmembermap (c = c.id)); 5                 long>. Instance); 6             });

Self-growing primary key solution for MongoDB long/int (Long Integer)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.