I have a MongoDB collection (let's call it myColl) with around 1000 documents like following:

   "_id" : ObjectId("5e94b03a8397f71c25d95abb"), 
   "name" : "NameExample" 

I want to get 10 random and unique documents from myColl, and actually I'm doing it in this way:

   [ { $sample: { size: 10 } } ]

But today I read in the documentation that $sample may output the same document more than once in its result set (source: https://docs.mongodb.com/manual/reference/operator/aggregation/sample/). Does it mean that in my case I can get the same document twice (or even more)? If yes, what is the most efficient way to get random and unique results?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.