Java中使用MongoDB数据库实例Demo

 更新时间:2023年12月09日 16:20:40   作者:栗筝i  
MongoDB是由C++语言编写的,基于分布式文件存储的数据库,是一个介于关系数据库和非关系数据库之间的产品,是最接近于关系型数据库的NoSQL数据库,下面这篇文章主要给大家介绍了关于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

总结 

到此这篇关于Java中使用MongoDB数据库的文章就介绍到这了,更多相关Java使用MongoDB内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • bool当成函数参数错误理解

    bool当成函数参数错误理解

    经常会在函数的参数里使用bool参数,这会大大地降低代码的可读性
    2012-11-11
  • springboot 如何重定向redirect 并隐藏参数

    springboot 如何重定向redirect 并隐藏参数

    这篇文章主要介绍了springboot 如何重定向redirect 并隐藏参数的操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-09-09
  • java 实现多线程的方法总结

    java 实现多线程的方法总结

    这篇文章主要介绍了java 实现多线程的方法总结的相关资料,需要的朋友可以参考下
    2016-10-10
  • JAVA多线程抢红包的实现示例

    JAVA多线程抢红包的实现示例

    这篇文章主要介绍了JAVA多线程抢红包的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-03-03
  • Java日志相关技术_动力节点Java学院整理

    Java日志相关技术_动力节点Java学院整理

    这篇文章主要介绍了Java日志相关技术_动力节点Java学院整理的相关资料,需要的朋友可以参考下
    2017-07-07
  • SpringBoot项目Jar包如何瘦身部署的实现

    SpringBoot项目Jar包如何瘦身部署的实现

    这篇文章主要介绍了SpringBoot项目Jar包如何瘦身部署的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-09-09
  • Spring Cache+Redis缓存数据的实现示例

    Spring Cache+Redis缓存数据的实现示例

    本文主要介绍了Spring Cache+Redis缓存数据,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-01-01
  • Java如何构造DSL方法重构

    Java如何构造DSL方法重构

    这篇文章主要介绍了Java如何构造DSL方法重构,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的小伙伴可以参考价值
    2022-07-07
  • SpringAOP+RabbitMQ+WebSocket实战详解

    SpringAOP+RabbitMQ+WebSocket实战详解

    这篇文章主要介绍了SpringAOP+RabbitMQ+WebSocket实战详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-11-11
  • Springboot实现VNC的反向代理功能

    Springboot实现VNC的反向代理功能

    这篇文章主要介绍了Springboot实现VNC的反向代理,搭建过程也很简单,通过注册bean拦截指定URL路径进行自定义操作,具体实例代码跟随小编一起看看需要的朋友可以参考下
    2021-09-09

最新评论