Bobo
Bobo

Reputation: 9163

spring data mongodb , use MongoRepository or MongoTemplate?

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!

Upvotes: 4

Views: 5344

Answers (2)

Amit Nayak
Amit Nayak

Reputation: 621

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.

Upvotes: 4

Bobo
Bobo

Reputation: 9163

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.

Upvotes: 6

Related Questions