Main Tutorials

Spring Data MongoDB – Select fields to return

In MongoDB console, you can use field:1 to select the fields to return from a query :


> db.hosting.find({},{domain:1, count:1});

In Spring Data for MongoDB, you use query.fields().include :

HostingDaoImpl.java

package com.mkyong.core.hosting.dao;

import java.util.List;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;
import com.hostingcompass.core.db.dao.MongoDaoImpl;

@Repository
public class HostingDaoImpl 
	extends MongoDaoImpl<Hosting> implements HostingDao {

	@Override
	public List<Hosting> findTopHosting(int numOfRecord) {
		
		Query query = new Query();
		
		if (numOfRecord > 0)
			query.limit(numOfRecord);
		
		query.with(new Sort(Sort.Direction.DESC, "count"));
		query.fields().include("_id");
		query.fields().include("domain");
		query.fields().include("count");
		
		return findAll(query, Hosting.class);
		
	}

}

References

  1. Limit Fields to Return from a Query

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
4 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Test
3 years ago

What happaned mkyong? You used to post nice articles, this is completely useless

Anton
2 years ago

where is findAll(query, Hosting.class) function definition or it`s magic?

Jack Jack
4 years ago

Thank you very much. It is very difficult for Chinese website to find the solution.

Shyam
6 years ago

I would like to report this. This is pretty much useless and obvious. May be it might help if you explore complex requirements and put it in blog.