You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoRepository中带Limit的@Query使用:如何获取3条MongoDB文档

解决MongoDB @Query获取3条文档的问题

首先纠正你@Query里的一个小问题:fields参数是用来指定返回字段的投影文档,不需要用$and,直接写{productCode: 1, tourOperatorCode: 1}就可以了。

要限制返回3条文档,有两种常用方式:

方式一:使用Pageable参数

在你的Repository接口方法中添加Pageable参数,调用时传入PageRequest.of(0, 3)即可只获取前3条数据。示例代码如下:

@Query(value = "{$and:[{'contentRoot.basicData.code':{$ne:null}}, {'contentRoot.basicData.tourOperatorCode':{$ne:null}}]}",
       fields = "{productCode: 1, tourOperatorCode: 1}")
List<YourEntity> findLimitedDocuments(Pageable pageable);

调用示例:

List<YourEntity> result = yourRepository.findLimitedDocuments(PageRequest.of(0, 3));

方式二:使用Spring Data的命名规则(结合@Query)

如果不想用Pageable,也可以在方法名中加入Top3,结合@Query来实现:

@Query(value = "{$and:[{'contentRoot.basicData.code':{$ne:null}}, {'contentRoot.basicData.tourOperatorCode':{$ne:null}}]}",
       fields = "{productCode: 1, tourOperatorCode: 1}")
List<YourEntity> findTop3By();

注意点

不要尝试把{$limit: 3}写到@Query的value或fields参数里,因为value是查询条件,fields是返回字段配置,limit属于查询的分页选项,不属于这两个参数的范畴。

内容的提问来源于stack exchange,提问作者Artem Brazhnyk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 13:40:41