I wonder how, if possible, I can execute a find query with Spring Data MongoDB using mongoTemplate but not return the entire document? With the "native" Java Sync driver from MongoDB I can do like this:
Document document = myCollection.find(eq("something", 12)).sort(descending("field")).limit(1).projection(include("field")).first();
so that the document only includes the "field" and nothing else.
How can I do the same with mongoTemplate since I cannot seem to find something similar to projection when using mongoTemplate.findOne(..). Do you need to using an Aggregate pipeline to do this with mongoTemplate?
I'm using Spring Data MongoDB version 3.0.1.RELEASE (spring boot 2.3.3).
You can use include() or exclude() options in the query.
ex:
Query query = new Query();
query.fields().include("name").exclude("id");
List<User> john = mongoTemplate.find(query, User.class);
Documentation Reference: data/mongodb/core/query/Field
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