Spring Data MongoDB - 自定义查询

时间:2017-10-25 16:02:14

标签: spring mongodb spring-data-mongodb spring-mongodb

我想存储跟踪信息,如下所示:

{
    "timestamp": 1394343677415,
    "info": {
        "method": "GET",
        "path": "/trace",
        "headers": {
            "request": {
                "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
                "Connection": "keep-alive",
                "Accept-Encoding": "gzip, deflate",
                "User-Agent": "Mozilla/5.0 Gecko/Firefox",
                "Accept-Language": "en-US,en;q=0.5",
                "Cookie": "_ga=GA1.1.827067509.1390890128; ..."
                "Authorization": "Basic ...",
                "Host": "localhost:8080"
            },
            "response": {
                "Strict-Transport-Security": "max-age=31536000 ; includeSubDomains",
                "X-Application-Context": "application:8080",
                "Content-Type": "application/json;charset=UTF-8",
                "status": "200"
            }
        }
    }

我的@Document实体正在扩展HashMap。

现在我必须为分页编写自定义查询。

在Mongo客户端shell中我会写它:

db.traceInfo.find({"headers.response.status": "404"}).limit(n);

它有效,但我不知道如何在Spring MongoRepository中将此查询写为@Query?我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

这很简单,但spring-data-mongodb不支持关键字limit,请查看此处的参考:https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#repository-query-keywords

可能的解决方案:

@Query({"headers.response.status": "?1"})
List<T> findByGivenStatus(int status);