1
Create your Node.js Application
Create a file to contain your application called index.js
in yournode_quickstart
project directory.
Copy and paste the following code into the index.js
file:
const { MongoClient } = require("mongodb"); // Replace the uri string with your connection string. const uri = "<connection string uri>"; const client = new MongoClient(uri); async function run() { try { 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);
2
Assign the Connection String
Replace the <connection string uri>
placeholder with theconnection string that you copied from the Create a Connection Stringstep of this guide.
3
Run your Node.js Application
In your shell, run the following command to start this application:
node index.js
The output includes details of the retrieved movie document:
{ _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 see no output, check whether you specified theproper connection string in the index.js
file, and that you loaded thesample data.
After you complete these steps, you have a working application thatuses the driver to connect to your MongoDB deployment, runs a query onthe sample data, and prints out the result.
Note
If you run into issues on this step, ask for help in theMongoDB Community Forumsor submit feedback by using the Rate this pagetab on the right or bottom right side of this page.