Iterate over large collection in MongoDB via spring-data

前端 未结 7 2047
误落风尘
误落风尘 2021-01-31 17:18

Friends!

I am using MongoDB in java project via spring-data. I use Repository interfaces to access data in collections. For some processing I need to iterate over all el

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-31 18:14

    Late response, but maybe will help someone in the future. Spring data doesn't provide any API to wrap Mongo DB Cursor capabilities. It uses it within find methods, but always returns completed list of objects. Options are to use Mongo API directly or to use Spring Data Paging API, something like that:

            final int pageLimit = 300;
            int pageNumber = 0;
            Page page = repository.findAll(new PageRequest(pageNumber, pageLimit));
            while (page.hasNextPage()) {
                processPageContent(page.getContent());
                page = repository.findAll(new PageRequest(++pageNumber, pageLimit));
            }
            // process last page
            processPageContent(page.getContent());
    

    UPD (!) This method is not sufficient for large sets of data (see @Shawn Bush comments) Please use Mongo API directly for such cases.

提交回复
热议问题