ホームページ  >  記事  >  ウェブフロントエンド  >  MongoDB 集約パイプライン

MongoDB 集約パイプライン

PHPz
PHPzオリジナル
2024-07-31 20:32:41873ブラウズ

MongoDB Aggregation Pipelines

こんにちは、宇宙人!私はパヴァンです。そこで、このリポジトリでは、基本的な例を使用してすべての集計ステージを詳しく説明します。さらに学習するためのリソースへのリンクも記載します。

このリポジトリには、さまざまな MongoDB 集約パイプラインの JSON ファイルが含まれています。これらのパイプラインは、さまざまな集計ステージと操作を使用してデータを処理および分析する方法を示します。

目次

  • はじめに
  • CRUD オペレーション
  • 集約ステージ
    • $match
    • $グループ
    • $プロジェクト
    • $ソート
    • $limit
    • $スキップ
    • $lookup
    • $アンワインド
    • $addFields
    • $replaceRoot
  • 集計操作
    • $sum
    • 平均金額
    • $min
    • $max
    • $first
    • $last
  • データセットの例
  • さらなる学習のためのリソース

導入

MongoDB の集約は、コレクションに保存されたデータを処理および分析するための強力な方法です。データのフィルタリング、グループ化、並べ替え、変換などの操作を実行できます。

CRUD操作

作成する

db.orders.insertOne({
  "order_id": 26,
  "cust_id": 1006,
  "status": "A",
  "amount": 275,
  "items": ["apple", "banana"],
  "date": "2023-01-26"
});

読む

db.orders.find().pretty();

アップデート

db.orders.updateOne(
  { "order_id": 2 },
  {
    $set: { "status": "C", "amount": 500 },
    $currentDate: { "lastModified": true }
  }
);

消去

db.orders.deleteOne({ "order_id": 1 });

集約ステージ

$match

ドキュメントをフィルタリングして、指定された条件に一致するドキュメントのみを次のパイプライン ステージに渡します。

db.orders.aggregate([
  { $match: { "status": "A" } }
]);

$グループ

指定された _id 式によって入力ドキュメントをグループ化し、個別のグループごとにドキュメントを出力します。 _id フィールドには、値による一意のグループが含まれます。

db.orders.aggregate([
  {
    $group: {
      _id: "$cust_id",
      totalSpent: { $sum: "$amount" }
    }
  }
]);

$プロジェクト

リクエストされたフィールドを含むドキュメントをパイプラインの次のステージに渡します。

db.orders.aggregate([
  { $project: { "order_id": 1, "items": 1, "_id": 0 } }
]);

$sort

すべての入力ドキュメントを並べ替え、並べ替えられた順序でパイプラインに返します。

db.orders.aggregate([
  { $sort: { "amount": -1 } }
]);

$limit

パイプラインの次のステージに渡されるドキュメントの数を制限します。

db.orders.aggregate([
  { $limit: 5 }
]);

$スキップ

最初の n 個のドキュメントをスキップし、残りのドキュメントをパイプラインの次のステージに渡します。

db.orders.aggregate([
  { $skip: 5 }
]);

$lookup

同じデータベース内の別のコレクションに対して左外部結合を実行し、「結合された」コレクションからドキュメントをフィルタリングして処理します。

db.orders.aggregate([
  {
    $lookup: {
      from: "orderDetails",
      localField: "order_id",
      foreignField: "order_id",
      as: "details"
    }
  }
]);

$unwind

入力ドキュメントから配列フィールドを分解して、要素ごとにドキュメントを出力します。

db.orders.aggregate([
  { $unwind: "$items" }
]);

$addFields

ドキュメントに新しいフィールドを追加します。

db.orders.aggregate([
  { $addFields: { totalWithTax: { $multiply: ["$amount", 1.1] } } }
]);

$replaceRoot

入力ドキュメントを指定されたドキュメントに置き換えます。

db.orders.aggregate([
  { $replaceRoot: { newRoot: "$items" } }
]);

集計操作

$sum

数値の合計を計算して返します。 $sum は数値以外の値を無視します。

db.orders.aggregate([
  {
    $group: {
      _id: "$cust_id",
      totalSpent: { $sum: "$amount" }
    }
  }
]);

平均$

数値の平均値を計算して返します。

db.orders.aggregate([
  {
    $group: {
      _id: "$cust_id",
      averageSpent: { $avg: "$amount" }
    }
  }
]);

$分

数値の最小値を返します。

db.orders.aggregate([
  {
    $group: {
      _id: "$cust_id",
      minSpent: { $min: "$amount" }
    }
  }
]);

$max

数値の最大値を返します。

db.orders.aggregate([
  {
    $group: {
      _id: "$cust_id",
      maxSpent: { $max: "$amount" }
    }
  }
]);

$first

各グループのドキュメントから最初の値を返します。

db.orders.aggregate([
  {
    $group: {
      _id: "$cust_id",
      firstOrder: { $first: "$amount" }
    }
  }
]);

$last

各グループのドキュメントから最後の値を返します。

db.orders.aggregate([
  {
    $group: {
      _id: "$cust_id",
      lastOrder: { $last: "$amount" }
    }
  }
]);

データセットの例

CRUD および集計操作の実行に使用されるドキュメントの例:

[
  { "order_id": 1, "cust_id": 1001, "status": "A", "amount": 250, "items": ["apple", "banana"], "date": "2023-01-01" },
  { "order_id": 2, "cust_id": 1002, "status": "B", "amount": 450, "items": ["orange", "grape"], "date": "2023-01-02" },
  { "order_id": 3, "cust_id": 1001, "status": "A", "amount": 300, "items": ["apple", "orange"], "date": "2023-01-03" },
  { "order_id": 4, "cust_id": 1003, "status": "A", "amount": 150, "items": ["banana", "grape"], "date": "2023-01-04" },
  { "order_id": 5, "cust_id": 1002, "status": "C", "amount": 500, "items": ["apple", "banana"], "date": "2023-01-05" },
  { "order_id": 6, "cust_id": 1004, "status": "A", "amount": 350, "items": ["orange", "banana"], "date": "2023-01-06" },
  { "order_id": 7, "cust_id": 1005, "status": "B", "amount": 200, "items": ["grape", "banana"], "date": "2023-01-07" },
  { "order_id": 8, "cust_id": 1003, "status": "A", "amount": 100, "items": ["apple", "orange"], "date": "2023-01-08" },
  { "order_id": 9, "cust_id": 1004, "status": "C", "amount": 400, "items": ["banana", "grape"], "date": "2023-01-09" },
  { "order_id": 10, "cust_id": 1001, "status": "A", "amount": 250, "items": ["apple", "grape"], "date": "2023-01-10" },
  { "order_id": 11, "cust_id": 1002, "status": "B", "amount": 350, "items": ["orange", "banana"], "date": "2023-01-11" },
  { "order_id": 12, "cust_id": 1003, "status": "A", "amount": 450, "items": ["apple", "orange"], "date": "2023-01-12" },
  { "order_id": 13, "cust_id": 1005, "status": "A", "amount": 150, "items": ["banana", "grape"], "date": "2023-01-13" },
  { "order_id": 14, "cust_id": 1004, "status": "C

", "amount": 500, "items": ["apple", "banana"], "date": "2023-01-14" },
  { "order_id": 15, "cust_id": 1002, "status": "A", "amount": 300, "items": ["orange", "grape"], "date": "2023-01-15" },
  { "order_id": 16, "cust_id": 1003, "status": "B", "amount": 200, "items": ["apple", "banana"], "date": "2023-01-16" },
  { "order_id": 17, "cust_id": 1001, "status": "A", "amount": 250, "items": ["orange", "grape"], "date": "2023-01-17" },
  { "order_id": 18, "cust_id": 1005, "status": "A", "amount": 350, "items": ["apple", "banana"], "date": "2023-01-18" },
  { "order_id": 19, "cust_id": 1004, "status": "C", "amount": 400, "items": ["orange", "grape"], "date": "2023-01-19" },
  { "order_id": 20, "cust_id": 1001, "status": "B", "amount": 150, "items": ["apple", "orange"], "date": "2023-01-20" },
  { "order_id": 21, "cust_id": 1002, "status": "A", "amount": 500, "items": ["banana", "grape"], "date": "2023-01-21" },
  { "order_id": 22, "cust_id": 1003, "status": "A", "amount": 450, "items": ["apple", "banana"], "date": "2023-01-22" },
  { "order_id": 23, "cust_id": 1004, "status": "B", "amount": 350, "items": ["orange", "banana"], "date": "2023-01-23" },
  { "order_id": 24, "cust_id": 1005, "status": "A", "amount": 200, "items": ["grape", "banana"], "date": "2023-01-24" },
  { "order_id": 25, "cust_id": 1001, "status": "A", "amount": 300, "items": ["apple", "orange"], "date": "2023-01-25" }
]

さらなる学習のためのリソース

  • MongoDB 集約ドキュメント
  • MongoDB 大学コース
  • MongoDB 集約パイプライン ビルダー

自由にこのリポジトリのクローンを作成し、提供されている集計パイプラインを試してみてください。ご質問やご提案がある場合は、問題を開くか、プル リクエストを送信してください。

$グループ

注文をステータスごとにグループ化し、各ステータスの合計金額と平均金額を計算します。

db.orders.aggregate([
  {
    $group: {
      _id: "$status",
      totalAmount: { $sum: "$amount" },
      averageAmount: { $avg: "$amount" }
    }
  }
]);

$プロジェクト

注文 ID、顧客 ID、および税込合計金額 (税 10% を想定) の計算フィールドを投影します。

db.orders.aggregate([
  {
    $project: {
      "order_id": 1,
      "cust_id": 1,
      "totalWithTax": { $multiply: ["$amount", 1.1] }
    }
  }
]);

$sort

注文をまずステータスで昇順に並べ替え、次に金額で降順に並べ替えます。

db.orders.aggregate([
  { $sort: { "status": 1, "amount": -1 } }
]);

$limit

金額が最も高い上位 3 件の注文に結果を制限します。

db.orders.aggregate([
  { $sort: { "amount": -1 } },
  { $limit: 3 }
]);

$スキップ

最初の 5 つの注文をスキップし、残りを返します。

db.orders.aggregate([
  { $skip: 5 }
]);

$lookup

orders コレクションを orderDetails コレクションと結合して、注文の詳細を追加します。

db.orders.aggregate([
  {
    $lookup: {
      from: "orderDetails",
      localField: "order_id",
      foreignField: "order_id",
      as: "details"
    }
  }
]);

$unwind

Deconstructs the items array in each order to output a document for each item.

db.orders.aggregate([
  { $unwind: "$items" }
]);

$addFields

Adds a new field discountedAmount which is 90% of the original amount.

db.orders.aggregate([
  { $addFields: { discountedAmount: { $multiply: ["$amount", 0.9] } } }
]);

$replaceRoot

Replaces the root document with the items array.

db.orders.aggregate([
  { $replaceRoot: { newRoot: "$items" } }
]);

$sum

Calculates the total amount for all orders.

db.orders.aggregate([
  {
    $group: {
      _id: null,
      totalAmount: { $sum: "$amount" }
    }
  }
]);

$avg

Calculates the average amount spent per order.

db.orders.aggregate([
  {
    $group: {
      _id: null,
      averageAmount: { $avg: "$amount" }
    }
  }
]);

$min

Finds the minimum amount spent on an order.

db.orders.aggregate([
  {
    $group: {
      _id: null,
      minAmount: { $min: "$amount" }
    }
  }
]);

$max

Finds the maximum amount spent on an order.

db.orders.aggregate([
  {
    $group: {
      _id: null,
      maxAmount: { $max: "$amount" }
    }
  }
]);

$first

Gets the first order placed (by date).

db.orders.aggregate([
  { $sort: { "date": 1 } },
  {
    $group: {
      _id: null,
      firstOrder: { $first: "$$ROOT" }
    }
  }
]);

$last

Gets the last order placed (by date).

db.orders.aggregate([
  { $sort: { "date": -1 } },
  {
    $group: {
      _id: null,
      lastOrder: { $last: "$$ROOT" }
    }
  }
]);

So, we have covered basic CRUD operations, all major aggregation stages, and operations, and looked into resources for further learning.

以上がMongoDB 集約パイプラインの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。