Skip to content
Related Articles

Related Articles

How to find all the values of particular key of MongoDB Database using Node.js ?
  • Last Updated : 12 Feb, 2021

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() is the main method that is used for connecting to 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 to resolve the object contains all the methods and properties required for collection manipulation and reject the error that occurs during connection.

Project() method of MongoDB module is allowed only documents that specified as a parameter in this Method. This Method takes the document’s key name and with 0 and 1 value. 

  • 0 means except this key show all other’s keys value of MongoDB Collection.
  • 1 means show only given keys value. Of MongoDB Collection.

Installing module: You can install the mongodb module using the following command:

node install mongodb

Project Structure: The project structure will look like the following.

Running the server on Local IP: In the following command, data is the folder name.

mongod --dbpath=data --bind_ip

MongoDB Database: Our database name and collection is shown below with some dummy data.


Filename: index.js


// Requiring module
const MongoClient = require("mongodb");
// Connection URL
// Database name
const databasename = "GFG";
MongoClient.connect(url).then((client) => {
    const connect = client.db(databasename);
    // Connect to collection
    const collection = connect.collection("aayush");
    // Fetching the records of name key
    collection.find({ }).project({name:1})
        .toArray().then((values) => {
        // Printing the values
}).catch((err) => {
    // Printing the error message

 Run the index.js file using the following command:

node index.js


Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :