2

I have been querying mongodb using mongorepository and spring data.

My function looks like this:

@Repository
public interface UserRepository extends MongoRepository<User,String> {
    @Query(value="{'email' : ?0}")
    User findByEmail(String email);
}

My collection in mongodb looks like this

> db.user.find();
{ "_id" : "1", "email" : "[email protected]", "password" : "$2a$12$lDJgMZNLAcxv2J.QTZSjAuWJdPleBxXq.M4aj9itrR1RMDkgmwN7m", "name" : "def", "active" : 1, "isLoacked" : false, "isExpired" : false, "isEnabled" : true, "_class" : "com.x.gateway.auth.User" }

It always returns null value.

4
  • which email are you use for query ? Commented Apr 15, 2020 at 19:57
  • email :[email protected] Commented Apr 16, 2020 at 14:45
  • Try to use List<User> may be email is not a unique field at all. Commented Apr 16, 2020 at 14:47
  • @AbinashGhosh Your suggestion worked ` public interface UserRepository extends MongoRepository<User,String> { //@Query(value="{'email' : ?0}") List<User> findByEmail(String email); } ` Thanks man. Now will try to make the field unique. If you got any cheatsheet on db schema standards in mongo please attach it would be great help in this topic. Commented Apr 16, 2020 at 15:14

2 Answers 2

1

Since email is not a unique property, multiple users can be fetched. So map the method to List<User>.

@Query(value="{'email' : ?0}")
List<User> findByEmail(String email);

Offical doc, here you can find more details.

Sign up to request clarification or add additional context in comments.

2 Comments

In official doc 6.3 Query methods is all about different query method.
if you find any solution helpful try to upvote it also
0

Why are you using

@Query(value="{'email' : ?0}")

As email is the direct field (Not nested) , only

User findByEmail(String email);

is enough and should work.

3 Comments

@Alien : i had commented the annotation still no luck
@AbinashGhosh : i had used email :[email protected] for querying
Ok then check you have only one record with this email in your db + Repository is autowired properly in service or controller class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.