

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

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

バージョン 8.0.1 から新規。

Amazon DocumentDB の`$sortByCount`集約ステージは、指定された式の値に基づいて受信ドキュメントをグループ化し、各個別のグループのドキュメントの数を計算して、結果をカウント別に降順にソートします。これは、`$sum`アキュムレータ`$group`とそれに続くカウントフィールドの`$sort`ステージに相当します。

**パラメータ**
+ `expression`: グループ化する式。これは、フィールドパス (プレフィックスは `$`) または任意の有効な集計式にすることができます。

## 例 (MongoDB シェル)
<a name="sortByCount-examples"></a>

次の例は、 `$sortByCount`ステージを使用して、カテゴリフィールドでドキュメントをカウントおよびソートする方法を示しています。

**サンプルドキュメントを作成する**

```
db.products.insertMany([
  { name: "Widget", category: "electronics" },
  { name: "Gadget", category: "electronics" },
  { name: "Doohickey", category: "electronics" },
  { name: "Apple", category: "food" },
  { name: "Banana", category: "food" },
  { name: "Hammer", category: "tools" }
]);
```

**クエリの例**

```
db.products.aggregate([
  { $sortByCount: "$category" }
]);
```

**出力**

```
[
  { "_id": "electronics", "count": 3 },
  { "_id": "food", "count": 2 },
  { "_id": "tools", "count": 1 }
]
```

結果は降順`count`で自動的にソートされます。

## コードの例
<a name="sortByCount-code"></a>

`$sortByCount` ステージを使用するためのコード例を表示するには、使用する言語のタブを選択します。

------
#### [ 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');
    const collection = db.collection('products');

    const result = await collection.aggregate([
      { $sortByCount: "$category" }
    ]).toArray();

    console.log(result);
  } 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']
        collection = db['products']

        result = list(collection.aggregate([
            { '$sortByCount': '$category' }
        ]))

        print(result)
    finally:
        client.close()

example()
```

------