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");

    }

}

 

posted on 2022-06-02 11:53  oktokeep  阅读(123)  评论(1编辑  收藏  举报