Integrate MongoDB with NodeJS Application

Sunil Majhi
2 min readJul 15, 2021

Setup MongoDB

  1. Install mongodb to use the mongodb driver (npm install mongodb)

Initial Code:-

const mongodb = require(‘mongodb’);
const MongoClient = mongodb.MongoClient;
const connectionURL = ‘mongodb://127.0.0.1:27017’;
const databaseName = ‘test’;
MongoClient.connect(connectionURL, { useNewUrlParser : true }, (error, client) => {
if(error){
return console.log(‘Unable to connect to database’);
}
console.log(‘Connected Successfully!’);
const db = client.db(databaseName);
})

Inserting a single document

db.collection(“users”).insertOne(
{name: “Sunil”,age: 27},
(error, result) => {
if (error) return console.log(“Unable to insert user”);
console.log(result.ops);
});

Inserting multiple documents

db.collection(‘users’).insertMany([
{name: “Sunil”,age: 27},
{name: “Sibun”,age: 25}
], (error, result) => {
if(error) return console.log(“Unable to insert user”);
console.log(result.ops);
})

What is ObjectID?

Returns a new ObjectId value. The 12-byte ObjectId value consists of:

  1. a 4-byte timestamp value, representing the ObjectId’s creation, measured in seconds since the Unix epoch
  2. a 5-byte random value
  3. a 3-byte incrementing counter, initialized to a random value

Code: -

const { MongoClient, ObjectID } = require(‘mongodb’);
const id = new ObjectID();
console.log(id);
console.log(id.getTimestamp());
console.log(id.id.length);

Querying Documents

db.collection(‘users’).findOne({‘name’ : ‘Sunil’, ‘age’ : 27}, (error, user) => {
if(error) return console.log(‘Unable to fetch’);
console.log(user);
})
db.collection(‘users’).find({age : 27}).toArray((error, users) => {
console.log(users);
})
db.collection(‘users’).find({age : 27}).count((error, users) => {
console.log(users);
})

Updating Documents

db.collection(‘users’).updateOne(
{
_id : new ObjectID(‘60e9c76a814e3017a3e49fb9’)
}, {
$set: {name : ‘Manu’},
$inc: {age : 1}
}).then((result) => {
console.log(result);
}).catch(error => {
console.error(error);
})

Deleting Documents

db.collection(‘users’).deleteOne(
{_id : new ObjectID(‘60e9c76a814e3017a3e49fb9’)}
).then(result => {
console.log(result);
}).catch(error => {
console.error(error);
})
db.collection(‘users’).deleteMany({age: 27}).then(result => {
console.log(result);
}).catch(error => {
console.error(error);
})

GitHub URL: https://github.com/msunil037/NodeJS-MongoDB-Integration

--

--