Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select Random 10 documents from mongoDB [duplicate]

I am learning node and mongo and currently working on a simple server which will just fetch 10 random documents from mongodb and send them as response on receiving a get request. My next aim is to create a single page which will display these 10 records in a html page with some basic styling. The page also has a next button which will fetch another 10 random records from the database. The problem is how can I make sure that the same records are not fetched twice in this process?

like image 939
A Rogue Otaku Avatar asked Aug 06 '26 09:08

A Rogue Otaku


1 Answers

To pick 10 random documents you can use $sample pipeline stage.

let randomDocs = db.col.aggregate(
    [ { $sample: { size: 10 } } ]
)

If you want to make sure that next $sample call will not return the same documents you need to make it stateful meaning that you should filter out the documents that were returned in previous call:

db.col.aggregate(
    [
        { $match: { _id: { $nin: randomDocs.map(doc => doc._id) } } },
        { $sample: { size: 10 } } 
    ]
)
like image 86
mickl Avatar answered Aug 09 '26 00:08

mickl