是否可以在Spring Data MongoDB中将group()与ArrayOperators.arrayOf()结合使用?

时间:2017-03-02 11:17:17

标签: spring mongodb spring-data-mongodb

鉴于数据:

{
    "_id" : ObjectId("58b7fb9acdcf58886fa86136"),
    "cost" : 50,
    "nodes" : [ 
        4, 8, 15, 16, 23, 42
    ]
}

{
    "_id" : ObjectId("58b7fba3cdcf58886fa86137"),
    "cost" : 25,
    "nodes" : [ 
        1, 2, 3, 4, 23, 6
    ]
}

{
    "_id" : ObjectId("58b7fbaecdcf58886fa86138"),
    "cost" : 75,
    "nodes" : [ 
        1, 2, 17, 19, 20, 21
    ]
}

我可以在MongoDB中使用聚合按数组中的第二个元素进行分组:

db.stuff.aggregate([
{
  "$group": {
    "_id": {"$arrayElemAt": ["$nodes", 1]},
    "costs": {$sum: "$cost"}
  }
}])

在Spring Data MongoDB中,我最终使用以下Java代码来获得相同的结果:

Aggregation aggTest = Aggregation.newAggregation(
    project()
        .and(ArrayOperators.arrayOf("nodes").elementAt(1)).as("node")
        .and("cost").as("cost"),
    group("node").sum("cost").as("costs")
);

是否可以在Spring Data MongoDB中将group()与ArrayOperators.arrayOf()。elementAt结合使用,从而删除其他项目()?

1 个答案:

答案 0 :(得分:1)

看起来春天mongo db中的群组阶段没有AggregationExpression _id

您可以尝试创建AggregationOperation

AggregationOperation group = new AggregationOperation() {
      @Override
      public DBObject toDBObject(AggregationOperationContext context) {
        return new BasicDBObject(
                "$group", new BasicDBObject(
                  "_id", new BasicDBObject(
                    "$arrayElemAt", Arrays.asList("nodes", 1))).append(
                "costs", new BasicDBObject("$sum", "cost")));
       }
    };

Aggregation agg = Aggregation.newAggregation(group);