Docs HomeMongoDB Manual

$rand (aggregation)

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. Trailing 0s are dropped so the actual number of digits may vary.每次调用$rand时,它都会返回一个浮点值,该值在小数点后最多有17位数字。后面的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阶段更新金额字段。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字段,并为donors(捐赠者)集合中的每个文档更新该值。

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.第一个管道阶段匹配选民来自第三选区的所有文件。

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生成一个介于01之间的值。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. There are 7 voters in District 3, running the code selects about half of them.$project阶段,筛选所选文档以返回nameregistered(已注册)字段。第三区域共有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: 另请参阅: