Search code examples
javaspringmongodbspring-mongodb

Add extra key-value pair in 'project' in MongoDB aggregate functionality using spring mongo template


Aggregation agg = newAggregation(
                    match(criteria),
                    group("username").count().as("userCount"),
                    project("userCount").and("_id").as("user")
            );

   AggregationResults<MyTarget> dataObjects = mongoTemplate
            .aggregate(agg, <collectionName>, MyTarget.class);

In above example, I have one more field say - 'extraField' - in MyTarget class which can be assigned one of the few predefined values (let us say - "abc" and "xyz"). I know this value prior to hitting the MongoDB.

How can I add this extra key-value ["extraField" : "abc"]pair into projection above.


Solution

  • Use $literal

     project("userCount").and("_id").as("user").and("abc").asLiteral().as("extraField")