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);
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)
In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With