Mongoose prototype.Aggregate()函数
Mongoose API的API.prototype.Aggregate()方法 用于构建聚合管道。聚合是一种通过多个阶段处理多个文档的方法。
语法:
Model.aggregate()
参数:
- pipeline(管道): 它是一个由对象组成的聚合管道数组。
- model(模型): 这是与此聚合一起使用的方法。
返回值: 它返回一个计划的JavaScript对象。
设置Node.js应用:
步骤1: 使用以下命令创建一个Node.js应用程序:
npm init
步骤2: 在创建NodeJS应用程序之后,使用以下命令安装所需的模块:
npm install mongoose
项目结构: 项目结构将如下所示:
示例1: 在这个示例中,我们使用mongoose建立了一个数据库连接,并定义了一个基于模式的模型,拥有三个列或字段“name”、“marks”和“mobile”。最后,我们在User模型上使用了aggregate()方法,该方法将使用match和filter来从User集合中选取一些列表的元组。
数据库结构: 数据库结构将如下所示,集合中有三个文档,我们使用匹配条件选择了marks大于87的文档。在集合中,我们只有两个marks大于87的文档。
文件名: app.js
// Require the mongoose module
const mongoose = require("mongoose");
// Path to our cloud DataBase
const url = "mongodb://localhost:27017/geeksforgeeks";
// Connecting to database
mongoose.set("strictQuery", false);
mongoose
.connect(url)
.then((ans) => {
console.log("Connected Successful");
})
.catch((err) => {
console.log("Error in the Connection");
});
// Calling Schema class
let Schema = mongoose.Schema;
// Creating Structure of the model
let schema = new Schema({
name: String,
marks: Number,
mobile: Number,
});
// compile our model
let Person = mongoose.model("gfgs", schema);
let find = async () => {
const aggregate = await Person.aggregate([
{ match: { marks: {gte: 87 } } },
]);
return aggregate;
};
find().then((x, y) => {
for (let i of x) console.log(`{i.name} got{i.marks}`);
});
输出:
示例2: 在这个示例中,我们在异步函数中使用计数管道来计算集合中匹配的文档数量。
文件名: script.js
// Require the mongoose module
const mongoose = require('mongoose');
// Path to our cloud Database
const url = 'mongodb://localhost:27017/geeksforgeeks'
// Connecting to database
mongoose.set('strictQuery', false);
mongoose.connect(url)
.then((ans) => {
console.log("Connected Successful")
})
.catch((err) => {
console.log("Error in the Connection")
})
// Calling Schema class
const Schema = mongoose.Schema;
// Creating Structure of the model
let schema = new Schema({
firstName: String,
lastName: String,
});
// Compile our model
let Person = mongoose.model('person', schema);
let find = async () => {
const aggregate = await Person.aggregate([
{ match: { lastName: 'Verma' } },
{count: 'Matched' }
]).exec((err, fi) => {
if (err) throw err;
console.log(fi);
})
return aggregate;
}
find();
输出:
参考: https://mongoosejs.com/docs/api/mongoose.html#mongoose_Mongoose