MongoDB Random VS Sample VS Sample Rate Operators

What are MongoDB operators?

MongoDB offers different types of operators that can be used to interact with the database. Operators are special keywords that inform a compiler or an interpreter to carry out mathematical or logical operations.

There are different types and sub-types of operators. Today we will check out the difference between random and sample operators of Aggregation Operator type.

Random Operator

Whenever it calls a random operator it will return a floating value between 0 to 1 only. A Floating number will have 17 digits after the decimal point. Trailing zero (0) is dropped so the actual number of digits may vary.

Syntax

{ $rand: {} }

Example

Let’s say we have a product collection. Now we want to add a discount to all products between 0 to 10 percent. So, in this case, we can use the random operator. Let’s check out an experiment with the below sample query.

Data Before inserting the discount field into the collection.

Sample query

Query

db.products.aggregate(
   [
      { $set: { discount: { $multiply: [ { $rand: {} }, 10 ] } } },
      { $set: { discount: { $floor: "$discount" } } },
      { $merge: "products" }
   ]
)

Result

Result

Sample Operator

Randomly selects the specified number of documents from the input documents. It uses a pseudo-random cursor to select the N documents:

Syntax

{ $sample: { size: <positive integer N> } }

Query

db.products.aggregate(
   [ { $sample: { size: 3 } } ]
)

Result

Query

Sample Rate Operator

The selection process uses a uniform random distribution. The sample rate is a floating point number between 0 and 1, inclusive, which represents the probability that a given document will be selected as it passes through the pipeline.

For example, a sample rate of 0.33 selects roughly one document in three.

Syntax

{ $match: { $sampleRate: 0.33 } }

Query

db.products.aggregate(
   [
     { $match: { $sampleRate: 0.50 } },
     { $count: "numMatches" }
   ]
)

Result

Local

Ecommerce

Summary

In this article, we cover the three operators Random, Sample, and sample rate operator. All look the same but there are special features of each which we can see by the example given in the article. Also, based on the scenario or the case we can use these operators.


Similar Articles