Quick Start (2024)

Docs HomeDevelop ApplicationsMongoDB DriversNode.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 requires

  • Saves the package in the node_modules directory

  • Records 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.

Quick Start (8)

Quick Start (9)

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.

Quick Start (10)

Quick Start (11)

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 urivariable 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.

Quick Start (2024)
Top Articles
The High 5 Banking Method
How do healthcare providers diagnose intellectual and developmental disabilities (IDDs)?
Non Omnis Moriar: The Heartbreaking Haunting of Disneyland Paris' Phantom Manor - Park Lore
Sdn Md 2023-2024
Heccymar Salerno Video
Innovation and entrepreneurship - Peter F Drucker - PDFCOFFEE.COM
Wednesday Morning Gifs
R&B Music Near Me Tonight
330-556-3579
Devotion Showtimes Near The Grand 16 - Pier Park
A Whole Lotta Zozo
Cape Girardeau Mo Inmate Roster
Wrongplanet.net
Call2Recycle Sites At The Home Depot
One Facing Life Maybe Crossword
Kwik Kar Guymon Ok
Missed Connections Inland Empire
Howdy Porta
Imbigswoo
Tooquteforyou Skype
Buzzr Tv Schedule Tonight
Atrium Attorney Portal
9-1-1 Kidnapped Boy Episode Cast
24 Hour Pawn Shop San Antonio
Anbf Bodybuilding
Fort Bragg Cif Appointment
Teksystems Time And Expense
Barber Gym Quantico Hours
CDT to CST Converter - Savvy Time
Lucki White House Lyrics
Huniepop Jessie Questions And Answers
Able To Feel Things Figgerits
Dr Bizzaro Bubble Tea Menu
Brent Yorgey - Solved Kattis problems
Shiawassee County 911 Active Events
Arre St Wv Srj
Weil Cornell Connect
Kaitlyn Krems Leak: The Truth Behind The Controversy
Jasmine9966
Obtenir et afficher les itinéraires - Ordinateur
Humanplex
Rubios Listens Com
Craigslist South Jersey Nj
Chicago PD Season 12's Upton Replacement Is Already Great (Despite No One Official Yet)
Kaden Deane Abal
Rcs Carnival Laveen Az
Neos Urgent Care Springfield Ma
Craigslist Portland Oregon Motorcycles
Do sprzedania Zenith Captain Power Reserve Elite za cene 11 124 zł od Seller na Chrono24
O’Fallon, Illinois | Build Your Life and Family Here
ROG STRIX B550-E GAMING | Motherboards | ROG Global
Latest Posts
Article information

Author: Mrs. Angelic Larkin

Last Updated:

Views: 6176

Rating: 4.7 / 5 (67 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Mrs. Angelic Larkin

Birthday: 1992-06-28

Address: Apt. 413 8275 Mueller Overpass, South Magnolia, IA 99527-6023

Phone: +6824704719725

Job: District Real-Estate Facilitator

Hobby: Letterboxing, Vacation, Poi, Homebrewing, Mountain biking, Slacklining, Cabaret

Introduction: My name is Mrs. Angelic Larkin, I am a cute, charming, funny, determined, inexpensive, joyous, cheerful person who loves writing and wants to share my knowledge and understanding with you.