4

If use MongoRepository, You can have following code:

@Repository
public interface UserRepo extends MongoRepository<User, String> {

    // additional methods go here 

} 

then you do userRepo.save() find() etc to do CRUD ops.

or you just MongoTemplate and do CRUD ops.

My question is which is preferred? what are the pros and cons for each approach? Thanks!

Bobo
  • 8,777
  • 18
  • 66
  • 85
  • 2
    Possible duplicate of [What's the difference between Spring Data's MongoTemplate and MongoRepository?](http://stackoverflow.com/questions/17008947/whats-the-difference-between-spring-datas-mongotemplate-and-mongorepository) – cassiomolin Jun 09 '16 at 09:25

2 Answers2

6

ok, by looking at source code MongoRepository consume mongoTemplate and provide a set of common DAO API so in other words, use MongoRepository is preferred way.

Bobo
  • 8,777
  • 18
  • 66
  • 85
4

MongoTemplate :

  • More Flexible and powerfull (used for more complex queries, aggregations)
  • Low Level; You need to know how Mongo queries work

MongoRepository

  • Easier to use because they are a higher abstraction (90% cases)
  • Friendly Syntax for filtering data
  • Built on top of JPA, consistent syntax, same methods as repositories over SQL
  • Do not work on all usecases, when you need more complex queries sometimes you need to fallback to the MongoTemplate.
Amit Nayak
  • 583
  • 1
  • 6
  • 17