Mongodb学习笔记(一)

1. 启动 Mongodb 数据库

  1. 在 Mongodb 的 bin 文件夹下打开控制台

  2. 输入 mongod.exe --dbpath D:\MongoDB\data\db 回车

  3. 重复步骤一,在控制台中输入 mongo.exe --port 27017

  4. 步骤三的服务可以按 ctrl C 停止,但步骤一的服务不能停止,是数据库的服务

2.nodejs连接mongodb

代码部分

// nodejs 连接 mongodb
// 体会 nodejs 连接 mongodb 的能力,不会真正的用到路由上
// mongoose 对接路由的功能

const MongoClient = require("mongodb").MongoClient  // mongodb 客户端
// compass, 命令行, nodejs 都可以作为数据库的客户端
const url = 'mongodb://localhost:27017'  // 本地启动的 mongodb 服务
const dbName = 'comment1'  // 数据库(留言板项目的数据库)

MongoClient.connect(url, {
  useUnifiedTopology: true,
  useNewUrlParser: true
}, (err, client) => {
  if (err) {
    console.error('mongodb 连接出错', err)
    return
  }

  console.log('mongodb 连接成功')

  const db = client.db(dbName)  // 切换数据库 命令行:use comment1

  // 切换到指定的集合 collection
  const userCollection = db.collection('users')

  // 查询数据
  userCollection.find().toArray((err, result) => {
    if (err) {
      console.error('查询数据出错', err)
      return
    }
    console.log('查询结果', result)
  })

  // 关闭
//   client.close()
})

带条件查询:

userCollection.find({ city: 'beijing', username: 'zhangsan' }).toArray()

排序:

​ 1. userCollection.find().sort({ age: 1 }).toArray() // -1为倒序

2. 按插入顺序排序:`sort({ _id: 1 })`

新增数据:

userCollection.insertOne({
    username: 'liudehua',
    password: 'abc',
    age: 30,
    city: 'xianggang'
  }, (err, result) => {
    if (err) {
      console.error('查询数据出错', err)
      return
    }
    console.log('插入后的返回结果', result)
  })

修改数据:

userCollection.updateOne(
    { username: 'zhangsan' },   // 修改条件
    { $set: { age:22 , city: 'guangzhou'} },   // 修改内容
    (err, result) => {
      if (err) {
        console.error('修改数据出错', err)
        return
      }
      console.log('修改后的返回结果', result)
    }
  )

删除数据:

  userCollection.deleteOne({ username: 'wangwu' }, (err, result) => {
      if (err) {
        console.error('删除数据出错', err)
        return
      }
      console.log('删除成功')
    }
  )
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值