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

4 comments on “Spring Data MongoDB – Select fields to return

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

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

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

    Reply
  4. 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.

    Reply

Leave a Comment

Your email address will not be published. Required fields are marked *