Mongoose 聚合(Aggregate)API

Mongoose 聚合(Aggregate)API

Mongoose API 中的 聚合(Aggregate)API Aggregate() 方法用于执行聚合任务。它允许我们创建聚合管道。聚合构造函数用于构建和配置聚合管道。建议不直接实例化 Aggregation 类,而是在已经定义了 Mongoose 模式的任何模型上使用它。让我们通过一个示例来理解 aggregate() 方法。

语法:

Model.aggregate( <pipeline>, <model>);

参数: 该方法接受如下两个参数:

  • pipeline: 用于指定对象的聚合管道数组。
  • model: 用于确定我们将使用的模型名称与聚合管道一起使用。

返回值: 该方法以对象数组的形式返回结果集,根据聚合管道的要求。

设置Node.js的Mongoose模块:

步骤1: 使用以下命令创建一个Node.js应用程序:

npm init

步骤2: 创建NodeJS应用程序后,使用以下命令安装所需的模块:

npm install mongoose

项目结构: 项目的结构将如下所示:

Mongoose 聚合(Aggregate)API

数据库结构: 数据库的结构将会是这样的,以下的文档都存在于该集合中。

Mongoose 聚合(Aggregate)API

示例1: 在这个示例中,我们使用mongoose建立了一个数据库连接,并通过studentSchema定义了一个模型。最后,我们在mongoose模型上使用aggregate()方法并配置了管道。

文件名:app.js

// Require mongoose module 
const mongoose = require("mongoose"); 
  
// Set Up the Database connection 
const URI = "mongodb://localhost:27017/geeksforgeeks"
  
const connectionObject = mongoose.createConnection(URI, { 
    useNewUrlParser: true, 
    useUnifiedTopology: true, 
}); 
  
const studentSchema = new mongoose.Schema({ 
    name: { type: String }, 
    age: { type: Number }, 
    rollNumber: { type: Number }, 
}); 
  
const Student = connectionObject.model('Student', studentSchema); 
  
Student.aggregate([{ $project: { name: 1, rollNumber: 1, 
    _id: 0 } }]).exec((error, resultSet) => { 
    if (error) { 
        console.log(error); 
    } else { 
        console.log(resultSet); 
    } 
})

运行程序的步骤:

要运行该应用程序,请在项目的根目录中执行以下命令:

node app.js

输出:

[
    { name: 'Student1', rollNumber: 9 },
      { name: 'Student3', rollNumber: 178 },
      { name: 'Student4', rollNumber: 152 },
      { name: 'Student2', rollNumber: 176 }
]

示例2: 下面的示例演示了Mongoose API Aggregate的功能,使用了then和catch语句块。

文件名:app.js

// Require mongoose module 
const mongoose = require("mongoose"); 
  
// Set Up the Database connection 
const URI = "mongodb://localhost:27017/geeksforgeeks"
  
const connectionObject = mongoose.createConnection(URI, { 
    useNewUrlParser: true, 
    useUnifiedTopology: true, 
}); 
  
const studentSchema = new mongoose.Schema({ 
    name: { type: String }, 
    age: { type: Number }, 
    rollNumber: { type: Number }, 
}); 
  
const Student = connectionObject.model('Student', studentSchema); 
  
Student.aggregate().project({ age: 1 }).then(resultSet => { 
    console.log(resultSet); 
}).catch(error => console.log(error));

运行程序的步骤: 从项目的根目录中执行以下命令来运行应用程序:

node app.js

输出:

[
    { _id: new ObjectId("63a40a1065e8951038a391b1"), age: 20 },
      { _id: new ObjectId("63a4a98407370cdcd1961b1a"), age: 19 },
      { _id: new ObjectId("63a4a99307370cdcd1961b1d"), age: 24 },
      { _id: new ObjectId("63a4a9a207370cdcd1961b2c"), age: 18 }
]

参考: https://mongoosejs.com/docs/api/aggregate.html#aggregate_Aggregate

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程