$sampleRate

Randomly selects documents from the input at the specified rate, useful for sampling large datasets or creating representative subsets for analysis.

Syntax

{ $sampleRate: <rate> }

Parameters

ratenumberrequired

The sample rate as a number between 0 and 1, representing the percentage of documents to select

Examples

Sample 10% of documents

Randomly select 10% of documents from a collection

Query:

db.products.aggregate([{ $sampleRate: 0.1 }])

Output:

Approximately 10% of the documents from the products collection

Sample for analysis

Sample 5% of large dataset for statistical analysis

Query:

db.sales.aggregate([{ $sampleRate: 0.05 }, { $group: { _id: null, avgSales: { $avg: "$amount" } } }])

Output:

Average sales amount calculated from 5% sample of the sales data

Sample with additional filtering

Sample documents after applying filters

Query:

db.orders.aggregate([{ $match: { status: "completed" } }, { $sampleRate: 0.2 }])

Output:

20% sample of completed orders for analysis

Related