Mongoose get a random element except one
Run two queries where the first fetches the chosen document and the other uses the aggregation framework to run a pipeline with the $sample
operator to return 2 random documents from the collection except the chosen one.
The following query uses Mongoose's built-in Promises
to demonstrate this:
let chosenArticle = article.find({ "url": articleUrl }).exec();let randomArticles = article.aggregate([ { "$match": { "url": { "$ne": articleUrl } } }, { "$sample": { "size": 2 } }]).exec();Promise.all([chosenArticle, randomArticles]).then(articles => { console.log(articles);});