Random document from a collection in Mongoose

后端 未结 6 2178
北恋
北恋 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:57

    A shorter and maybe more performant solution
    (we don't iterate through the collection once to count and a second time to skip elements, but mongoose might do that behind the scenes):

    Use aggregate and $sample:

    Model.aggregate([{ $sample: { size: 1 } }])
    

提交回复
热议问题