Nodejs操作mongodb

Nodejs操作mongodb

使用该命令安装mongodb

npm install mongodb
const { MongoClient } = require('mongodb')
const client = new MongoClient('mongodb://127.0.0.1:27017')
const main = async () => {
  await client.connect()
  const db = client.db('mytest')
  const cc = db.collection('cc')
  const d = await cc.find()
  console.log(await d.toArray())
}
main().finally(() => client.close())

将以上代码优化

// nodejs链接mongodb
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 () => {
  let cc = await clientFun('cc')
  let d = await cc.find() //查询
  console.log(await d.toArray()) //默认返回的是游标 需要toArray方法转换
  //增加一条
  let addOne = await cc.insertOne({ usename: 'moncias', age: 30 })
  //增加多条数据
  let addMore = await cc.insertMany([
    { usename: 'moncias', age: 30 },
    { usename: 'moncia1', age: 40 },
    { usename: 'moncia2', age: 41 },
    { usename: 'moncia3', age: 42 }
  ])
  //条件查询 查询一条
  const filter = await cc.findOne({ age: { $gt: 15 } })
  //条件查询多条
  const filters = await cc.find({ age: { $gt: 15 } })
  // 根据条件更新一条
  const updateOne = await cc.updateOne({ age: { $gt: 15 } }, { $set: { usename: 'ws' } })
  //根据条件更新多条
  const updateMany = await cc.updateOne({ age: { $gt: 15 } }, { $set: { usename: 'ms' } })
  //根据条件删除一条
  const deleteOne = await cc.deleteOne({ age: { $gt: 10 } })
   //根据条件删除多条
  const deleteMore = await cc.deleteMany({ age: { $gt: 40 } })
}
main().finally(() => client.close())
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值