How can I implement addFields mongoDB query in Java
You are mixing the java driver Aggregates
method with Spring Aggregation
methods.
Also $addFields
is still not supported
in spring mongo.
You have to use below aggregation.
import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
Aggregation myDocAggr = newAggregation(
match(Criteria.where("metaId.ref.uuid").is(someUUID)),
group("uuid").max("version").as("version"),
lookup("simple","execId.ref.uuid","uuid","simple"),
unwind("simple"),
new AggregationOperation(){
@Override
public Document toDocument(AggregationOperationContext aoc) {
return new Document("$addFields",new Document("metaId.ref.name","$simple.name"));
}
}
)
List<Document> mydocumentList=mongoTemplate.aggregate(myDocAggr,"myDocument",Document.class).getMappedResults();
Although the $addFields are not supported by spring mongo you can implement it by yourself:
import org.bson.Document;
import org.springframework.data.mongodb.core.aggregation.*;
import java.util.LinkedHashMap;
import java.util.Map;
public class AddFieldsOperation implements FieldsExposingAggregationOperation {
private Map<String, Object> fields = new LinkedHashMap<>();
public AddFieldsOperation(String field, AggregationExpression expression) {
addField(field, expression);
}
public AddFieldsOperation addField(String field, AggregationExpression expression) {
this.fields.put(field, expression.toDocument(Aggregation.DEFAULT_CONTEXT));
return this;
}
@Override
public Document toDocument(AggregationOperationContext context) {
Document doc = new Document();
fields.forEach(doc::append);
return new Document("$addFields", doc);
}
@Override
public boolean inheritsFields() {
return true;
}
@Override
public ExposedFields getFields() {
final String[] fieldsArray = fields.keySet().toArray(new String[0]);
return ExposedFields.synthetic(Fields.fields(fieldsArray));
}
And use it like this:
...
ArithmeticOperators.Add value1 = ArithmeticOperators.Add.valueOf(0);
ArithmeticOperators.Add value2 = ArithmeticOperators.Add.valueOf(0);
AddFieldsOperation addFields
= new AddFieldsOperation("value1", value1)
.addField("value2", value2);
pipeline.add(addFields);
...
Add value1PlusValue2 = Add.valueOf("$value1").add("$value2");
...
Hope it will help someone.