Spring Boot中使用MongoDB完成数据存储

我们在开发中用到的数据存储工具有许多种,我们常见的数据存储工具包括:

  1. 关系性数据库:使用表格来存储数据,支持事务和索引。(如:MySQL,Oracle,SQL Server等)。
  2. NoSQL数据库:不使用表格来存储数据,而是使用键值对、文档、或者图形等方式来存储数据,适合处理高并发和大规模数据。(Redis,MongoDB,Cassandra等)
  3. 文件存储:将数据存储在本地或者远程服务器文件中,常用与存储较小的文件。(FTP,SFTP,AWS C3等)
  4. 云存储:数据存储在云端,方便多人协作和备份。(Google Drive,Dropbox,OneDriver等)
  5. 内存存储 :将数据存储在内存中,提供快速的读写速度,但是不适用存储持久化数据(Redis,Memcache等)。
  6. 缓存:将数据存储在缓存中,提高访问速度,减少数据库压力。(Apc,Memcache,Redis等)
  7. 队列:将任务分发到不同的队列中进行处理,提高系统的可靠性和可拓展性。(RabbitMQ,Kafka等)

这篇我们将围绕MongoDB进行,MongoDB是一个开源的,面向文档的NoSQL数据库管理系统,使用类似JSON的BSON(二进制JSON)格式来存储数据,具有灵活的数据模型和强大的查询功能。

与传统的关系型数据库不同的是,MongoDB不使用表和行的结构,而是使用集合和文档进行的,一个集合就相当于关系型数据库里边的表,一个文档就相当于表中的一行数据,每个文档都是一个键值对的集合,可以包含不同类型的数据。

MongoDB的特点:

  • 面向文档:MongoDB使用灵活的文档模型,可以存储不同结构的数据,无需事先定义表结构。
  • 可扩展性:MongoDB支持水平扩展,可以通过添加更多的服务器来处理大规模的数据和高并发访问。
  • 高性能:MongoDB具有快速的读写性能,支持索引和复杂查询。
  • 强大的查询语言:MongoDB支持丰富的查询语言,包括条件查询、范围查询、正则表达式查询等。
  • 数据复制和故障恢复:MongoDB支持数据复制和自动故障恢复,可以提供高可用性和数据安全性。
  • 地理空间索引:MongoDB支持地理空间索引,可以进行地理位置相关的查询和分析。
  • 开源和活跃的社区:MongoDB是开源的,拥有庞大的用户社区和活跃的开发者社区。

首先在我们测试MongoDB之前,我们需要安装MongoDB,MongoDB下载网站:https://www.mongodb.com/try/download/community

在这里插入图片描述之后安装后,创建一个test数据库:
在这里插入图片描述
引入相关依赖:

		<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-mongodb</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><scope>provided</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>

在application.properties中配置相关连接:

spring.data.mongodb.uri=mongodb://localhost:27017/testserver.port=7723

创建一个实体类User

public class User {@Idprivate Long id;private String username;private Integer age;public Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public User() {}public User(Long id, String username, Integer age) {this.id = id;this.username = username;this.age = age;}
}

实现用户实体User的数据访问对象

public interface UserRepository extends MongoRepository<User, Long> {User findByUsername(String username);}

接下来创建一个单元测试用例:

@SpringBootTest(classes = Application.class)
public class ApplicationTests {@Autowiredprivate UserRepository userRepository;@Testpublic void test() throws Exception {userRepository.deleteAll();// 创建三个User,并验证User总数userRepository.save(new User(1L, "麻衣**", 22));userRepository.save(new User(2L, "娜*", 24));userRepository.save(new User(3L, "玩偶**", 26));Assertions.assertEquals(3, userRepository.findAll().size());// 删除一个User,再验证User总数User u = userRepository.findById(1L).get();userRepository.delete(u);Assertions.assertEquals(2, userRepository.findAll().size());// 删除一个User,再验证User总数u = userRepository.findByUsername("娜*");userRepository.delete(u);Assertions.assertEquals(1, userRepository.findAll().size());}}

控制台输出

2023-11-17 15:39:39.655  INFO 15808 --- [           main] org.mongodb.driver.cluster               : Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms'}
2023-11-17 15:39:39.737  INFO 15808 --- [localhost:27017] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:2, serverValue:26}] to localhost:27017
2023-11-17 15:39:39.737  INFO 15808 --- [localhost:27017] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:1, serverValue:27}] to localhost:27017
2023-11-17 15:39:39.737  INFO 15808 --- [localhost:27017] org.mongodb.driver.cluster               : Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, minWireVersion=0, maxWireVersion=17, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=58204100}
2023-11-17 15:39:39.963  INFO 15808 --- [           main] c.miaow.demo.ApplicationTests   : Started ApplicationTests in 2.079 seconds (JVM running for 2.619)
2023-11-17 15:39:40.106  INFO 15808 --- [           main] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:3, serverValue:28}] to localhost:27017
2023-11-17 15:39:40.184  INFO 15808 --- [extShutdownHook] org.mongodb.driver.connection            : Closed connection [connectionId{localValue:3, serverValue:28}] to localhost:27017 because the pool has been closed.
2023-11-17 15:39:40.184  INFO 15808 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'

注意,MongoDB的语法有所区别,具体的如下:
查询语法:

插入文档:db.collection.insertOne(document)db.collection.insertMany(documents)

查询文档:db.collection.find(query, projection)

更新文档:db.collection.updateOne(filter, update)db.collection.updateMany(filter, update)

删除文档:db.collection.deleteOne(filter)db.collection.deleteMany(filter)

条件查询:db.collection.find({ field: value })

范围查询:db.collection.find({ field: { $gt: value1, $lt: value2 } })
正则表达式查询:db.collection.find({ field: /pattern/ })

排序:db.collection.find().sort({ field: 1 })(1表示升序,-1表示降序)

分页:db.collection.find().skip(offset).limit(limit)

聚合查询:db.collection.aggregate(pipeline)

在Java中的相关操作:
连接MongoDB:使用MongoClient类来连接MongoDB数据库。
普通连接方式,如果是Spring Boot中就是配置一下

MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase database = mongoClient.getDatabase("mydatabase");

获取集合:使用getCollection方法获取集合对象。

MongoCollection<Document> collection = database.getCollection("mycollection");

插入文档:

Document document = new Document("name", "miaow").append("age", 24).append("email", "miaow@example.com");
collection.insertOne(document);

查询文档:

FindIterable<Document> result = collection.find(new Document("name", "miaow"));
for (Document document : result) {// 处理查询结果
}

更新文档:

collection.updateOne(eq("name", "miaow"), new Document("$set", new Document("age", 24)));

删除文档:

collection.deleteOne(eq("name", "miaow"));

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

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

相关文章

鸿蒙:Harmony开发基础知识详解

一.概述 工欲善其事&#xff0c;必先利其器。 上一篇博文实现了一个"Hello Harmony"的Demo&#xff0c;今天这篇博文就以Demo "Hello Harmony" 为例&#xff0c;以官网开发文档为依据&#xff0c;从鸿蒙开发主要的几个方面入手&#xff0c;详细了解一下鸿…

大模型是怎么知道 “我赚了200万” 的?

今天在和 chatGPT 聊天时&#xff0c;我说“我赚了200万”&#xff0c;他立刻就根据这句话给我了一句。 我当然没有赚到200万&#xff0c;只是想引出一个话题&#xff1a;“大模型是如何识别出这句话&#xff0c;又是怎么知道该回答什么的呢&#xff1f;" 在学习自然语言…

vue之浏览器存储方法封装实例

我们在项目中通常会对缓存进行一些操作&#xff0c;为了便于全局调用&#xff0c;会对缓存的设置、获取及删除方法进行封装成一个工具类。 首先我们在src目录下创建一个plugins文件夹&#xff0c;在plugins下创建cache文件夹并创建index.js&#xff0c;代码如下&#xff1a; c…

腾讯云服务器带宽计费模式_按流量和带宽收费说明

腾讯云服务器带宽计费模式分为“按带宽计费”和“按使用流量”两种计费模式&#xff1a;按带宽计费是预付费&#xff0c;一次性购买固定带宽值&#xff0c;先付费&#xff1b;按使用流量计费是先使用后付费&#xff0c;根据云服务器公网出方向实际产生流量来计算。如何选择带宽…

基于token的鉴权机制-JWT

在实际开发项目中&#xff0c;由于Http是一种无状态的协议&#xff0c;我们想要记录用户的登录状态&#xff0c;或者为用户创建身份认证的凭证&#xff0c;可以使用Session认证机制或者JWT认证机制。 什么是JWT? 网络应用环境间传递声明执行的一种基于JSON的开放标准。适用于…

Windows 下 Sublime Text 2.0.2 下载及配置

1 下载地址&#xff1a; https://www.sublimetext.com/2 Sublime Text 2.0.2 (此版本选择了 portable version)&#xff0c;直接解压就可以使用。 https://download.sublimetext.com/Sublime Text 2.0.2.zip 2 配置Python相关环境 (前提 Pyhon 已加入环境变量) 2.1 新建 py …

公司会倒闭,但大模型肯定不会

咋玩抖音的我&#xff0c;前几天在抖音上发了一张图片&#xff0c;没想到竟然有1000多的播放量。 当然这个播放量不算高&#xff0c;甚至在抖音的体系里属于很低的&#xff0c;但是比我预料的可能只有个位数的播放量是高了不少。 这张图片是我用某国产 AI 软件生成的&#xff…

谈谈 MySQL 事务隔离级别

程序员的公众号&#xff1a;源1024&#xff0c;获取更多资料&#xff0c;无加密无套路&#xff01; 最近整理了一份大厂面试资料《史上最全大厂面试题》&#xff0c;Springboot、微服务、算法、数据结构、Zookeeper、Mybatis、Dubbo、linux、Kafka、Elasticsearch、数据库等等 …

接口调用微信公众号群发功能,绕过微信自身限制

微信群发功能要求要微信认证。微信认证要求要企业账号、而且需要认证费用。 本篇文章教大家非微信认证账号如何群发公众号信息 本篇文章基于python语言开发,其他的语言一样的方式,不需要拘泥于语言 注意事项: 要求有微信公众平台登陆状态,也就是Cookie数据, 如何通过Py…

QEMU显示虚拟化的几种选项

QEMU可以通过通过命令行"-vga type"选择为客户机模拟的VGA卡的类别,可选择的类型有多个: -vga typeSelect type of VGA card to emulate. Valid values for type arecirrusCirrus Logic GD5446 Video card. All Windows versions starting from Windows 95 should …