当前位置: 首页 > news >正文

【MongoDB】三、使用Java连接MongoDB

【MongoDB】三、使用Java连接MongoDB

  • 实验目的
  • 实验内容
    • 练习
      • 1、开启Eclipse,创建Java Project项目,命名为Mongo1
      • 2、添加项目依赖的jar包
      • 3、创建类MongoDemo
      • 4、连接数据库
      • 5、查看集合
      • 6、创建集合
      • 7、删除集合
      • 8、查看文档
      • 9、插入文档
      • 10、更新文档
      • 11、删除文档
    • 测试
      • 新建集合course
      • 删除新建集合course
      • 在student集合中插入文档
      • 将_id为1014的学生成绩修改为80
      • 删除_id为1012的学生
  • 实验小结


实验目的

(1)了解使用Java操作MongoDB的流程;
(2)能够编写Java操作MongoDB的代码。


实验内容

练习

1、开启Eclipse,创建Java Project项目,命名为Mongo1

在这里插入图片描述


2、添加项目依赖的jar包

在这里插入图片描述


3、创建类MongoDemo

       在类的构造函数MongoDemo()中编写代码实现对MongoDB服务器的连接。

MongoClient connection =null;  //存储MongoDB数据库连接对象MongoDatabase db=null;   //存储连接的数据库对象public MongoDemo() {ServerAddress serverAddress = new ServerAddress("127.0.0.1", 27017);// 第一个"root" 为账号,第二个"admin"为创建账户时的数据库名称,第三个参数为密码MongoCredential mongoCredential = MongoCredential.createCredential("root", "admin", "123456".toCharArray());//MongoClientOptions 是连接的相关配置,类似数据库连接池的相关配置,使用默认即可connection = new MongoClient(serverAddress,mongoCredential, MongoClientOptions.builder().build());             }

4、连接数据库

       在类MongoDemo中定义DatabaseConn ()方法,用来连接指定的数据库。

public void DatabaseConn(String dbName) {db = connection.getDatabase(dbName);}
mongdemo.DatabaseConn("stu");

5、查看集合

       在类MongoDemo中定义getCollection ()方法,主要用于查看数据库中的集合。

public void getCollection() {MongoIterable<String> listCollectionNames = db.listCollectionNames();// 获取db数据库中的集合列表for (String collectionName : listCollectionNames) {System.out.println(collectionName.toString());}}

6、创建集合

       在类MongoDemo中定义createCollection ()方法,主要用于创建集合。

//创建集合public void createCollection(String collectionname){db.createCollection(collectionname);}

7、删除集合

       在类MongoDemo中定义dropCollection()方法,主要用于删除集合。

//删除集合public void dropCollection(String collectionname){MongoCollection<Document> collection = db.getCollection(collectionname);collection.drop();}

8、查看文档

       在类MongoDemo中定义findDocument ()方法,主要用于查看文档。

//查看文档public void findDocument(String collectionname){MongoCollection<Document> collection =db.getCollection(collectionname);FindIterable<Document> documents = collection.find();System.out.println("集合"+collectionname+"中的文档有:");for (Document document : documents) {System.out.println(document);}}

9、插入文档

       在类MongoDemo中定义insertOneDocument()方法,主要用于插入单个文档。

//插入文档public void insertOneDocument(String collectionname,Document document){MongoCollection<Document> collection = db.getCollection(collectionname);      collection.insertOne(document);}

10、更新文档

       在类MongoDemo中定义updateDocument ()方法,主要用于更新文档。

//更新文档public void updateDocument(String collectionname){MongoCollection<Document> collection =db.getCollection(collectionname);//修改的键以及修改的值Document document = new Document("score","80");//用作修改collection.updateOne(Filters.eq("_id","1014"),new Document("$set",document));}

11、删除文档

       在类MongoDemo中定义deleteDocument()方法,主要用于删除文档。

//删除文档public void deleteDocument(String collectionname){MongoCollection<Document> collection = db.getCollection(collectionname);collection.deleteOne(Filters.eq("_id","1012"));}

测试

       在类MongoDemo中定义主函数main(),主要对以上定义的功能函数进行测试。在主函数中连接数据库stu,在数据库stu中新建集合course,删除新建集合course,在student集合中插入文档{_id:“1016”,name:“唐开平”,sex:“女”,age:18,major:“软件技术”,credits:42,score:74},将_id为1014的学生成绩修改为80,删除_id为1012的学生。

新建集合course

mongdemo.createCollection("course");
mongdemo. getCollection();

删除新建集合course

mongdemo.dropCollection("course");
mongdemo.getCollection();

在student集合中插入文档

Document document = new Document("_id","1016").append("name", "唐开平").append("sex", "女").append("age","18").append("major", "软件技术").append("credits", "42").append("score", "74");
mongdemo.insertOneDocument("students",document);
mongdemo.findDocument("students");

将_id为1014的学生成绩修改为80

	//更新文档public void updateDocument(String collectionname){MongoCollection<Document> collection =db.getCollection(collectionname);//修改的键以及修改的值Document document = new Document("score","80");//用作修改collection.updateOne(Filters.eq("_id","1014"),new Document("$set",document));}
mongdemo.updateDocument("students");	
mongdemo.findDocument("students");

删除_id为1012的学生

//删除文档public void deleteDocument(String collectionname){MongoCollection<Document> collection = db.getCollection(collectionname);collection.deleteOne(Filters.eq("_id","1012"));}  mongdemo.deleteDocument("students");
mongdemo.findDocument("students");

实验小结

       通过本次实验,我掌握了通过使用Java连接MongoDB的具体流程以及使用Java对MongoDB数据库进行的增删改查等一系列操作。在实验过程中遇到了很多硬件或者是软件上的问题,请教老师,询问同学,上网查资料,都是解决这些问题的途径。最终将遇到的问题一一解决最终完成实验。
注意事项:
1、有疑问前,知识学习前,先用搜索。
2、熟读写基础知识,学得会不如学得牢。
3、选择交流平台,如QQ群,网站论坛等。
4、尽我能力帮助他人,在帮助他人的同时你会深刻巩固知识。

http://www.lryc.cn/news/93936.html

相关文章:

  • 【C++】通讯录的基本实现,附有源码分享
  • UI 自动化测试 —— selenium的简单介绍和使用
  • mybatisPlus中apply的使用以进行联表等复杂sql语句
  • 自学Python技术的方法
  • python熟悉python基础语法,了解html网络结构,了解json格式数据,含有字符串
  • linux mail -s发送邮件异常解决
  • Netty核心技术七--Google Protobuf
  • 【Docker】Docker常用命令总结
  • React 对比class与Effect Hook优化响应式数据更新监听,感受useEffect真正的强大
  • AWS Lambda 介绍
  • linux之权限管理
  • 【设计模式与范式:行为型】61 | 策略模式(下):如何实现一个支持给不同大小文件排序的小程序?
  • 【C++】auto_ptr为何被唾弃?以及其他智能指针的学习
  • 数据结构练习题1:基本概念
  • 如何消除Msxml2.XMLHTTP组件的缓存
  • 深入理解Java虚拟机jvm-运行时数据区域(基于OpenJDK12)
  • (OpenCV) 基础demo
  • using 的使用
  • Websocket、Socket、HTTP之间的关系
  • hustoj LiveCD版系统在局域网虚拟机安装和配置
  • 读书-代码整洁之道10-14
  • UDP 广播/组播
  • 高效创作助手:ChatGPT最新版实现批量撰写聚合文章的全新水平
  • Python中的包是什么,如何创建和使用包?
  • Spring Cloud Alibaba Seata(二)
  • 如何在 MySQL 中使用 COALESCE 函数
  • Python爬虫之Scrapy框架系列(22)——初识分布式爬虫scrapy_redis
  • ChatGPT的前世今生
  • WireShark常用协议抓包与原理分析
  • Mysql数据库操作总结