MongoDB is a cross-platform, document-oriented database that works on the concept of collections and documents. It stores data in the form of key-value pairs and is a NoSQL database program. The term NoSQL means non-relational.
MongoDB module: This module of Node.js is used for connecting the MongoDB database as well as used for manipulating the collections and databases in MongoDB. The mongodb.connect() method is used for connecting the MongoDB database which is running on a particular server on your machine. (Refer to this article). We can also use promises in this method in resolve the object contains all the methods and properties required for collection manipulation and in reject, the error occurs during connection.
collection.distinct() method of mongodb module is used to finding the distinct documents of a particular database in MongoDB.
syntax:
collection.distinct(key,callbackfunction)
Parameters: This function takes two parameters as mentioned above and described below:
- The name of the key of the MongoDB database to find distinct values of it
- Callback function to make this function asynchronous
Installing module:
npm install mongodb
Project structure:

Running the server on Local IP:
mongod --dbpath=data --bind_ip 127.0.0.1

MongoDB Database:
Database:GFG
Collection:GFGcollection
Database Structure:

Index.js
Javascript
const MongoClient = require( "mongodb" );
const database = "GFG" ;
MongoClient.connect((url)).then((client) => {
const connect = client.db(database);
const collection = connect.collection( "GFGcollection" );
collection.distinct( "class" ).then((ans) => {
console.log(ans);
}). catch ((err) => {
console.log(err.Message);
})
})
|
Output:

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!