简体   繁体   中英

How to get random record from one collection MongoDB

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.

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

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

Example here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM