Docs Menu

Docs HomeDevelop ApplicationsMongoDB DriversNode.js

Usage Examples

On this page

  • Overview
  • How to Use the Usage Examples
  • Available Usage Examples

Usage examples provide convenient starting points for popular MongoDB operations. Each example provides:

  • an explanation of the operation in the example showing the purpose and a sample use case for the method

  • an explanation of how to use the operation, including parameters, return values, and common exceptions you might encounter

  • a full Node.js program that you can copy and paste to run the example in your own environment

These examples use the MongoDB Atlas sample data database. You can use this sample data on the free tier of MongoDB Atlas by following the Get Started with Atlas guide or you can import the sample dataset into a local MongoDB instance.

Once you have imported the dataset, you can copy and paste a usage example into your development environment of choice. You can follow the quick start guide to learn more about getting started with Node.js, npm, and the Node.js driver. Once you've copied a usage example, you'll have to edit one line to get the example running with your instance of MongoDB:

// Replace the following with your MongoDB deployment's connection string.
const uri =

All examples use ES module imports. You can enable ES module imports by adding the following key-value pair to your package.json file:

"type": "module"



You can use any usage example with CommonJS require. To use CommonJS require, you must swap out the ES module import statement for your CommonJS require statement.

Click on the tabs to see the syntax for importing the driver with ES module import and CommonJS require:

You can use the Atlas Connectivity Guide to enable connectivity to your instance of Atlas and find the connection string to replace the uri variable in the usage example. If your instance uses SCRAM authentication, you can replace <user> with your username, <password> with your password, and <cluster-url> with the IP address or URL of your instance. Consult the Connection Guide for more information about getting connected to your MongoDB instance.

←  What's NewFind Operations →