首页 > 解决方案 > 将字符串数组添加到 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"
 }

我喜欢避免检查列表是否包含项目中所需的字段。

标签: javamongodbspring-bootspring-mongodb

解决方案


您是否可能只是在这里混淆了一些变量(fieldsvs 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);
}

推荐阅读