2

I need to get distinct values from a collection. Those data is in a field of a collection. It means I need to get set of name from the user collection.I tried it using cmd and I get the result as I need. But I can't understand how to write the query in the spring file.Since I'm new to java I have not enough knowledge how to handle this.

Given below is a image of the database collection enter image description here

Services.java

package limark.internal.css.services;

import limark.internal.css.core.model.User;
import limark.internal.css.exceptions.ResourceNotFoundException;
import limark.internal.css.persistence.UserRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;
import java.lang.reflect.Array;
import java.time.OffsetDateTime;
import java.util.List;

import static limark.internal.css.core.MessageConstants.USER_NOT_FOUND;

@Service
@Slf4j
public class UserService {

  private final UserRepository userRepository;

  @Autowired
  public UserService(final UserRepository userRepository){
    this.userRepository = userRepository;
  }

  /**
   * Creates a new User
   * @param user object
   * @return user object
   */
  public User create(User user){
    user.setCreatedByLoginId("");
    user.setCreatedTs(OffsetDateTime.now());

    return userRepository.save(user);
  }

  /**
   * Returns list of users.
   */
  public List<User> findUsers(){
    return userRepository.findAll();
  }

  /**
   * Find user by id
   * @param id userId
   * @return user
   */
  public User findById(@NotNull String id){
    return userRepository.findById(id).orElseThrow(()->new ResourceNotFoundException(USER_NOT_FOUND,
      id));
  }


  public User update(@NotNull User user){

    user.setLastUpdatedByLoginId("");
    user.setLastUpdatedTs(OffsetDateTime.now());

    return userRepository.save(user);
  }

  /**
   * sets a user to not active on delete with the given id
   *
   * @param userId valid user id
   * @throws ResourceNotFoundException when user is not found
   */
  public void deleteUser(String userId) {
    User user =
      userRepository
        .findById(userId)
        .orElseThrow(() -> new ResourceNotFoundException(USER_NOT_FOUND, userId));
    user.setActive(false);
    user.setLastUpdatedByLoginId("");
    user.setLastUpdatedTs(OffsetDateTime.now());
    userRepository.save(user);
    log.info("The user {} is deleted successfully.", user.getId());

  }

  /**
   * Returns list of users.
   */
  public Array findUsersList(){
    return userRepository.distinct( "firstName" );
  }
}

I need to add this query inside

/**
   * Returns list of users.
   */
  public Array findUsersList(){
    return userRepository.distinct( "firstName" );
  }
1

1 Answer 1

7

You can introduce a method in the UserRepository to retrieve the distinct firstName field values and return a List<String>.

public interface UserRepository extends MongoRepository<User, String> {

    @Aggregation(pipeline = { "{ '$group': { '_id' : '$firstName' } }" })
    List<String> findDistinctFirstNames();
}

The call to get the list of distinct first names:

List<String> firstNamesDistinct = userRepository.findDistinctFirstNames();

This worked fine using Spring Data MongoDB v2.4 and MongoDB v4.2.

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

Comments

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.