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

news2024/10/8 18:10:51

在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 = new
					ArrayList<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.coloradmin.cn/o/948852.html

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

相关文章

【SpringBoot系列】 测试框架之@SpringBootTest的使用

SpringBootTest的详细介绍 SpringBootTest 是 Spring Boot 测试框架中的注解&#xff0c;用于标识一个测试类&#xff0c;以指示该类是一个 Spring Boot 应用程序的测试类。它允许你在测试环境中加载整个 Spring Boot 应用程序上下文&#xff0c;测试应用程序的各种组件、服务…

如何备考 PMP 考试?

一、PMP学习7步走攻略 ​1、熟悉考试大纲&#xff1a; PMP考试大纲是备考的基础&#xff0c;考生需要详细熟悉考试大纲&#xff0c;了解各个知识领域的重点和难点。 2、制定学习计划&#xff1a; 根据考试大纲和个人情况&#xff0c;制定学习计划&#xff0c;合理分配学习时间…

OA项目之我的会议(查询会议排座送审)

目录 会议查询 会议排座 会议送审 思路&#xff1a; 关键性会议SQL的编写后台实现前台实现 会议查询 MeetingInfoDao.java // 通用的会议查询SQL语句&#xff0c;包含会议信息表数据&#xff0c;主持人姓名、审批人姓名、会议状态private String getSQL() {return "…

android:新建工程文件介绍

一、前言当我们新建一个app时会呈现出固定的工程文件&#xff0c;这篇文章介绍新建工程里的文件。 二、介绍 Structure:就是你选择哪个页面就会显示那个页面的结构&#xff0c;就比如说我选择的是MainActivity他就会显示这个页面所使用的方法。 1-2&#xff1a;是android自动生…

【ESP32】解决接串口助手时,无法启动问题

本文主要记录ESP32正常烧录程序后&#xff0c;接上串口助手就无法启动&#xff0c;报错 waiting for download&#xff0c;拔掉串口助手后&#xff0c;程序可以正常启动 &#x1f4cb; 个人简介 &#x1f496; 作者简介&#xff1a;大家好&#xff0c;我是喜欢记录零碎知识点的…

小程序隐私保护授权处理方式之弹窗组件

欢迎点击关注-前端面试进阶指南&#xff1a;前端登顶之巅-最全面的前端知识点梳理总结 *分享一个使用比较久的&#x1fa9c; 小程序隐私保护授权弹窗组件 调用wx.getUserProfile进行授权时&#xff0c;返回错误信息&#xff1a;{errMsg: “getUserProfile:fail api scope is…

nvm和volta对node版本控制的区别

前言——我们做前端开发的都会需要node.js环境&#xff0c;我们直接安装指定的版本可以么&#xff1f;可以&#xff0c;只不过在需要换版本的时候还得卸载重新装。那有工具可以帮助我们不用卸载就更改node版本么&#xff1f;有啊&#xff0c;nvm就可以。那又有没有什么工具不用…

高忆管理:沪指震荡微涨,半导体板块走强,卫星导航概念拉升

30日早盘&#xff0c;A股两市维持震动格式。到午间收盘&#xff0c;沪指涨0.06%报3137.72点&#xff0c;深成指涨0.33%&#xff0c;创业板指涨0.12%&#xff0c;两市合计成交6424亿元。北向资金净流出8.82亿元。盘面上&#xff0c;半导体、纺织机械、元器件、通信设备、软件服务…

1.网络空间搜素引擎

网络空间搜素引擎 地址 &#xff1a;shodan.io 简介 &#xff1a; 这句话还是有点东西得 。 区别&#xff1a; 平常得搜素引擎主要搜网页&#xff0c;shadan可以搜所以带有ip地址的设备。使用 &#xff1a; 1.提供官方api 2.可以去淘宝15元买个初级会员 3.过滤器查看官方…

C# Dapper 操作Oracle数据库

nuget安装内容 1.配置连接字符串 OracleConnectionString这个可用 {"Logging": {"LogLevel": {"Default": "Information","Microsoft.AspNetCore": "Warning"}},"AllowedHosts": "*","…

多维时序 | Matlab实现GRU-Adaboost和GRU多变量时间序列预测对比

多维时序 | Matlab实现GRU-Adaboost和GRU多变量时间序列预测对比 目录 多维时序 | Matlab实现GRU-Adaboost和GRU多变量时间序列预测对比预测效果基本介绍模型描述程序设计参考资料 预测效果 基本介绍 多维时序 | Matlab实现GRU-Adaboost和GRU多变量时间序列预测对比 模型描述 M…

基于Googlenet深度学习网络的螺丝瑕疵检测matlab仿真

目录 1.算法运行效果图预览 2.算法运行软件版本 3.部分核心程序 4.算法理论概述 5.算法完整程序工程 1.算法运行效果图预览 2.算法运行软件版本 matlab2022a 3.部分核心程序 ....................................................................................% 获…

python爬虫关于ip代理池的获取和随机生成

前言 在进行爬虫开发时&#xff0c;代理IP池是一个非常重要的概念。代理IP池是指一个包含多个可用代理IP的集合&#xff0c;这些代理IP可以用来绕过网站的防爬虫策略&#xff0c;从而提高爬取数据的成功率。 在本文中&#xff0c;我们将介绍如何获取代理IP池&#xff0c;并且随…

统一使用某一个包管理工具,比如yarn pnpm

原因&#xff1a;前端每个人的习性不一样&#xff0c;有人用npm 有人用yarn等包管理工具&#xff0c;混合下载插件容易出bug&#xff0c;就用个小工具锁住就行了&#xff0c;只能使用yarn或者pnpm反向下载依赖和下载插件。不然就报错 1.在项目主目录下创建preinstall.js // 如…

直播预告!生鲜与零售商品识别系统产业实践与部署详解

生鲜零售作为民生消费的重要一环&#xff0c;在促进行业新消费升级的进程中有着至关重要的作用。在超市等无人零售场景中&#xff0c;目前结算方式主要有以下几种&#xff1a; 但是以上几种方法存在如下缺点&#xff1a; 条形码方式&#xff1a;对于成品包装的商品较为成熟&…

MindSponge分子动力学模拟——软件架构(2023.08)

技术背景 在前面一篇文章中&#xff0c;我们介绍了MindSponge的两种不同的安装与使用方法&#xff0c;让大家能够上手使用。这篇文章主要讲解MindSponge的软件架构&#xff0c;并且协同mindscience仓库讲解一下二者的区别。 整体架构 首先我们来了解一下MindSponge独立仓库的软…

day28 异常

to{}catch{} try{}catch{}的流传输 try {fis new FileInputStream("file-APP\\fos.txt");fos new FileOutputStream("fos.txt");int a ;while ((a fis.read())! -1){fos.write(a);}System.out.println(a); } catch (IOException e) {e.printStackTrace()…

ECharts图表动态修改series显示隐藏

文章目录 1、前言2、思路3、实现 1、前言 最近做的大数据平台&#xff0c;里面很多部分用到了ECharts&#xff0c;其中有个功能&#xff0c;要求将图表分组&#xff0c;根据用户选择的组&#xff0c;来确定ECharts要显示那些线条和柱子&#xff0c;也就是动态的显示option.seri…

习题练习 C语言(暑期第三弹)

自我小提升&#xff01; 前言一、存储地址二、逗号表达式三、除自身以外数组的乘积四、字节与二进制五、符号计算六、不用加减乘除做加法七、unsigned判断八、移位计算九、sizeof宏十、移位计算十一、移位计算十二、优先级判断十三、单词倒排总结 前言 重要的事说三遍&#xf…

仓储24代电子标签操作指导

服务器使用 服务器环境需求 数据库&#xff1a;Mysql5.7 Java环境&#xff1a;jdk1.8 软件容器&#xff1a; Tomcat8.5/9.0 软件部署步骤 mysql5.7, 创建db_wms数据库并导入原始数据库文件 安装jdk1.8, 配置java环境变量 下载tomca8.0, 部署wms.war到tomcat, 并启动tomc…