Skip to content

Instantly share code, notes, and snippets.

@lineus lineus/nsuchy3.js Secret
Last active Apr 6, 2018

Embed
What would you like to do?
mongodb aggregation $sample returns a random doc
#!/usr/bin/env node
'use strict'
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/test')
const Schema = mongoose.Schema
const schema = new Schema({
name: String,
bool: Boolean
})
const Test = mongoose.model('test', schema)
const tests = []
for (let i = 1; i < 1001; i++) {
let george = (i % 2 === 0)
tests.push(new Test({
name: `test${i}`,
bool: george
}))
}
async function run () {
await Test.remove({})
await Test.create(tests)
let ranDoc = await Test.aggregate([
{ $match: { 'bool': true } },
{ $sample: { size: 1 } }
]).exec()
console.log(ranDoc[0].name)
return mongoose.connection.close()
}
run()
gitter: while true; do ./nsuchy3.js ;done
test362
test892
test730
test342
test150
test638
test614
test922
test370
test954
test132
test584
^C
gitter:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.