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

后端 未结 4 787
滥情空心
滥情空心 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:54

    skip didn't work out for me. Here is what I wound up with:

    var randomDoc = db.getCollection("collectionName").aggregate([ {
        $match : {
    // criteria to filter matches
        }
    }, {
        $sample : {
            size : 1
        }
    } ]).result[0];
    

    gets a single random result, matching the criteria.

提交回复
热议问题