

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

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

8.0.1 版的新功能。

Amazon DocumentDB 中的`$minN`運算子會傳回 N 個最小值。在`$group`階段中用作累積器時，它會傳回每個群組中 N 個最小值的陣列。用作陣列表達式運算子時，它會傳回陣列的 N 個最小元素。

**參數**
+ `input`：解析為要傳回`n`最小值的陣列或欄位的表達式。
+ `n`：解析為正整數的表達式，指定要傳回多少最小值。

## Behavior (行為)
<a name="minN-behavior"></a>

**陣列表達式運算子行為**
+ 您無法指定`n`小於 的值`1`。
+ `$minN` 會篩選掉`input`陣列中找到`null`的值。
+ 如果指定的 `n` 大於或等於`input`陣列中的元素數目，則 會`$minN`傳回`input`陣列中的所有元素。
+ 如果 `input`解析為非陣列值，則彙總操作錯誤。
+ 如果 同時`input`包含數值和字串元素，則會根據 BSON 比較順序，在字串元素之前排序數值元素。

**累積器行為**
+ 用作累積器時， `n` 必須是正整數表達式，其為常數或取決於 `_id`的值`$group`。
+ `$minN` 會篩選掉 null 值和遺失值。
+ 如果群組包含的`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()
```

------