mongoDB-javaAPI

mongoDB-javaAPI

丁起男 65 2022-05-26

mongoDB-javaAPI

导入依赖

        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>3.12.6</version>
        </dependency>

使用

        try {
            //连接到服务
            MongoClient mongoClient = new MongoClient(MONGO_HOST, MONGO_PORT);
            //连接到数据库
            MongoDatabase database = mongoClient.getDatabase(MONGO_DB);
            //创建集合
            database.createCollection("t1");
            //获取集合
            MongoCollection<Document> t1 = database.getCollection("t1");
            //插入文档
            Document document = new Document().append("k1", "v1").append("k2", "v2")
                    .append("k3", new Document("sk1", "sv1").append("sk2", "sv2"));
            t1.insertOne(document);
            //统计数量
            System.out.println(t1.countDocuments());
            //获取第一条文档
            Document first = t1.find().first();
            System.out.println(first.toJson());
            //获取所有文档
            MongoCursor<Document> iterator = t1.find().iterator();
            try {
                while (iterator.hasNext()){
                    System.out.println(iterator.next().toJson());
                }
            }finally {
                iterator.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }