Skip to content

Commit b335602

Browse files
mungitoperritoandf-mongodb
authored andcommitted
DOCS-13883 add random number generator
1 parent b1faa52 commit b335602

File tree

7 files changed

+329
-26
lines changed

7 files changed

+329
-26
lines changed

source/includes/extracts-agg-operators.yaml

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -489,12 +489,19 @@ content: |
489489
* - Name
490490
- Description
491491
492+
* - :expression:`$rand`
493+
- Returns a random float between 0 and 1
494+
495+
.. versionadded:: 4.4.2
496+
492497
* - :expression:`$sampleRate`
493498
494499
- Randomly select documents at a given rate. Although the exact
495500
number of documents selected varies on each run, the quantity
496501
chosen approximates the sample rate expressed as a percentage
497502
of the total number of documents.
503+
504+
.. versionadded:: 4.4.2
498505
499506
---
500507
ref: agg-operators-objects

source/reference/operator/aggregation.txt

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -647,7 +647,13 @@ Alphabetical Listing of Expression Operators
647647
* - :expression:`$radiansToDegrees`
648648

649649
- Converts a value from radians to degrees.
650-
650+
651+
652+
* - :expression:`$rand`
653+
654+
- Returns a random float between 0 and 1.
655+
656+
.. versionadded:: 4.4.2
651657

652658
* - :expression:`$range`
653659

@@ -718,7 +724,8 @@ Alphabetical Listing of Expression Operators
718724
chosen approximates the sample rate expressed as a percentage
719725
of the total number of documents.
720726

721-
727+
.. versionadded:: 4.4.2
728+
722729
* - :expression:`$second`
723730

724731
- Returns the seconds for a date as a number between 0 and 60
Lines changed: 171 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,171 @@
1+
===================
2+
$rand (aggregation)
3+
===================
4+
5+
.. default-domain:: mongodb
6+
7+
.. contents:: On this page
8+
:local:
9+
:backlinks: none
10+
:depth: 1
11+
:class: singlecol
12+
13+
Definition
14+
----------
15+
16+
.. expression:: $rand
17+
18+
.. versionadded:: 4.4.2
19+
20+
Returns a random float between 0 and 1 each time it is called.
21+
22+
:expression:`$rand` has the following syntax:
23+
24+
.. code-block:: javascript
25+
26+
{ $rand: {} }
27+
28+
The :expression:`$rand` operator doesn't take any arguments.
29+
30+
Behavior
31+
--------
32+
Each time ``$rand`` is called it will return a floating point value
33+
that has up to 17 digits after the decimal point. Trailing 0s are
34+
dropped so the actual number of digits may vary.
35+
36+
Examples
37+
--------
38+
39+
This code initializes a ``randomSamples`` collection with 100 documents
40+
that is used in the following examples.
41+
42+
.. code-block:: javascript
43+
44+
N = 100
45+
bulk = db.randomSamples.initializeUnorderedBulkOp()
46+
for ( i = 0; i < N; i++) { bulk.insert( {_id: i, random: 0 } ) }
47+
bulk.execute()
48+
49+
50+
Usage with Update Queries
51+
~~~~~~~~~~~~~~~~~~~~~~~~~
52+
53+
The ``$rand`` operator can be used with update query operations. In
54+
this example :method:`~db.collection.updateMany()` uses the ``$rand``
55+
operator to insert a different random number into each document
56+
in the ``randomSamples`` collection.
57+
58+
.. code-block:: javascript
59+
60+
db.randomSamples.updateMany(
61+
{},
62+
[
63+
{ $set: { "random": { $rand: {} } } }
64+
]
65+
)
66+
67+
We can use :pipeline:`$project` to see the output. The
68+
:pipeline:`$limit` stage halts the pipeline after the third document.
69+
70+
.. code-block:: javascript
71+
72+
db.randomSamples.aggregate(
73+
[
74+
{ $project: {_id: 0, random: 1 } },
75+
{ $limit: 3 }
76+
]
77+
)
78+
79+
The output shows the random values.
80+
81+
.. code-block:: javascript
82+
:copyable: false
83+
84+
{ "random" : 0.8751284485870464 }
85+
{ "random" : 0.515147067802108 }
86+
{ "random" : 0.3750004525681561 }
87+
88+
Rounding to Control the Number of Output Digits
89+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
90+
91+
If you want a shorter random value, consider using :expression:`$round`.
92+
Note that the :pipeline:`$set` stage updates the document, if ``$rand``
93+
is called in a :pipeline:`$project` stage the underlying document is
94+
not modified.
95+
96+
.. code-block:: javascript
97+
98+
db.randomSamples.aggregate(
99+
[
100+
{ $match: {} },
101+
{ $set: { rounded: { $round: [ "$random", 4 ] } } },
102+
{ $out: "randomSamples" }
103+
]
104+
)
105+
106+
The :pipeline:`$project` stage displays the original and rounded value
107+
for each document.
108+
109+
.. code-block:: javascript
110+
111+
db.randomSamples.aggregate(
112+
[
113+
{ $project: {_id:0, random:1, rounded: 1 } },
114+
{ $limit: 3 }
115+
]
116+
)
117+
118+
The update documents look like this:
119+
120+
.. code-block:: javascript
121+
:copyable: false
122+
123+
{ "random" : 0.8751284485870464, "rounded" : 0.8751 }
124+
{ "random" : 0.515147067802108, "rounded" : 0.5151 }
125+
{ "random" : 0.3750004525681561, "rounded" : 0.375 }
126+
127+
.. note::
128+
129+
Like ``$rand``, the value returned by the ``$round`` operator does
130+
not include any trailing 0s so the number of digits returned may
131+
vary.
132+
133+
Selecting Random Items From a Collection
134+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
135+
136+
The ``$rand`` operator can be used in an aggregation pipeline to select
137+
random documents from a collection. In this example we use ``$rand`` to
138+
select about half the documents in the ``randomSamples`` collection.
139+
140+
.. code-block:: javascript
141+
142+
db.randomSamples.aggregate(
143+
[
144+
{ $match: { $expr: { $lt: [0.5, {$rand: {} } ] } } },
145+
{ $count: "numMatches" }
146+
]
147+
)
148+
149+
There are 100 documents in ``randomSamples``. Running the sample code 5
150+
times produces the following output which approaches the expected value
151+
of 50 matches in a collection this size.
152+
153+
.. code-block:: javascript
154+
:copyable: false
155+
156+
{ "numMatches" : 49 }
157+
{ "numMatches" : 52 }
158+
{ "numMatches" : 54 }
159+
{ "numMatches" : 48 }
160+
{ "numMatches" : 59 }
161+
162+
.. note::
163+
164+
This example shows that the number of documents selected is
165+
different each time. If you need to select an exact number of
166+
documents, consider using :pipeline:`$sample` instead of ``$rand``.
167+
168+
.. seealso::
169+
170+
:query:`$rand (query) <$rand>`, :pipeline:`$sample`, :expression:`$round`
171+

source/reference/operator/aggregation/sample.txt

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,3 +74,8 @@ collection:
7474
)
7575

7676
The operation returns three random documents.
77+
78+
.. seealso::
79+
80+
:expression:`$rand (aggregation) <$rand>`
81+
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
=============================
2+
Miscellaneous Query Operators
3+
=============================
4+
5+
.. default-domain:: mongodb
6+
7+
.. contents:: On this page
8+
:local:
9+
:backlinks: none
10+
:depth: 1
11+
:class: singlecol
12+
13+
.. include:: /includes/extracts/operators-toc-explanation.rst
14+
15+
.. list-table::
16+
:widths: 25,75
17+
:header-rows: 1
18+
19+
* - Name
20+
21+
- Description
22+
23+
* - :query:`$comment`
24+
25+
- Adds a comment to a query predicate.
26+
27+
* - :query:`$rand`
28+
29+
- Generates a random float between 0 and 1.
30+
31+
.. versionadded:: 4.4.2
32+
33+
34+
.. toctree::
35+
:titlesonly:
36+
:hidden:
37+
38+
/reference/operator/query/comment
39+
/reference/operator/query/rand

source/reference/operator/query.txt

Lines changed: 33 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ Query and Projection Operators
1010
:depth: 1
1111
:class: singlecol
1212

13+
1314
.. include:: /includes/extracts/operators-toc-explanation.rst
1415

1516
.. _query-selectors:
@@ -23,6 +24,7 @@ Comparison
2324
.. only:: website
2425

2526
.. include:: /includes/fact-comparison-order.rst
27+
2628
.. list-table::
2729
:widths: 30,70
2830
:header-rows: 1
@@ -299,64 +301,71 @@ Bitwise
299301

300302
/reference/operator/query-bitwise
301303

302-
Comments
303-
~~~~~~~~
304+
305+
.. _query-projection-operators:
306+
307+
Projection Operators
308+
--------------------
304309

305310
.. only:: website
306311

307312
.. list-table::
308-
:widths: 30,70
313+
:widths: 25,75
309314
:header-rows: 1
310315

311316
* - Name
312317

313318
- Description
314319

315-
* - :query:`$comment`
320+
* - :projection:`$`
316321

317-
- Adds a comment to a query predicate.
322+
- Projects the first element in an array that matches the query condition.
318323

324+
* - :projection:`$elemMatch`
325+
326+
- Projects the first element in an array that matches the specified :projection:`$elemMatch` condition.
327+
328+
* - :projection:`$meta`
329+
330+
- Projects the document's score assigned during :query:`$text` operation.
331+
332+
* - :projection:`$slice`
333+
334+
- Limits the number of elements projected from an array. Supports skip and limit slices.
319335

320336
.. toctree::
321337
:titlesonly:
322338
:hidden:
323339

324-
/reference/operator/query/comment
340+
/reference/operator/projection
325341

326-
.. _query-projection-operators:
342+
.. _query-miscelaneous-operators:
327343

328-
Projection Operators
329-
--------------------
344+
Miscellaneous Operators
345+
-----------------------
330346

331347
.. only:: website
332348

333349
.. list-table::
334-
:widths: 30,70
350+
:widths: 25,75
335351
:header-rows: 1
336352

337353
* - Name
338354

339355
- Description
340356

341-
* - :projection:`$`
342-
343-
- Projects the first element in an array that matches the query condition.
344-
345-
* - :projection:`$elemMatch`
346-
347-
- Projects the first element in an array that matches the specified :projection:`$elemMatch` condition.
348-
349-
* - :projection:`$meta`
350-
351-
- Projects the document's score assigned during :query:`$text` operation.
357+
* - :query:`$comment`
352358

353-
* - :projection:`$slice`
359+
- Adds a comment to a query predicate.
354360

355-
- Limits the number of elements projected from an array. Supports skip and limit slices.
361+
* - :query:`$rand`
356362

363+
- Generates a random float between 0 and 1.
357364

358365
.. toctree::
359366
:titlesonly:
360367
:hidden:
361368

362-
/reference/operator/projection
369+
/reference/operator/query-miscellaneous
370+
371+

0 commit comments

Comments
 (0)