什么是 MongoDB 的 Aggregation Pipeline?

发布: (2025年12月14日 GMT+8 22:47)
2 min read
原文: Dev.to

Source: Dev.to

Cover image for 什么是 MongoDB 中的聚合管道?

聚合概述

聚合 是在 MongoDB 中对集合内的多个文档执行各种操作的过程。它使用由不同阶段组成的管道,每个阶段的输出会成为下一个阶段的输入。

聚合管道的类型

$match

过滤文档。工作方式类似 find() 查询,但作为多阶段管道中的一步。

const channel = await User.aggregate([
  {
    $match: {
      username: username?.toLowerCase()
    }
  },
  // …other stages
]);

$lookup

在同一数据库的两个集合之间执行左外连接,将外部集合的数据合并到本地集合的文档中。

{
  $lookup: {
    from: 'subscriptions',
    localField: '_id',
    foreignField: 'channel',
    as: 'subscribers'
  }
},
{
  $lookup: {
    from: 'subscriptions',
    localField: '_id',
    foreignField: 'subscriber',
    as: 'subscribedTo'
  }
},

$addFields(别名:$set

向文档添加新字段或覆盖已有字段,同时保留所有其他字段。

{
  $addFields: {
    subscribersCount: { $size: '$subscribers' },
    channelsSubscribedToCount: { $size: '$subscribedTo' },
    isSubscribed: {
      $cond: {
        if: { $in: [req.user?._id, '$subscribers.subscribers'] },
        then: true,
        else: false
      }
    }
  }
}

$cond 是一种三元运算符,用于在聚合管道中实现 if‑then‑else 逻辑。

$project

选择要传递到下一个阶段的字段,也可以创建或重命名字段。

{
  $project: {
    fullName: 1,
    username: 1,
    subscribersCount: 1,
    channelsSubscribedToCount: 1,
    isSubscribed: 1,
    avatar: 1,
    coverImage: 1,
    email: 1
  }
}

Aggregation pipeline example

Back to Blog

相关文章

阅读更多 »