Skip to content

Instantly share code, notes, and snippets.

@zakuni
Created March 11, 2012 08:28
Show Gist options
  • Save zakuni/2015601 to your computer and use it in GitHub Desktop.
Save zakuni/2015601 to your computer and use it in GitHub Desktop.
Getting a random document from MongoDB collection
var count = db.collections.count()
var rand = function(){return Math.floor( Math.random() * count )}
db.collection.find().limit(-1).skip(rand()).next();
@mkyung
Copy link

mkyung commented Aug 16, 2013

Skip is a very inefficient function in Mongodb.

@toblerpwn
Copy link

agreed; we have something like ~8 million records in one database, and skipping deep in to the collection takes almost 2 seconds (depending on the skip value). not ideal in most production environments.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment