Open In App
Related Articles

How to get Distinct Documents from MongoDB using Node.js ?

Improve Article
Save Article
Like Article

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.



Parameters: This function takes two parameters as mentioned above and described below:

  1. The name of the key of the MongoDB database to find distinct values of it
  2. 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

MongoDB Database:


Database Structure:



const MongoClient = require("mongodb");
const database = "GFG";   // Database name
MongoClient.connect((url)).then((client) => {
    // Database reference
    const connect = client.db(database); 
    // Connect database to connection
    const collection = connect.collection("GFGcollection");
    // class key
    collection.distinct("class").then((ans) => {
        // Printing distinct value of class key
    }).catch((err) => {


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!

Last Updated : 05 Aug, 2021
Like Article
Save Article
Similar Reads
Related Tutorials