java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java使用MongoDB

Java中使用MongoDB数据库实例Demo

作者:栗筝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内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文