Custom queries using MongoTemplate

1.2k views Asked by At

I need to make some aggregation using MongoTemplate. I am using Spring Data MongoDB, so most of my CRUD operations are made through MongoRepository interface. I have read about @NoRepositoryBean but I don't know how to use it in my case.

// UserRepository.java
// imports omitted
@Repository
public interface UserRepository extends MongoRepository<User, String> {

    User findOneByUsername(String username);

    @Query(value = "{ '_id' : ?0 }", fields = "{ 'username' : 1 }")
    User getUserDetails(String userId);

}

// CustomUserRepo.java
// imports omitted
@Component
public class CustomUserRepo {

    @Autowired
    private final UserRepository userRepository;

    public List<Todo> getUserTodos(String userId){
        TypedAggregation<User> aggregation = newAggregation(
                User.class, Aggregation.match(Criteria.where("_id").is(userId)),
                Aggregation.unwind("todos")
        );
        AggregationResults<Todo> groupResults = mongoTemplate.aggregate(aggregation, User.class, Todo.class);
        return groupResults.getMappedResults();
    }

}

How to make it as the same UserRepository bean?

If I inherit UserRepository I have to implement all methods. If I make CustomUserRepo abstract it can't be instantiated.


Update:

Useful articles:

But the solution is in using conventions of class names. Is there any way to make it by class design?

0

There are 0 answers