【问题标题】:How to get random documents using spring mongorepository? [duplicate]如何使用 spring mongorepository 获取随机文档? [复制]
【发布时间】:2017-11-14 19:30:30
【问题描述】:

让我们假设以下结构:

一个用户类:

public class User {

@Id
String id;
String name;
//...

}

用户存储库:

public interface UserRepository extends MongoRepository<User, String> {

List<User> findByRandom(); // this method signature does not exist but would do what I intend to do

}

用户控制器:

@Component
public class UserController {

    private UserRepository users;

      @Autowired
      public UserController(
          UserRepository users) {
        this.users= users;
      }

public List<User> getRandomUsers() {
return(users.findByRandom()); // limit is missing here
}

        }

如何从这样的结构中接收随机文档。 在文档上有一个具有随机值的字段将不是一个理想的解决方案,因为这些值应该始终是随机的(例如,如果我命中随机 int 值 4 并接收 x 以下项目,这些将始终相同)。也不希望查询 x 次,因为这将是太重的负载。 有人可以帮忙吗?

提前致谢,

码海

【问题讨论】:

    标签: java mongodb spring-data spring-mongo spring-mongodb


    【解决方案1】:

    只需使用$sample 阶段:

    通过 Spring-Data(从 v2.0 开始):

    SampleOperation matchStage = Aggregation.sample(5);
    Aggregation aggregation = Aggregation.newAggregation(sampleStage);
    AggregationResults<OutType> output = mongoTemplate.aggregate(aggregation, "collectionName", OutType.class);
    

    直接通过Java驱动:

    import static com.mongodb.client.model.Aggregates.*;
    users.aggregate(Arrays.asList(sample(5)));
    

    【讨论】:

    • 你能给出更详细的答案吗,因为聚合方法似乎不是 org.springframework.data.mongodb.repository.MongoRepository 基本方法的一部分( throws can't resolve 方法),我在网上查找示例时遇到问题
    • 很抱歉,这里已经很晚了 - 我不知何故没有看到“Spring”部分,所以我最初只是给出了“标准 Java 驱动程序”的答案......
    • 遗憾的是,这只适用于 Spring Data 2.0 以上的版本
    猜你喜欢
    • 1970-01-01
    • 2012-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 2021-09-03
    相关资源
    最近更新 更多