【问题标题】:Add an array of string to ProjectionOperation in MongoDB将字符串数组添加到 MongoDB 中的 ProjectionOperation
【发布时间】:2018-05-23 09:02:50
【问题描述】:

我需要添加需要使用 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);
}

但该字段未添加到 projectionOperation 如果 projectOperation 需要喜欢有

{ "$project" : {"id":1, "name":1 } }

Aggregation aggregation = newAggregation(            
        project,
        skip((page-1)*limit),
        limit(limit)
        );

 The output need to be

{
    "_id" : "3a237c007a87d", 
    "name" : "Available"
 }

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

【问题讨论】:

    标签: java mongodb spring-boot spring-mongodb


    【解决方案1】:

    您是否可能只是在这里混淆了一些变量(fieldsfieldList)?此外,您需要使用 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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-19
      • 2017-08-03
      • 2012-12-15
      • 2011-04-03
      • 2015-02-15
      相关资源
      最近更新 更多