Linux node js mongodb

MongoDB with Node.js

MongoDB and Node.js work seamlessly together in modern tech stacks. Learn how to set up Node.js and MongoDB as well as how to query data stored in a MongoDB database from a Node.js script.

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:

Using MongoDB with Node.js

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.

How to Set Up Node.js and MongoDB

In this section, we’ll walk through how to set up a Node.js script that connects to a MongoDB database.

Prerequisites

Before you begin, you’ll need to ensure you’ve completed a few prerequisite steps.

  1. If you haven’t already, install Node.js and create a new Node.js project.
  2. Create a MongoDB database. The easiest way to get started with MongoDB is to create a free cluster in MongoDB Atlas, MongoDB’s fully-managed, multi-cloud document database service.
  3. Then load the sample dataset.
  4. Add the MongoDB Node.js Driver to your Node project dependencies using the following command:

Now that you have completed the prerequisites, you’re ready to begin coding!

Get Connected

You can use the MongoClient to connect to a MongoDB database. Import the MongoClient in a new Node.js script:

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:

Читайте также:  Linux настройка прав sftp

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.

What You Need to Know

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.

How MongoDB Stores Data

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.

CRUD Operations

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.

Create

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.

Read

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.

Читайте также:  Linux delete path variable

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.

Update

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.

Delete

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.

How to Use MongoDB with Node.js

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.

Источник

MongoDB Node Driver

Welcome to the documentation site for the official MongoDB Node.js driver. You can add the driver to your application to work with MongoDB in JavaScript or TypeScript. For more information about downloading and installing the Node.js driver, see Download and Install in the Quick Start guide.

Читайте также:  Unzipping tar gz in linux

Quick Start

Learn how to establish a connection to MongoDB Atlas and begin working with data in the step-by-step Quick Start .

Quick Reference

See driver syntax examples for common MongoDB commands in the Quick Reference section.

What’s New

For a list of new features and changes in each version, see the What’s New section.

Usage Examples

For fully runnable code snippets and explanations for common methods, see the Usage Examples section.

Fundamentals

Learn how to perform the following tasks using the Node.js driver in the Fundamentals section:

  • Connect to MongoDB
  • Use the Stable API
  • Authenticate with MongoDB
  • Read from and Write to MongoDB
  • Access Return Values
  • Transform your Data
  • Create and Manage Transactions
  • Run a Database Command
  • Create Indexes to Speed Up Queries
  • Sort Using Collations
  • Log Events in the Driver
  • Monitor Driver Events
  • Store and Retrieve Large Files in MongoDB
  • Encrypt Fields from the Client
  • Create and Query Time Series Collection
  • Specify Type Parameters with TypeScript
  • Specify BSON Serialization Settings

API

For detailed information about classes and methods in the MongoDB Node.js driver, see the MongoDB Node.js driver API documentation .

FAQ

For answers to commonly asked questions about the MongoDB Node.js Driver, see the Frequently Asked Questions (FAQ) section.

Connection Troubleshooting

For solutions to issues you might encounter when using the driver to connect to a MongoDB deployment, see the Connection Troubleshooting section.

Issues & Help

Learn how to report bugs, contribute to the driver, and to find help in the Issues & Help section.

Compatibility

For the compatibility tables that show the recommended Node.js driver version for each MongoDB Server version, see the Compatibility section.

Upgrade Driver Versions

Learn what changes you may need to make to your application to upgrade driver versions in the Upgrade Driver Versions section.

Learn

Visit the Developer Hub and MongoDB University to learn more about the Node.js driver.

Developer Hub

The Developer Hub provides tutorials and social engagement for developers.

To learn how to use MongoDB features with the Node.js driver, see the How To’s and Articles page .

To ask questions and engage in discussions with fellow developers using the Node.js driver, see the Developer Community forums .

MongoDB University

MongoDB University provides free courses to teach everyone how to use MongoDB.

Источник

Оцените статью
Adblock
detector