首頁 > web前端 > js教程 > 主體

MongoDB 聚合管道

PHPz
發布: 2024-07-31 20:32:41
原創
873 人瀏覽過

MongoDB Aggregation Pipelines

嗨,外星人!我是帕萬。因此,在這個儲存庫中,我將透過基本範例深入解釋所有聚合階段。我還將提供進一步學習資源的連結。

所以這個儲存庫包含各種 MongoDB 聚合管道的 JSON 檔案。這些管道示範如何使用不同的聚合階段和操作來處理和分析資料。

目錄

  • 簡介
  • CRUD 操作
  • 聚合階段
    • $匹配
    • $組
    • $項目
    • $排序
    • $限額
    • $跳過
    • $查找
    • $放鬆
    • $addFields
    • $replaceRoot
  • 聚合操作
    • $總和
    • 平均$
    • $分鐘
    • $max
    • $第一
    • $最後
  • 範例資料集
  • 進一步學習的資源

介紹

MongoDB 中的聚合是處理和分析儲存在集合中的資料的強大方法。它允許您執行過濾、分組、排序和轉換資料等操作。

增刪改查操作

創造

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 });
登入後複製

聚合階段

$匹配

過濾文檔,僅將符合指定條件的文檔傳遞到下一個管道階段。

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 } }
]);
登入後複製

$排序

對所有輸入文件進行排序,並按排序順序將它們返回到管道。

db.orders.aggregate([
  { $sort: { "amount": -1 } }
]);
登入後複製

$限額

限制傳遞到管道中下一階段的文件數量。

db.orders.aggregate([
  { $limit: 5 }
]);
登入後複製

$跳過

跳過前 n 個文檔,並將剩餘文檔傳遞到管道中的下一階段。

db.orders.aggregate([
  { $skip: 5 }
]);
登入後複製
登入後複製

$查找

對同一資料庫中的另一個集合執行左外連接,以過濾「已連接」集合中的文件進行處理。

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

$放鬆

從輸入文件中解構數組字段,以輸出每個元素的文件。

db.orders.aggregate([
  { $unwind: "$items" }
]);
登入後複製
登入後複製

$addFields

為文件新增欄位。

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

$replaceRoot

用指定文件取代輸入文件。

db.orders.aggregate([
  { $replaceRoot: { newRoot: "$items" } }
]);
登入後複製
登入後複製

聚合操作

$總和

計算並傳回數值的總和。 $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" }
    }
  }
]);
登入後複製

最高$

傳回數值中的最大值。

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

$第一

傳回每個群組文檔中的第一個值。

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

$最後

傳回每個群組文檔中的最後一個值。

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] }
    }
  }
]);
登入後複製

$排序

先依狀態升序對訂單進行排序,然後再依金額降序排序。

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

$限額

將結果限制為金額最高的前 3 個訂單。

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

$跳過

跳過前 5 個訂單並返回其餘訂單。

db.orders.aggregate([
  { $skip: 5 }
]);
登入後複製
登入後複製

$查找

將訂單集合與 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中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!