- Node & MongoDB Tutorial
- Node & MongoDB - Home
- Node & MongoDB - Overview
- Node & MongoDB - Environment Setup
- Node & MongoDB Examples
- Node & MongoDB - Connect Database
- Node & MongoDB - Show Databases
- Node & MongoDB - Drop Database
- Node & MongoDB - Create Collection
- Node & MongoDB - Drop Collection
- Node & MongoDB - Display Collections
- Node & MongoDB - Insert Document
- Node & MongoDB - Select Document
- Node & MongoDB - Update Document
- Node & MongoDB - Delete Document
- Node & MongoDB - Embedded Documents
- Node & MongoDB - Limiting Records
- Node & MongoDB - Sorting Records
- Node & MongoDB Useful Resources
- Node & MongoDB - Quick Guide
- Node & MongoDB - Useful Resources
- Node & MongoDB - Discussion
Node & MongoDB - Select Documents
To select documents of a collection, you can use collection.findOne() or collection.find() methods to select one or multiple documents.
database.collection("sampleCollection").findOne({}, function(error, result) { if (error) throw error; console.log(result); }); database.collection("sampleCollection").find({}).toArray(function(error, result) { if (error) throw error; console.log(result); });
Example
Try the following example to select documents in a mongodb collection −
Copy and paste the following example as mongodb_example.js −
const MongoClient = require('mongodb').MongoClient; // Prepare URL const url = "mongodb://localhost:27017/"; // make a connection to the database MongoClient.connect(url, function(error, client) { if (error) throw error; console.log("Connected!"); // Connect to the database const database = client.db('myDb'); database.collection("sampleCollection").findOne({}, function(error, result) { if (error) throw error; console.log(result); }); database.collection("sampleCollection").find({}).toArray(function(error, result) { if (error) throw error; console.log(result); }); // close the connection client.close(); });
Output
Execute the mysql_example.js script using node and verify the output.
node mongodb_example.js Connected! { _id: 60c4bbb40f8c3920a0e30fdd, First_Name: 'Radhika', Last_Name: 'Sharma', Date_Of_Birth: '1995-09-26', e_mail: 'radhika_sharma.123@gmail.com', phone: '9000012345' } [ { _id: 60c4bbb40f8c3920a0e30fdd, First_Name: 'Radhika', Last_Name: 'Sharma', Date_Of_Birth: '1995-09-26', e_mail: 'radhika_sharma.123@gmail.com', phone: '9000012345' }, { _id: 60c4bbb40f8c3920a0e30fde, First_Name: 'Rachel', Last_Name: 'Christopher', Date_Of_Birth: '1990-02-16', e_mail: 'rachel_christopher.123@gmail.com', phone: '9000054321' }, { _id: 60c4bbb40f8c3920a0e30fdf, First_Name: 'Fathima', Last_Name: 'Sheik', Date_Of_Birth: '1990-02-16', e_mail: 'fathima_sheik.123@gmail.com', phone: '9000012345' }, { _id: 60c4bbb40f8c3920a0e30fdc, First_Name: 'Mahesh', Last_Name: 'Parashar', Date_Of_Birth: '1990-08-21', e_mail: 'mahesh_parashar.123@gmail.com', phone: '9034343345' } ]
Advertisements
To Continue Learning Please Login
Login with Google