如何编写查询以从mongodb集合中获取不同的值? [英] How to write a query to get distinct values from mongodb collection?

查看:48
本文介绍了如何编写查询以从mongodb集合中获取不同的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从集合中获取不同的值.这些数据在集合的字段中.这意味着我需要从用户集合中获取一组名称.我使用cmd进行了尝试,并根据需要获得了结果.但是我不明白如何在spring文件中编写查询.由于我是java的新手,所以我对如何处理该查询知识不足.

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

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" );
  }

推荐答案

您可以在 UserRepository 中引入一个方法来检索不同的 firstName 字段值并返回 List< String> .

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();

使用Spring Data MongoDB v2.4和MongoDB v4.2可以很好地工作.

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

这篇关于如何编写查询以从mongodb集合中获取不同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆