Mongoose Aggregate.prototype.match()函数

Mongoose Aggregate.prototype.match()函数

Aggregate API.prototype.match() 函数 是用来在数据库中查找与 API 参数中提到的条件相匹配的现有文档的 Mongoose API。

语法 :

Aggregate.prototype.match()

参数: 如上所述,它接受以下4个参数,并在下面进行了描述:

  • args: 它是一个 mongoose 对象,用于标识操作符的匹配条件。

返回类型: 将匹配的文档作为响应返回。

设置 Node.js Mongoose 模块:

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

npm init

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

npm install mongoose

下面的示例将演示Mongoose聚合API.prototype.match()方法。

示例1: 在这个示例中,我们将使用这个方法来查找已存在的名字为“Luffy”的文档。

const mongoose = require('mongoose') 
  
// Database connection 
mongoose.connect('mongodb://localhost:27017/query-helpers', 
    { 
        dbName: 'event_db', 
        useNewUrlParser: true, 
        useUnifiedTopology: true
    }, err => err ? console.log(err) 
        : console.log('Connected to database')); 
  
const personSchema = new mongoose.Schema({ 
    name: { 
        type: String, 
        select: false
    }, 
    age: { 
        type: Number, 
    } 
}); 
  
const personsArray = [ 
    { 
        name: 'Luffy', 
        age: 19 
    }, 
    { 
        name: 'Nami', 
        age: 30 
    }, 
    { 
        name: 'Zoro', 
        age: 35 
    } 
] 
  
const Person = mongoose.model('Person', personSchema); 
  
(async () => { 
    await Person.insertMany(personsArray); 
    const res = await Person.aggregate() 
        .match({ name: 'Luffy' }); 
  
    console.log({ res }); 
})()

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

node main.js

输出:

Mongoose Aggregate.prototype.match()函数

MongoDB Compass使用图形用户界面(GUI)表示的数据库:

Mongoose Aggregate.prototype.match()函数

示例2: 在这个示例中,我们将使用这种方法来查找具有名称“Nami”或“Zoro”的现有文件。

const mongoose = require('mongoose') 
  
// Database connection 
mongoose.connect('mongodb://localhost:27017/query-helpers', 
    { 
        dbName: 'event_db', 
        useNewUrlParser: true, 
        useUnifiedTopology: true
    }, err => err ? console.log(err) 
        : console.log('Connected to database')); 
  
const personSchema = new mongoose.Schema({ 
    name: { 
        type: String, 
        select: false
    }, 
    age: { 
        type: Number, 
    } 
}); 
  
const personsArray = [ 
    { 
        name: 'Luffy', 
        age: 19 
    }, 
    { 
        name: 'Nami', 
        age: 30 
    }, 
    { 
        name: 'Zoro', 
        age: 35 
    } 
] 
  
const Person = mongoose.model('Person', personSchema); 
  
(async () => { 
    await Person.insertMany(personsArray); 
    const res = await Person.aggregate() 
        .match({ name: { $in: ['Nami', 'Zoro'] } }); 
  
    console.log({ res }); 
})()

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

node main.js

输出:

Mongoose Aggregate.prototype.match()函数

GUI表示MongoDB Compass中的数据库:

Mongoose Aggregate.prototype.match()函数

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程