Spring Boot中对MongoDB中的Map列表数据进行进行列表查询?
ztj100 2025-05-30 19:01 16 浏览 0 评论
在SpringBoot项目中,想要对MongoDB中的Map列表数据进行处理,我们可以通过Spring Data MongoDB来实现这个操作,并且通过一些自定义的查询操作来对返回结果进行处理。下面我们就来看看详细的实现步骤。
数据模型
首先需要创建好我们需要进行接收对象的数据模型,如下所示,我们接下来的操作都是按照这个数据模型来进行操作。
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.util.List;
import java.util.Map;
@Document(collection = "your_collection")
public class YourDocument {
@Id
private String id;
private List<Map<String, Object>> mapList;
// Getters and setters
}
添加依赖
在POM文件中引入Spring Data MongoDB的依赖配置。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
配置MongoDB的数据库连接信息。如下所示。
spring.data.mongodb.uri=mongodb://localhost:27017/your_database
创建Repository接口
继承MongoRepository接口,创建一个YourDocumentRepository的操作接口,用来进行CRUD操作。
import org.springframework.data.mongodb.repository.MongoRepository;
public interface YourDocumentRepository extends MongoRepository<YourDocument, String> {
}
如何获取列表
首先我们先来看看如何获取到Map的列表并进行展示。我们可以通过Spring Data MongoDB的MongoTemplate来执行复杂的查询,并提取出需要的字段,如下所示。
配置MongoTemplate
首先需要在Spring Boot应用程序中配置MongoTemplate,以便支持后续的操作,如下所示。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
@Configuration
public class MongoConfig {
@Bean
public MongoTemplate mongoTemplate(MongoDatabaseFactory mongoDatabaseFactory) {
return new MongoTemplate(mongoDatabaseFactory);
}
}
使用MongoTemplate进行查询
在Service层中通过MongoTemplate来完成查询操作,并且提取出需要的数据字段,如下所示。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
@Service
public class YourDocumentService {
@Autowired
private MongoTemplate mongoTemplate;
public List<Map<String, Object>> findMapListByKeyValue(String key, Object value) {
Query query = new Query();
query.addCriteria(Criteria.where("mapList").elemMatch(Criteria.where(key).is(value)));
query.fields().include("mapList");
List<YourDocument> documents = mongoTemplate.find(query, YourDocument.class);
// Extract mapList from documents
return documents.stream()
.flatMap(doc -> doc.getMapList().stream())
.filter(map -> map.containsKey(key) && map.get(key).equals(value))
.collect(Collectors.toList());
}
}
创建Controller
在Controller层的对象中,调用Service层的方法来进行接口的返回,如下所示。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
@RestController
public class YourDocumentController {
@Autowired
private YourDocumentService service;
@GetMapping("/search")
public List<Map<String, Object>> search(@RequestParam String key, @RequestParam Object value) {
return service.findMapListByKeyValue(key, value);
}
}
实现对Map中的内容查询
我们可以通过Spring Data MongoDB提供的@Query注解来编写自定义查询方法,来实现查询包含某个键值对的Map,如下所示。
import org.springframework.data.mongodb.repository.Query;
import java.util.List;
public interface YourDocumentRepository extends MongoRepository<YourDocument, String> {
@Query("{ 'mapList': { $elemMatch: { 'key': ?0, 'value': ?1 } } }")
List<YourDocument> findByMapListContainingKeyValue(String key, Object value);
}
使用Service和Controller
创建一个Service来使用这个Repository,并在Controller中调用它,如下所示。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class YourDocumentService {
@Autowired
private YourDocumentRepository repository;
public List<YourDocument> findByMapListContainingKeyValue(String key, Object value) {
return repository.findByMapListContainingKeyValue(key, value);
}
}
Controller层对象
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class YourDocumentController {
@Autowired
private YourDocumentService service;
@GetMapping("/search")
public List<YourDocument> search(@RequestParam String key, @RequestParam Object value) {
return service.findByMapListContainingKeyValue(key, value);
}
}
总结
上面操作分别展示了如何获取Map列表和如何通过@Query注解来实现自定义的查询,当然我们还可以根据需求来编写更加复杂的查询来满足不同的需求场景的使用。
相关推荐
- 这个 JavaScript Api 已被废弃!请慎用!
-
在开发过程中,我们可能会不自觉地使用一些已经被标记为废弃的JavaScriptAPI。这些...
- JavaScript中10个“过时”的API,你的代码里还在用吗?
-
JavaScript作为一门不断发展的语言,其API也在持续进化。新的、更安全、更高效的API不断涌现,而一些旧的API则因为各种原因(如安全问题、性能瓶颈、设计缺陷或有了更好的替代品)被标记为“废...
- 几大开源免费的 JavaScript 富文本编辑器测评
-
MarkDown编辑器用的时间长了,发现发现富文本编辑器用起来是真的舒服。...
- 比较好的网页里面的 html 编辑器 推荐
-
如果您正在寻找嵌入到网页中的HTML编辑器,以便用户可以直接在网页上编辑HTML内容,以下是几个备受推荐的:CKEditor:CKEditor是一个功能强大的、开源的富文本编辑器,可以嵌入到...
- Luckysheet 实现excel多人在线协同编辑
-
前言前些天看到Luckysheet支持协同编辑Excel,正符合我们协同项目的一部分,故而想进一步完善协同文章,但是遇到了一下困难,特此做声明哈,若侵权,请联系我删除文章!若侵犯版权、个人隐私,请联系...
- 从 Element UI 源码的构建流程来看前端 UI 库设计
-
作者:前端森林转发链接:https://mp.weixin.qq.com/s/ziDMLDJcvx07aM6xoEyWHQ引言...
- 手把手教你如何用 Decorator 装饰你的 Typescript?「实践」
-
作者:Nealyang转发连接:https://mp.weixin.qq.com/s/PFgc8xD7gT40-9qXNTpk7A...
- 推荐五个优秀的富文本编辑器
-
富文本编辑器是一种可嵌入浏览器网页中,所见即所得的文本编辑器。对于许多从事前端开发的小伙伴来说并不算陌生,它的应用场景非常广泛,平时发个评论、写篇博客文章等都能见到它的身影。...
- 基于vue + element的后台管理系统解决方案
-
作者:林鑫转发链接:https://github.com/lin-xin前言该方案作为一套多功能的后台框架模板,适用于绝大部分的后台管理系统(WebManagementSystem)开发。基于v...
- 开源富文本编辑器Quill 2.0重磅发布
-
开源富文本编辑器Quill正式发布2.0版本。官方TypeScript声明...
- Python之Web开发框架学习 Django-表单处理
-
在Django中创建表单实际上类似于创建模型。同样,我们只需要从Django类继承,则类属性将是表单字段。让我们在myapp文件夹中添加一个forms.py文件以包含我们的应用程序表单。我们将创建一个...
- Django测试入门:打造坚实代码基础的钥匙
-
这一篇说一下django框架的自动化测试,...
- Django ORM vs SQLAlchemy:到底谁更香?从入门到上头的选择指南
-
阅读文章前辛苦您点下“关注”,方便讨论和分享,为了回馈您的支持,我将每日更新优质内容。...
- 超详细的Django 框架介绍,它来了!
-
时光荏苒,一晃小编的Tornado框架系列也结束了。这个框架虽然没有之前的FastAPI高流量,但是,它也是小编的心血呀。总共16篇博文,从入门到进阶,包含了框架的方方面面。虽然小编有些方面介绍得不是...
- 20《Nginx 入门教程》使用 Nginx 部署 Python 项目
-
今天的目标是完成一个PythonWeb项目的线上部署,我们使用最新的Django项目搭建一个简易的Web工程,然后基于Nginx服务部署该PythonWeb项目。1.前期准备...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- idea eval reset (50)
- vue dispatch (70)
- update canceled (42)
- order by asc (53)
- spring gateway (67)
- 简单代码编程 贪吃蛇 (40)
- transforms.resize (33)
- redisson trylock (35)
- 卸载node (35)
- np.reshape (33)
- torch.arange (34)
- npm 源 (35)
- vue3 deep (35)
- win10 ssh (35)
- vue foreach (34)
- idea设置编码为utf8 (35)
- vue 数组添加元素 (34)
- std find (34)
- tablefield注解用途 (35)
- python str转json (34)
- java websocket客户端 (34)
- tensor.view (34)
- java jackson (34)
- vmware17pro最新密钥 (34)
- mysql单表最大数据量 (35)