Skip to content

How to use MongoDB with Node.js

New Course Coming Soon:

Get Really Good at Git

In this tutorial I'll show you how to interact with a MongoDB database from Node.js

If you are unfamiliar with MongoDB check our guide on its basics and on how to install and use it :)

We’ll be using the official mongodb npm package. If you already have a Node.js project you are working on, install it using

npm install mongodb

If you start from scratch, create a new folder with your terminal and run npm init -y to start up a new Node.js project, and then run the npm install mongodb command.

Connecting to MongoDB

You require the mongodb package and you get the MongoClient object from it.

const mongo = require('mongodb').MongoClient

Create a URL to the MongoDB server. If you use MongoDB locally, the URL will be something like mongodb://localhost:27017, as 27017 is the default port.

const url = 'mongodb://localhost:27017'

Then use the mongo.connect() method to get the reference to the MongoDB instance client:

mongo.connect(url, {
    useNewUrlParser: true,
    useUnifiedTopology: true
  }, (err, client) => {
  if (err) {

Now you can select a database using the client.db() method:

const db = client.db('kennel')

Create and get a collection

You can get a collection by using the db.collection() method. If the collection does not exist yet, it’s created.

const collection = db.collection('dogs')

Insert data into a collection a Document

Add to app.js the following function which uses the insertOne() method to add an object dogs collection.

collection.insertOne({name: 'Roger'}, (err, result) => {


You can add multiple items using insertMany(), passing an array as the first parameter:

collection.insertMany([{name: 'Togo'}, {name: 'Syd'}], (err, result) => {


Find all documents

Use the find() method on the collection to get all the documents added to the collection:

collection.find().toArray((err, items) => {

Find a specific document

Pass an object to the find() method to filter the collection based on what you need to retrieve:

collection.find({name: 'Togo'}).toArray((err, items) => {

If you know you are going to get one element, you can skip the toArray() conversion of the cursor by calling findOne():

collection.findOne({name: 'Togo'}, (err, item) => {

Update an existing document

Use the updateOne() method to update a document:

collection.updateOne({name: 'Togo'}, {'$set': {'name': 'Togo2'}}, (err, item) => {

Delete a document

Use the deleteOne() method to delete a document:

collection.deleteOne({name: 'Togo'}, (err, item) => {

Closing the connection

Once you are done with the operations you can call the close() method on the client object:


Use promises or async/await

I posted all those examples using the callback syntax. This API supports promises (and async/await) as well.

For example this

collection.findOne({name: 'Togo'}, (err, item) => {

Can be used with promises:

collection.findOne({name: 'Togo'})
  .then(item => {
  .catch(err => {

or async/await:

const find = async () => {
  try {
    const item = await collection.findOne({name: 'Togo'})
  } catch(err => {

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching May 21, 2024. Join the waiting list!
→ Get my Node.js Handbook
→ Read my Node.js Tutorial on The Valley of Code

Here is how can I help you: