1

I have entity Article I'm trying to retrieve one random record from database collection.

This is entity Article:

@Data
@Document(value = "article")
public class Article {

    @Id
    private String articleId;
    private String title;
    private String description;
    private String fullArticle;

This is service to save it:

@Override
public Article save(Article article) {
    return articleRepository.save(article);
}

And repository:

@Repository
public interface ArticleRepository extends MongoRepository<Article, String> {
}

So, now I'm trying to create a method that will get me one random record from my collection Article also, I want to create a controller so when I go to some endpoint and submit some get method to retrieve one record from the collection and so I can check it in postman or with Swagger. I find some answers to similar question to mine but no one solved my problem, I want to have API for something like that.

asu
  • 61
  • 5

1 Answers1

1

You can use $sample in an aggregation query to get a random document:

db.collection.aggregate([
  {
    "$sample": {
      "size": 1
    }
  }
])

Example here

I've tested the code and it works as expected.

You can create add this method into repository:

@Aggregation(pipeline={"{$sample:{size:1}}"})
AggregationResults<Article> random();

And call from service like this:

@Override
public Article random(){
  return articleRepository.random().getMappedResults().stream().findFirst().orElse(null);
  // also you can use .orElseThrow() or whatever you want
}
J.F.
  • 13,927
  • 9
  • 27
  • 65
  • Thank you, but on which way I can implement that so I can use it on some endpoint and etc.? – asu Feb 03 '22 at 18:58
  • Check [this answer](https://stackoverflow.com/a/62865095/13464279). I can't test now but `@Aggregation(pipeline = {/*the query*/})` should works. Also I'll try to test in a while and post an example. – J.F. Feb 03 '22 at 19:08
  • Edited question added repository and service methods. – J.F. Feb 03 '22 at 22:17