Harish
Harish

Reputation: 169

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.

Upvotes: 1

Views: 1169

Answers (1)

s7vr
s7vr

Reputation: 75964

Use $literal

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

Upvotes: 4

Related Questions