代码之家  ›  专栏  ›  技术社区  ›  bart

返回springdatamongodb中$last聚合中的对象

  •  1
  • bart  · 技术社区  · 9 年前

    我希望使用springdatamongodb实现以下查询:

    db.getCollection('collection').aggregate([
    { $group: {_id: "$profile", last: { $last: { firstname:"$firstname", lastname:"$lastname"}}}}])
    

    其结果如下:

    {
      "_id": "",
      "last": {
                "firstname": "",
                "lastname": ""
              }
    }
    

    然而,似乎唯一可用的API是

    GroupOperation groupOperation = Aggregation.group("profile").last("firstname").as("firstname").last("lastname").as("lastname");
    

    这转化为:

    db.getCollection('collection').aggregate([
    { $group: {_id: "$profile", firstname: { $last: "$firstname"}, lastname: { $last: "$lastname"}}}])
    

    给:

    {
      "_id": "",
      "firstname": "",
      "lastname": ""
    }
    

    GroupOperation.last(AggregationExpression expr) 但我不知道如何使用它。

    另一方面,在一次聚合中多次使用$last是否会导致性能损失?

    1 回复  |  直到 9 年前
        1
  •  0
  •   Blakes Seven    9 年前

    是的,这是当前spring-mongo聚合助手的构造所不允许的。但您可以构建自己的“自定义”聚合操作Object,然后在管道中使用它:

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

    这里的用法是:

        Aggregation agg = newAggregation(
          new CustomAggregationOperation(
            new BasicDBObject("$group",
                new BasicDBObject("last",
                    new BasicDBObject("$last",
                        new BasicDBObject("fisrname","$firstname")
                            .append("lastname","$lastname")
                    )
                )
            )
          )
        );
    

    因此,您可以只使用BSON对象构造器来按您所需的方式塑造管道阶段。这种快乐与 group() project() 以及所有其他辅助运算符,因为它实现了 AggregationOperation 界面