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);
在上面的示例中,我在 MyTarget
类中还有一个字段说 - 'extraField' - 可以为其分配少数预定义值之一(让我们说 - “abc”和“xyz” ).我在访问 MongoDB 之前就知道这个值。
如何将这个额外的键值 ["extraField": "abc"] 对添加到上面的投影中。
最佳答案
使用$literal
project("userCount").and("_id").as("user").and("abc").asLiteral().as("extraField")
关于java - 使用 spring mongo 模板在 MongoDB 聚合功能的 'project' 中添加额外的键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44682583/