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.mzph.cn/news/60681.shtml

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

相关文章

Android scrollTo、scrollBy、以及scroller详解 自定义ViewPager

Scroller VelocityTracker VelocityTracker 是一个速度跟踪器&#xff0c;通过用户操作时&#xff08;通常在 View 的 onTouchEvent 方法中&#xff09;传进去一系列的 Event&#xff0c;该类就可以计算出用户手指滑动的速度&#xff0c;开发者可以方便地获取这些参数去做其他…

【期末复习笔记】计算机操作系统

计算机操作系统 进程的描述与控制程序执行进程进程的定义与特征相关概念定义特征进程与程序的区别 进程的基本状态和转换PCBPCB中的信息作用PCB的组织方式 线程进程与线程的比较 处理机调度与死锁处理机调度处理机调度的层次 调度算法处理机调度算法的目标处理机调度算法的共同…

大语言模型之五 谷歌Gemini

近十年来谷歌引领着人工智能方向的发展&#xff0c;从TensorFlow到TPU再到Transformer&#xff0c;都是谷歌在引领着&#xff0c;然而&#xff0c;在大语言模型上&#xff0c;却被ChatGPT&#xff08;OpenAI&#xff09;抢了风头&#xff0c;并且知道GPT-4&#xff08;OpenAI&a…

7.Oracle视图创建与使用

1、视图的创建与使用 在所有进行的SQL语句之中&#xff0c;查询是最复杂的操作&#xff0c;而且查询还和具体的开发要求有关&#xff0c;那么在开发过程之中&#xff0c;程序员完成的并不是是和数据库的所有内容&#xff0c;而更多的是应该考虑到程序的设计结构。可以没有一个项…

854之数据结构

一.线性表 1.顺序表 #include <iostream> #include<stdlib.h> using namespace std; #define max 100 typedef struct {int element[max];int last; } List; typedef int position ; void Insert(int x, position p, List &L) {position q;if (L.last > ma…

关于Vue CLI项目 运行发生了 less-lorder错误的解决方案

Module node found :Error: Can’t resolve ‘less-loader’ 报错 文章目录 Module node found :Error: Cant resolve less-loader 报错解决方案&#xff1a;安装 webpack 和 less安装 less-loader 问题&#xff1a; 在运行vue项目的时候发生&#xff1a; Module not found: Er…

删除无点击数据offer数据分析使用

梳理思路&#xff1a; 1、 获取 7month 和 8month fullreport 报表中 所有offer&#xff1b;输出结果&#xff1a;offerid&#xff0c; totalClickCount&#xff1b; 2、 分析数据7month totalClickCount0 and 8month totalClickCount0 的offer去除&#xff1b; result.…

Python报错DeprecationWarning: invalid escape sequence ‘\T‘

在Python中&#xff0c;如果在字符串中使用反斜杠&#xff0c;需要使用转义字符&#xff08;例如\n代表换行符&#xff09;。当您需要一个反斜杠时&#xff0c;但没有转义字符时&#xff0c;会出现上述错误。 为了解决此错误&#xff0c;您可以在路径字符串前面添加“r”以表示…

【教程分享】Docker搭建Zipkin,实现数据持久化到MySQL、ES

1 拉取镜像 指定版本&#xff0c;在git查看相应版本&#xff0c;参考&#xff1a; https://github.com/openzipkin/zipkin 如2.21.7 docker pull openzipkin/zipkin:2.21.7 2 启动 Zipkin默认端口为9411。启动时通过-e server.portxxxx设置指定端口 docker run --name zi…

数据结构--KMP算法

模板&#xff1a; // s[]是长文本&#xff0c;p[]是模式串&#xff0c;n是s的长度&#xff0c;m是p的长度 求模式串的Next数组&#xff1a; for (int i 2, j 0; i < m; i ) {while (j && p[i] ! p[j 1]) j ne[j];if (p[i] p[j 1]) j ;ne[i] j; }// 匹配 f…

Windows系统下几个占用C盘比较大空间的程序及位置

WPS 1G C:\Users\Thinkpad\AppData\Roaming\kingsoft\wps\addons\ VSCode 10G C:\Users\Thinkpad\AppData\Roaming\Code\User\workspaceStorage\ Python的模块 可以使用虚拟环境venv Maven本地缓存 更改配置文件&#xff0c;设置缓存位置 NodeJS 配置全局变量和模块存放位置…

无涯教程-Android - RadioGroup函数

RadioGroup类用于单选按钮集。 如果我们选中属于某个单选按钮组的一个单选按钮,它将自动取消选中同一组中以前选中的任何单选按钮。 RadioGroup属性 以下是与RadioGroup控制相关的重要属性。您可以查看Android官方文档以获取属性的完整列表以及可以在运行时更改这些属性的相关…

IDEA、git如何修改历史提交commit的邮箱

第一种情况&#xff1a;当前提交不是从其他分支clone过来的&#xff1a; step1&#xff1a; git log 查看提交日志&#xff0c;获取commit ID step2&#xff1a; git rebase -i [你的commitID] git rebase -i c2ef237854290051bdcdb50ffbdbb78481d254bb step3&#xff1a;…

可视化工具 netron pt 转 onnx 格式

用于学习记录 文章目录 前言一、Netron 在线使用二、pt 格式转换为 ONNX 格式总结 前言 Netron 是一个开源的网络可视化工具&#xff0c;可以帮助开发人员和数据科学家可视化、理解和调试深度学习模型。它支持多种常见模型格式&#xff0c;如 TensorFlow、PyTorch、ONNX、Caff…

企业网络安全:威胁情报解决方案

什么是威胁情报 威胁情报是网络安全的关键组成部分&#xff0c;可为潜在的恶意来源提供有价值的见解&#xff0c;这些知识可帮助组织主动识别和防止网络攻击&#xff0c;通过利用 STIX/TAXII 等威胁源&#xff0c;组织可以检测其网络中的潜在攻击&#xff0c;从而促进快速检测…

网络中的问题2

距离-向量算法的具体实现 每个routerY的路由表表项 involve<目的网络N&#xff0c;距离d&#xff0c;下一跳X> 对邻居X发来的报文,先把下一跳改为X,再把距离1,if original route table doesn’t involve N,add this item&#xff1b; else if original table’s relate…

SPSS--s04典型相关分析

典型相关基本原理 典型相关分析是主成分分析和因子分析的进一步发展 ,是研究两组变量间的相互依赖关系 ,把两组变量之间的相互关系变为研究两个新的变量之间的相关,而且又不抛弃原来变量的信息 ,这两个新的变量分别由第一组变量和第二组变量的线性组合构成 ,并且两组变量的个数…

「MySQL-00」MySQL在Linux上的安装、登录与删除

目录 一、安装MySQL 0. 安装前请先执行一遍删除操作&#xff0c;把预装或残留的MySQL删除掉 1. 安装yum源 &#xff08;解决了在哪里找MySQL的问题&#xff09; 2. 安装哪个版本的MySQL 二、启动和登录MySQL 三、删除MySQL / MariaDB 安装与卸载前&#xff0c;建议先将用户切换…

如何解决MySQL中的崩溃

MySQL崩溃最常见的原因是由于内存不足而停止或无法启动。要检查这一点&#xff0c;你需要查看MySQL崩溃后的错误日志。 首先&#xff0c;尝试启动MySQL服务器&#xff0c;输入: sudo systemctl start mysql然后查看错误日志&#xff0c;看看是什么原因导致MySQL崩溃。你可以使…

渲染如何做到超强渲染?MAX插件CG MAGIC中的渲染功能!

渲染工作应该算是设计师的日常工作流程中最重要的环节之一了。如果渲染速度加快&#xff0c;可能是要看渲染技巧掌握的有多少了。 大家熟悉的3d Max本地渲染通道&#xff0c;对于CG MAGIC渲染功能你也一定不能错过&#xff0c;要知道操作简单易使用&#xff0c;就完全拿捏了效率…