Apply projection before sending result over the wire

In M220J Chapter 1: Query Builders, we see how projections can be applied to the result of a query on client side. At this time, the whole result set has already been sent over the wire while in this example we are really just interested in the fields “title” and “year”:

collection.find(queryFilter).projection(someConfig);

How can I provide my projection configuration to the server side so the projection is executed before data is sent over the wire, thus at least saving in terms of bandwidth and transmission times?
Or will the query only be executed when the client requests a result as in into(Collection) or iterator(), and not on the call to the find() method?

Don’t mix up the MongoDB collection with a Java Collection. The objects are not stored in the MongoDB collection. You can consider the find() and projection() methods as builder functionality. When you later iterate over the collection, the data will be loaded and transformed into BsonDocuments at the server side.
Take a look at MongoIterableImpl.into() where you can see, when a read is done.

2 Likes