

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# $minN
<a name="minN"></a>

8.0.1 版中的新增内容。

Amazon DocumentDB 中的`$minN`运算符返回 N 个最小值。当在`$group`阶段中用作累加器时，它返回每组中 N 个最小值的数组。当用作数组表达式运算符时，它返回数组的最少 N 个元素。

**参数**
+ `input`：解析为从中返回最小`n`值的数组或字段的表达式。
+ `n`：解析为正整数的表达式，用于指定要返回的最小值的数量。

## 行为
<a name="minN-behavior"></a>

**数组表达式运算符行为 **
+ 您不能指定`n`小于的值`1`。
+ `$minN`过滤掉`input`数组中找到的`null`值。
+ 如果指定的值大`n`于或等于数组中元素的数量，则`$minN`返回`input`数组中的`input`所有元素。
+ 如果`input`解析为非数组值，则聚合操作出错。
+ 如果同时`input`包含数字和字符串元素，则根据 BSON 比较顺序在字符串元素之前对数字元素进行排序。

**蓄能器行为 **
+ 当用作累加器时，`n`必须是正整数表达式，该表达式要么是常数，要么取决于的`_id`值。`$group`
+ `$minN`过滤掉空值和缺失值。
+ 如果该组包含的元素少于`n`元素，则`$minN`返回该组中的所有元素。
+ `$minN`按照 BSON 比较顺序比较输入数据，以确定相应的输出类型。当输入数据包含多个数据类型时，`$minN`输出类型是比较顺序中最低的。

**输出排序 **

`$minN`不按特定的排序顺序返回值。如果要求保证特定的排序顺序，则`$bottomN`改用或将结果包装为`$sortArray`。

## 示例（MongoDB Shell）
<a name="minN-examples"></a>

以下示例说明如何使用`$minN`累加器检索每个科目的两个最低分数。

**创建示例文档 **

```
db.scores.insertMany([
  { subject: "math", score: 85 },
  { subject: "math", score: 72 },
  { subject: "math", score: 93 },
  { subject: "math", score: 68 },
  { subject: "science", score: 90 },
  { subject: "science", score: 78 },
  { subject: "science", score: 65 },
  { subject: "science", score: 88 }
]);
```

**查询示例 **

```
db.scores.aggregate([
  { $group: { _id: "$subject", lowestTwo: { $minN: { input: "$score", n: 2 } } } }
]);
```

**输出**

```
[
  { "_id": "math", "lowestTwo": [72, 68] },
  { "_id": "science", "lowestTwo": [78, 65] }
]
```

## 表达式用法示例（MongoDB Shell）
<a name="minN-expression-examples"></a>

该`$minN`运算符也可以用作`$project`阶段内的表达式，从数组字段中返回 N 个最小元素。

**创建示例文档 **

```
db.readings.insertMany([
  { _id: 1, sensor: "A", values: [45, 12, 78, 3, 56] },
  { _id: 2, sensor: "B", values: [90, 23, 67, 11, 44] }
]);
```

**查询示例 **

```
db.readings.aggregate([
  { $project: {
      lowestThree: { $minN: { input: "$values", n: 3 } }
    }}
]);
```

**输出**

```
[
  { "_id": 1, "lowestThree": [45, 12, 3] },
  { "_id": 2, "lowestThree": [44, 23, 11] }
]
```

## 代码示例
<a name="minN-code"></a>

要查看使用`$minN`运算符的代码示例，请选择要使用的语言的选项卡。以下示例显示了累加器的用法（输入`$group`）和表达式用法（中`$project`）：

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = new MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');

  try {
    await client.connect();
    const db = client.db('test');

    // Accumulator usage: N smallest values per group
    const scores = db.collection('scores');
    const accumulatorResult = await scores.aggregate([
      { $group: { _id: "$subject", lowestTwo: { $minN: { input: "$score", n: 2 } } } }
    ]).toArray();
    console.log('Accumulator result:', accumulatorResult);

    // Expression usage: N smallest elements from an array field
    const readings = db.collection('readings');
    const expressionResult = await readings.aggregate([
      { $project: { lowestThree: { $minN: { input: "$values", n: 3 } } } }
    ]).toArray();
    console.log('Expression result:', expressionResult);

  } finally {
    await client.close();
  }
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')

    try:
        db = client['test']

        # Accumulator usage: N smallest values per group
        scores = db['scores']
        accumulator_result = list(scores.aggregate([
            { '$group': { '_id': '$subject', 'lowestTwo': { '$minN': { 'input': '$score', 'n': 2 } } } }
        ]))
        print('Accumulator result:', accumulator_result)

        # Expression usage: N smallest elements from an array field
        readings = db['readings']
        expression_result = list(readings.aggregate([
            { '$project': { 'lowestThree': { '$minN': { 'input': '$values', 'n': 3 } } } }
        ]))
        print('Expression result:', expression_result)

    finally:
        client.close()

example()
```

------