Skip to content

How to use MongoDB with Node.js

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) {
    console.error(err)
    return
  }
  //...
})

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) => {
  console.log(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) => {
  console.log(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) => {
  console.log(item)
})

Update an existing document

Use the updateOne() method to update a document:

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

Delete a document

Use the deleteOne() method to delete a document:

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

Closing the connection

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

client.close()

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) => {
  console.log(item)
})

Can be used with promises:

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

or async/await:

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

find()

→ Get my Node.js Handbook

download all my books for free

  • javascript handbook
  • typescript handbook
  • css handbook
  • node.js handbook
  • astro handbook
  • html handbook
  • next.js pages router handbook
  • alpine.js handbook
  • htmx handbook
  • react handbook
  • sql handbook
  • git cheat sheet
  • laravel handbook
  • express handbook
  • swift handbook
  • go handbook
  • php handbook
  • python handbook
  • cli handbook
  • c handbook

subscribe to my newsletter to get them

Terms: by subscribing to the newsletter you agree the following terms and conditions and privacy policy. The aim of the newsletter is to keep you up to date about new tutorials, new book releases or courses organized by Flavio. If you wish to unsubscribe from the newsletter, you can click the unsubscribe link that's present at the bottom of each email, anytime. I will not communicate/spread/publish or otherwise give away your address. Your email address is the only personal information collected, and it's only collected for the primary purpose of keeping you informed through the newsletter. It's stored in a secure server based in the EU. You can contact Flavio by emailing flavio@flaviocopes.com. These terms and conditions are governed by the laws in force in Italy and you unconditionally submit to the jurisdiction of the courts of Italy.

Related posts about node: