Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude some fields form MongoOperations result

My User POJO looks like the following:

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "User")
public class User {
    @Id
    private String id;
    private String username;
    private String password;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
}

I am able to get all document based on the query:

List<User> testBedsFromDB = mongoOperations.findAll(User.class);

I want to skip some of the fields like password. I want to get all the document with values only in id and username, password may be null or empty. How I can achieve this?

like image 451
Shashi Ranjan Avatar asked Dec 19 '25 05:12

Shashi Ranjan


1 Answers

I was able to get all field excluding one field. Code spinet bellow:

Query searchQuery = new Query();
searchQuery.fields().exclude("password");
List<User> userList = mongoOperations.find(searchQuery, User.class);

With above code password field value will be null. You can use multiple exclude like:

searchQuery.fields().exclude("username").exclude("password");
like image 136
Shashi Ranjan Avatar answered Dec 20 '25 20:12

Shashi Ranjan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!