Shashi Ranjan Shashi Ranjan - 5 months ago 22
Java Question

Get all documents based on query using Spring MongoOperations

My User POJO look like:

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 single document based on this query:

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


I want to get all the document for this query. Some method call like
mongoOperations.findAll(searchQuery, User.class);

How I can do this?

Answer

You have Two Option,

Option 1:

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

Option 2:

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

Note: For further details You can refer THIS LINK

Comments