$rand (查询错误)

适用对象: MongoDB vCore

$rand 运算符生成介于 0 和 1 之间的随机浮点值。 这对于文档的随机采样或在聚合管道中创建随机值非常有用。

语法

运算符的 $isArray 语法如下所示:

{ $rand: {} }

示例:

让我们了解数据集中示例数据的 stores 使用情况。

db.stores.aggregate([
   { 
     $project: {
       name: 1,
       randomValue: { $rand: {} },
       "sales.totalSales": 1
     }
   },
   { $limit: 2 }
])

此查询将随机值添加到每个存储文档。 执行后,可能会返回如下所示的内容:

[
  {
    "_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f",
    "name": "First Up Consultants | Bed and Bath Center - South Amir",
    "randomValue": 0.7645893472947384,
    "sales": {
      "totalSales": 37701
    }
  },
  {
    "_id": "40d6f4d7-50cd-4929-9a07-0a7a133c2e74",
    "name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury",
    "randomValue": 0.23456789012345678,
    "sales": {
      "totalSales": 151864
    }
  }
]