MongoDB实验——在Java应用程序中操作 MongoDB 数据

在Java应用程序中操作 MongoDB 数据

1. 启动MongoDB Shell

image-20221105195433796

2. 切换到admin数据库,使用root账户

在这里插入图片描述

3.开启Eclipse,创建Java Project项目,命名为MongoJava

File --> New --> Java Project

image-20221105200322144

4.在MongoJava项目下新建包,包名为mongo

MongoJava右键 --> New --> mongo

image-20221105200601149

5. 在mongo包下新建类,类名为mimalianjie

mongo右键 --> New --> Class

在这里插入图片描述

6. 添加项目依赖的jar包,右键单击MongoJava,选择Import

7. 选择General中的File System,点击Next

在这里插入图片描述

8. 选择存放mongo连接java的驱动程序的文件夹,并进行勾选Create top-level folder

image-20221105202015205

9. 选中导入的文件夹中的mongo-java-driver-3.2.2.jar,右击选择Build Path中的Add to Build Path。

10. 连接数据库:编写代码,功能为连接Mongodb数据库。我们需要指定数据库名称,如果指定的数据库不存在,mongo会自动创建数据库

package mongo;import java.util.ArrayList;import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoDatabase;public class mimalianjie {public static void main(String[] args) {try {ServerAddress serverAddress = new ServerAddress("localhost",27017);ArrayList<ServerAddress> addrs = new ArrayList<ServerAddress>();addrs.add(serverAddress);MongoCredential credential = MongoCredential.createScramSha1Credential("root", "admin", "strongs".toCharArray());ArrayList<MongoCredential> credentials = newArrayList<MongoCredential>();credentials.add(credential);MongoClient mongoClient = new MongoClient(addrs,credentials);MongoDatabase mongoDatabase = mongoClient.getDatabase("databaseName");System.out.println("Connect to database successfully");} catch (Exception e) {System.err.println( e.getClass().getName() + ": " + e.getMessage() );}}}

image-20221105203409301

11. 创建集合:与上述步骤相同,在mongo包下新建类,类名为chuangjianjihe,编写代码,功能为在test库下创建集合mycol(使用com.mongodb.client.MongoDatabase类中的createCollection()来创建集合)

package mongo;import java.util.ArrayList;import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoDatabase;public class chuanjianjihe {public static void main(String[] args) {try {ServerAddress serverAddress = new ServerAddress("localhost",27017);ArrayList<ServerAddress> addrs = new ArrayList<ServerAddress>();addrs.add(serverAddress);MongoCredential credential = MongoCredential.createScramSha1Credential("root","admin","strongs".toCharArray());ArrayList<MongoCredential> credentials = new ArrayList<MongoCredential>();credentials.add(credential);MongoClient mongoClient = new MongoClient(addrs,credentials);MongoDatabase mongoDatabase = mongoClient.getDatabase("test");System.out.println("Connect to database successfully");mongoDatabase.createCollection("mycol");System.out.println("集合mycol创建成功");}catch (Exception e) {System.err.println( e.getClass().getName() + ": " + e.getMessage());}}}

在这里插入图片描述

12. 在mongodb中进行验证

在这里插入图片描述

13. 获取集合:在mongo包下新建类,名为huoqujihe,并编写代码,功能为获取所需集合(使用com.mongodb.client.MongoDatabase类的 getCollection() 方法来获取一个集合)

package mongo;import java.util.ArrayList;import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;public class huoqujihe {public static void main(String[] args) {try {ServerAddress serverAddress = new ServerAddress("localhost",27017);ArrayList<ServerAddress> addrs = new ArrayList<ServerAddress>();addrs.add(serverAddress);MongoCredential credential = MongoCredential.createScramSha1Credential("root","admin","strongs".toCharArray());ArrayList<MongoCredential> credentials = new ArrayList<MongoCredential>();credentials.add(credential);MongoClient mongoClient = new MongoClient(addrs,credentials);MongoDatabase mongoDatabase = mongoClient.getDatabase("test");System.out.println("Connect to database successfully");MongoCollection<org.bson.Document> collection = mongoDatabase.getCollection("mycol");System.out.println("集合mycol选择成功");} catch (Exception e) {System.err.println( e.getClass().getName() + ": " + e.getMessage());}}}

image-20221105203826565

14.插入文档:在mongo包中新建类,名为charuwendang,功能为连接test库,选择mycol集合并向其中插入文档。(使用com.mongodb.client.MongoCollection类的insertMany()方法来插入一个文档)

package mongo;import java.util.ArrayList;
import java.util.List;import org.bson.Document;import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;public class charuwendang {public static void main (String[] args) {try {ServerAddress serverAddress = new ServerAddress("localhost",27017);ArrayList<ServerAddress> addrs = new ArrayList<ServerAddress>();addrs.add(serverAddress);MongoCredential credential = MongoCredential.createScramSha1Credential("root","admin","strongs".toCharArray());ArrayList<MongoCredential> credentials = new ArrayList<MongoCredential>();credentials.add(credential);MongoClient mongoClient = new MongoClient(addrs,credentials);MongoDatabase mongoDatabase = mongoClient.getDatabase("test");System.out.println("Connect to database successfully");MongoCollection<org.bson.Document> collection = mongoDatabase.getCollection("mycol");System.out.println("集合mycol选择成功");Document document = new Document("name", "zhangyudashuju").append("description", "YXCX").append("likes", 100).append("location", "BJ");List<Document> documents = new ArrayList<Document>();documents.add(document);collection.insertMany(documents);System.out.println("文档插入成功");}catch(Exception e) {System.err.println( e.getClass().getName() + ": " + e.getMessage() );}}
}

image-20221105203931797

15.在mongodb中进行查询验证

在这里插入图片描述

16. 检索文档:在mongo包中新建类,名为jiansuosuoyouwendang,功能为检索test库下,mycol集合中的所有文档(使用 com.mongodb.client.MongoCollection 类中的 find() 方法来获取集合中的所有文档)

package mongo;import java.util.ArrayList;import org.bson.Document;import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;public class jiansuosuoyouwendang {public static void main( String args[] ){try{ServerAddress serverAddress = new ServerAddress("localhost",27017);ArrayList<ServerAddress> addrs = new ArrayList<ServerAddress>();addrs.add(serverAddress);MongoCredential credential = MongoCredential.createScramSha1Credential("root","admin", "strongs".toCharArray());ArrayList<MongoCredential> credentials = new ArrayList<MongoCredential>();credentials.add(credential);MongoClient mongoClient = new MongoClient(addrs,credentials);MongoDatabase mongoDatabase = mongoClient.getDatabase("test");System.out.println("Connect to database successfully");MongoCollection<org.bson.Document> collection = mongoDatabase.getCollection("mycol");System.out.println("集合mycol选择成功");FindIterable<Document> findIterable = collection.find();MongoCursor<Document> mongoCursor = findIterable.iterator();while(mongoCursor.hasNext()){System.out.println(mongoCursor.next());}}catch(Exception e){System.err.println( e.getClass().getName() + ": " + e.getMessage() );}}
}

image-20221105204526011

17. 更新文档:在mongo包中新建类,名为gengxinwendang,功能为选择test库下mycol集合,将文档中的likes=100改为likes=200(使用 com.mongodb.client.MongoCollection 类中的updateMany()方法来更新集合中的文档)

package mongo;import java.util.ArrayList;import org.bson.Document;import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;public class gengxinwendang {public static void main( String args[] ){try{ServerAddress serverAddress = new ServerAddress("localhost",27017);ArrayList<ServerAddress> addrs = new ArrayList<ServerAddress>();addrs.add(serverAddress);MongoCredential credential = MongoCredential.createScramSha1Credential("root","admin", "strongs".toCharArray());ArrayList<MongoCredential> credentials = new ArrayList<MongoCredential>();credentials.add(credential);MongoClient mongoClient = new MongoClient(addrs,credentials);MongoDatabase mongoDatabase = mongoClient.getDatabase("test");System.out.println("Connect to database successfully");MongoCollection<org.bson.Document> collection = mongoDatabase.getCollection("mycol");System.out.println("集合mycol选择成功");collection.updateMany(Filters.eq("likes", 100), new Document("$set",new Document("likes",200)));FindIterable<Document> findIterable = collection.find();MongoCursor<Document> mongoCursor = findIterable.iterator();while(mongoCursor.hasNext()){System.out.println(mongoCursor.next());}}catch(Exception e){System.err.println( e.getClass().getName() + ": " + e.getMessage() );}}
}

image-20221105204700589

18. 在mongodb中进行查询验证

image-20221105204726180

19. 删除文档:在mongo包中新建类,名为sanchuwendang,功能为选择test库下mycol集合,删除所有符合条件(likes=200)的文档。(使用com.mongodb.DBCollection类中的findOne()方法来获取第一个文档,然后使用remove方法删除)

package mongo;import java.util.ArrayList;import org.bson.Document;import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;public class shanchuwendang {public static void main( String args[] ){try{ServerAddress serverAddress = new ServerAddress("localhost",27017);ArrayList<ServerAddress> addrs = new ArrayList<ServerAddress>();addrs.add(serverAddress);MongoCredential credential = MongoCredential.createScramSha1Credential("root","admin", "strongs".toCharArray());ArrayList<MongoCredential> credentials = new ArrayList<MongoCredential>();credentials.add(credential);MongoClient mongoClient = new MongoClient(addrs,credentials);MongoDatabase mongoDatabase = mongoClient.getDatabase("test");System.out.println("Connect to database successfully");MongoCollection<org.bson.Document> collection = mongoDatabase.getCollection("mycol");System.out.println("集合mycol选择成功");//删除符合条件的第一个文档//collection.deleteOne(Filters.eq("likes", 200));//删除所有符合条件的文档collection.deleteMany (Filters.eq("likes", 200));//检索查看结果FindIterable<Document> findIterable = collection.find();MongoCursor<Document> mongoCursor = findIterable.iterator();while(mongoCursor.hasNext()){System.out.println(mongoCursor.next());}}catch(Exception e){System.err.println( e.getClass().getName() + ": " + e.getMessage() );}}
}

image-20221105204811718

20. 在mongodb中进行查询验证

image-20221105205113965

查询结果为空,证明文档已被删除。

至此,实验结束!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/91126.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

关闭浏览器的跨域校验

首发博客地址 问题描述 当你访问资源失败&#xff0c;并遇到以下类似提示时&#xff1a; Access to script at 资源路径 from origin null has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, isolated-app, chrom…

【原创】jmeter并发测试计划

bankQPS 创建线程组 设置并发参数 HTTP请求GET 添加HTTP请求 GET请求 查看结果树 HTTP请求 POST 添加HTTP请求 参数必须设置头信息格式&#xff1a; 添加HTTP头信息 查看结果树 可以选择&#xff0c;仅查看错误日志 汇总报告

LiteOS qemu realview-pbx-a9 环境搭建与运行

前言 最近打算移植搭建 一些常见的 RTOS 的 qemu 开发学习环境&#xff0c;当前 RT-Thread、FreeRTOS 已经成功运行 qemu&#xff0c;LiteOS 初步验证可以正常 运行 qemu realview-pbx-a9&#xff0c;这里做个记录 首先学习或者研究 RTOS&#xff0c;只是看内核源码&#xff0…

kubesphere中部署grafana实现dashboard以PDF方式导出

1&#xff0c;部署grafana-image-renderer 2&#xff0c;部署grafana GF_RENDERING_SERVER_URL http://ip:30323/render #grafana-image-renderer地址 GF_RENDERING_CALLBACK_URL http://ip:32403/ #grafana地址 GF_LOG_FILTERS rend…

Unity碰撞检测(3D和2D)

Unity碰撞检测3D和2D 前言准备材料3D2D 代码3D使用OnCollisionEnter()进行碰撞Collider状态代码 使用OnTriggerEnter()进行碰撞Collider状态代码 2D使用OnCollisionEnter2D()进行碰撞Collider2D状态代码 使用OnTriggerEnter2D()进行碰撞Collider2D状态代码 区别3D代码OnCollisi…

数据结构:八种数据结构大全

数据结构 1.1 数据结构概述 数据结构是计算机存储、组织数据的方式&#xff1b;通常情况下&#xff0c;精心选择的数据结构可以带来更高的运行或者存储效率。数据结构的优良将直接影响着我们程序的性能&#xff1b;常用的数据结构有&#xff1a;数组&#xff08;Array&#xff…

Baklib是比语雀、Notion、石墨文档更好用的在线知识库管理工具

在当今信息爆炸的时代&#xff0c;如何高效地管理和利用知识成为了每个人都面临的问题。在线知识库管理工具应运而生&#xff0c;帮助用户整理、存储和共享知识。在这篇文章中&#xff0c;我将介绍一个更好用的在线知识库管理工具——Baklib&#xff0c;并探讨它相对于其他知识…

解决Android Studio中Plugin version和Gradle version不匹配的问题

生命中最艰难的那段路是要自己一个人走过来的&#xff0c;这样&#xff0c;学到更多的是坚强&#xff0c;而不是感动。 《红猪》 前言 导入一个百度云的Demo而已&#xff0c;居然遇到这么多问题&#xff0c;纠结了很久&#xff0c;也查了很多资料&#xff0c;弯弯绕绕了好多路…

小米手机便签怎么导出到华为mate60Pro手机上?

华为mate60Pro手机于2023年8月29日发布了先锋计划&#xff0c;有不少网友都抢到了这款新机。而有一些网友表示自己在换手机之前遇到了问题&#xff0c;这就是之前使用的手机是小米&#xff0c;所以需要把重要的图片、短信、通讯录、便签等数据导出到新的手机上&#xff0c;但是…

ubuntu20.04 编译安装运行emqx

文章目录 安装依赖编译运行登录dashboard压力测试 安装依赖 Erlang/OTP OTP 24 或 25 版本 apt-get install libncurses5-dev sudo apt-get install erlang如果安装的erlang版本小于24的话&#xff0c;可以使用如下方法自行编译erlang 1.源码获取 wget https://github.com/erla…

springBoot--终

目录 Web定制SpringMVC定制某些mvc配置定制mvc核心组件完全自定义mvc 静态资源静态资源映射静态资源缓存示例自定义静态资源规则配置方式代码方式 欢迎页Favicon&#xff08;网站图标&#xff09;路径匹配策略内容协商制定返回json类型数据制定返回xml类型数据制定返回自定义类…

Matlab 使用经验分享(常用函数介绍;矩阵常见计算)

Matlab 使用经验分享 大家好&#xff01;最近有很多朋友询问我关于 Matlab 的使用&#xff0c;于是我决定写一篇博客来分享一下我的经验。对于数学和编程爱好者来说&#xff0c;Matlab 是一个非常有用的工具。我自己在数学实验和数学建模竞赛中也经常使用它。那么&#xff0c;…