To connect Node.js with MongoDB and read data, follow these steps:
Step 1: Install Dependencies
Make sure you have Node.js installed, then install the MongoDB Node.js driver using npm:
npm init -y
npm install mongodb
Step 2: Create a Connection to MongoDB
Create a file index.js
and write the following code:
const { MongoClient } = require("mongodb");
// Connection URL
const uri = "mongodb://localhost:27017"; // Change to your MongoDB URL
const client = new MongoClient(uri);
// Database and Collection Name
const dbName = "testDB"; // Change to your database name
const collectionName = "users"; // Change to your collection name
async function readData() {
try {
// Connect to MongoDB
await client.connect();
console.log("Connected to MongoDB");
const db = client.db(dbName);
const collection = db.collection(collectionName);
// Read Data
const result = await collection.find({}).toArray();
console.log("Data:", result);
} catch (err) {
console.error("Error:", err);
} finally {
// Close connection
await client.close();
}
}
// Call the function
readData();
Step 3: Run the Script
Run the file using:
node index.js
Explanation
- MongoClient is used to connect to MongoDB.
- client.connect() establishes the connection.
- db.collection().find({}).toArray() fetches all documents from the collection.
- await client.close() closes the connection after execution.
Additional Tips
- If you’re using MongoDB Atlas (Cloud), replace
"mongodb://localhost:27017"
with your MongoDB Atlas connection string. - To filter data, modify
find({})
, e.g.,find({ age: { $gt: 25 } })
to get users older than 25.