Java manipulates MongoDB_3 (preliminary study of MongoDB)
Click on the jar package of MongoDB to see that there are many methods for the Mongo class, including getAddress (), dropDatabase (String), getDB (String), and so on. Let's demonstrate the use of Mongo.class one by one.
The demonstration of Mongo is mainly done in a test class, so I set up a java class for JUnitTest_1 here. The main code is as follows, because the comments are rich, they will not be explained one by one.
Import com.mongodb.Mongo
Public class JUnitTest_1 {
@ Test
Public void test1 () throws Exception {
Mongo mongo = new Mongo ()
/ / get all databases
List dbs = mongo.getDatabaseNames ()
For (String db: dbs) {
System.out.println (db)
}
/ / get the version of the current MongoDB
System.out.println ("mongo version =" + mongo.getVersion ())
/ / get the server address
System.out.println ("mongo server address =" + mongo.getAddress ())
/ / Delete a database
/ / mongo.dropDatabase ("test")
/ / you can also view the maximum setting value of the BSON document
System.out.println ("bsonObjectSize =" + mongo.getMaxBsonObjectSize ())
/ / debugString
System.out.println ("debugString =" + mongo.debugString ())
Mongo.close ()
}
}
Running on my computer, the output is as follows:
Local
Test
Mongo version = 2.10.1
Mongo server address = / 127.0.0.1purl 27017
BsonObjectSize = 16777216
DebugString = DBTCPConnector: / 127.0.0.1 27017 / 127.0.0.1 purl 27017
In practice, it is recommended to use MongoClient instead of the Mongo class. MongoClient is thread-safe and can share the same instance among multiple threads. The test code for calling the MongoClient class is as follows
Public void test2 () throws Exception {
MongoClient client = new MongoClient ()
/ / query all current databases
List dbs = client.getDatabaseNames ()
For (String db: dbs) {
System.out.println (db)
}
/ / get the version of the current MongoDB
System.out.println ("mongo version =" + client.getVersion ())
/ / get the server address
System.out.println ("mongo server address =" + client.getAddress ())
/ / Delete a database
/ / client.dropDatabase ("test")
/ / you can also view the maximum setting value of the BSON document
System.out.println ("bsonObjectSize =" + client.getMaxBsonObjectSize ())
/ / debugString
System.out.println ("debugString =" + client.debugString ())
Client.close ()
}
The printed results are shown in one.