MongoDB is a flexible, general-purpose document database that is ideally suited for modern applications.. Node.js is a JavaScript runtime that commonly powers web servers. Developers can use these two pieces of technology, along with MongoDB Atlas, a fully managed, multi-cloud database service, to rapidly create modern applications.
In this article, you'll learn the following:
MongoDB and Node.js have a long history of working well together and are paired in many popular tech stacks, including the MEAN stack (MongoDB, Express.js, AngularJS, and Node.js) and and, more recently, the MERN stack (MongoDB, Express.js, React.js, and Node.js).
The MongoDB Node.js driver makes working with MongoDB from inside a Node.js script simple and intuitive for developers—saving time and increasing productivity.
In this section, we'll walk through how to set up a Node.js script that connects to a MongoDB database.
Before you begin, you'll need to ensure you've completed a few prerequisite steps.
npm install mongodb
Now that you have completed the prerequisites, you're ready to begin coding!
You can use the MongoClient to connect to a MongoDB database. Import the MongoClient in a new Node.js script:
const { MongoClient } = require('mongodb');
Then create an instance of MongoClient by passing your connection URI to it. For more information on how to find your connection URI and ensure your Atlas database is ready for connection, see the official MongoDB documentation on connecting to a cluster.
const client = new MongoClient(yourConnectionURI);
Now you're ready to get connected:
await client.connect();
These are the basics of getting connected. For more detailed information on how to get connected to a MongoDB database from a Node.js script, see Connect to a MongoDB Database Using Node.js.
To begin working with MongoDB from a Node.js script, you should understand how MongoDB stores data as well as the basic methods you can use to query your data. We'll cover both topics below.
MongoDB stores data as BSON documents. BSON is a binary representation of JSON (JavaScript Object Notation).
Documents are similar in structure to JavaScript objects and store information in field-value pairs. Every document is required to have an _id field. The value stored in _id must be unique for every document in the collection.
Documents typically contain information about one object and any information that will be queried with that object. Related documents are grouped together in collections. Related collections are stored together in databases.
The MongoDB Node.js driver provides a variety of methods to help you query your data. These methods are known as CRUD (create, read, update, and delete) operations.
Use insertOne() to create a new document. insertOne() has only one required parameter: the document to insert. If the document does not include a field named _id, the MongoDB Node.js driver will add one automatically.
To create multiple documents, use insertMany(). The only argument you are required to pass to insertMany() is an array of documents to insert.
Both insertOne() and insertMany() allow you to pass optional settings. One optional setting to note for insertMany() is the boolean ordered. If an insert fails when ordered is to true, the remaining inserts will not be executed. If an insert fails when ordered is to false, the remaining inserts will be executed. See the official documentation for more information.
To retrieve a single document from your database, use findOne(). findOne() requires that you pass a query object. The query can contain zero to many properties.
To retrieve multiple documents from your database, use find(). Like findOne(), find() requires you to pass a query object that contains zero to many properties. find() returns a cursor that you can use to iterate over the results.
Both findOne() and find() allow you to pass optional settings when you call them. One handy option is projection, which allows you to explicitly exclude or include the fields that are returned in the query.
Use updateOne() when you want to update a single document. updateOne() has two required parameters: a filter object that indicates which document should be updated and an update object that indicates the update operations that should be applied to the document.
To update multiple documents, you can use updateMany(). updateMany() has the same required parameters as updateOne(): a filter object and an update object.
Both updateOne() and updateMany() allow you to pass optional settings to them when you call them. upsert is one of the options you can pass. When upsert is set to true, a new document will be created if no document matches the query. upsert can be really helpful as it allows you to combine multiple operations into one: checking to see if a document exists and then updating the document if it exists or creating a new document if it does not.
To delete a single document, use deleteOne(). A filter object that indicates the document to be deleted is the only required parameter.
Use deleteMany() when you want to delete multiple documents. Like deleteOne(), the only required parameter is the filter object.
Both deleteOne() and deleteMany() allow you to pass optional settings as well. See the official documentation for more information.
Now you know the basics of querying data stored in a MongoDB database from a Node.js script. For more detailed information on how to execute the CRUD operations in a Node.js script, see MongoDB and Node.js Tutorial - CRUD Operations.
The MongoDB Node.js driver makes using MongoDB with Node.js a seamless experience. The driver automatically maps JavaScript objects to BSON documents, meaning that developers can easily work with their data.
Want to learn more about using MongoDB with Node.js?
Check out the following resources:
If you have any questions about MongoDB, join the MongoDB Community.