文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

MongoDB:在 Java 中使用 MongoDB

2023-09-14 09:12

关注

除了通过启动 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.mongodbgroupId>            <artifactId>bsonartifactId>            <version>3.12.11version>        dependency>        <dependency>            <groupId>org.mongodbgroupId>            <artifactId>mongodb-driverartifactId>            <version>3.12.11version>        dependency>        <dependency>            <groupId>org.mongodbgroupId>            <artifactId>mongodb-driver-coreartifactId>            <version>3.12.11version>        dependency>               ...    dependencies>

二、Java 操作 MongoDB 数据库 Demo

1、连接数据库

package com.lizhengi.demo;import com.mongodb.client.MongoDatabase;import com.mongodb.MongoClient;import com.mongodb.MongoCredential;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;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;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;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;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;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;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=, mechanismProperties=}Connect to database successfully!MongoDatabase info is : lizhengichose collection : lizhengi.lizhengiDocument 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;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;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

来源地址:https://blog.csdn.net/weixin_45187434/article/details/128553717

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     807人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     351人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     314人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     433人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     221人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯