How to find all the values of particular key of MongoDB Database using Node.js ?
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 127.0.0.1
MongoDB Database: Our database name and collection is shown below with some dummy data.
Database:GFG
Collection:aayush
Filename: index.js
Javascript
const MongoClient = require( "mongodb" );
const databasename = "GFG" ;
MongoClient.connect(url).then((client) => {
const connect = client.db(databasename);
const collection = connect.collection( "aayush" );
collection.find({ }).project({name:1})
.toArray().then((values) => {
console.log(ans);
});
}). catch ((err) => {
console.log(err.Message);
})
|
Run the index.js file using the following command:
node index.js
Output:
Last Updated :
12 Feb, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...