根据条件获取MongoDB数据库中的随机条数的数据

726 阅读1分钟

听说最近博客园崩了,只能来掘金发表了.....

本文重点:mongoose的aggregate聚合管道,原理就不讲了,直接讲怎么获取随机数据

官方地址:www.mongoosejs.net/docs/api.ht…

有三种写法:

Activity.aggregate([
    {
        $match: {
            'act_status': '1',
            'verifycode': 1
        }
    }
 ]).sample(6);

第二种写法:

Activity.aggregate([
    {
        $match: {
            'act_status': '1',
            'verifycode': 1
        }
    },{
        $sample: {
            size: 6
        }
    }
]);

第三种写法(更简洁):

Activity.aggregate().match({
    'act_status': '1',
    'verifycode': 1
}).sample(6);

$match 里面是数据筛选条件,$sample 是需要获取的随机数据条数