”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > MongoDB 聚合管道

MongoDB 聚合管道

发布于2024-08-07
浏览:485

MongoDB Aggregation Pipelines

Hi, aliens! I am Pavan. So in this repository, I will explain all the aggregation stages in depth with basic examples. I will also include links to resources for further learning.

So this repository contains JSON files for various MongoDB aggregation pipelines. These pipelines demonstrate how to use different aggregation stages and operations to process and analyze data.

Table of Contents

  • Introduction
  • CRUD Operations
  • Aggregation Stages
    • $match
    • $group
    • $project
    • $sort
    • $limit
    • $skip
    • $lookup
    • $unwind
    • $addFields
    • $replaceRoot
  • Aggregation Operations
    • $sum
    • $avg
    • $min
    • $max
    • $first
    • $last
  • Example Datasets
  • Resources for Further Learning

Introduction

Aggregation in MongoDB is a powerful way to process and analyze data stored in collections. It allows you to perform operations like filtering, grouping, sorting, and transforming data.

CRUD Operations

Create

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

Read

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

Update

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

Delete

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

Aggregation Stages

$match

Filters the documents to pass only the documents that match the specified condition(s) to the next pipeline stage.

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

$group

Groups input documents by the specified _id expression and for each distinct grouping, outputs a document. The _id field contains the unique group by value.

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

$project

Passes along the documents with the requested fields to the next stage in the pipeline.

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

$sort

Sorts all input documents and returns them to the pipeline in sorted order.

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

$limit

Limits the number of documents passed to the next stage in the pipeline.

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

$skip

Skips the first n documents and passes the remaining documents to the next stage in the pipeline.

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

$lookup

Performs a left outer join to another collection in the same database to filter in documents from the "joined" collection for processing.

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

$unwind

Deconstructs an array field from the input documents to output a document for each element.

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

$addFields

Adds new fields to documents.

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

$replaceRoot

Replaces the input document with the specified document.

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

Aggregation Operations

$sum

Calculates and returns the sum of numeric values. $sum ignores non-numeric values.

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

$avg

Calculates and returns the average value of the numeric values.

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

$min

Returns the minimum value from the numeric values.

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

$max

Returns the maximum value from the numeric values.

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

$first

Returns the first value from the documents for each group.

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

$last

Returns the last value from the documents for each group.

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

Example Datasets

Example documents used for performing CRUD and aggregation operations:

[
  { "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" }
]

Resources for Further Learning

  • MongoDB Aggregation Documentation
  • MongoDB University Courses
  • MongoDB Aggregation Pipeline Builder

Feel free to clone this repository and experiment with the aggregation pipelines provided. If you have any questions or suggestions, please open an issue or submit a pull request.

$group

Groups orders by status and calculates the total amount and average amount for each status.

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

$project

Projects the order ID, customer ID, and a calculated field for the total amount with tax (assuming 10% tax).

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

$sort

Sorts orders first by status in ascending order and then by amount in descending order.

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

$limit

Limits the result to the top 3 orders with the highest amount.

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

$skip

Skips the first 5 orders and returns the rest.

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

$lookup

Joins the orders collection with an orderDetails collection to add order details.

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.

版本声明 本文转载于:https://dev.to/bpk45_0670a02e0f3a6839b3a/mongodb-aggregation-pipelines-25mc?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • 如何从Google API中检索最新的jQuery库?
    如何从Google API中检索最新的jQuery库?
    从Google APIS 问题中提供的jQuery URL是版本1.2.6。对于检索最新版本,以前有一种使用特定版本号的替代方法,它是使用以下语法: https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js(google hosted...
    编程 发布于2025-02-07
  • 如何使用不同数量列的联合数据库表?
    如何使用不同数量列的联合数据库表?
    合并列数不同的表 当尝试合并列数不同的数据库表时,可能会遇到挑战。一种直接的方法是在列数较少的表中,为缺失的列追加空值。 例如,考虑两个表,表 A 和表 B,其中表 A 的列数多于表 B。为了合并这些表,同时处理表 B 中缺失的列,请按照以下步骤操作: 确定表 B 中缺失的列,并将它们添加到表的末...
    编程 发布于2025-02-07
  • 对象拟合:IE和Edge中的封面失败,如何修复?
    对象拟合:IE和Edge中的封面失败,如何修复?
    解决此问题,我们采用了一个巧妙的CSS解决方案来解决问题:高度:100%; 高度:auto; 宽度:100%; //对于水平块 ,使用绝对定位将图像定位在中心,以object-fit:object-fit:cover in IE和edge消除了问题。现在,图像将按比例扩展,保持所需的效果而不会失...
    编程 发布于2025-02-07
  • 如何在Java列表中有效计算元素的发生?
    如何在Java列表中有效计算元素的发生?
    计数列表中的元素出现在列表 中,在java编程中,列举列表中列举元素出现的任务来自列表。为此,收集框架提供了全面的工具套件。在这种情况下,Batocurrences变量将保持值3,代表动物列表中的“ BAT”出现的数量。 &&& [此方法是简单的,可以得出准确的结果,使其成为计算列表中元素出现的理...
    编程 发布于2025-02-07
  • 为什么使用固定定位时,为什么具有100%网格板柱的网格超越身体?
    为什么使用固定定位时,为什么具有100%网格板柱的网格超越身体?
    网格超过身体,用100%grid-template-columns 问题:考虑以下CSS和HTML: position:fixed; grid-template-columns:40%60%; grid-gap:5px; 背景:#eee; 当位置未固定时,网格将正确显示。但是,当...
    编程 发布于2025-02-07
  • 如何使用FormData()处理多个文件上传?
    如何使用FormData()处理多个文件上传?
    )处理多个文件输入时,通常需要处理多个文件上传时,通常是必要的。可以将fd.append("fileToUpload[]", files[x]);方法用于此目的,允许您在单个请求中发送多个文件。 初始尝试 在JavaScript中,一种常见方法是:); 但是,此代码仅处理第一...
    编程 发布于2025-02-07
  • 如何在JavaScript对象中动态设置键?
    如何在JavaScript对象中动态设置键?
    如何为JavaScript对象变量创建动态键,尝试为JavaScript对象创建动态键,使用此Syntax jsObj['key' i] = 'example' 1;将不起作用。正确的方法采用方括号:他们维持一个长度属性,该属性反映了数字属性(索引)和一个数字属性的数量。标准对象没有模仿这...
    编程 发布于2025-02-07
  • 如何从PHP服务器发送文件?
    如何从PHP服务器发送文件?
    将文件发送到user
    编程 发布于2025-02-07
  • PHP阵列键值异常:了解07和08的好奇情况
    PHP阵列键值异常:了解07和08的好奇情况
    PHP数组键值问题,使用07&08 在给定数月的数组中,键值07和08呈现令人困惑的行为时,就会出现一个不寻常的问题。运行print_r($月份)返回意外结果:键“ 07”丢失,而键“ 08”分配给了9月的值。此问题源于PHP对领先零的解释。当一个数字带有0(例如07或08)的前缀时,PHP将...
    编程 发布于2025-02-07
  • 如何干净地删除匿名JavaScript事件处理程序?
    如何干净地删除匿名JavaScript事件处理程序?
    在这里工作/},false); 不幸的是,答案是否。除非在Creation中存储对处理程序的引用。要解决此问题,请考虑将事件处理程序存储在中心位置,例如页面的主要对象,请考虑将事件处理程序存储在中心位置,否则无法清理匿名事件处理程序。 。这允许在需要时轻松迭代和清洁处理程序。
    编程 发布于2025-02-07
  • HTML格式标签
    HTML格式标签
    HTML 格式化元素 **HTML Formatting is a process of formatting text for better look and feel. HTML provides us ability to format text without us...
    编程 发布于2025-02-07
  • 微实验标准:它是评估系统性能的可靠工具吗?
    微实验标准:它是评估系统性能的可靠工具吗?
    [2代码或小型系统调用。它旨在确定特定操作完成所需的时间和资源。但是,了解Microbenching的作用和不涉及的是至关重要。什么是microbenchmarking是 的名称,Microbenchmarking着重于测量小型,特定的特定,特定的,特定的,特定的,特定的,特定的,特定的,特定的,特...
    编程 发布于2025-02-07
  • 如何有效地加入SQL中的表以从多列中检索数据?
    如何有效地加入SQL中的表以从多列中检索数据?
    [2 使用SQL Table Joins 从多个列中检索数据 本指南演示了如何有效地组合来自多个SQL表的数据以在各种列中检索信息。我们将重点介绍方法,突出显示其使用并解决Microsoft Access的特定注意事项。 [2 基于共享列值从两个或多个表中合并行。 结果表仅包含所有连接表中匹配的...
    编程 发布于2025-02-07
  • 为什么Microsoft Visual C ++无法正确实现两台模板的实例?
    为什么Microsoft Visual C ++无法正确实现两台模板的实例?
    [2明确担心Microsoft Visual C(MSVC)在正确实现两相模板实例化方面努力努力。该机制的哪些具体方面无法按预期运行?背景:说明:的初始Syntax检查在范围中受到限制。它未能检查是否存在声明名称的存在,导致名称缺乏正确的声明时会导致编译问题。为了说明这一点,请考虑以下示例:一个符合...
    编程 发布于2025-02-07
  • 可以在纯CS中将多个粘性元素彼此堆叠在一起吗?
    可以在纯CS中将多个粘性元素彼此堆叠在一起吗?
    </main> <section> ,但无法使其正常工作,如您所见。任何洞察力都将不胜感激! display:grid; { position:sticky; top:1em; z-index:1 1 ; { { { pos...
    编程 发布于2025-02-07

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3