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; } public interface BatchRepository extends MongoRepository<Batch,String> { }
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();
原创文章,作者:优速盾-小U,如若转载,请注明出处:https://www.cdnb.net/bbs/archives/31472