spring-projects / spring-projects/spring-data-mongodb
Allow complex field projects in group.addToSet [DATAMONGO-940]
@christophstrobl is already working on this.
Since Dec 30, 2020.
- Dominant language
- Java
- Stars
- 1.7k
- Forks
- 1.1k
- PR merge metrics
- No merged PRs in 30d
Description
Thomas Darimont opened DATAMONGO-940 and commented
Currently one can only refer to single fields or values in group.addToSet.
Sometimes it is necessary to be able to use addToSet with more complex projections.
In order to express custom projections in group expressions with addToSet one currently has to resort to use a DbObject with the required fields which are not checked for references.
@Test
public void foo() {
String chartId = "6c3f4415eb0d70c3441e2d724f36fc33a0351b1b";
long startTime = 1356998400000L;
long endTime = 1400735915579L;
Aggregation agg = newAggregation( //
match(where("chartId").is(chartId).and("timestamp").gte(startTime).lte(endTime)) //
, unwind("values") //
, group("values.statistic", "values.unit", "values.divisorUnit").avg("values.data").as("averageData")//
, group("statistic") //
.addToSet(new BasicDBObject() { // we have to use a DBO here since addToSet doesn't allow to refer to multiple fields yet.
{
put("statistic", "$_id.statistic");
put("unit", "$_id.unit");
put("divisorUnit", "$_id.divisorUnit");
put("data", "$averageData");
}
}).as("values"));
AggregationResults<DBObject> result = mongoTemplate.aggregate(agg, "measurement", DBObject.class);
System.out.println(result.getMappedResults());
}
Which produces the following aggregation pipeline:
[
{
"$match":{
"chartId":"6c3f4415eb0d70c3441e2d724f36fc33a0351b1b",
"timestamp":{
"$gte":1356998400000,
"$lte":1400735915579
}
}
},
{
"$unwind":"$values"
},
{
"$group":{
"_id":{
"statistic":"$values.statistic",
"unit":"$values.unit",
"divisorUnit":"$values.divisorUnit"
},
"averageData":{
"$avg":"$values.data"
}
}
},
{
"$group":{
"_id":"$_id.statistic",
"values":{
"$addToSet":{
"statistic":"$_id.statistic",
"unit":"$_id.unit",
"divisorUnit":"$_id.divisorUnit",
"data":"$averageData"
}
}
}
}
]
Affects: 1.5 GA (Dijkstra)
Reference URL: https://gist.github.com/thomasdarimont/fecc60aef26c08e1f21a
2 votes, 2 watchers
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Assessment
This issue has not been assessed yet.