使用 spring mongo 模板在 MongoDB 中的 'project' 聚合功能中添加额外的键值对

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);

在上面的示例中,我还有一个字段说 - 'extraField' - 在 MyTarget class 中,可以为其分配少数预定义值之一(让我们说 - "abc" 和 "xyz")。我在点击 MongoDB.

之前知道这个值

如何将这个额外的键值 ["extraField" : "abc"] 对添加到上面的投影中。

使用$literal

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