MongoDB: how to find 10 random document in a collection of 100?

后端 未结 4 792
滥情空心
滥情空心 2020-12-15 21:00

Is MongoDB capable of funding number of random documents without making multiple queries?

e.g. I implemented on the JS side after loading all the document in the col

4条回答
  •  难免孤独
    2020-12-15 21:33

    Here is what I came up in the end:

    var numberOfItems = 10;
    
    
    // GET LIST OF ALL ID's
    SchemaNameHere.find({}, { '_id': 1 }, function(err, data) {
    
        if (err) res.send(err);
    
        // shuffle array, as per here  https://github.com/coolaj86/knuth-shuffle
        var arr = shuffle(data.slice(0));
    
        // get only the first numberOfItems of the shuffled array
        arr.splice(numberOfItems, arr.length - numberOfItems);
    
        // new array to store all items
        var return_arr = [];
    
        // use async each, as per here http://justinklemm.com/node-js-async-tutorial/
        async.each(arr, function(item, callback) {
    
            // get items 1 by 1 and add to the return_arr
            SchemaNameHere.findById(item._id, function(err, data) {
    
                if (err) res.send(err);
                return_arr.push(data);
    
                // go to the next one item, or to the next function if done
                callback();
    
            });
    
        }, function(err) {
    
            // run this when looped through all items in arr
            res.json(return_arr);
    
        });
    
    });
    

提交回复
热议问题