使用Spring MongoOperations获取基于查询的所有文档

时间:2016-06-24 06:02:37

标签: java spring-data-mongodb

我的用户POJO看起来像:

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;
    }
}

我可以根据此查询获取单个文档:

Query searchQuery = new Query(Criteria.where("name").is("shashi"));
mongoOperations.findOne(searchQuery, User.class);

我想获取此查询的所有文档。一些方法调用如mongoOperations.findAll(searchQuery, User.class); 我怎么能这样做?

1 个答案:

答案 0 :(得分:3)

你有两个选项,

选项1:

List<User> listUser = mongoOperations.find(searchQuery, User.class);
System.out.println("Number of user = " + listUser.size());

选项2:

List<User> listUser = mongoOperation.findAll(User.class);
System.out.println("Number of user = " + listUser.size());

注意:有关详细信息,请参阅THIS LINK