MongoDB快速上手

前面我们介绍了 NeDB 数据库,它是一个 NoSQL 的嵌入式数据库。今天我们再来介绍一款 NoSQL 的数据库 MongoDB

在开始学习前,需要准备 MongoDB 的环境。如果还没有 MongoDB 环境,请先阅读 MongoDB环境准备 一节。

安装mongodb

npm 库提供了 mongodb模块 。执行如下命令,安装该模块:

$ npm install mongodb --save

引入依赖

使用 require 引入 mongodb 模块,并获取 MongoClient 对象。

1
const MongoClient = require('mongodb').MongoClient

连接数据库服务器

NeDB 不同的是,我们在操作 MongoDB 数据库前,需要先连接数据库。

1
2
3
4
5
6
7
8
const url = 'mongodb://root:to0r@localhost:27017'
MongoClient.connect(
    url,
    function(err, client) {
        // 其他数据操作
        ...
    }
)

使用 connect 方法建立连接,connect 方法接收两个参数: urlcallback。 其中,url 表示数据库服务器的地址,格式为:

mongodb://{username}:{password}@{host}:{port}

回到本文中具体的例子,即:

const url = 'mongodb://root:to0r@localhost:27017'

callback 接收两个参数,errclientclient 表示已连接的 MongoClient 对象实例。

新建数据库

连上了数据库服务器,我们现在还没有任何数据库,因此需要先新建一个:

1
2
3
  // create database
  const dbName = 'user'
  const db = client.db(dbName)

定义数据库名为 user,使用 db 方法建立数据库。

建表

MongoDB 中,表被称为 collection。建表,也即是建立 collection

1
2
3
  // create collection named user
  const collectionName = 'user'
  const user = await Promise.resolve(db.createCollection(collectionName))

定义表名为 user,使用 createCollection 方法建表。

数据操作

插入

建表后,我们往 user 表中插入一条数据:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
  // insert data
  user.insertOne({
    name: 'Alice',
    age: 19
  }, function(err, res) {
    if (err) {
      return console.log('insert fail', err)
    }
    console.log('insert data: ', res.result)
  })

学过 NeDB 的同学就会发现,这样的数据操作跟 NeDB 的写法如出一辙。 实际上,NeDBMongoDB 的简化版,因此在写法上延续了 MongoDB 的风格。

查询

查询 Alice 的数据:

1
2
3
4
5
6
  // find
  user.find({
    name: 'Alice'
  }).toArray(function(err, result) {
    console.log('find Alice: ', result)
  })

find 方法并不会返回最终结果集,而是返回一个游标 Cursor。 要想获取全部结果,需要操作游标一个个寻找数据。 第4行,toArray 方法封装了这样的操作,并将数据组织成数组返回。

更新

Alice 的年龄更改为 20

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
  // update
  user.updateOne({
    name: 'Alice'
  }, {
    $set: {
      age: 20
    }
  }, function(err, res) {
    if (err) {
      return console.log(err)
    }
    console.log('update Alice data')
  })

updateOne 对应的,有 updateMany 方法,用于更新多条数据。

验证下是否更改了 Alice 的数据:

1
2
3
4
5
6
  // find update
  user.find({
    name: 'Alice'
  }).toArray(function(err, result) {
    console.log('find Alice new data: ', result)
  })

删除

删除 Alice 的数据:

1
2
3
4
5
6
7
8
9
  // delete
  user.deleteOne({
    name: 'Alice'
  }, function(err, obj) {
    if (err) {
      return console.log(err)
    }
    console.log('remove data')
  })

deleteOne 用于删除一条数据。如要删除多条数据,可以使用 deleteMany 方法。

关闭数据库

最后,使用 close 方法关闭数据库:

1
2
3
4
5
6
7
  // close database
  client.close(function(err) {
    if (err) {
      return console.log(err)
    }
    console.log('close database')
  })

运行demo

执行命令:

$ node demo.js

终端输出如下结果:

insert data:  { n: 1, ok: 1 }
update Alice data
find Alice:  [ { _id: 5dcd1195c792ec2f720e8dc7, name: 'Alice', age: 19 } ]
find Alice new data:  [ { _id: 5dcd1195c792ec2f720e8dc7, name: 'Alice', age: 20 } ]
remove data
close database

下一步

订阅更新,获取更多学习资料,请关注我们的 微信公众号

../../_images/wechat-mp-qrcode.png

小菜学编程