mongodb连接类

2022/6/3 2:20:21

本文主要是介绍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");

    }

}

 



这篇关于mongodb连接类的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程