集計パイプラインの$sort ステージは、指定したフィールドでパイプライン内のドキュメントを並べ替えるために使用されます。 このステージは、売上を金額別に並べ替えたり、日付別にイベントを並べ替えたりするのに役立ちます。
構文
$sort ステージの構文は次のとおりです。
{
$sort: { <field1>: <sort order>, <field2>: <sort order>, ... }
}
パラメーター
説明 | |
---|---|
field |
並べ替えの基準となるフィールド |
sort order |
フィールドを並べ替える順序。 昇順の場合は 1、降順の場合は -1。 |
例示
例 1: 降順での売上合計による並べ替え
売上カテゴリを合計売上別に降順で並べ替えるには:
db.collection.aggregate([
{
$unwind: "$store.sales.salesByCategory"
},
{
$sort: { "store.sales.salesByCategory.totalSales": -1 }
}
])
サンプル出力
[
{
"_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
"store": {
"name": "Downtown Store",
"sales": {
"salesByCategory": [
{
"category": "Electronics",
"totalSales": 15000
},
{
"category": "Clothing",
"totalSales": 12000
},
{
"category": "Home Goods",
"totalSales": 10000
}
]
}
}
},
{
"_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c6",
"store": {
"name": "Uptown Store",
"sales": {
"salesByCategory": [
{
"category": "Electronics",
"totalSales": 20000
},
{
"category": "Clothing",
"totalSales": 18000
},
{
"category": "Home Goods",
"totalSales": 15000
}
]
}
}
}
]
例 2: イベント開始日を昇順で並べ替える
プロモーション イベントを開始日の昇順で並べ替えるには:
db.collection.aggregate([
{
$unwind: "$store.promotionEvents"
},
{
$sort: { "store.promotionEvents.promotionalDates.startDate": 1 }
}
])
サンプル出力
[
{
"_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
"store": {
"name": "Downtown Store",
"promotionEvents": [
{
"eventName": "Summer Sale",
"promotionalDates": {
"startDate": ISODate("2024-06-01T00:00:00Z"),
"endDate": ISODate("2024-06-30T23:59:59Z")
}
},
{
"eventName": "Black Friday",
"promotionalDates": {
"startDate": ISODate("2024-11-25T00:00:00Z"),
"endDate": ISODate("2024-11-25T23:59:59Z")
}
},
{
"eventName": "Holiday Deals",
"promotionalDates": {
"startDate": ISODate("2024-12-01T00:00:00Z"),
"endDate": ISODate("2024-12-31T23:59:59Z")
}
}
]
}
},
{
"_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c6",
"store": {
"name": "Uptown Store",
"promotionEvents": [
{
"eventName": "Back to School",
"promotionalDates": {
"startDate": ISODate("2024-08-01T00:00:00Z"),
"endDate": ISODate("2024-08-31T23:59:59Z")
}
},
{
"eventName": "Winter Sale",
"promotionalDates": {
"startDate": ISODate("2024-12-01T00:00:00Z"),
"endDate": ISODate("2024-12-31T23:59:59Z")
}
}
]
}
}
]
関連コンテンツ
- MongoDB から Azure Cosmos DB for MongoDB (仮想コア) に移行するためのオプションを確認します。
- アカウントの作成から始める。