Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using forEach on Documents in MongoDB

I am following this. I am unable to understand why the following would mean print each Document in JSON format. That is how forEach works and why the method name apply is run for each Document

Block<Document> printBlock = new Block<Document>() {
       @Override
       public void apply(final Document document) {
           System.out.println(document.toJson());
       }
};

collection.find(new Document()).forEach(printBlock);
like image 480
Abhishek Singh Avatar asked Aug 24 '17 07:08

Abhishek Singh


People also ask

What is forEach in MongoDB?

forEach() method is used to apply a JavaScript function for each document in a cursor. The forEach() method has the following prototype form: db.collection.find().forEach(<function>) Syntax: cursor.forEach(function)

What does find () do in MongoDB?

In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents.

What is cursor in MongoDB?

In MongoDB, when the find() method is used to find the documents present in the given collection, then this method returned a pointer which will points to the documents of the collection, now this pointer is known as cursor.

How do you unset a field in MongoDB?

The $unset operator deletes a particular field. Consider the following syntax: { $unset: { <field1>: "", ... } } The specified value in the $unset expression (i.e. "" ) does not impact the operation.


1 Answers

This is because the find operation return a MongoIterable which has declared a forEach method for java-7 Iterable which has no forEach method at all.

So you can call the forEach method on a MongoIterable as in your question. In java8, the Iterable includes the forEach(Consumer) operation. if you use forEach with inlined Lambda Expression or Method Reference Exception in java8, you must to cast the lambda to the explicit target type, for example:

collection.find(new Document())
          .forEach( it-> System.out.println(it.toJson())); // compile-error

// worked with inlined lambda expression
collection.find(new Document())
          .forEach((Consumer<Document>) it -> System.out.println(it.toJson()));


collection.find(new Document())
          .forEach((Block<Document>) it -> System.out.println(it.toJson()));

// worked with method reference expression
collection.find(new Document())
          .forEach((Consumer<Document>) printBlock::apply);

collection.find(new Document())
          .forEach((Block<Document>) printBlock::apply);

For more details about lambda expression you can see here.

like image 187
holi-java Avatar answered Nov 15 '22 08:11

holi-java