$rand (aggregation)

On this page本页内容

Definition定义

$rand

New in version 4.4.2.在版本4.4.2中新增

Returns a random float between 0 and 1 each time it is called.每次调用时返回0和1之间的随机浮点。

$rand has the following syntax:语法如下:

{ $rand: {} }

The $rand operator doesn't take any arguments.$rand运算符不接受任何参数。

Behavior行为

Each time $rand is called it will return a floating point value that has up to 17 digits after the decimal point. 每次调用$rand时,它将返回一个浮点值,该值在小数点后最多有17位数字。Trailing 0s are dropped so the actual number of digits may vary.尾随0被删除,因此实际位数可能会有所不同。

Examples示例

Generate Random Data Points生成随机数据点

This example models charitable donations. 这个例子模拟了慈善捐款。The collection starts with a list of donors.集合从捐赠者名单开始。

db.donors.insertMany(
   [
     { donorId: 1000, amount: 0, frequency: 1 },
     { donorId: 1001, amount: 0, frequency: 2 },
     { donorId: 1002, amount: 0, frequency: 1 },
     { donorId: 1003, amount: 0, frequency: 2 },
     { donorId: 1004, amount: 0, frequency: 1 }
   ]
)

We use an aggregation pipeline to update each document with a random donation amount.我们使用聚合管道以随机捐赠金额更新每个文档。

db.donors.aggregate(
   [
      { $set: { amount: { $multiply: [ { $rand: {} }, 100 ] } } },
      { $set: { amount: { $floor: "$amount" } } },
      { $merge: "donors" }
   ]
)

The first $set stage updates the amount field. 第一个$set阶段更新amount字段。An initial value between 0 and 1 is generated using $rand. 使用$rand生成0到1之间的初始值。Then $multiply scales it upward 100 times.然后$multiply将其向上扩展100倍。

The $floor operator in the second $set stage removes the decimal portion from the amount to leave an integer value.第二个$set阶段中的$floor运算符从amount中删除小数部分,以保留一个整数值。

Finally, $merge writes the random value created in the previous steps to the amount field, updating it for each document in the donors collection.最后,$merge将前面步骤中创建的随机值写入amount字段,并为捐助者集合中的每个文档更新它。

You can view the results with a projection stage:您可以使用投影阶段查看结果:

db.donors.aggregate(
   [
      { $project: {_id: 0, donorId: 1, amount: 1 } }
   ]
)

The projection shows the scaled amounts are now random values in the range from 0 to 99.投影显示,缩放的数量现在是0到99范围内的随机值。

{ "donorId" : 1000, "amount" : 27 }
{ "donorId" : 1001, "amount" : 10 }
{ "donorId" : 1002, "amount" : 88 }
{ "donorId" : 1003, "amount" : 73 }
{ "donorId" : 1004, "amount" : 5 }

Select Random Items From a Collection从集合中随机选择项目

You can use $rand in an aggregation pipeline to select random documents from a collection. 您可以在聚合管道中使用$rand从集合中随机选择文档。Consider a collection of voter records:考虑集合选民记录:

db.voters.insertMany(
   [
     { name: "Archibald", voterId: 4321, district: 3, registered: true },
     { name: "Beckham", voterId: 4331, district: 3, registered: true },
     { name: "Carolin", voterId: 5321, district: 4, registered: true },
     { name: "Debarge", voterId: 4343, district: 3, registered: false },
     { name: "Eckhard", voterId: 4161, district: 3, registered: false },
     { name: "Faberge", voterId: 4300, district: 1, registered: true },
     { name: "Grimwald", voterId: 4111, district: 3, registered: true },
     { name: "Humphrey", voterId: 2021, district: 3, registered: true },
     { name: "Idelfon", voterId: 1021, district: 4, registered: true },
     { name: "Justo", voterId: 9891, district: 3, registered: false }
   ]
)

Imagine you want to select about half of the voters in District 3 to do some polling.想象一下,你想选择第三区大约一半的选民进行投票。

db.voters.aggregate(
   [
      { $match: { district: 3 } },
      { $match: { $expr: { $lt: [0.5, {$rand: {} } ] } } },
      { $project: { _id: 0, name: 1, registered: 1 } }
   ]
)

The first pipeline stage matches all documents where the voter is from district 3.第一个管道阶段匹配选民来自3区的所有文件。

The second $match stage uses $rand in a match expression to further refine the selection. 第二个$match阶段在匹配表达式中使用$rand进一步优化选择。For each document, $rand generates a value between 0 and 1. 对于每个文档,$rand生成一个介于0和1之间的值。The threshold of 0.5 in the less than ($lt) comparison means that $expr will be true for about half the documents.在小于($lt)的比较中,阈值为0.5意味着$expr将适用于大约一半的文档。

In the $project stage the selected documents are filtered to return the name and registered fields. $project阶段,将筛选所选文档以返回nameregistered字段。There are 7 voters in District 3, running the code selects about half of them.第三区有7名选民,运行该代码可以选择其中大约一半的选民。

{ "name" : "Archibald", "registered" : true }
{ "name" : "Debarge", "registered" : false }
{ "name" : "Humphrey", "registered" : true }
Note注意

The number of documents selected is different each time. 每次选择的文档数都不同。If you need to select an exact number of documents, consider using $sample instead of $rand.如果需要选择准确的文档数,请考虑使用$sample而不是$rand

Tip提示
See also: 参阅:
←  $radiansToDegrees (aggregation)$range (aggregation) →