Reputation: 477
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.
Upvotes: 0
Views: 1033
Reputation: 587
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) } }]);
Upvotes: 1