$rand¶
On this page
Examples¶
Generate Random Data Points¶
This example models charitable donations. The collection starts with a list of donors.
Then we construct an operation to update each document with a random donation amount:
The empty update filter matches every document in the collection.
For each document we generate a value between 0 and 1 using $rand
then scale the value with $multiply
.
The $floor
operator removes the decimal portion so the
updated amount
is an integer value.
After updating the collection, the documents look like this:
Select Random Items From a Collection¶
The $rand
operator can be used to select random documents from a
collection. Given a collection of voter records:
Imagine you want to select about half of the voters in District 3 to do some polling.
The intial match on the district
field selects documents where the
voter is from district 3.
The $expr
operator uses $rand
to further refine the
find
operation. For each document, $rand
generates a
value between 0 and 1. The threshold of 0.5
means the less than
($lt)
comparison will be true for about half the
documents in the set.
There are 7 voters in District 3, running the code selects about half of them.
See also