Docs 菜单
Docs 主页
/ / /
Node.js 驱动程序

聚合教程

在此页面上

  • Overview
  • 聚合模板应用程序
  • 可用教程

聚合教程以分步格式详细解释常见聚合任务。 这些教程改编自《 Practical MongoDB Aggregations》一书中 的示例 作者:Paul Done。

每个教程都包括以下部分:

  • 简介,描述聚合类型的用途和常见用例。本节还描述了本教程演示的示例和预期结果。

  • 开始之前,这个部分介绍了在构建聚合管道和执行聚合之前必须具备的必要数据库、集合和示例数据。

  • 教程,其中介绍了如何构建和运行聚合管道。本节介绍已完成聚合教程的每个阶段,然后说明如何运行和解释聚合的输出结果。

在每个聚合教程的末尾,您可以找到一个链接,该链接指向在环境中完全可运行的 Node.js 代码文件。

提示

要了解有关执行聚合的更多信息,请参阅聚合指南。

在开始按照聚合教程进行操作之前,您必须设置一个新的 Node.js 应用。您可以使用此应用连接到 MongoDB 部署、将示例数据插入到 MongoDB 以及运行每个教程中的聚合管道。

提示

要了解如何安装驱动程序和连接 MongoDB,请参阅快速入门指南中的下载和安装以及创建 MongoDB 部署步骤。

安装驱动程序后,创建一个名为 agg_tutorial.js的文件。 将以下代码粘贴到此文件中,为聚合教程创建应用模板:

const { MongoClient } = require("mongodb");
// Replace the placeholder with your connection string.
const uri = "<connection string>";
const client = new MongoClient(uri);
async function run() {
try {
const aggDB = client.db("agg_tutorials_db");
// Get a reference to relevant collections.
// ... const someColl =
// ... const anotherColl =
// Delete any existing documents in collections.
// ... await someColl.deleteMany({});
// Insert sample data into the collection or collections.
// ... const someData = [ ... ];
// ... await someColl.insertMany(someData);
// Create an empty pipeline array.
const pipeline = [];
// Add code to create pipeline stages.
// ... pipeline.push({ ... })
// Run the aggregation.
// ... const aggregationResult = ...
// Print the aggregation results.
for await (const document of aggregationResult) {
console.log(document);
}
} finally {
await client.close();
}
}
run().catch(console.dir);

重要

在前面的代码中,请阅读代码注释,找到您必须根据教程进行修改的代码部分。

如果您尝试在不进行任何更改的情况下运行代码,则会遇到连接错误。

对于每个教程,您必须用部署的连接字符串替换连接字符串占位符。

提示

如要了解如何找到部署的连接字符串,请参阅《快速入门》指南中的创建连接字符串步骤。

例如,如果连接字符串为 "mongodb+srv://mongodb-example:27017",则其赋值应如下所示:

const uri = "mongodb+srv://mongodb-example:27017";

要在修改教程模板后运行完成的文件,请在 shell 中运行以下命令:

node agg_tutorial.js

后退

正在使用的加密