Johan
Johan

Reputation: 40608

Project only certain fields when using MongoTemplate from Spring Data MongoDB for a find query?

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).

Upvotes: 4

Views: 4346

Answers (1)

Deepak Patankar
Deepak Patankar

Reputation: 3302

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

Upvotes: 7

Related Questions