Mongoose Query.prototype.distinct()方法

Mongoose Query.prototype.distinct()方法

Mongoose Query API distinct() 方法用于在集合中查找特定字段的不同值,并将响应作为数组返回。

语法:

Query.prototype.distinct(field, filter, callback)

参数: 它接受上述提及的参数,并描述如下:

  • field: 它是一个字符串,用于标识要返回不同值的字段。
  • filter: 它是一个可选的mongoose对象,它是从Query.prototype.setOptions()派生而来的。
  • callback: 它是一个接受两个参数(错误和数组)的回调函数。

返回类型: 它返回一个Query对象作为响应。

创建Node应用并安装Mongoose:

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

mkdir folder_name
cd folder_name
npm init -y
touch main.js

步骤2: 在完成Node.js应用程序之后,使用以下命令安装所需的模块:

npm install mongoose

示例1: 在这个示例中,我们将使用这种方法来查找集合中字段“age”的不同值。

文件名: main.js

// Importing the module 
const mongoose = require('mongoose') 
  
// Connecting to the database 
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, 
    }, 
    age: { 
        type: Number, 
    } 
}); 
  
const personsArray = [ 
    { 
        name: 'Luffy', 
        age: 20 
    }, 
    { 
        name: 'Nami', 
        age: 20, 
    }, 
    { 
        name: 'Zoro', 
        age: 35 
    } 
] 
  
const Person = mongoose.model('Person', personSchema); 
  
(async () => { 
    await Person.insertMany(personsArray); 
    const res = await Person.distinct('age'); 
    console.log({ res }); 
})()

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

node main.js

输出:

Mongoose Query.prototype.distinct()方法

MongoDB Compass可视化数据库的GUI表示:

Mongoose Query.prototype.distinct()方法

示例2: 在这个示例中,我们将使用这个方法在集合中找到字段“name”的不同值。

文件名: main.js

// Importing the module 
const mongoose = require('mongoose') 
  
// Connecting to the mongodb 
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, 
    }, 
    age: { 
        type: Number, 
    } 
}); 
  
const personsArray = [ 
    { 
        name: 'Luffy', 
        age: 20 
    }, 
    { 
        name: 'Nami', 
        age: 20, 
    }, 
    { 
        name: 'Zoro', 
        age: 35 
    } 
] 
  
const Person = mongoose.model('Person', personSchema); 
  
(async () => { 
    await Person.insertMany(personsArray); 
    const res = await Person.distinct('name'); 
    console.log({ res }); 
})()

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

node main.js

输出:

Mongoose Query.prototype.distinct()方法

使用MongoDB Compass的数据库的GUI表示:

Mongoose Query.prototype.distinct()方法

参考: https://mongoosejs.com/docs/api/query.html#query_Query-distinct

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程