在投影中对大小数组进行除法运算来编写聚合查询的方法

Way to write a aggregation query with a divide operation on size array in projection

我想 运行 使用 Spring 数据 MongoDB 进行此聚合查询。

db.collectionname.aggregate(
   {
        "$group": {
        "_id": "$searchTerm",
        "dateAddToSet": {
            "$addToSet": "$date"
        }
    }
  },
  {
    "$project": {
        "searchTerm": "$_id.searchTerm",
        "percent": {
            "$divide": [{ "$size": "$dateAddToSet" }, 28]
        }
    }
  })

我找不到在 $dataAddToSet 大小上编写除法运算来执行此查询的方法。

非常感谢。

抱歉耽搁了。这里的主要问题是 $size 目前在 spring mongo 中不受支持。因此,构造操作的唯一方法是使用 DBObject 构造。

但是您可以通过提供自己的包装器 class 来混合使用这两种方法,例如:

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);
    }
}

因此,通常将 .toDBObject() 方法重写为仅 return 提供给 class.

构造函数的 DBObject 数据

然后在构建聚合时使用:

    Aggregation agg = newAggregation(
            group("searchTerm")
                    .addToSet("date").as("dateAddToSet"),
            new CustomAggregationOperation(
                new BasicDBObject("$project",
                    new BasicDBObject("_id",0)
                        .append("searchTerm","$_id")
                        .append("percent",new BasicDBObject(
                                "$divide", new Object[]{
                                    new BasicDBObject("$size","dateAddToSet"),
                                    28
                                }

                            )
                        )
                )
            )
    );

这会生成格式正确的管道:

{ 
    "aggregate" : "__collection__" , 
    "pipeline" : [ 
        { "$group" : { 
            "_id" : "$searchTerm" , 
            "dateAddToSet" : { "$addToSet" : "$date" }
        }}, 
        { "$project" : { 
            "_id" : 0 ,
            "searchTerm" : "$_id" , 
            "percent" : { "$divide" : [ { "$size" : "$dateAddToSet" } , 28] }
        }}
    ]
}

因此,这是将可用构建器与自定义构造混合在一起的一种方法,因此您可以在目前不存在构建器的情况下使用方法。