Reputation: 65
How do i get random a single document from a collection in MongoDB.
How can I fix the code.
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
if(err) throw err;
var query = { };
var total = db.collection('cities').count();
var random = Math.floor(Math.random()*total);
db.collection('cities').find({}).skip(random).limit(1).toArray(function (err, doc) {
if(err) throw err;
console.dir(doc);
db.close();
});
});
i am getting error : undefined is not a function
$ node afindone
c:\Users\Administrator\node_modules\mongodb\lib\mongodb\connection\base.js:245
throw message;
^
TypeError: undefined is not a function
at c:\Users\Administrator\node_modules\mongodb\lib\mongodb\collection\commands.js:52:5
at c:\Users\Administrator\node_modules\mongodb\lib\mongodb\db.js:1131:7
at c:\Users\Administrator\node_modules\mongodb\lib\mongodb\db.js:1847:9
at Server.Base._callHandler (c:\Users\Administrator\node_modules\mongodb\lib\mongodb\connection\base.js:445:41)
at c:\Users\Administrator\node_modules\mongodb\lib\mongodb\connection\server.js:478:18
at MongoReply.parseBody (c:\Users\Administrator\node_modules\mongodb\lib\mongodb\responses\mongo_reply.js:68:5)
at null.<anonymous> (c:\Users\Administrator\node_modules\mongodb\lib\mongodb\connection\server.js:436:20)
at emit (events.js:95:17)
at null.<anonymous> (c:\Users\Administrator\node_modules\mongodb\lib\mongodb\connection\connection_pool.js:201:13)
at emit (events.js:98:17)
-------------------------------------- ok. i fixed. ----------------------------
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
if(err) throw err;
var cities = db.collection('cities');
var query = {};
var cursor = cities.find(query);
var total,random;
cities.count(function(err, count) {
random = Math.floor(Math.random()*count);
cursor.sort({_id : -1});
cursor.skip(random);
cursor.limit(1);
cursor.each(function(err, doc) {
if(err) throw err;
if(doc == null) {
return db.close();
}
console.dir(doc);
});
});
});
Upvotes: 5
Views: 4488
Reputation: 6915
Here is answer how to get random n number of mongodb docs. MongoDB: how to find 10 random document in a collection of 100?
The line which makes magic: db.products.aggregate([{$sample: {size: 10}}]);
Upvotes: 2