Originally want to write a Java operation MongoDB database additions and deletions to check the demo, but recently there is no time, only the previous record of the connection MongoDB method posted ...
And so have time to complete the additions and deletions to check the demo to fill it ....
I installed the local MongoDB database, so I was running under windos ...
No jar package ... Look here....
Java connection MongoDB Driver jar Pack
These constants ... Modify it according to your actual environment ... If the MONGO database does not have a username and password, do not check ...
Private static final String host = "localhost";
private static final int port = 27017;
private static final String userName = "";
Private static final String password = "";
private static final String DataBaseName = "Mongotest";
Private static final String tablename = "User";
Version one, pay attention to see: I use here is Mongo Mongo = new Mongo (host, Port); To connect with ...
public void Connmongodb () throws Exception {
Mongo Mongo = new Mongo (host, port);
DB db = Mongo.getdb (dataBaseName);
if (! Stringutils.isempty (userName) | | ! Stringutils.isempty (password)) {
db.authenticate (UserName, Password.tochararray ());
}
Dbcollection dbcollection = db.getcollection (tablename);
Dbcursor dbcursor = Dbcollection.find ();
while (Dbcursor.hasnext ()) {
map map = (map) dbcursor.next ();
SYSTEM.OUT.PRINTLN (map);
}
Result diagram:
This is my MongoDB database.
Then the version 2.
Pay attention to see Ah ... Here I am using mongoclient mongoclient = new Mongoclient (host,port); Connect the MongoDB ...
public void Connectmongodb () {
try{
mongoclient mongoclient = new Mongoclient (host,port);
DB db = Mongoclient.getdb (dataBaseName);
Dbcollection dbcollection = db.getcollection (tablename);
Dbcursor dbcursor = Dbcollection.find ();
while (Dbcursor.hasnext ()) {
System.out.println (Dbcursor.next ());
}
} catch (Exception e) {
e.printstacktrace ();
}
}
Although their results are the same.
They can all connect to the MongoDB database, but what difference does it make?
Baidu Check the next, find this article, analysis of the good, interested can see ...
However, official documentation and source code suggest using the Mongoclient class ... No, the future will be abandoned MONGO
Analysis on difference of writing performance between Mongoclient and MONGO