定义
注意
消歧
本页介绍了用作表达式的 $median,该表达式计算值大量的中位数。
您还可以在其他上下文中使用 $median:
$median (accumulator),用于分组以返回一群组输入文档的中位数值。$median (window function),在$setWindowFields阶段使用,返回窗口中文档的中位数值。
语法
{ $median: { input: <expression>, method: <string> } }
命令字段
字段 | 类型 | 必要性 | 说明 |
|---|---|---|---|
| 阵列 | 必需 | 可以为以下任一项:
|
| 字符串 | 必需 | MongoDB用于计算中位数值的方法。该方法必须是 |
行为
当 $median 用作表达式时,即使指定了 method: "approximate",它也始终使用精确的百分位数计算算法,而不是近似算法。
这是因为表达式对大小有界的数组进行操作,因此可以将所有输入值保留在内存中。
例子
以下示例使用 testScores集合来演示 $median 的大量输入形式。
创建 testScores 集合:
db.testScores.insertMany( [ { studentId: "2345", scores: [ 62, 81, 80, 75, 68 ] }, { studentId: "2356", scores: [ 60, 83, 79, 72, 65 ] }, { studentId: "2358", scores: [ 67, 82, 78, 70, 84 ] }, { studentId: "2367", scores: [ 64, 72, 77, 58, 91 ] }, { studentId: "2369", scores: [ 60, 53, 72, 85, 63 ] } ] )
以下管道使用 $median 计算每个学生的测试成绩中位数:
db.testScores.aggregate( [ { $project: { _id: 0, studentId: 1, testMedians: { $median: { input: "$scores", method: 'approximate' } } } } ] )
在前面的管道中:
$project和$median在scores大量中查找每个文档的中位数值,并将其作为testMedians返回。每个结果都反映了该学生记录的测试分数的中位数位数。