Java-based self-growth field in MongoDB

Source: Internet
Author: User

In the database design principle, the purpose of the Self-increasing field is to determine the uniqueness of each record for the unique index, and to ensure the query speed when the database volume is large.

However, there are separate fields in Oracle and mongodb databases to determine uniqueness. Therefore, there is no self-increasing field method in the design (both mysql and mssql), and it is not recommended to design the table structure with self-increasing fields.

But programmers who often get used to this method can also implement similar functions in oracle and mongodb databases, and sequence in oracle.

We can also try to implement the self-increasing field mode in the mongodb database; it is to imitate the sequence mode in oracle.

1. Create a collection named sequence in the mongodb database;
Two fields: coll_name (record other collection names) and cnt (maximum number of self-incrementing fields of other collections ).
2: java code:
// Obtain the sequence auto-increment id of the User table
Private static int getSequence (String tableName ){
DBCollection table = conn. getDb (). getCollection ("sequence ");
DBObject query = new BasicDBObject ();
Query. put ("coll_name", tableName );
DBObject newDocument = new BasicDBObject ();
NewDocument. put ("$ inc", new BasicDBObject (). append ("cnt", 1 ));
DBObject ret = table. findAndModify (query, newDocument );
If (ret = null ){
Return 0;
} Else {
Return (Integer) ret. get ("cnt") + 1;
}
}

// Add a user
Public static void addUser (UserInfo user ){
Int id = getSequence ("admin_user ");
If (id! = 0 ){
DBCollection table = conn. getDb (). getCollection ("admin_user ");
DBObject query = new BasicDBObject ();
Query. put ("id", id );
Query. put ("name", user. getName ());
Query. put ("e_mail", user. geteEmail ());
Query. put ("passwd", user. getPassword ());
Query. put ("is_del", false );
Query. put ("create_time", user. getCreateTime ());
Table. insert (query );
}
}

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.