0

I need to add the fields(get from ui) which need to be fetched using mongodb Aggregation,

From uri i will get param as fields which has comma seperated string of fields

http://foo.com?fields=id,name

A document looks like:

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

The below will work as i want and produce the result

Aggregation aggregation = newAggregation(            
            project(fields.contains("name") ? "name" : "",
                    fields.contains("id") ? "id" : ""),
                    fields.contains("is_active") ? "is_active" : ""),
            skip((page-1)*limit),
            limit(limit)
            );

The above query gets what i want and its shown belo

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

IF i run with below query i m getting atleast one field need to specify in project And the code:

ProjectionOperation project = project();
for(String field : fields) {
    project.andInclude(field);
}

but the field is not adding in projectionOperation if projectOperation need to like to have

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

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

 The output need to be

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

I like to avoid check whether the list contain the field as they want in project.

selva
  • 2,676
  • 3
  • 12
  • 11

1 Answers1

0

Is it possible that you're just confusing some variables here (fields vs fieldList)? Also, you need to use the return value of the andInclude() call Try this instead:

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);
}
dnickless
  • 10,733
  • 1
  • 19
  • 34