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
author image

mkyong

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. Read all published posts by

Comments

avatar
3000
newest oldest most voted
Shyam
Guest
Shyam

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.

Jack Jack
Guest
Jack Jack

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