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.