Spring Data MongoRepository 获取最新一条记录

Posted Defonds

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring Data MongoRepository 获取最新一条记录相关的知识,希望对你有一定的参考价值。

Mongodb 某张表结构示例如下:


	"instanceSpec": "ecs.c6e.xlarge", 
	"productName": "云服务器 ECS", 
	"instanceID": "i-j6cioly7ub9e0hqh0od5", 
	"deductedByCashCoupons": 0, 
	"listPriceUnit": "", 
	"billingDate": "2021-06-08", 
	"listPrice": "", 
	"paymentAmount": 16.18, 
	"deductedByPrepaidCard": 0, 
	"invoiceDiscount": 0, 
	"subscriptionType": "PayAsYouGo", 
	"item": "PayAsYouGoBill", 
	"pretaxGrossAmount": 16.202998, 
	"instanceConfig": "iz:香港可用区 D;实例规格名称:ecs.c6e.xlarge;CPU:4;内存:8192;磁盘:4;外网出方向带宽:0.0Mbps;OS:UBUNTU;是否io优化:io_optimized_only", 
	"currency": "CNY", 
	"commodityCode": "ecs", 
	"costUnit": "未分配", 
	"resourceGroup": "默认资源组", 
	"billingType": "其它", 
	"usage": "", 
	"deductedByCoupons": 0, 
	"productDetail": "云服务器ECS-按量付费", 
	"productCode": "ecs", 
	"zone": "cn-hongkong-d", 
	"productType": "", 
	"outstandingAmount": 0, 
	"billingItem": "", 
	"nickName": "prod-Online-Mongo3-new3", 
	"intranetIP": "18.31.25.14", 
	"pipCode": "ecs", 
	"servicePeriodUnit": "秒", 
	"servicePeriod": "39600", 
	"deductedByResourcePackage": "", 
	"usageUnit": "", 
	"ownerID": "1644990457084567", 
	"pretaxAmount": 16.18, 
	"internetIP": "47.43.38.27", 
	"region": "中国(香港)", 
	"tag": "key:国际部 value:香港"

现在需要根据 instanceID 查出其 billingDate 最新的一条记录,Spring Data MongoRepository 可以使用如下写法:

    // 找到给定实例最新的一条账单数据
    @Query(value="'instanceID':?0")
    AliyunInstanceEcsBill findTop1ByBillingDateDesc(String instanceId);

参考自《Get last created document in Mongodb using Spring Data repository》。
提问者的示例代码:

@Data
@Document
public class Batch

    @Id
    String id;
    LocalDateTime created;
    //other stuff


public interface BatchRepository extends MongoRepository<Batch,String>

    //this does not work
    //Batch findOneOrderByCreatedDesc();

Andriy Simonov

Notice that the method name slightly differs from your variant, this difference is important as spring parses the method name and builds a query based on the result of parsing.

Zon

findTopByOrderByCreatedDesc(); -> findTop1ByCreatedDesc();

以上是关于Spring Data MongoRepository 获取最新一条记录的主要内容,如果未能解决你的问题,请参考以下文章

如何利用spring data mongodb 进行多条件查询

Spring Data 系列 Spring+JPA(spring-data-commons)

初探 spring data--- spring data 概述

spring-data-jpa 和 spring-boot-starter-data-jpa 的区别

无法将 Spring Data MongoDB + Spring Data JPA 与 Spring Boot 一起使用

是否有适用于 JPA、spring-data、spring-data-rest 的通用 REST 查询语言