2

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?

mickl
  • 48,568
  • 9
  • 60
  • 89
A Rogue Otaku
  • 913
  • 10
  • 20
  • this question is not a duplicate because it asks how to avoid querying the same elements... – Bersan Oct 22 '22 at 16:58

1 Answers1

9

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 } } 
    ]
)
mickl
  • 48,568
  • 9
  • 60
  • 89
  • So you mean I should keep all the previously returned random docs in an array? Will that be an efficient way? – A Rogue Otaku Apr 09 '19 at 13:18
  • You should keep them somewhere if you want to gurantee that those will not be randomly picked again – mickl Apr 09 '19 at 13:27