Home > Blockchain >  How to get random record from one collection MongoDB
How to get random record from one collection MongoDB

Time:02-04

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.

CodePudding user response:

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
}
  •  Tags:  
  • Related