Random Sampling from Mongo

Aditya Singh picture Aditya Singh · Sep 30, 2012 · Viewed 13.4k times · Source

I have a mongo collection with documents. There is one field in every document which is 0 OR 1. I need to random sample 1000 records from the database and count the number of documents who have that field as 1. I need to do this sampling 1000 times. How do i do it ?

Answer

dalanmiller picture dalanmiller · Feb 9, 2016

For people coming to the answer, you should now use the new $sample aggregation function, new in 3.2.

https://docs.mongodb.org/manual/reference/operator/aggregation/sample/

db.collection_of_things.aggregate(
   [ { $sample: { size: 15 } } ]
)

Then add another step to count up the 0s and 1s using $group to get the count. Here is an example from the MongoDB docs.