Connecting to MongoDB with Node.js: Insert, Query, and Delete Made Easy

Saketh
@Saketh
MongoDB is one of the most popular NoSQL databases, and Node.js is a leading JavaScript runtime for backend development. In this blog post, we'll walk through how to connect to MongoDB using Node.js, insert data into a collection, query it, and delete records. Whether you're building an API or automating a script, this guide will give you a solid foundation.
β¨ Prerequisites
- Node.js installed (
>= v14
) - MongoDB Atlas or a local MongoDB server
- A MongoDB URI (you can get this from your MongoDB Atlas dashboard)
Install the required npm package:
npm install mongodb
π Connect to MongoDB
Create a file called connect.js
:
const { MongoClient } = require('mongodb');
const uri = 'mongodb+srv://<username>:<password>@<cluster>.mongodb.net/?retryWrites=true&w=majority';
const client = new MongoClient(uri);
async function connectToMongoDB() {
try {
await client.connect();
console.log('Connected to MongoDB!');
} catch (err) {
console.error('Connection failed:', err);
} finally {
await client.close();
}
}
connectToMongoDB();
Replace <username>
, <password>
, and <cluster>
with your actual MongoDB Atlas credentials.
π Insert Documents into a Collection
Create a file insertData.js
:
const { MongoClient } = require('mongodb');
const uri = 'mongodb+srv://<username>:<password>@<cluster>.mongodb.net/?retryWrites=true&w=majority';
const client = new MongoClient(uri);
async function insertDocument() {
try {
await client.connect();
const db = client.db('your_database');
const collection = db.collection('your_collection');
const result = await collection.insertOne({
name: 'John Doe',
email: 'john@example.com',
age: 30,
joined: new Date()
});
console.log('Document inserted with ID:', result.insertedId);
} finally {
await client.close();
}
}
insertDocument();
π Query Documents
Create a file queryData.js
:
const { MongoClient } = require('mongodb');
const uri = 'mongodb+srv://<username>:<password>@<cluster>.mongodb.net/?retryWrites=true&w=majority';
const client = new MongoClient(uri);
async function findDocuments() {
try {
await client.connect();
const db = client.db('your_database');
const collection = db.collection('your_collection');
const cursor = collection.find({ age: { $gt: 25 } });
const results = await cursor.toArray();
console.log('Documents found:', results);
} finally {
await client.close();
}
}
findDocuments();
ποΈ Delete Documents
Create a file deleteData.js
:
const { MongoClient } = require('mongodb');
const uri = 'mongodb+srv://<username>:<password>@<cluster>.mongodb.net/?retryWrites=true&w=majority';
const client = new MongoClient(uri);
async function deleteDocuments() {
try {
await client.connect();
const db = client.db('your_database');
const collection = db.collection('your_collection');
const result = await collection.deleteMany({ age: { $lt: 18 } });
console.log(`Deleted ${result.deletedCount} document(s)`);
} finally {
await client.close();
}
}
deleteDocuments();
π Conclusion
With just a few lines of code, you can connect to MongoDB, insert documents, query them, and delete unwanted data using Node.js. Whether youβre building an application backend or automating database tasks, this basic setup provides everything you need to get started with MongoDB and Node.js.
Happy coding! π