Mongoose get a random element except one Mongoose get a random element except one mongoose mongoose

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);});


There is the mongodb command $sample, which is gonna read documents in a random way.


Example from the documentation :

db.users.aggregate( [ { $sample: { size: 3 } } ] )