1

I found mongoose-random package to get a JSON array of random records using mongoose.

I want to get three random records with a specific field. I read the documentation, but I still didn't find any solution. The following code doesn't work.

app.get('/get/random/song/:language/:gender', function (req, res) {

    var fields = {lang: req.params.language, gender: req.params.gender};
    var filter = {}
    var options = {skip: 3, limit: 3};
    Song.findRandom(filter, fields, options, function (err, songs) {
        res.json(songs);
    });
    
});
Engin
  • 755
  • 7
  • 20
  • 1
    Possible duplicate of [Random record from MongoDB](http://stackoverflow.com/questions/2824157/random-record-from-mongodb) – styvane Jan 20 '17 at 17:51
  • possible dupicate of https://stackoverflow.com/questions/14644545/random-document-from-a-collection-in-mongoose – Deepak Jul 31 '19 at 10:39

1 Answers1

6

Nowadays you could use aggregate , like this :

this.aggregate([ { $match: { "condition1" : "to_match" , "condition2" : "to_match" } } , { $sample: { size : 3 } } ]);

Where the $sample size is the number of random rows you'll get

DIIMIIM
  • 557
  • 7
  • 28