Article directory
Connect to MongoDB using Node.js
Using Node.js to connect to MongoDB requires a mongodb tool, which can be installed directly using the NPM command:
npm install mongodb
Then import it at the head of the code, and the connection operation can be performed normally:
I have divided the following code into three packages so that the structure can be clearly seen:
- The first part is to introduce mongodb, and then define the object that the client gets the link
- The second part is to perform a link operation, linking to the library named mytest
- The third part is to perform a specific operation, here is to search
const {
MongoClient } = require('mongodb')
const client = new MongoClient('mongodb://127.0.0.1:27017')
const clientFun = async function (c) {
await client.connect()
const db = client.db('mytest')
return db.collection(c)
}
const main = async () => {
var cc = await clientFun('cc')
var d = await cc.find()
}
main().finally(() => client.close()) //断开连接
adding data
Add a single piece of data
const {
MongoClient } = require('mongodb')
const client = new MongoClient('mongodb://127.0.0.1:27017')
const clientFun = async function (c) {
await client.connect()
const db = client.db('mytest')
return db.collection(c)
}
const main = async () => {
var cc = await clientFun('cc')
var d = await cc.insertOne({
username:'monica',age:60})// insertOne添加一条数据
console.log(d); // 打印结果
}
main().finally(() => client.close())
View console results:
View database content:
Add multiple data
Use insertMany to add multiple pieces of data
var d = await cc.insertMany([
{
username: 'Monica', age: 12 },
{
username: '卡卡', age: 6 },
{
username: '安迪', age: 12 },
{
username: '朱丽叶', age: 20 }
])
Check out the database:
find data
Here is an example to find data whose age is less than 15
var d = await cc.find({
age:{
$gt:15}})
console.log(await d.toArray());
Check the console:
find one can be achieved with findOne, the above find finds multiple by default
update data
The above uses to modify one piece of data, and the following is multiple.
The operation is to modify the username attribute of the data whose age is 15 to 'lisi'
// var d = await cc.updateOne({age:{$gt:15}},{$set:{username:'lisi'}})
var d = await cc.updateMany({
age:{
$lt:15}},{
$set:{
username:'lisi'}})
View database: modified successfully
delete data
The above is used to delete one piece of data, and the following is multiple. The
following operation is to delete data with an age greater than 10
// var d = await cc.deleteOne({age:{$gt:50}})
var d = await cc.deleteMany({
age:{
$gt:10}})
Check the database and find that the data is deleted successfully
at last
This section mainly talks about how Node.js connects to MongoDB for adding, checking, deleting, and modifying operations. First, link, and then use statements to perform corresponding operations. Later, it will continue to bring about the realization of other functions of nodejs+MongoDB