Skip to content

Allow complex field projects in group.addToSet [DATAMONGO-940] #1867

Open
@spring-projects-issues

Description

@spring-projects-issues

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

Metadata

Metadata

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions