Home > Blockchain >  Java and MongoDB: forEach(Block<? super Document>) is ambiguous
Java and MongoDB: forEach(Block<? super Document>) is ambiguous

Time:08-30

I'm trying to extend the Azure Java / MongoDB simple example with a filter from mongodb docs while getting my head around functional Java. The below code is throwing errors

        MongoDatabase database = mongoClient.getDatabase("my-db");
        Document queryResult = collection.find(Filters.eq("fruit", "apple")).first();

        Bson filter = Filters.and(Filters.eq("param", 2293), Filters.eq("param1", 202));
        final Document queryResult2 = collection.find(filter).forEach(doc -> 
        System.out.println(doc.toJson()));

is giving me the following error

The method forEach(Block<? super Document>) is ambiguous for the type FindIterable<Document>",

I have looked at this answer and tried various things including below but my lack of experience with forEach is obvious!

           //cannot convert from void to document error
            Document queryResult2 = collection.find(filter).forEach((Block<? super Document>) doc -> System.out.println(doc.toJson()));

            //cannot convert from void to document error
            final Document queryResult2 = collection.find(filter).forEach((Consumer<? super Document>) (Document document) -> {
                System.out.println(document.toJson());
            });

All help/tips appreciated

CodePudding user response:

There are two errors here:

Document queryResult2 = collection.find(filter).forEach((Block<? super Document>) doc -> System.out.println(doc.toJson()));

forEach has a return type of void, it doesn't return anything. So the assignment is wrong. That's why you get cannot convert from void to document error

Secondly Document, represents a single document, not a collection of documents. So the assignment to simply a Document object is wrong as well.

Try something like this:

List<Document> documents = collection.find(filter).map(doc -> doc).into(new ArrayList<Document>());

Here's the link to the forach and map Mongodb documentation.

  • Related