Skip to content

Instantly share code, notes, and snippets.

@jbottigliero
Last active December 14, 2015 09:39
Show Gist options
  • Select an option

  • Save jbottigliero/5066194 to your computer and use it in GitHub Desktop.

Select an option

Save jbottigliero/5066194 to your computer and use it in GitHub Desktop.
mongodb - random document(s)
// mongodb collection generator for getting random documents...
// set to the collection you wish to add a random attribute to.
var collection = 'myCollection',
// the name of the random collection to be generated; what you'll run queries against
// to obtain a random document
randCollection = 'rand' + collection.charAt(0).toUppderCase(),
// wheter or not the random collection should contain full documents, or a truncated
// version of the document (the mongo $_id and random attribute only)
useTruncatedDoc = false;
db[collection].find().forEach(function(doc){
if (useTruncatedDoc) {
doc = {
_id: doc._id
};
}
doc.randomAttr = Math.random(),
db[randCollection].insert(doc);
});
// generate an index on the new collection..
db[randCollection].ensureIndex({
randomAttr: 1
});
/**
// To grab a single random document after running the above code:
db[randCollection].findOne({
randomAttr: {
$gte: Math.random()
}
});
**/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment