Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将Mongo Json命令转换为Spring查询对象_Spring_Mongodb_Mongodb Query_Spring Data_Aggregation Framework - Fatal编程技术网

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

将Mongo Json命令转换为Spring查询对象,spring,mongodb,mongodb-query,spring-data,aggregation-framework,Spring,Mongodb,Mongodb Query,Spring Data,Aggregation Framework,有人能告诉我这个mongodb shell命令的正确Spring聚合对象是什么吗 {$sort: {labelId:1, dataId:1, updatedAt:1}}, {$group: { "_id": { "lid" : "$labelId", "dataId":"$dataId" }, "dat": { $last:"$updatedAt"

有人能告诉我这个mongodb shell命令的正确Spring聚合对象是什么吗

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

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

您可以使用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"
        }
      }
    }
  ]
}

谢谢你的回答。当我发现结果与我查询的集合不同时,如何执行此聚合?@skylla这对于聚合输出是常见的。通常最好像在mongoOperation.AggregateAgregation、spring、DBObject.class中一样使用DBObject.class。或者,将一个类定义为预期的输出形状,并使用该类对输出进行类型化聚合。