Mongoose Aggregate.prototype.cursor()函数

Mongoose Aggregate.prototype.cursor()函数

Mongoose的Aggregate API.prototype.cursor()方法用于执行聚合任务。它允许我们迭代结果集。聚合光标对象允许我们逐个对结果集中的每个文档对象执行迭代任务。

语法:

aggregate(...).cursor( options )

参数: 此方法接受一个参数,如下所述:

  • options: 它是一个用于设置方法参数的对象。此对象具有一个 batchSize 参数,可以用来设置游标的批处理大小。

返回值: 返回表示当前聚合管道操作的游标对象。

设置Node.js应用程序:

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

npm init

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

npm install mongoose

项目结构: 项目的结构将会是这样的:

Mongoose Aggregate.prototype.cursor()函数

数据库结构:

数据库结构将如下所示,集合中包含以下文档。

Mongoose Aggregate.prototype.cursor()函数

示例1: 在这个示例中,我们使用mongoose建立了一个数据库连接,并在cricketerSchema上定义了一个模型,其中有三个列或字段“_id”、“name”和“nationality”。最后,我们在聚合对象上调用 cursor() 方法来获取游标的引用。为了迭代聚合管道返回的所有文档对象,我们在 cursor 对象上使用了 eachAsyn() 方法。

文件名:app.js

// Require mongoose module 
const mongoose = require("mongoose"); 
  
// Set Up the Database connection 
mongoose.connect("mongodb://localhost:27017/geeksforgeeks", { 
    useNewUrlParser: true, 
    useUnifiedTopology: true, 
}); 
  
const cricketerSchema = new mongoose.Schema({ 
    _id: Number, 
    name: String, 
    nationality: String 
}); 
  
const Cricketer = mongoose.model('Cricketers', cricketerSchema); 
  
const cursorReference = Cricketer 
    .aggregate([{ $project: { name: 1 } }]) 
    .cursor({ batchSize: 1000 }); 
  
cursorReference.eachAsync((document, count) => { 
    console.log(document, count); 
}) 

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

node app.js

输出:

{ _id: 3, name: 'Ben Stokes' } 0
{ _id: 2, name: 'David Warner' } 1 
{ _id: 5, name: 'Aaron Finch' } 2  
{ _id: 7, name: 'K L Rahul' } 3    
{ _id: 6, name: 'Hardik Pandya' } 4
{ _id: 1, name: 'Virat Kohli' } 5  
{ _id: 4, name: 'Rohit Sharma' } 6 

示例2: 在这个示例中,我们使用mongoose建立了一个数据库连接,并在cricketerSchema上定义了一个模型,包括三个列或字段:“_id”,“name”和“nationality”。最后,为了获取当前聚合管道的第一个文档,我们在游标对象上使用 next() 方法,该方法返回当前管道操作的第一个文档。

文件名:app.js

// Require mongoose module 
const mongoose = require("mongoose"); 
  
// Set Up the Database connection 
mongoose.connect("mongodb://localhost:27017/geeksforgeeks", { 
    useNewUrlParser: true, 
    useUnifiedTopology: true, 
}); 
  
const cricketerSchema = new mongoose.Schema({ 
    _id: Number, 
    name: String, 
    nationality: String 
}); 
  
const Cricketer = mongoose.model('Cricketers', cricketerSchema); 
  
Cricketer 
    .aggregate([{ $project: { name: 1 } }]) 
    .cursor({ batchSize: 1000 }) 
    .next() 
    .then((firstDocument) => { 
        console.log(firstDocument) 
    });

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

node app.js

输出:

{ _id: 3, name: 'Ben Stokes' }

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程