Node.js MongoDb - 获取随机n个文档

时间:2014-08-13 01:33:12

标签: node.js mongodb random collections

如何从MongoDB中的集合中随机获取单个文档。

如何修复代码。

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

我收到错误:undefined不是函数

$ 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) 

--------------------------------------好的。我解决了。 ----------------------------

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

1 个答案:

答案 0 :(得分:1)

以下是如何获取随机n个mongodb文档的答案。 MongoDB: how to find 10 random document in a collection of 100?

制造魔法的线:db.products.aggregate([{$sample: {size: 10}}]);