0
は、次のような構造を仮定します:スプリング・モンゴリポジトリを使用してランダムな文書を取得する方法は?
ユーザークラス:
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
}
}
がどのように1がに達成するであろうこのような構造からランダムな文書を受け取る。 値が常にランダムでなければならないので、ドキュメント上にランダムな値を持つフィールドを持つことは望ましい解決法ではありません(例えば、ランダムなint値4に達し、xの後続アイテムを受け取ると、それらは常に同じになります)。 x回のクエリを行うことは、あまりにも重い負荷になるので、あまり好ましくない。 誰も助けることができますか?
経由春データ(V2.0から以降):Javaのを介して直接
SampleOperation matchStage = Aggregation.sample(5);
Aggregation aggregation = Aggregation.newAggregation(sampleStage);
AggregationResults<OutType> output = mongoTemplate.aggregate(aggregation, "collectionName", OutType.class);
事前に
おかげで、
Codehai
集計メソッドがorg.springframework.data.mongodb.repository.MongoRepositoryベースメソッドの一部ではないように思われるので、より詳細な回答を与えることができます(スローはメソッドを解決できません)。ウェブ – Codehai
残念ですが、ここに遅れています - 私は何とか "春"の部分を見ていなかったので、最初は "標準Javaドライバ"の答えを返しました... – dnickless
悲しいことに、これは春のデータ2.0以上でしか動作しません – Codehai