将Mongo Json命令转换为Spring查询对象

时间:2017-06-26 12:36:28

标签: spring mongodb mongodb-query spring-data aggregation-framework

有人可以告诉我这个mongodb shell命令的正确Spring Aggregation对象是什么:

{$sort: {labelId:1, dataId:1, updatedAt:1}}, 

{$group:
  {
    "_id": 
        {
            "lid" : "$labelId", 
            "dataId":"$dataId"
        }, 
    "dat":
        {
            $last:"$updatedAt"
        }, 
    "value":
        {
            $last:"$value"
        }
  }
}

1 个答案:

答案 0 :(得分:1)

你可以像这样用spring-mongo写它:

    Aggregation aggregation = newAggregation(
            sort(Direction.ASC,"labelId")
              .and(Direction.ASC,"dataId")
              .and(Direction.ASC,"updatedAt"),
            group(Fields.fields().and("labelId","lid").and("dataId"))
              .last("updatedAt").as("dat")
              .last("value").as("value")
    );

作为一个小小的提示,我喜欢在运行之前有东西来转储管道:

    Gson gson = new GsonBuilder().setPrettyPrinting().create();

    // debug pipeline
    System.out.println(
        gson.toJson(
            gson.fromJson(aggregation.toDbObject("spring", Aggregation.DEFAULT_CONTEXT).toString(), Object.class)
        )
    );

这给了我一个非常序列化的输出来检查:

{
  "aggregate": "spring",
  "pipeline": [
    {
      "$sort": {
        "labelId": 1.0,
        "dataId": 1.0,
        "updatedAt": 1.0
      }
    },
    {
      "$group": {
        "_id": {
          "labelId": "$lid",
          "dataId": "$dataId"
        },
        "dat": {
          "$last": "$updatedAt"
        },
        "value": {
          "$last": "$value"
        }
      }
    }
  ]
}