Database Reference
In-Depth Information
D.2.2
Connections
Creating a single-node connection is easy as long as you remember to wrap the call in
a try block:
try {
Mongo conn = new Mongo("localhost", 27017);
} catch (Exception e) {
throw new RuntimeException(e);
}
To c o n n e c t t o a r e p l i c a s e t , f i r s t b u i l d a l i s t o f ServerAddress objects. Then pass that
list to the Mongo constructor:
List servers = new ArrayList();
servers.add( new ServerAddress( "localhost" , 30000 ) );
servers.add( new ServerAddress( "localhost" , 30001 ) );
try {
Mongo replConn = new Mongo( servers );
} catch (Exception e) {
throw new RuntimeException(e);
The Java driver includes flexible support for write concern. You can specify a different
write concern on the Mongo , DB , and DBCollection objects, as well as on any of
DBCollection 's write methods. Here we specify a global write concern on the connec-
tion using the WriteConcern configuration class:
WriteConcern w = new WriteConcern( 1, 2000 );
conn.setWriteConcern( w );
D.2.3
Sample program
This Java program is a direct translation of the previous PHP program, and it should
be self-explanatory:
import com.mongodb.Mongo;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.WriteConcern;
import java.util.Date;
public class Sample {
public static void main(String[] args) {
Mongo conn;
try {
conn = new Mongo("localhost", 27017);
} catch (Exception e) {
throw new RuntimeException(e);
}
WriteConcern w = new WriteConcern( 1, 2000 );
Search WWH ::




Custom Search