【问题标题】:Spring Data MongoDB: How do I represent $eq in project aggregation query?Spring Data MongoDB:如何在项目聚合查询中表示 $eq?
【发布时间】:2016-06-05 14:38:35
【问题描述】:

我正在尝试将此 javascript 代码转换为要在 Spring Data 中使用的 java 代码:

proj3={"$project": {
        "comms" : 1,
        "same" : { "$eq" : ["$comms.i" , "$max"]},
    "max" : 1,
    "_id" : 1
     }
};

我似乎无法弄清楚。

我试过这个:

    BasicDBObject o3 = new BasicDBObject();
    o3.append("$eq", "[\"$comms.i\",\"$max\"]");
    Aggregation aggCount2 = newAggregation(project("comms", "max", "_id").andExpression("same", o3));
    logger.info(aggCount2.toString());

这是记录的内容:

{ "$project" : { "comms" : 1 , "max" : 1 , "_id" : 1}}

我也读过这个帖子:Spring Data MongoDB - $eq within $project support,但发帖者似乎已经放弃并使用了 executeCommand 选项,这不是我想走的路线。

如何让这段代码在 java Spring Data Mongodb 中工作?

【问题讨论】:

    标签: java spring mongodb spring-data


    【解决方案1】:

    这就是我解决它的方法,它可能不是最有效的方法,但它似乎不需要太多代码重写就可以工作。

    首先,我查看了这个帖子中的答案: Aggregation Project Group By extracted day, month and year with Spring Data

    布雷克七号建议我使用一个特殊的自定义aggregationOperation 类,以便聚合代码将采用BasicDBObjects:

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

    接下来,您只需将所需的项目代码格式化为 BasicDBObject:

    BasicDBList basicDBList = new BasicDBList();
    basicDBList.add("$comms.i");
    basicDBList.add("$max");
    
    Aggregation aggCount2 = newAggregation(
            match(),
            project(),
            group(),
            new CustomGroupOperation(new BasicDBObject("$project",
                    new BasicDBObject("comms", 1)
                            .append("max", 1)
                            .append("_id", 1)
                            .append("same", new BasicDBObject("$eq", basicDBList)))),
            match(),
            project(),
            group(),
            sort());
    

    在记录器中打印出来,你会看到 javascript 代码的格式现在是正确的。

    { "$project" : { "comms" : 1 , "max" : 1 , "_id" : 1 , "same" : { "$eq" : [ "$comms.i" , "$max"]}}}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-09
      • 2015-12-17
      • 1970-01-01
      • 1970-01-01
      • 2018-01-08
      • 2020-04-29
      • 2021-04-07
      相关资源
      最近更新 更多