java - 将字符串数组添加到 MongoDB 中的 ProjectionOperation
问题描述
我需要添加需要使用 mongodb 聚合获取的字段(从 ui 获取),
从 uri 我将获取参数作为字段,其中包含逗号分隔的字段字符串
http://foo.com?fields=id,name
一个文档看起来像:
{
"_id" : "3a237c007a87d",
"name" : "Available",
"is_active" : true,
}
以下将按我的意愿工作并产生结果
Aggregation aggregation = newAggregation(
project(fields.contains("name") ? "name" : "",
fields.contains("id") ? "id" : ""),
fields.contains("is_active") ? "is_active" : ""),
skip((page-1)*limit),
limit(limit)
);
上面的查询得到我想要的,它显示如下
{
"_id" : "3a237c007a87d",
"name" : "Available"
}
如果我使用以下查询运行,我至少需要在项目中指定一个字段 并且代码:
ProjectionOperation project = project();
for(String field : fields) {
project.andInclude(field);
}
但是如果 projectOperation 需要喜欢,该字段不会添加到 projectionOperation
{ "$project" : {"id":1, "name":1 } }
Aggregation aggregation = newAggregation(
project,
skip((page-1)*limit),
limit(limit)
);
The output need to be
{
"_id" : "3a237c007a87d",
"name" : "Available"
}
我喜欢避免检查列表是否包含项目中所需的字段。
解决方案
您是否可能只是在这里混淆了一些变量(fields
vs fieldList
)?此外,您需要使用andInclude()
调用的返回值试试这个:
List<String> fieldList = new ArrayList<>();
fieldList.add("id");
fieldList.add("name");
ProjectionOperation project = project();
for(String field : fieldList) { // note that I'm using 'fieldList' here
project = project.andInclude(field);
}
推荐阅读
- javascript - 在我自己的钩子中使用 fetch - 在 return() 中显示加载器
- algorithm - Recursive algorithm to solve change-making problem
- android - android:自定义小吃店在后台显示默认小吃店
- google-apps-script - createDraftReply 未更新 gmail 插件应用程序脚本中的密件抄送
- jquery - 如何从 html 中检索 jQuery 值
- docker - 生产环境中的 Docker 容器 - 操作方法
- php - 如何在 PHP 中为给定的语言环境输出适当的引号?
- wpf - 尝试在 xaml 中使用系统命名空间时出错
- reactjs - 使用复活的自定义开关组件
- c - 了解 getpid() 系统调用的 strace