Docs Home → Develop Applications → MongoDB Drivers → Node.js
On this page
- Set up Your Project
- Install Node and npm
- Create the Project
- Add MongoDB as a Dependency
- Create a MongoDB Cluster
- Connect to Your Application
- Next Steps
This version of the documentation is archived and no longer supported. View the
current documentation to learn how to upgrade your version of the MongoDB Node.js driver.
This guide shows you how to create an application that uses theMongoDB Node.js driver to connect to a MongoDB cluster hosted on MongoDB Atlas. Ifyou prefer to connect to MongoDB using a different driver or programminglanguage, see our list of official drivers.
The Node.js driver is a library you can use to connect to and communicatewith MongoDB.
MongoDB Atlas is a fully managed cloud database service that hosts yourMongoDB servers. You can get started with your own free (no credit cardrequired) MongoDB instance with this guide.
Follow the steps below to connect a sample Node.js application to a MongoDBinstance on MongoDB Atlas.
Set up Your Project
Install Node and npm
Ensure you have Node.js v12 or later and npm (Node Package Manager) installedin your development environment.
For information on how to install Node.js and npm, seedownloading and installing Node.js and npm.
Create the Project
First, in your shell, create a directory for your project:
mkdir node_quickstart
Then, navigate into that directory:
cd node_quickstart
Next, initialize your project:
npm init -y
Add MongoDB as a Dependency
Install the Node.js driver:
npm install mongodb@4.1
This command performs the following actions:
Downloads the
mongodb
package and the dependencies it requiresSaves the package in the
node_modules
directoryRecords the dependency information in the
package.json
file
At this point, you are ready to use the Node.js driver with yourapplication.
Create a MongoDB Cluster
1
Create a Free Tier Cluster in Atlas
Create a free tier MongoDB cluster on MongoDB Atlas to store and manageyour data. MongoDB Atlas hosts and manages your MongoDB database in thecloud. Complete the Get Started with Atlasguide to set up a new Atlas account, a free tier cluster (a sharedMongoDB instance) and load sample data into your cluster.
2
Connect to your Cluster
You can connect to your MongoDB cluster by providing aconnection string which instructs the driver on where and how toconnect. The connection string includes information on the hostnameor IP address and port of your cluster, the authentication mechanism,user credentials when applicable, and other connection options.
To connect to an instance or cluster not hosted on Atlas, seeOther Ways to Connect to MongoDB.
To retrieve your connection string for the cluster you created inthe previous step, log into your Atlas account and navigate to theDatabase section and click the Connect buttonfor the cluster that you want to connect to as shown below.
Proceed to the Connect Your Application section and selectthe Node.js driver. Select the Connection String Only taband click the Copy button to copy the connection string toyour clipboard as shown below.
Save your connection string to a safe location.
Connect to Your Application
1
Create your Node.js Application
Create a file to contain your application called index.js
in yourproject directory. Add the following code, assigning the uri
variable the value of your connection string.
const { MongoClient } = require("mongodb"); // Replace the uri string with your connection string. const uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority"; const client = new MongoClient(uri); async function run() { try { await client.connect(); const database = client.db('sample_mflix'); const movies = database.collection('movies'); // Query for a movie that has the title 'Back to the Future' const query = { title: 'Back to the Future' }; const movie = await movies.findOne(query); console.log(movie); } finally { // Ensures that the client will close when you finish/error await client.close(); } } run().catch(console.dir);
Tip
The preceding code example assigns the MongoClient
variable usingobject destructuring,introduced in Node.js v6. You can create an instance of aMongoClient
without using object destructuring as shown in thefollowing code:
const MongoClient = require("mongodb").MongoClient;
2
Run your Node.js Application
Run the application you created from the previous step from thecommand line:
node index.js
You should see the details of the retrieved movie document in the output:
{ _id: ..., plot: 'A young man is accidentally sent 30 years into the past...', genres: [ 'Adventure', 'Comedy', 'Sci-Fi' ], ... title: 'Back to the Future', ... }
If you encounter an error or no output, check whether you specified theproper connection string in the application code, and loaded the sampledata set in your Atlas cluster.
At this point, you should have a working application that usesthe Node.js driver to connect to your MongoDB instance, runs a queryon the sample data, and prints out the result.
Next Steps
Learn how to read and modify data using the Node.js driver in ourCRUD Operations guide or how to perform commonoperations in our Usage Examples.