Open In App

How does Query.prototype.distinct() work in Mongoose?

Last Updated : 17 Mar, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

The Query.prototype.distinct() function declares or executes a distinct() operation. And if we pass a callback, then the query executes.
Syntax: 
 

Query.prototype.distinct()

Parameters: This function has three optional parameters ie. field, filter and callback function.
Return Value: This function returns Query Object.
Installing mongoose : 

npm install mongoose

After installing the mongoose module, you can check your mongoose version in command prompt using the command. 

npm mongoose --version

Now, create a folder and add a file for example, index.js as shown below.

Database: The sample database used here is shown below: 
 

Example 1:

index.js




const mongoose = require('mongoose');
  
// Database connection
    useNewUrlParser: true,
    useCreateIndex: true,
    useUnifiedTopology: true
});
  
// User model
const User = mongoose.model('User', { 
    name: { type: String },
    age: { type: Number }
});
  
var query = User.distinct('age');
  
query.exec(function(error,result) {
    if(error) console.log(error)
    else console.log(result)
})


Steps to run the program:

The project structure will look like this: 
 

Run index.js file using below command: 
 

node index.js

Output: 

[ 10, 25, 5, 34 ]

Example 2:

index.js




const express = require('express');
const mongoose = require('mongoose');
const app = express()
  
// Database connection
    useNewUrlParser: true,
    useCreateIndex: true,
    useUnifiedTopology: true
});
  
// User model
const User = mongoose.model('User', { 
    name: { type: String },
    age: { type: Number }
});
  
var query = User.distinct('name');
  
query.exec(function(error,result) {
    if(error) console.log(error)
    else console.log(result)
})
  
app.listen(3000, function(error ) {
    if(error) console.log(error)
    console.log("Server listening on PORT 3000")
});


Steps to run the program: 
 

The project structure will look like this: 
 

Run index.js file using below command: 
 

node index.js

Output: 

Server listening on PORT 3000
[ 'Gourav', 'Lalit', 'Piyush', 'Manish' ]

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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads