2017-11-14 17 views
0

는 다음과 같은 구조를 가정 할 수 있습니다 :봄 mongrepository를 사용하여 임의의 문서를 얻는 방법?

사용자 클래스 :

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 번을 쿼리하는 것은 너무 무거운 짐이기 때문에 바람직하지 않습니다. 아무도 도와 줄 수 있습니까? (이후 2.0에서)

통해 봄 - 데이터 : 사전에

감사합니다,

Codehai

답변

0

는 그냥 $sample 단계를 사용하여 직접

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

을 자바를 통해 드라이버 :

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

집계 메서드가 org.springframework.data.mongodb.repository.MongoRepository 기본 메서드 (throws는 메서드를 해결할 수 없음)의 일부가 아닌 것처럼 보였으므로보다 자세한 대답을 제공 할 수 있으며 예제를 찾는 데 문제가 있습니다. 웹 – Codehai

+0

미안 해요, 늦었어요 - 어떻게 든 처음에는 "표준 자바 드라이버"답변을 준 "봄"부분을 보지 못했습니다 ... – dnickless

+0

슬프게도 이것은 스프링 데이터 2.0 이상에서만 작동합니다 – Codehai