user1680104
user1680104

Reputation: 8887

Random document from a collection in Mongoose

I want to create a Schema.statics.random function that gets me a random element from the collection. I know there is an example for the native MongoDB driver, but I can't get it working in Mongoose.

Upvotes: 29

Views: 28870

Answers (10)

command which gives 3 random documents:

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

express line to get 4 random documents. i think it works in the latest versions of mongo.

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

see this link for further info

Upvotes: 0

Michael Lynch
Michael Lynch

Reputation: 3149

  1. Get the total number of documents in collection.
  2. Define a random number between 1 and the total number of documents.
  3. Get a document and skip that random number.
const total = await model.countDocuments();
const skip = Math.floor(Math.random() * total) + 1;
const randomDoc = await model.findOne({}).skip(skip).exec();

Upvotes: 0

FBaez51
FBaez51

Reputation: 551

// Getting estimated document count.
yourModel.estimatedDocumentCount().then((count) => {
  //Random number between 0 and count.
  const rand = Math.floor(Math.random() * count);

  // Finding ONE random document.
  yourModel
    .findOne()
    .skip(rand)
    .then((randomDocument) => {
      console.log(randomDocument);
    });
});

You can also use countDocuments(), but estimatedDocumentCount() is recommended for performance.

I prefer this method due to getting one document instead of an array.

Upvotes: 0

Jakub Siwiec
Jakub Siwiec

Reputation: 488

Nowadays Model.estimatedDocumentCount() is recommended. For the Model called Item an outline of a function would be:

const Item = require('../your/path/to/Model/Item')

async function getRandomItem() {
   const numItems = await Item.estimatedDocumentCount()
   const rand = Math.floor(Math.random() * numItems)
   const randomItem = await Item.findOne().skip(rand)
   return randomItem
}

Upvotes: 1

martinho
martinho

Reputation: 3379

You can use aggregate:

User.aggregate([
    {$match: {gender: "male"}},
    {$sample: {size: 10}}
], function(err, docs) {
    console.log(docs);
});

Or you can use npm package https://www.npmjs.com/package/mongoose-simple-random

User.findRandom({gender: "male"}, {}, {limit: 10}, function(err, results) { 
    console.log(results); // 10 elements
});

Upvotes: 14

Ioanna
Ioanna

Reputation: 1377

A shorter and maybe more performant solution
(we don't iterate through the collection once to count and a second time to skip elements, but mongoose might do that behind the scenes):

Use aggregate and $sample:

Model.aggregate([{ $sample: { size: 1 } }])

Upvotes: 19

embiem
embiem

Reputation: 113

For people looking at this in times of async/await, promises etc.:

MySchema.statics.random = async function() {
  const count = await this.count();
  const rand = Math.floor(Math.random() * count);
  const randomDoc = await this.findOne().skip(rand);
  return randomDoc;
};

Upvotes: 3

Eat at Joes
Eat at Joes

Reputation: 5037

If you are not wanting to add "test like" code into your schema, this uses Mongoose queries.

Model.count().exec(function(err, count){

  var random = Math.floor(Math.random() * count);

  Model.findOne().skip(random).exec(
    function (err, result) {

      // result is random 

  });

});

Upvotes: 23

Mihai Tomescu
Mihai Tomescu

Reputation: 1607

I've implemented a plugin for mongoose that does this in a very efficient way using a $near query on two randomly generated coordinates using a 2dsphere index. Check it out here: https://github.com/matomesc/mongoose-random.

Upvotes: 6

matthewtole
matthewtole

Reputation: 3247

I found this Mongoose Schema static function in a GitHub Gist, which should achieve what you are after. It counts number of documents in the collection and then returns one document after skipping a random amount.

QuoteSchema.statics.random = function(callback) {
  this.count(function(err, count) {
    if (err) {
      return callback(err);
    }
    var rand = Math.floor(Math.random() * count);
    this.findOne().skip(rand).exec(callback);
  }.bind(this));
};

Source: https://gist.github.com/3453567

NB I modified the code a bit to make it more readable.

Upvotes: 41

Related Questions