Java中使用MongoDB数据库_java执行mongodb命令

yumo6662个月前 (08-28)技术文章14

一、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.db.demo;

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

/**
 * @version 1.0.0
 * @description 连接数据库
 **/
public class ConnectToMongodb {

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

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

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

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

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

2、创建集合

package com.db.demo;

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

/**
 * @version 1.0.0
 * @description 创建集合
 **/
public class CreatingCollection {
    public static void main(String[] args) {
        // 创建 MongoDB 连接
        MongoClient mongo = new MongoClient("localhost", 27017);

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

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

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

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

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

create collection successfully!

3、列出所有集合

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

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

        // 访问数据库
        MongoDatabase database = mongo.getDatabase("study");
        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=‘study’, source=‘study’, password=, mechanismProperties=}
Connect to database successfully!
MongoDatabase info is : study

study
study_test_3
study_test_2

4、获取/选择集合

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

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

chose collection : study.study

5、插入文档

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

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

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

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

        Document document = new Document("title", "MongoDB")
                .append("description", "database")
                .append("likes", 200)
                .append("url", "https://study.xxx.xx/")
                .append("by", "study");

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

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

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

Document insert successfully!

6、查询文档

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

7、更新文档

.....
// 更新单个可用 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++;
}
......

8、删除文档

......
// 删除文档 删除多个可用 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++;
}
......

9、删除集合

......
// 删除集合
collection.drop();
System.out.println("drop collection : " + collection.getNamespace());
.....

相关文章

有了这些库,Android 开发效率提升好几倍

在 Android 开发的过程中,每个开发者或多或少的都使用过第三方开源库,使用第三方开源库可以大大减少开发者的精力和时间,从而更好的关注应用本身的业务逻辑。网络相关OkHttp一个处理网络请求的开源...

免装环境!SQLite 可视化神器,Java 开发者速通指南

作为 Java 开发者,你是否常为 SQLite 数据库的操作头疼?手写 SQL 建表、查数据太繁琐,命令行工具交互效率低,第三方库集成又容易踩坑?今天要安利的「DB Browser for SQLi...

基于Java实现,支持在线发布API接口读取数据库,有哪些工具?

基于java实现,不需要编辑就能发布api接口的,有哪些工具、平台?还能一键发布、快速授权和开放提供给第三方请求调用接口的解决方案。架构方案设计:以下是一些基于 Java 实现的无需编辑或只需少量编辑...

牛哇!MySQL中的日志“binlog”的三种格式这么好玩

MySQL 中的日志比较重要的有 binlog(归档日志)、redo log(重做日志)以及 undo log,那么跟我们本文相关的主要是 binlog,另外两个日志松哥将来有空了再和大家详细介绍。1...

「免费开源代码」java多商户电商系统

三勾商城多商户是开发友好的微信小程序商城,框架支持SAAS,支持发布 iOS + Android + 公众号 + H5 + 各种小程序(微信/支付宝/百度/头条/QQ/钉钉/淘宝)等多个平台,不可多得...