用Java操作Mongodb实现CRUD

举报
大数据梦想家 发表于 2021/09/28 22:38:18 2021/09/28
【摘要】         本篇博客,为大家带来在IDEA上通过Java代码实现Mongodb的CRUD操作! 文章目录 一....

        本篇博客,为大家带来在IDEA上通过Java代码实现Mongodb的CRUD操作!
在这里插入图片描述


一.连接数据库

        连接数据库一共有两种方法,分别为不通过认证获取连接数据库对象需要密码认证方式连接两种方式。因为对Mongodb数据库的每一步操作都需要先连接数据库,建议把连接数据库的操作封装到一个工具类方便后续的使用!

package com.czxy.mongodb;

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

import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: Alice菌
 * @Date: 2020/3/6 19:41
 * @Description: 流年笑掷 未来可期。以梦为马,不负韶华!
 */

// mongodb 连接数据库工具类
public class MongoDBUtil {
    // 不通过认证获取连接数据库对象
    public static MongoDatabase getConnect1(){

        // 连接到 mongodb 服务
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        // 连接到数据库
        MongoDatabase mongoDatabase = mongoClient.getDatabase("demo0304");
        // 返回连接数据库对象
        return mongoDatabase;

    }

    // 需要密码认证方式连接
    public static MongoDatabase getConnect2(){
        List<ServerAddress> adds = new ArrayList<>();
        //ServerAddress()两个参数分别为 服务器地址 和 端口
        ServerAddress serverAddress = new ServerAddress("localhost", 27017);
        adds.add(serverAddress);
        List<MongoCredential> credentials = new ArrayList<>();
        //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
        MongoCredential mongoCredential = MongoCredential.createScramSha1Credential("root", "demo0304", "root".toCharArray());
        credentials.add(mongoCredential);
        //通过连接认证获取MongoDB连接
        MongoClient mongoClient = new MongoClient(adds, credentials);
        //连接到数据库
        MongoDatabase mongoDatabase = mongoClient.getDatabase("demo0304");
        //返回连接数据库对象
        return mongoDatabase;

    }



}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52

二.插入文档

<1>插入一个文档

/**
     *  插入一个文档(对应于关系型数据库表中的一行)
     */
    @Test
    public void insertOneTest(){
        // 获取数据库连接对象
        MongoDatabase mongoDatabase = MongoDBUtil.getConnect1();
        // 获取集合
        MongoCollection<Document> collection = mongoDatabase.getCollection("table_01");
        // 创建文档对象<要插入的数据>
        Document document = new Document("name", "张三")
                          .append("sex","男")
                          .append("age",18);
        // 插入一个文档
        collection.insertOne(document);

    }

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

<2>插入多个文档

/**
     * 插入多个文档
     */
    @Test
    public void insertManyTest(){

        // 获取数据库连接对象
        MongoDatabase mongoDatabase = MongoDBUtil.getConnect1();
        // 获取集合
        MongoCollection<Document> collection = mongoDatabase.getCollection("table_01");
        // 要插入的数据
        List<Document> list = new ArrayList<>();
        for (int i = 1; i <= 3 ; i++) {

            Document document = new Document("name", "张三")
                    .append("sex","男")
                    .append("age",18);
            list.add(document);

        }

        // 插入多个文档
        collection.insertMany(list);
    }

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

三.删除文档

<1>删除与筛选器匹配的单个文档

/**
     * 删除与筛选器匹配的单个文档
     */
    @Test
    public void deleteOneTest(){

        // 获取数据库连接对象
        MongoDatabase mongoDatabase = MongoDBUtil.getConnect1();
        // 获取集合
        MongoCollection<Document> collection = mongoDatabase.getCollection("table_01");
        //申明删除条件
        Bson filter = Filters.eq("age",18);
        //删除与筛选器匹配的单个文档
        collection.deleteOne(filter);

    }

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

<2>删除与筛选器匹配的所有文档

    /**
     * 删除与筛选器匹配的所有文档
     */
    @Test
    public void deleteManyTest(){
        //获取数据库连接对象
        MongoDatabase mongoDatabase = MongoDBUtil.getConnect1();
        //获取集合
        MongoCollection<Document> collection = mongoDatabase.getCollection("table_01");
        //申明删除条件
        Bson filter = Filters.eq("age",18);
        //删除与筛选器匹配的所有文档
        collection.deleteMany(filter);


    }

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

四.修改文档

<1>修改单个文档

  /**
     * 修改单个文档
     */
    @Test
    public void updateOneTest(){

        //获取数据库连接对象
        MongoDatabase mongoDatabase = MongoDBUtil.getConnect1();
        //获取集合
        MongoCollection<Document> collection = mongoDatabase.getCollection("table_01");
        //修改过滤器
        Bson filter = Filters.eq("name", "张三");
        //指定修改的更新文档
        Document document = new Document("$set", new Document("age", 100));
        //修改单个文档
        collection.updateOne(filter, document);

    }

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

<2>修改多个文档

    /**
     * 修改多个文档
     */
    @Test
    public void updateManyTest(){

        //获取数据库连接对象
        MongoDatabase mongoDatabase = MongoDBUtil.getConnect2();
        //获取集合
        MongoCollection<Document> collection = mongoDatabase.getCollection("table_01");
        //修改过滤器
        Bson filter = Filters.eq("name", "张三");
        //指定修改的更新文档
        Document document = new Document("$set", new Document("age", 100));
        //修改单个文档
        collection.updateMany(filter, document);

    }

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

五.查询文档

<1>查询所有

    /**
     * 查询集合中的所有文档
     */
    @Test
    public void findTest(){

        //获取数据库连接对象
        MongoDatabase mongoDatabase = MongoDBUtil.getConnect1();
        //获取集合
        MongoCollection<Document> collection = mongoDatabase.getCollection("table_01");

        //查找集合中的所有文档
        FindIterable findIterable = collection.find();
        MongoCursor cursor = findIterable.iterator();
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }

    }

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

<2>查询第一个文档

 /**
     * 查询到的第一个文档
     */
    @Test
    public void findFirstTest(){
        //获取数据库连接对象
        MongoDatabase mongoDatabase = MongoDBUtil.getConnect1();
        //获取集合
        MongoCollection<Document> collection = mongoDatabase.getCollection("table_01");
        //查找集合中的所有文档
        FindIterable findIterable = collection.find();
        //取出查询到的第一个文档
        Document document = (Document) findIterable.first();
        //打印输出
        System.out.println(document);

    }

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

<3>指定过滤器查询

   /**
     * 指定查询过滤器查询
     */
    @Test
    public void FilterfindTest(){
        //获取数据库连接对象
        MongoDatabase mongoDatabase = MongoDBUtil.getConnect1();
        //获取集合
        MongoCollection<Document> collection = mongoDatabase.getCollection("table_01");
        //指定查询过滤器
        Bson filter = Filters.eq("name", "张三");
        //指定查询过滤器查询
        FindIterable findIterable = collection.find(filter);
        MongoCursor cursor = findIterable.iterator();

        //迭代器遍历
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    }

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

        上述的所有代码博主亲测,都能成功运行,小伙伴们大可不必担心。

        本次的记录分享就到这里,受益的朋友不妨点个赞支持一下~

在这里插入图片描述

文章来源: alice.blog.csdn.net,作者:大数据梦想家,版权归原作者所有,如需转载,请联系作者。

原文链接:alice.blog.csdn.net/article/details/104704828

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。