mongodb连接类
作者:互联网
import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoDatabase; public class MyMongodbConnTest { public static void main(String[] args) { // 连接到 mongodb 服务 // MongoClient mongoClient = new MongoClient("localhost",27017); // MongoClient mongoClient = MongoClients.create(); //根据连接字符串来连接 // MongoClient mongoClient = MongoClients.create("mongodb://127.0.0.1:27017/mycol"); //不带数据库的情况 // MongoClient mongoClient = MongoClients.create("mongodb://127.0.0.1:27017/"); MongoClient mongoClient = MongoClients.create("mongodb://远程IP:27017/"); // 连接到数据库 MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol"); System.out.println("Connect to database successfully"); mongoDatabase.createCollection("testPro"); System.out.println("集合创建成功"); closeMongoClient(mongoDatabase,mongoClient); } public static void closeMongoClient(MongoDatabase mongoDataBase,MongoClient mongoClient ) { if (mongoDataBase != null) { mongoDataBase = null; } if (mongoClient != null) { mongoClient.close(); } System.out.println("CloseMongoClient successfully"); } }
标签:MongoClients,mongodb,create,mongoClient,连接,MongoClient,27017 来源: https://www.cnblogs.com/oktokeep/p/16337272.html