Spring MongoDB 聚合中正确投影多个字段的实践方法
技术百科
心靈之曲
发布时间:2025-12-26
浏览: 次 在 spring data mongodb 中使用 `aggregation` 时,若需在 `project()` 阶段同时保留 `_id` 映射字段和分组统计字段(如 `countoffoousers`),应避免链式调用 `.and("xxx")` 的无效写法,而须使用 `andinclude()` 显式包含目标字段。
Spring Data MongoDB 的 ProjectionOperation 提供了多种字段投影方式,但初学者常误以为连续调用 .and("field") 即可添加多个投影字段——实际上,and(String) 方法仅用于定义新计算字段或别名字段,而不会自动“包含”已存在于上游 pipeline(如 group())中的字段。你原代码中:
projectByIDandCount.and("countOfFooUsers"); // ❌ 无效:未指定别名,也未触发包含逻辑这行代码既未设置别名,也未触发字段保留,导致 countOfFooUsers 在投影后被丢弃,最终 MAandUsers.countOfFooUsers 为 null。
✅ 正确做法是使用 andInclude(...) —— 它专为透传上游已存在字段而设计,支持单个或多个字段名:
ProjectionOperation projectByIDandCount = project()
.and("_id").as("defaultMasterAccountId") // 将 _id 重命名为 defaultMasterAccountId
.andInclude("countOfFooUsers"); // 显式包含上游 group 生成的 countOfFooUsers 字段完整修正后的聚合逻辑如下:
public MapgetUsersByAccount() { MatchOperation filterByAccountId = match( new Criteria(ACCOUNT_ID).nin(Arrays.asList(null, "")) ); GroupOperation groupByMasterAccount = group(DEFAULT_MASTER_ACCOUNT_ID) .count().as("countOfFooUsers"); ProjectionOperation projectByIDandCount = project() .and("_id").as("defaultMasterAccountId") .andInclude("countOfFooUsers"); // ✅ 关键修复:确保 countOfFooUsers 被投出 Aggregation aggregation = newAggr egation( filterByAccountId, groupByMasterAccount, projectByIDandCount ); AggregationResults
result = mongoTemplate.aggregate( aggregation, USERS_COLLECTION, MAandUsers.class ); return result.getMappedResults().stream() .collect(Collectors.toMap( MAandUsers::getDefaultMasterAccountId, MAandUsers::getCountOfFooUsers )); }
⚠️ 注意事项:
- andInclude() 是唯一推荐用于透传非计算字段的方式;and("field") 必须配合 .as("alias") 使用,否则无实际效果;
- 确保实体类 MAandUsers 字段名与投影后的 key 完全一致(区分大小写),且有对应 getter/setter(Lombok @Data 已满足);
- 若需重命名多个字段,可连续使用 .and("oldName").as("newName");
- 调试时可通过 aggregation.toString() 打印生成的原生聚合管道,验证 $project 阶段结构是否符合预期。
掌握 andInclude() 与 and().as() 的分工,是构建可靠、可维护 MongoDB 聚合查询的关键一步。
# 多个
# 链式
# 可通过
# 若需
# 命名为
# 专为
# app
# 是否符合
# go
# String
# stream
# gate
# NULL
# spring
# mongodb
# 也未
# 字段名
# 仅用
相关栏目:
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
AI推广<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
SEO优化<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
技术百科<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
谷歌推广<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
百度推广<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
网络营销<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
案例网站<?muma echo $count; ?>
】
<?muma
$count = M('archives')->where(['typeid'=>$field['id']])->count();
?>
【
精选文章<?muma echo $count; ?>
】
相关推荐
- Windows如何使用BitLocker To G
- Win10文件历史记录怎么用 Win10开启自动备
- 如何使用Golang实现基本类型比较_Golang
- Win10怎么卸载迅雷_Win10彻底卸载迅雷方法
- Win11怎么关闭小组件_Win11禁用任务栏天气
- Mac如何修改Hosts文件?(本地开发与屏蔽网站
- Win11怎么开启游戏模式_Windows11优化
- windows如何测试网速_windows系统网络
- C++ static_cast和dynamic_c
- Win11怎么更改账户头像_Windows 11自
- Win10如何卸载微软拼音输入法 Win10只保留
- php后缀怎么变mp4能播放_让php伪装mp4正
- Windows 11登录时提示“用户配置文件服务登
- 如何在 Pandas 中按元素交集合并两列字符串
- Win11怎么开启游戏模式_Win11优化游戏帧数
- 如何在Golang中使用replace替换模块_指
- c++怎么设置线程优先级与cpu亲和性_c++ 多
- Win11怎么关闭自动调节亮度_Windows11
- php查询数据怎么导出csv_查询结果转csv文件
- Win10怎样卸载自带Edge_Win10卸载Ed
- Windows驱动无法加载错误解决方法_驱动签名验
- Win11怎么查看显卡温度 Win11任务管理器查
- windows系统找不到无线网络怎么办_windo
- Win11截图快捷键是什么_Win11自带截图工具
- Go 语言标准库为何不提供泛型 Contains
- Win10怎么关闭自动更新错误弹窗_Win10策略
- Windows7如何安装系统镜像_Windows7
- Windows如何拦截腾讯视频广告_Windows
- php转mp4怎么设置帧率_调整php生成mp4视
- Mac如何开启夜览模式_Mac护眼模式设置与定时
- Win11任务栏怎么放到顶部_Win11修改任务栏
- Win11关机界面怎么改_Win11自定义关机画面
- 如何在Golang中理解指针比较_Golang地址
- 如何使用Golang实现跨域请求支持_Golang
- php能跑在stm32上吗_php在stm32微控
- 如何解决Windows字体显示模糊的问题?(Cle
- windows 10应用商店区域怎么改_windo
- 如何在JavaScript中动态拼接PHP的bas
- Windows怎样关闭开始菜单广告_Windows
- Windows10电脑怎么设置防火墙出站规则_Wi
- 如何使用Golang table-driven f
- php转exe用什么工具打包快_高效打包软件推荐【
- php内存溢出怎么排查_php内存限制调试与优化方
- MAC如何快速搜索大文件_MAC磁盘空间分析与冗余
- Windows10电脑怎么设置文件权限_Win10
- Windows10怎么用“讲述人”读屏辅助 Win
- Win10电脑怎么设置休眠快捷键_Windows1
- Win11怎么格式化U盘_Win11系统U盘格式化
- 如何在Golang中使用log包输出不同级别日志_
- Django 密码修改后会话失效的解决方案

egation(
filterByAccountId,
groupByMasterAccount,
projectByIDandCount
);
AggregationResults
QQ客服