JavaからMongoDBへのアクセスする方法まとめ

方法1
MongoClient mongoClient = new MongoClient();

方法2
MongoClient mongoClient = new MongoClient( “localhost" );

方法3
MongoClient mongoClient = new MongoClient( “localhost" , 27017 );

方法4
MongoClient mongoClient = new MongoClient(
Arrays.asList(new ServerAddress(“localhost", 27017),
new ServerAddress(“localhost", 27018),
new ServerAddress(“localhost", 27019)));

方法5
MongoClientURI connectionString = new MongoClientURI(“mongodb://localhost:27017,localhost:27018,localhost:27019");
MongoClient mongoClient = new MongoClient(connectionString);

サンプルコード
public void operatefunc(){
/*
* DB接続
*/
MongoClientURI connectionString = new MongoClientURI(“mongodb://172.17.2.100:27017");
MongoClient mongoClient = new MongoClient(connectionString);
/*
* DB選択
*/
MongoDatabase mongoDatabase = mongoClient.getDatabase(“db");
/*
* ドキュメント選択
*/
MongoCollection myCollection = mongoDatabase.getCollection(“mycollection");
}

Java

Posted by arkgame