0

As Mongoose doesn't have an option for random find, which of the following is better to use? (less resource consuming)

Minimal query and then big query:

Page.find()
    .select('_id')
    .then(function(pages){
        var randomPage = _.sample(pages);
        Page.findOne({id: randomPage._id})
        .populate('comments')
        .then(function(page){...}
    }

One query and picking a random item:

Page.find()
    .populate('comments')
    .then(function(pages){
        var randomPage = _.sample(pages);
        ...
    }
Ronen Teva
  • 1,345
  • 1
  • 23
  • 43
  • Possible duplicate of [Random record from MongoDB](http://stackoverflow.com/questions/2824157/random-record-from-mongodb) – Hongbo Miao Aug 14 '16 at 21:25

1 Answers1

0

Most efficient way is to use $sample operator in aggregation pipeline, which allowed since mongodb v3.2

DOCS: $sample (aggregation)

evilive
  • 1,781
  • 14
  • 20