The problem of Spring+MongoDB using MongoTemplate query.

  mongodb, question

There is data that meets this condition in db.

Query query=new Query(

Find () method:

List<XXObject> result = mongoTemplate.find(query, XXObject.class);
 if(result!  =null && !  result.isEmpty()){
 return result.get(0);

FindOne () method:

XXObject obj = mongoTemplate.findOne(query, XXObject.class);
 if(obj!  =null){
 return obj;

Why are the results of these two queries different under the same conditions? (The problem I encountered was that the findOne query result was empty).

Official document description of findole find findole:
findOneMap the results of an ad-hoc query on the collection to a single instance of an object of the specified type.

findMap the results of an ad-hoc query on the collection to a List of the specified type.

It doesn’t seem to make any difference.


 public class MgUser {
 private String nikename;
 private String phone;

Test class:

 public void test() {
 MgUser mgUser = new MgUser();
 Query query=new Query(Criteria.where("nikename").is(mgUser.getNikename()).orOperator(Criteria.where("phone").is(mgUser.getPhone())));
 MgUser selectMgUser = mongoTemplate.findOne(query, MgUser.class);
 Assert.assertTrue(selectMgUser!  =null);
 List<MgUser> list = mongoTemplate.find(query,MgUser.class);
 Assert.assertTrue(list.size() >= 1);

I have found out that it is valuable and I hope I can help you.