- Reference >
- Operators >
- Aggregation Pipeline Stages >
- $sample (aggregation)
$sample (aggregation)¶
On this page
Definition¶
Behavior¶
If all of the following conditions are true, $sample uses a
pseudo-random cursor to select the N documents:
$sampleis the first stage of the pipeline.Nis less than 5% of the total documents in the collection.- The collection contains more than 100 documents.
If any of the previous conditions are false, $sample:
- Reads all documents that are output from a preceding aggregation stage or a collection scan.
- Performs a random sort to select
Ndocuments.
Note
Random sorts are subject to the sort memory restrictions.
Example¶
Given a collection named users with the following documents:
The following aggregation operation randomly selects 3 documents from the
collection:
The operation returns three random documents.
See also