12 - nodejs 操作 mongodb

  1. 安装mongodb依赖
npm install mongodb
  1. 引入
const MongoClient = require('mongodb').MongoClient;
  1. 构建 mongodb 的连接地址
const url = 'mongodb://127.0.0.1:27017';
  1. 连接
MongoClient.connect(url, function(err, client) {
    // 4.1 选择数据库
    const db = client.db('数据库名称');

    // 4.2 选择集合并操作
    db.collection('集合名称').find();
    ...

    // 4.3 记得关闭连接
    client.close();
});

增加操作

  • 增加一条 insertOne
  • 增加多条 insertMany

删除操作

  • 删除一条 deleteOne
  • 删除多条 deleteMany

修改操作

  • 修改一条 updateOne
  • 修改多条 updateMany

查询操作

  • 查询全部
.find()
  • 查询特定的数据
.find(whereObj)
  • 排序
.find().soft(softObj)
  • 查询指定条数
.find().limit(count)
  • 跳过的条数
.find().skip(count)

猜你喜欢

转载自blog.csdn.net/weixin_34059951/article/details/86846417
今日推荐