How to use Stream with Mongo db in spring boot

5.1k Views Asked by At

I want to query large collection in Mongodb and tryin to use Stream com.mongodb.connection.Stream . I am doing this in spring boot using MongoRepository. I get error Type 'com.mongodb.connection.Stream' does not have type parameters for the method Stream<Population> findAllStates(String state);. Not sure what is the Type its complaining.

I have collection Population in the mongodb.

My Repository class is

package com.krk.samplemongodb;

import com.mongodb.connection.Stream;
import org.springframework.data.mongodb.repository.Aggregation;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface PopulationRepository extends MongoRepository<Population, String> {


    @Query(value = "{'state' :?0}")
    Stream<Population> findAllStates(String state);

    List<Population> findAll();
    
}

Thanks

2

There are 2 best solutions below

4
On

You should change your import to

import java.util.stream.Stream;

Also, make sure to use at least version 1.7 of Spring Data MongoDB as stated in this answer

0
On

Up to @neoczar. Maybe too late but according to the documentation of Spring Data Mongodb the stream should be closed to release the server-side resources (cursor). So you can use try with resources to automatically close cursor.

https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mongodb.repositories.queries.aggregation