栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Spring Boot数据和MongoDB-筛选子文档数组查询

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring Boot数据和MongoDB-筛选子文档数组查询

好吧,在Spring Data中,这种查询不是

trivial

坏消息:
Spring Data Repository没有针对的解决方案

MongoDBAggregation
。因此,您无法在MongoRepository中实现任何方法,例如
aggregateBy...

好消息:
Spring Data提供了

MongoTemplate
允许您执行复杂查询的类,就像在标准MongoDB shell中所做的那样。

因此,由于您只想对

exclude
不符合某些条件的子文档进行分类,因此我们需要定义集合
pipelines

我假设:

zip pres are Numeric (In your example is string)And, to exclude subdocument, we filter by `zip`There is no any other filter

MongoDB聚合为:

db.person.aggregate([    {$unwind: "$address"},    {$match: {"address.zip": 12345}},    {$group: { _id: { "firstName":"$firstName", "lastName":"$lastName", _id:"$_id" }, address: { $push: "$address" } } },    {$project: {_id:0, "firstName":"$_id.firstName", "lastName":"$_id.lastName", "address": "$address"}}])

如果所有筛选器均成功,则我们得到:

[     {        "address" : [  {     "zip" : 12345 },  {     "zip" : 12345 }        ],        "firstName" : "George",        "lastName" : "Washington"    }]

现在,以Spring Data的方式,您需要在项目中添加一些更改:

首先,找到您

mongo-config.xml
需要添加的位置:

<!-- Define the mongoDbFactory with your database Name  --><mongo:db-factory uri="mongodb://user:pass@localhost:27017/db"/><!-- Define the MongoTemplate  --><bean id="mongoTemplate" >    <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" /></bean>

MongoTemplate
是Spring的MongoDB支持的核心类,提供与数据库交互的功能集。该模板
...
提供了 域对象
MongoDB文档 之间的映射。更多信息

其次,在您的

@Service
课程中,添加以下代码以供加载
@PostConstruct

@Autowiredprivate MongoOperations mongoOperations;...public List<Person> findByAddressZipCode(int zip) {    List<AggregationOperation> list = new ArrayList<AggregationOperation>();    list.add(Aggregation.unwind("address"));    list.add(Aggregation.match(Criteria.where("address.zip").is(zip)));    list.add(Aggregation.group("firstName", "lastName").push("address").as("address"));    list.add(Aggregation.project("firstName", "lastName", "address"));    TypedAggregation<Person> agg = Aggregation.newAggregation(Person.class, list);    return mongoOperations.aggregate(agg, Person.class, Person.class).getMappedResults();}

注: 这两个,

Person
并且
Address
应该有默认的空构造!



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/451637.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号