Open In App

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

Last Updated : 05 Aug, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  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 127.0.0.1

MongoDB Database:

Database:GFG
Collection:GFGcollection

Database Structure:

Index.js

Javascript




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
        console.log(ans);
    }).catch((err) => {
        console.log(err.Message);
    })
})


Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads