mongodbmongooseselectrandomnon-relational-database

How to select random documents from the MongoDB collection but not the previous ones?


I have a collection of videos in MongoDB and want to select random videos documents from that collection the below code is working fine

 const videos = await Video.aggregate([{ $sample: { size: Number(num) } }]);

but it also includes the previous result in the next query. I want to select random videos documents but not the previous ones.


Solution

  • I had the same issue while displaying stories to users.

    So I simply store 5 to 10 ids of first query result in frontend side and add $match filter with next query. And again replace previous ids with new result ids.

    let ids = req.body.alreadyShowedVideos;
    const videos = await Video.aggregate([{$match: {_id: {$ne: ids}}}, { $sample: { size: Number(num) } }]);