

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

# $底部
<a name="bottom"></a>

8.0.1 版中的新增内容。

使用`$group`阶段中的`$bottom`累加器根据指定的排序顺序返回每组排名最低的文档。

**参数**
+ `sortBy`：指定排序顺序的文档。`1`用于升序或降序`-1`。
+ `output`：一个表达式，它指定要从底部文档返回的字段。

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

以下示例说明如何使用`$bottom`累加器来查找销售产品系列中每件商品的最低销售额（最低数量）。

**创建示例文档 **

```
db.sales.insertMany([
  { item: "abc", quantity: 10, price: 5 },
  { item: "abc", quantity: 5, price: 8 },
  { item: "xyz", quantity: 15, price: 3 },
  { item: "xyz", quantity: 7, price: 6 }
])
```

**查询示例 **

```
db.sales.aggregate([
  { $group: { _id: "$item", bottomSale: { $bottom: { sortBy: { quantity: -1 }, output: { quantity: "$quantity", price: "$price" } } } } }
])
```

**输出**

```
[
  { "_id": "xyz", "bottomSale": { "quantity": 7, "price": 6 } },
  { "_id": "abc", "bottomSale": { "quantity": 5, "price": 8 } }
]
```

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

要查看使用`$bottom`运算符的代码示例，请选择要使用的语言的选项卡：

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

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

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

  try {
    await client.connect();

    const db = client.db('test');
    const collection = db.collection('sales');

    const result = await collection.aggregate([
      { $group: { _id: "$item", bottomSale: { $bottom: { sortBy: { quantity: -1 }, output: { quantity: "$quantity", price: "$price" } } } } }
    ]).toArray();

    console.log(result);

  } catch (error) {
    console.error('Error:', error);
  } finally {
    await client.close();
  }
}

example();
```

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

```
from pymongo import MongoClient
from pprint import pprint

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

        db = client['test']
        collection = db['sales']

        result = list(collection.aggregate([
            { '$group': { '_id': '$item', 'bottomSale': { '$bottom': { 'sortBy': { 'quantity': -1 }, 'output': { 'quantity': '$quantity', 'price': '$price' } } } } }
        ]))

        pprint(result)

    except Exception as e:
        print(f"An error occurred: {e}")

    finally:
        if client:
            client.close()

example()
```

------