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?
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 } }
]
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With