Spring-data-mongodb 查询内嵌数组的分页,筛选等

前言

mongodb利用Aggregation查询内嵌的数组并分页

需求:需要查询出用户子节点下的用户列表,并分页、筛选等

大概的数据结构长这样

{"_id": ObjectId("628b929183e3526f05d1a681"),"user_name": "祝","user_img": "img","content": "内容","childs": [{"_id": ObjectId("628b9e172b40eb7422eac342"),"user_name": "祝1","user_img": "img1","content": "内容11111"},{"_id": ObjectId("628b9e172b40eb7422eac341"),"user_name": "祝2","user_img": "img2","content": "内容22222"},{"_id": ObjectId("628b9e172b40eb7422eac343"),"user_name": "祝3","user_img": "img3","content": "内容33333"},{"_id": ObjectId("628b9e172b40eb7422eac34f"),"user_name": "祝4","user_img": "img4","content": "内容44444"}]
}

直接上代码咯

ObjectId objectId = new ObjectId("628b929183e3526f05d1a681");Aggregation agg = newAggregation(match(Criteria.where("_id").is(objectId))  // 查询指定根的id,可以替换条件,project("childs")          // 筛选出指定的字段,已可以不筛选,unwind("childs")           // 分裂,将字节点的数组分开,replaceRoot("childs")      // 替换根(重点)// ,match(Criteria.where("user_name").is("祝1")) // 此时根已替换为了子节点,可以进行筛选了,sort(ASC, "user_name")    // 根据用户名排序,skip(0L)            		// 指定跳过的数量,从0开始,limit(3)                   // 需要查几个// Tip:可以往回一个一个注销然后运行,就可以看到每一步都做了啥!
);// mongo为注入的MongoTemplate, comment是集合的名字, Object可以替换为要输出的实体类
AggregationResults<Object> comment = mongo.aggregate(agg, "comment", Object.class);
List<Object> resultList = comment.getMappedResults();
// 遍历打印一下下
resultList.forEach((result)-> System.out.println("result = " + result));

需要注意导入下面这个包,不要导错了,哈哈哈

import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;

结果

在这里插入图片描述

更多的功能可以翻看官方的文档哦 文档才是正道

官方文档链接:https://docs.spring.io/spring-data/mongodb/docs/2.0.5.RELEASE/reference/html/#mongo.aggregation.supported-aggregation-operations


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部