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

    How to Use the Usage Examples

    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 =

    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.