Last active
December 14, 2015 09:39
-
-
Save jbottigliero/5066194 to your computer and use it in GitHub Desktop.
mongodb - random document(s)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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