Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I retrieve a subset of fields using Spring's MongoTemplate and Query classes?

Tags:

I want to be able to execute the following console command to return all rows with only a subset of fields populated but using Spring's MongoTemplate class:

Console Command

db.person.find(null,{name:1}) 

MongoTemplate

mongoTemplate.find(new Query(...), Person.class) 

Info on projection (subset) queries can be found in the MongoDB manual.

like image 568
JARC Avatar asked May 01 '12 10:05

JARC


People also ask

How do you use MongoTemplate aggregation?

To perform and aggregation, first, create aggregation pipelines using the static builder methods on Aggregation class, then create an instance of Aggregation using the newAggregation() method on the Aggregation class and finally run the aggregation using MongoTemplate: MatchOperation matchStage = Aggregation.

What is @document annotation in spring boot?

@Document is an annotation provided by Spring data project. It is used to identify a domain object, which is persisted to MongoDB. So you can use it to map a Java class into a collection inside MongoDB. If you don't use Spring Data, you don't need this annotation.

What is MongoRepository?

MongoRepository is an interface provided by Spring Data in the package org. springframework. data. mongodb.

Which Annotation used on domain class is spring data MongoDB?

The @Id annotation tells the mapper which property you want to use for the MongoDB _id property and the @Indexed annotation tells the mapping framework to call ensureIndex on that property of your document, making searches faster.


2 Answers

Query q = new Query(); q.fields().include("name"); mongoTemplate.find(q, Person.class); 
like image 80
JARC Avatar answered Oct 04 '22 22:10

JARC


mongoTemplate.getCollection(COLLECTION).find(null, new BasicDBObject(FIELD, "1")) 
like image 33
dan andrei zaharia Avatar answered Oct 04 '22 22:10

dan andrei zaharia