med.tu
med.tu

Reputation: 135

add new field to the result of a mongo aggregation

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

Answers (4)

May Rest in Peace
May Rest in Peace

Reputation: 2197

This might be late but $addFields is now supported in spring-data support library.

Official Docs Link

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

Booyakacha
Booyakacha

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

Bajal
Bajal

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

Related Questions