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

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

    Since 3.2 there is an easier way to to get a random sample of documents from a collection:

    $sample New in version 3.2.

    Randomly selects the specified number of documents from its input.

    The $sample stage has the following syntax:

    { $sample: { size: } }

    Source: MongoDB Docs

    In this case:

    db.products.aggregate([{$sample: {size: 10}}]);
    

提交回复
热议问题