Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

Is it possible to convert a MongoDb query result into a stream and collect it?

For example, to get a list of _id values, something like this:

getMongoDatabaseInstance()
                .getCollection("some_collection_name")
                .find()
                .projection(new Document("_id", 1 ))
                .map(d -> d.getString("_id") )
                .collect(Collectors.toList());

This results in a compilation error:

The method collect(Collectors.toList()) is undefined for the type MongoIterable<String>

because a MongoIterable is not a stream and cannot be collected.

Of course, I could declare a cursor and iterate over the result set, but that requires adding declarations and loops etc. I need to collect small number of documents at many places in my program, and it would be much more clean and easy to convert them to a stream and collect.

Is that possible?

Try use StreamSupport#stream By using this utility you can convert iterable interface to stream or parallel stream.

StreamSupport.stream(getMongoDatabaseInstance()
             .getCollection("some_collection_name")
             .find()
             .projection(new Document("_id", 1 )).spliterator(),false)
             .map(d->d.getString("_id"))
             .collect(Collectors.toList());
                I would suggest splitting the spliterator as a local variable. Also, though this should work, the client library until some version for mongo didn't support the implementation.
– Naman
                May 17, 2020 at 11:50
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.