2017-06-21 26 views
1
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類預定義的值(讓我們說 - 「abc」和「xyz」)。在打MongoDB之前,我知道這個值。MongoDB中聚合功能的添加額外的鍵 - 值對在「項目」利用彈簧蒙戈模板

如何在上面的投影中添加這個額外的鍵值[「extraField」:「abc」]對。

回答

2

使用$literal

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

可以PLZ看看這個 - https://stackoverflow.com/questions/45077570/mongodb-aggregation-add-arrays-value-by-value-in-group -步 – Harish