Calculated group-by fields in MongoDB

前端 未结 2 874
时光取名叫无心
时光取名叫无心 2020-12-30 06:10

For this example from the MongoDB documentation, how do I write the query using MongoTemplate?

db.sales.aggregate(
   [
      {
        $group : {
                   


        
2条回答
  •  执笔经年
    2020-12-30 06:59

    Another alternative is to use a custom aggregation operation class defined like so:

    public class CustomAggregationOperation implements AggregationOperation {
        private DBObject operation;
    
        public CustomAggregationOperation (DBObject operation) {
            this.operation = operation;
        }
    
        @Override
        public DBObject toDBObject(AggregationOperationContext context) {
            return context.getMappedObject(operation);
        }
    }
    

    Then implement it in the pipeline like so:

    Aggregation aggregation = newAggregation(
        new CustomAggregationOperation(
            new BasicDBObject(
                "$group",
                new BasicDBObject("_id",
                    new BasicDBObject("day", new BasicDBObject("$dayOfMonth", "$date" ))
                    .append("month", new BasicDBObject("$month", "$date"))
                    .append("year", new BasicDBObject("$year", "$date"))
                )
                .append("totalPrice", new BasicDBObject(
                    "$sum", new BasicDBObject(
                        "$multiply", Arrays.asList("$price","$quantity")
                    )
                ))
                .append("averageQuantity", new BasicDBObject("$avg", "$quantity"))
                .append("count",new BasicDBObject("$sum",1))
            )
        )
    )
    

    So it's basically just an interface that is consistent with that used by the existing pipeline helpers, but instead of using other helper methods it directly takes a DBObject definition to return in pipeline construction.

提交回复
热议问题