Reputation: 135
when i try to add new field with a specific value it's working fine on mongo shell :
db.getCollection('collName').aggregate([
{ "$group" : { "_id" : "$idcpt" , "sum" : { "$sum" : "$val"}}},
{$addFields : {idcpt : 1092}}
])
But when i try to implement this aggregation in spring using org.springframework.data.mongodb.core.aggregation.Aggregation
i have difficulties with the "addFields", i can't find the right combination :
Aggregation.match(criteria),
Aggregation.group("idcpt").sum("val").as("sum"),
Aggregation.fields(....)
any help please?
Upvotes: 0
Views: 4873
Reputation: 2197
This might be late but $addFields
is now supported in spring-data support library.
You can create it like this:
Aggregation.addFields()
.addFieldWithValue("idcpt", 1092))
.build()
Upvotes: 1
Reputation: 1
Based on spring docs and I found we could use Aggregation as below.
Aggregation aggregation = Aggregation.newAggregation( Aggregation.project("test",...).andExpression("[0]",1092).as("idcpt "));
and like this.
Aggregation aggregation = Aggregation.newAggregation( Aggregation.project("test",...).and(1092).asLiteral().as("idcpt "));
Hopes to help you.
Upvotes: 0
Reputation: 1
I had the same problem and I found in the link provided by @Bajal that you can make a project AND add new fields at the same time with 'andExpression'
Aggregation.project("_id", ...).andExpression("1092").as("idcpt");
this is the idea but it doesn't work. To make it work you need to change slightly the expression :
Aggregation.project("_id", ...).andExpression("0 + [0]", 1092).as("idcpt");
I guess andExpression needs an expression to calculate, but I didn't cheked more closely.
see for exemple : https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mongo.aggregation.examples.example5
Upvotes: 0
Reputation: 5986
$addFields
is not part of the spring data support library yet, https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mongo.aggregation.supported-aggregation-operations.
I faced the same issue earlier, and I ended up just running it as raw query.
BasicDBList doc = (BasicDBList) JSON.parse(aggregateQuery.toString()); //where aggregateQuery is a StringBuilder that prepares the query string.
List<DBObject> pipeline = new ArrayList<>();
for (Object aDoc : doc) {
DBObject stage = (DBObject) aDoc;
pipeline.add(stage);
}
AggregationOutput output = mongoTemplate.getDb().getCollection("collName").aggregate(pipeline);
Upvotes: 0