Random document from a collection in Mongoose

后端 未结 6 2180
北恋
北恋 2020-12-02 23:45

I want to create a Schema.statics.random function that gets me a random element from the collection. I know there is an example for the native MongoDB driver, b

6条回答
  •  时光说笑
    2020-12-02 23:52

    You can use aggregate:

    User.aggregate([
        {$match: {gender: "male"}},
        {$sample: {size: 10}}
    ], function(err, docs) {
        console.log(docs);
    });
    

    Or you can use npm package https://www.npmjs.com/package/mongoose-simple-random

    User.findRandom({gender: "male"}, {}, {limit: 10}, function(err, results) { 
        console.log(results); // 10 elements
    });
    

提交回复
热议问题