MongoDB:在 Java 中使用 MongoDB

除了通过启动 mongo 进程进如 Shell 环境访问数据库外,MongoDB 还提供了其他基于编程语言的访问数据库方法。MongoDB 官方提供了 Java 语言的驱动包,利用这些驱动包可使用多种编程方法来连接并操作 MongoDB 数据库。

想要在 Java 程序中使用 MongoDB,需要确保您的电脑上已经安装了 MongoDB,并搭建好了 Java 的环境。

本篇内容主要介绍:Java 实现对 MongDB 的操作、Java 操作 MongoDB 数据库 Demo



一、Java 实现对 MongDB 的操作

1、前提条件

除了通过启动 mongo 进程进如 Shell 环境访问数据库外,MongoDB 还提供了其他基于编程语言的访问数据库方法。MongoDB 官方提供了 Java 语言的驱动包,利用这些驱动包可使用多种编程方法来连接并操作 MongoDB 数据库。

想要在 Java 程序中使用 MongoDB,需要确保您的电脑上已经安装了 MongoDB,并搭建好了 Java 的环境。

2、添加依赖

在 Maven 中添加以下依赖来使用操作 MongoDB 数据库:

    <dependencies>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>bson</artifactId>
            <version>3.12.11</version>
        </dependency>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongodb-driver</artifactId>
            <version>3.12.11</version>
        </dependency>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongodb-driver-core</artifactId>
            <version>3.12.11</version>
        </dependency>
       
        ...
    </dependencies>

二、Java 操作 MongoDB 数据库 Demo

1、连接数据库
package com.lizhengi.demo;

import com.mongodb.client.MongoDatabase;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;

/**
 * @author liziheng
 * @version 1.0.0
 * @description 连接数据库
 * @date 2023-01-04 5:19 下午
 **/
public class ConnectToMongodb {

    public static void main(String[] args) {
        // 创建 MongoDB 连接
        MongoClient mongo = new MongoClient("localhost", 27017);

        // 连接到 MongoDB
        MongoCredential credential = MongoCredential.createCredential("lizhengi", "lizhengi", "password".toCharArray());
        System.out.println("Credentials ::" + credential);

        // 访问数据库
        MongoDatabase database = mongo.getDatabase("lizhengi");
        System.out.println("Connect to database successfully!");
        System.out.println("MongoDatabase info is : " + database.getName());
    }
}

运行 Main 函数,返回以下结果:

Credentials ::MongoCredential{mechanism=null, userName=‘lizhengi’, source=‘lizhengi’, password=, mechanismProperties=}
Connect to database successfully!
MongoDatabase info is : lizhengi

2、创建集合
package com.lizhengi.demo;

import com.mongodb.client.MongoDatabase;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;

/**
 * @author liziheng
 * @version 1.0.0
 * @description 创建集合
 * @date 2023-01-04 7:36 下午
 **/
public class CreatingCollection {
    public static void main(String[] args) {
        // 创建 MongoDB 连接
        MongoClient mongo = new MongoClient("localhost", 27017);

        // 连接到 MongoDB
        MongoCredential credential = MongoCredential.createCredential("lizhengi", "lizhengi", "password".toCharArray());
        System.out.println("Credentials ::" + credential);

        // 访问数据库
        MongoDatabase database = mongo.getDatabase("lizhengi");
        System.out.println("Connect to database successfully!");
        System.out.println("MongoDatabase info is : " + database.getName());

        // 创建集合
        database.createCollection("lizhengi_test_3");
        System.out.println("create collection successfully!");
    }
}

运行 Main 函数,返回以下结果:

Credentials ::MongoCredential{mechanism=null, userName=‘lizhengi’, source=‘lizhengi’, password=, mechanismProperties=}
Connect to database successfully!
MongoDatabase info is : lizhengi

create collection successfully!

3、列出所有集合
package com.lizhengi.demo;

import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

/**
 * @author liziheng
 * @version 1.0.0
 * @description 列出所有集合
 * @date 2023-01-04 7:56 下午
 **/
public class ListOfCollection {

    public static void main(String[] args) {
        // 创建 MongoDB 连接
        MongoClient mongo = new MongoClient("localhost", 27017);

        // 连接到 MongoDB
        MongoCredential credential = MongoCredential.createCredential("lizhengi", "lizhengi", "password".toCharArray());
        System.out.println("Credentials ::" + credential);

        // 访问数据库
        MongoDatabase database = mongo.getDatabase("lizhengi");
        System.out.println("Connect to database successfully!");
        System.out.println("MongoDatabase info is : " + database.getName());

        // 检索集合列表
        for (String name : database.listCollectionNames()) {
            System.out.println(name);
        }
    }
}

运行 Main 函数,返回以下结果:

Credentials ::MongoCredential{mechanism=null, userName=‘lizhengi’, source=‘lizhengi’, password=, mechanismProperties=}
Connect to database successfully!
MongoDatabase info is : lizhengi

lizhengi
lizhengi_test_3
lizhengi_test_2

4、获取/选择集合
package com.lizhengi.demo;

import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

/**
 * @author liziheng
 * @version 1.0.0
 * @description 获取/选择集合
 * @date 2023-01-04 7:40 下午
 **/
public class SelectingCollection {

    public static void main(String[] args) {
        // 创建 MongoDB 连接
        MongoClient mongo = new MongoClient("localhost", 27017);

        // 连接到 MongoDB
        MongoCredential credential = MongoCredential.createCredential("lizhengi", "lizhengi", "password".toCharArray());
        System.out.println("Credentials ::" + credential);

        // 访问数据库
        MongoDatabase database = mongo.getDatabase("lizhengi");
        System.out.println("Connect to database successfully!");
        System.out.println("MongoDatabase info is : " + database.getName());

        // 创建集合
        MongoCollection<Document> collection = database.getCollection("lizhengi");
        System.out.println("chose collection : " + collection.getNamespace());
    }
}

运行 Main 函数,返回以下结果:

Credentials ::MongoCredential{mechanism=null, userName=‘lizhengi’, source=‘lizhengi’, password=, mechanismProperties=}
Connect to database successfully!
MongoDatabase info is : lizhengi
chose collection : lizhengi.lizhengi

5、插入文档
package com.lizhengi.demo;

import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

/**
 * @author liziheng
 * @version 1.0.0
 * @description 插入文档
 * @date 2023-01-04 7:45 下午
 **/
public class InsertingDocument {

    public static void main(String[] args) {
        // 创建 MongoDB 连接
        MongoClient mongo = new MongoClient("localhost", 27017);

        // 连接到 MongoDB
        MongoCredential credential = MongoCredential.createCredential("lizhengi", "lizhengi", "password".toCharArray());
        System.out.println("Credentials ::" + credential);

        // 访问数据库
        MongoDatabase database = mongo.getDatabase("lizhengi");
        System.out.println("Connect to database successfully!");
        System.out.println("MongoDatabase info is : " + database.getName());

        // 检索集合
        MongoCollection<Document> collection = database.getCollection("lizhengi");
        System.out.println("chose collection : " + collection.getNamespace());

        Document document = new Document("title", "MongoDB")
                .append("description", "database")
                .append("likes", 200)
                .append("url", "https://lizhengi.blog.csdn.net/")
                .append("by", "lizhengi");

        // 将文档插入到集合中
        collection.insertOne(document);
        System.out.println("Document insert successfully!");
    }
}

运行 Main 函数,返回以下结果:

Credentials ::MongoCredential{mechanism=null, userName=‘lizhengi’, source=‘lizhengi’, password=, mechanismProperties=}
Connect to database successfully!
MongoDatabase info is : lizhengi
chose collection : lizhengi.lizhengi

Document insert successfully!

6、查询文档
package com.lizhengi.demo;

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;

/**
 * @author liziheng
 * @version 1.0.0
 * @description 查询文档
 * @date 2023-01-04 7:52 下午
 **/
public class RetrievingAllDocuments {

    public static void main(String[] args) {
        // 创建 MongoDB 连接
        MongoClient mongo = new MongoClient("localhost", 27017);

        // 连接到 MongoDB
        MongoCredential credential = MongoCredential.createCredential("lizhengi", "lizhengi", "password".toCharArray());
        System.out.println("Credentials ::" + credential);

        // 访问数据库
        MongoDatabase database = mongo.getDatabase("lizhengi");
        System.out.println("Connect to database successfully!");
        System.out.println("MongoDatabase info is : " + database.getName());

        // 检索集合
        MongoCollection<Document> collection = database.getCollection("lizhengi");
        System.out.println("chose collection : " + collection.getNamespace());

        // 获取 iterable 对象
        FindIterable<Document> iterDoc = collection.find();
        int i = 1;
        // 获取迭代器
        for (Document document : iterDoc) {
            System.out.println(document);
            i++;
        }
    }
}

运行 Main 函数,返回以下结果:

Credentials ::MongoCredential{mechanism=null, userName=‘lizhengi’, source=‘lizhengi’, password=, mechanismProperties=}
Connect to database successfully!
MongoDatabase info is : lizhengi
chose collection : lizhengi.lizhengi

Document{{_id=63b5676adcb7bc291eb5285d, title=MongoDB, description=database, likes=200, url=https://lizhengi.blog.csdn.net/, by=lizhengi}}
Document{{_id=63b568fa76a0f93c0a6c9f2a, title=MongoDB, description=database, likes=200, url=https://lizhengi.blog.csdn.net/, by=lizhengi2}}

7、更新文档
package com.lizhengi.demo;

import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
import org.bson.Document;

/**
 * @author liziheng
 * @version 1.0.0
 * @description 更新文档
 * @date 2023-01-04 7:59 下午
 **/
public class UpdatingDocuments {

    public static void main(String[] args) {
        // 创建 MongoDB 连接
        MongoClient mongo = new MongoClient("localhost", 27017);

        // 连接到 MongoDB
        MongoCredential credential = MongoCredential.createCredential("lizhengi", "lizhengi", "password".toCharArray());
        System.out.println("Credentials ::" + credential);

        // 访问数据库
        MongoDatabase database = mongo.getDatabase("lizhengi");
        System.out.println("Connect to database successfully!");
        System.out.println("MongoDatabase info is : " + database.getName());

        // 检索集合
        MongoCollection<Document> collection = database.getCollection("lizhengi");
        System.out.println("chose collection : " + collection.getNamespace());

        // 更新单个可用 updateOne
        collection.updateMany(Filters.eq("title", "MongoDB"), Updates.set("likes", 150));
        System.out.println("Document update successfully...");
        // 更新后检索文档
        // 获取 iterable 对象
        FindIterable<Document> iterDoc = collection.find();
        int i = 1;
        // 获取迭代器
        for (Document document : iterDoc) {
            System.out.println(document);
            i++;
        }
    }
}

运行 Main 函数,返回以下结果:

Credentials ::MongoCredential{mechanism=null, userName='lizhengi', source='lizhengi', password=<hidden>, mechanismProperties=<hidden>}
Connect to database successfully!
MongoDatabase info is : lizhengi
chose collection : lizhengi.lizhengi
Document update successfully...
Document{{_id=63b5676adcb7bc291eb5285d, title=MongoDB, description=database, likes=150, url=https://lizhengi.blog.csdn.net/, by=lizhengi}}
Document{{_id=63b568fa76a0f93c0a6c9f2a, title=MongoDB, description=database, likes=200, url=https://lizhengi.blog.csdn.net/, by=lizhengi2}}
8、删除文档
package com.lizhengi.demo;

import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import org.bson.Document;

/**
 * @author liziheng
 * @version 1.0.0
 * @description 删除文档
 * @date 2023-01-04 8:03 下午
 **/
public class DeletingDocuments {

    public static void main(String[] args) {
        // 创建 MongoDB 连接
        MongoClient mongo = new MongoClient("localhost", 27017);

        // 连接到 MongoDB
        MongoCredential credential = MongoCredential.createCredential("lizhengi", "lizhengi", "password".toCharArray());
        System.out.println("Credentials ::" + credential);

        // 访问数据库
        MongoDatabase database = mongo.getDatabase("lizhengi");
        System.out.println("Connect to database successfully!");
        System.out.println("MongoDatabase info is : " + database.getName());

        // 检索集合
        MongoCollection<Document> collection = database.getCollection("lizhengi");
        System.out.println("chose collection : " + collection.getNamespace());

        // 删除文档 删除多个可用 deleteMany
        collection.deleteOne(Filters.eq("title", "MongoDB"));
        System.out.println("Document delete successfully...");
        // 删除后检索文档
        // 获取 iterable 对象
        FindIterable<Document> iterDoc = collection.find();
        int i = 1;
        // 获取迭代器
        for (Document document : iterDoc) {
            System.out.println(document);
            i++;
        }
    }
}

运行 Main 函数,返回以下结果:

Credentials ::MongoCredential{mechanism=null, userName=‘lizhengi’, source=‘lizhengi’, password=, mechanismProperties=}
Connect to database successfully!
MongoDatabase info is : lizhengi
chose collection : lizhengi.lizhengi

Document delete successfully…
Document{{_id=63b568fa76a0f93c0a6c9f2a, title=MongoDB, description=database, likes=200, url=https://lizhengi.blog.csdn.net/, by=lizhengi2}}

9、删除集合
package com.lizhengi.demo;

import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

/**
 * @author liziheng
 * @version 1.0.0
 * @description 删除集合
 * @date 2023-01-04 8:06 下午
 **/
public class DropingCollection {

    public static void main(String[] args) {
        // 创建 MongoDB 连接
        MongoClient mongo = new MongoClient("localhost", 27017);

        // 连接到 MongoDB
        MongoCredential credential = MongoCredential.createCredential("lizhengi", "lizhengi", "password".toCharArray());
        System.out.println("Credentials ::" + credential);

        // 访问数据库
        MongoDatabase database = mongo.getDatabase("lizhengi");
        System.out.println("Connect to database successfully!");
        System.out.println("MongoDatabase info is : " + database.getName());

        // 检索集合
        MongoCollection<Document> collection = database.getCollection("lizhengi_test_3");
        System.out.println("chose collection : " + collection.getNamespace());
        // 删除集合
        collection.drop();
        System.out.println("drop collection : " + collection.getNamespace());

        // 检索集合列表
        for (String name : database.listCollectionNames()) {
            System.out.println(name);
        }
    }
}

运行 Main 函数,返回以下结果:

Credentials ::MongoCredential{mechanism=null, userName=‘lizhengi’, source=‘lizhengi’, password=, mechanismProperties=}
Connect to database successfully!
MongoDatabase info is : lizhengi
chose collection : lizhengi.lizhengi_test_3

drop collection : lizhengi.lizhengi_test_3
lizhengi
lizhengi_test_2

评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

栗筝i

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值