Skip to content
Related Articles
Open in App
Not now

Related Articles

How to find all the values of particular key of MongoDB Database using Node.js ?

Improve Article
Save Article
  • Last Updated : 12 Feb, 2021
Improve Article
Save Article

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


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!