MongoDB
 Computer >> コンピューター >  >> プログラミング >> MongoDB

MongoDBの集計パイプラインでドキュメントを昇順に並べ替えるには?

MongoDBの集計パイプラインでドキュメントを昇順に並べ替える方法

MongoDBの集計(アグリゲーション)フレームワークでは、$sortステージを使用することで、結果を特定のフィールドの値に基づいて並べ替えることができます。1を指定すると昇順、-1を指定すると降順になります。

ここでは、サンプルコレクションを作成し、$unwindや$groupと組み合わせて$sortによる昇順ソートを実行する手順を解説します。

サンプルコレクションの作成

まず、ドキュメントを含むコレクションを作成しましょう。

> db.demo652.insertOne({
...    value:10,
...    "details" : [{
...       "ProductName" : "Product-1",
...       "ProductQuantity" : 8,
...       "ProductPrice" : 500
...    }, {
...        "ProductName" : "Product-2",
...        "ProductQuantity" : 7,
...        "ProductPrice" : 500
...
...     }]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9f0730e3c3cd0dcff36a62")
}
>
> db.demo652.insertOne({
...    value:5,
...    "details" : [{
...       "ProductName" : "Product-1",
...       "ProductQuantity" : 8,
...       "ProductPrice" : 500
...      }, {
...          "ProductName" : "Product-2",
...          "ProductQuantity" : 7,
...          "ProductPrice" : 500
...
...      }]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9f0740e3c3cd0dcff36a63")
}

登録済みドキュメントの確認

find()メソッドを使って、コレクション内のすべてのドキュメントを表示します。

> db.demo652.find();

これにより、次のような出力が得られます。

{ "_id" : ObjectId("5e9f0730e3c3cd0dcff36a62"), "value" : 10, "details" : [ { "ProductName" : "Product-1", "ProductQuantity" : 8, "ProductPrice" : 500 }, { "ProductName" : "Product-2", "ProductQuantity" : 7, "ProductPrice" : 500 } ] }
{ "_id" : ObjectId("5e9f0740e3c3cd0dcff36a63"), "value" : 5, "details" : [ { "ProductName" : "Product-1", "ProductQuantity" : 8, "ProductPrice" : 500 }, { "ProductName" : "Product-2", "ProductQuantity" : 7, "ProductPrice" : 500 } ] }

昇順に並べ替えるクエリ

以下は、$sortステージを使って昇順に並べ替える集計クエリの例です。

> db.demo652.aggregate([{
...    "$unwind": "$details"
...    }, {
...       "$match": {}
...    }, {
...       "$group": {
...          "ProductPrice": {
...             "$first": "$value"
...          },
...          "details": {
...             "$push": {
...                "ProductName": "$details.ProductName"
...             }
...          },
...          "_id": "$_id"
...       }
...    }, {
...       "$sort": {
...          "ProductPrice": 1
...       }
...    }, {
...       "$project": {
...          "_id": 0,
...          "ProductPrice": 1,
...          "details": 1
...    }
... }]).pretty()

このパイプラインでは、まず$unwindでdetails配列を個々のドキュメントに展開し、$groupで_idごとにグループ化しています。その際、$first演算子によってvalueフィールドの値をProductPriceとして取得しています。そして$sortの「ProductPrice: 1」により、ProductPriceフィールドを基準に昇順で並べ替えを行います。最後に$projectで出力するフィールドを絞り込んでいます。

実行すると、次のような結果が出力されます。

{
   "ProductPrice" : 5,
   "details" : [
      {
         "ProductName" : "Product-1"
      },
      {
         "ProductName" : "Product-2"
      }
   ]
}
{
   "ProductPrice" : 10,
   "details" : [
      {
         "ProductName" : "Product-1"
      },
      {
         "ProductName" : "Product-2"
      }
   ]
}

まとめ

$sortステージでは、並べ替えの基準となるフィールドに対して1(昇順)または-1(降順)を指定します。上記の例では、valueの値が5のドキュメントが先に、10のドキュメントが後に表示されており、正しく昇順ソートが行われていることが確認できます。大きなコレクションに対して頻繁にソートを行う場合は、対象フィールドにインデックスを作成しておくことでパフォーマンスを大幅に改善できます。

  1. 【MongoDB】aggregate()と$groupで異なるドキュメント内の同じIDを持つ要素を集約する方法

    複数のドキュメントにまたがって同じIDを持つ要素をグループ化したい場合には、MongoDBの aggregate() メソッドと $group ステージを組み合わせるのが効果的です。本記事では、実際にサンプルコレクションを作成しながら、IDごとにドキュメントを集約する手順をわかりやすく解説します。1. サンプルコレクションの作成まずは動作確認用のコレクションを作成し、ドキュメントを挿入していきます。ここでは「id」と「Name」というフィールドを持つドキュメントを6件登録します。> db.demo602.insertOne({id:1,Name:"Chris"});{

  2. MongoDBの集計パイプラインで複数フィールドをカウントする方法($facet活用)

    MongoDBで複数のフィールドごとにドキュメントをカウントしたい場合、$facet演算子を使うのが効果的です。$facetは、同じ入力ドキュメント群に対して、単一のステージ内で複数の集計パイプラインを同時に処理できる強力な機能です。この記事では、実際にコレクションを作成し、$facetを組み合わせた集計クエリで複数フィールドの値をカウントする手順を解説します。1. サンプルコレクションの作成まず、insertOne()メソッドを使ってサンプルドキュメントを挿入します。各ドキュメントにはdetails1・details2・details3という3つのネストされたフィールドを持たせます。>