5

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);
        });
    });
});
2
  • I made a slight correction in the code. I get the error:$ 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: Commented Aug 13, 2014 at 2:03
  • Relatedly, there is a MongoDB cookbook recipe for selecting a random document from a collection. Your current method works but using skip() on a large collection will lead to performance problems as you still have to iterate over all the skipped documents to return 1. Commented Aug 13, 2014 at 16:18

1 Answer 1

2

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}}]);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.