How to connect mongodb using javascript

PHPz
Release: 2023-04-26 14:47:33
Original
1072 people have browsed it

MongoDB is a non-relational database that is often used to store semi-structured or unstructured data, such as logs, pictures, videos, etc. It uses JavaScript as its operating language, so when connecting to the MongoDB database, JavaScript is required. The steps and methods of connecting to MongoDB will be introduced in detail below.

Step 1: Install the MongoDB driver

First, you need to install the MongoDB driver in the project. You can use the npm command to install it. Enter the following command on the command line:

npm install mongodb
Copy after login

Step 2: Introduce the MongoDB driver

To introduce the MongoDB driver into the project, you can add the following code to the project's entry file to introduce the driver :

const MongoClient = require('mongodb').MongoClient;
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri, { useNewUrlParser: true });
Copy after login

Here, you need to replace localhost:27017 with your MongoDB server address and port number.

Step 3: Connect to MongoDB database

To connect to the MongoDB database in the program, you can use the connect method to establish the connection. In this method, you need to pass the MongoDB server address and port number, and you also need to pass a callback function to tell us whether the connection is successful. The following is the code to connect to the MongoDB database:

client.connect((err) => {
  if (err) {
    console.log('连接 MongoDB 数据库失败!', err);
  } else {
    console.log('连接 MongoDB 数据库成功!');
  }
});
Copy after login

In this callback function, if there is an error, the prompt "Failed to connect to the MongoDB database!" will be output. If there is no error, the prompt "Connect to the MongoDB database successfully" will be output. !".

Step 4: Connect to the MongoDB database collection

After connecting to the MongoDB database, you need to connect to the collection in the MongoDB database. In MongoDB, a collection is equivalent to a table in a relational database, and documents with the same characteristics are stored in the collection. The following is the code to connect to the MongoDB database collection:

const db = client.db('test');
const collection = db.collection('users');
Copy after login

Here test is the name of the database and users is the name of the collection. Here, we use the db method to connect to the database and then the collection method to connect to the collection.

Step 5: Operate the MongoDB database collection

After connecting to the MongoDB database collection, you can perform some operations, such as inserting data, querying data, updating data, and deleting data.

Insert data

In MongoDB, insert data using the insertOne method and the insertMany method.

const user = { name: '张三', age: 18 };
collection.insertOne(user, (err, res) => {
  console.log('插入成功!', res);
});
Copy after login

In this example, we use the insertOne method to insert user data named "Zhang San" with an age of "18". After the insertion is successful, it returns a result object.

Query data

In MongoDB, query data using the find method.

collection.find({ name: '张三' }).toArray((err, docs) => {
  console.log('查询结果:', docs);
});
Copy after login

In this example, we use the find method to query the user data named "Zhang San". Query results are returned in the form of an array. If the user does not exist, the returned result will be an empty array.

Update data

In MongoDB, update data using the updateOne method and the updateMany method.

collection.updateOne({ name: '张三' }, { $set: { age: 20 } }, (err, res) => {
  console.log('更新成功!', res);
});
Copy after login

In this example, we use the updateOne method to update the user data named "Zhang San" and update the age from "18" to "20". After the update is successful, it returns a result object.

Delete data

In MongoDB, delete data using the deleteOne method and the deleteMany method.

collection.deleteOne({ name: '张三' }, (err, res) => {
  console.log('删除成功!', res);
});
Copy after login

In this example, we use the deleteOne method to delete the user data named "Zhang San". After the deletion is successful, it returns a result object.

Summary

MongoDB is a non-relational database that uses JavaScript as its operating language. When connecting to a MongoDB database, you need to install the MongoDB driver first, and then use JavaScript to connect to the MongoDB database collection and perform operations such as inserting, querying, updating, and deleting.

The above is the detailed content of How to connect mongodb using javascript. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template