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 );
}
}