MongoDB provides the driver jar for the Java language operation, and the version I am using is: Mongo-java-driver-3.2.2.jar
Drive jar:https://mongodb.github.io/mongo-java-driver/
Here are the ways to create a MONGO connection, get a database and a table, get a table, and then update the next section.
1 /**2 * Initialize connection pool, set parameters. 3 */4 Private Static voidinit () {5 6 //The parameters are: number of link pools max wait time scoket timeout set connection pool maximum lifetime connection time-out7Mongoclientoptions options =Mongoclientoptions.builder ()8. Connectionsperhost (Integer.parseint (Configutil.getparameter ("Mongodb.connectionsperhost")))9. Maxwaittime (Integer.parseint (Configutil.getparameter ("Mongodb.maxwaittime")))Ten. Sockettimeout (Integer.parseint (Configutil.getparameter ("Mongodb.sockettimeout"))) One. Maxconnectionlifetime (Integer.parseint (Configutil.getparameter ("Mongodb.maxconnectionlifetime"))) A. ConnectTimeout (Integer.parseint (Configutil.getparameter ("Mongodb.connecttimeout")) . Build (); - - //Connect to a MONGODB service if a remote connection can replace "localhost" with the IP address of the server the //serveraddress () Two parameters are server address and port, respectively -ServerAddress serveraddress =NewServerAddress (Configutil.getparameter ("Mongodb.hostname"), -Integer.parseint (Configutil.getparameter ("Mongodb.port"))); -List<serveraddress> Addrs =NewArraylist<serveraddress>(); + Addrs.add (serveraddress); - + //three parameters for user name database name password AMongocredential credential =mongocredential.createscramsha1credential ( atConfigutil.getparameter ("Mongodb.username"), Configutil.getparameter ("Mongodb.databasename"), -Configutil.getparameter ("Mongodb.password"). ToCharArray ()); -List<mongocredential> credentials =NewArraylist<mongocredential>(); - Credentials.add (credential); - - //obtaining MongoDB connections through connection authentication inClient =Newmongoclient (Addrs, credentials, options); -}
1 /**2 * Get DB by name, equivalent to a connection3 * 4 * @paramDbName5 * @return6 */7 Public Staticmongodatabase getdatabase () {8 if(Client = =NULL) {9 //InitializeTen init (); One } A returnClient.getdatabase (Configutil.getparameter ("Mongodb.databasename")); - } - /** the * Get Collection - * @paramCollectionName - * @return - */ + Public StaticMongocollection<document>getcollection (String collname) { - if(Client = =NULL) { + //Initialize A init (); at } -Mongodatabase db =getdatabase (); -Mongocollection<document> collection =db.getcollection (collname); - returncollection; -}
Java Operation mongodb--Connection database