Like Share Discussion Bookmark Smile

J.J. Huang   2020-02-13   Node.js   瀏覽次數:次   DMCA.com Protection Status

Node.js | MongoDB 連接

環境準備

MongoDB的安裝可以參閱Docker - 第十一章 | 安裝MongoDB

  • 顯示目前的資料庫清單:
1
2
3
4
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB

安裝 MongoDB 驅動

要使用Node.js訪問MongoDB資料庫,你需要一個MongoDB驅動程序。

1
npm install mongodb --save

連接資料庫

要在MongoDB中建立一個資料庫,首先我們需要建立一個MongoClient對象,然後配置好指定的URL和端口號。

如果資料庫不存在,MongoDB將建立資料庫並建立連接。

1
2
3
4
5
6
7
8
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/jjtest";
 
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
  if (err) throw err;
  console.log("資料庫已建立!");
  db.close();
});

執行結果如下:

1
2
3
$ node test.js
(node:4753) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
資料庫已建立!

建立集合

使用createCollection()方法來建立集合:

1
2
3
4
5
6
7
8
9
10
11
12
13
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/jjtest";
 
MongoClient.connect(url, { useNewUrlParser: true }, function (err, db) {
    if (err) throw err;
    console.log('資料庫已建立');
    var dbase = db.db("jjtest");
    dbase.createCollection('site', function (err, res) {
        if (err) throw err;
        console.log("建立集合!");
        db.close();
    });
});

執行結果如下:

1
2
3
4
$ node test.js
(node:4861) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
資料庫已建立
建立集合!

資料庫操作 (CURD)

MySQL不同的是MongoDB會自動建立資料庫和集合,所以使用前我們不需要手動去建立。

插入資料

1
2
3
4
5
6
7
8
9
10
11
12
13
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/jjtest";
 
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
if (err) throw err;
var dbo = db.db("jjtest");
var myobj = { name: "J.J.'s blogs", url: "morosedog.gitlab.io" };
dbo.collection("site").insertOne(myobj, function(err, res) {
if (err) throw err;
console.log("資料插入成功");
db.close();
});
});

執行結果如下:

1
2
3
$ node test.js
(node:4872) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
資料插入成功

MongoDB客戶端:

1
2
3
4
5
6
7
8
9
10
11
12
> show dbs
admin 0.000GB
config 0.000GB
jjtest 0.000GB
local 0.000GB
> use jjtest
switched to db jjtest
> show tables
site
> db.site.find()
{ "_id" : ObjectId("5e44ef0cda14ed1308971ca7"), "name" : "J.J.'s blogs", "url" : "morosedog.gitlab.io" }
>

插入多筆資料

插入多條資料可以使用insertMany()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/jjtest";
 
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
if (err) throw err;
var dbo = db.db("jjtest");
var myobj = [
{ name: "J.J.'s blogs", url: "morosedog.gitlab.io" },
{ name: 'Google', url: 'https://www.google.com'},
{ name: 'Facebook', url: 'https://zh-tw.facebook.com'}
];
dbo.collection("site").insertMany(myobj, function(err, res) {
if (err) throw err;
console.log("插入的資料數量為: " + res.insertedCount);
db.close();
});
});

執行結果如下:

1
2
3
$ node test.js
(node:4977) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
插入的資料數量為: 3

MongoDB客戶端:

1
2
3
4
5
6
> use jjtest
switched to db jjtest
> db.site.find()
{ "_id" : ObjectId("5e44f141b5d2871371235873"), "name" : "J.J.'s blogs", "url" : "morosedog.gitlab.io" }
{ "_id" : ObjectId("5e44f141b5d2871371235874"), "name" : "Google", "url" : "https://www.google.com" }
{ "_id" : ObjectId("5e44f141b5d2871371235875"), "name" : "Facebook", "url" : "https://zh-tw.facebook.com" }

查詢資料

使用find()來查找資料,find()可以返回匹配條件的所有資料。

  • 如果未指定條件,find()返回集合中的所有資料。
1
2
3
4
5
6
7
8
9
10
11
12
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/jjtest";
 
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
    if (err) throw err;
    var dbo = db.db("jjtest");
    dbo.collection("site"). find({}).toArray(function(err, result) {
        if (err) throw err;
        console.log(result);
        db.close();
    });
});

執行結果如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$ node test.js
(node:4989) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
[
{
_id: 5e44f141b5d2871371235873,
name: "J.J.'s blogs",
url: 'morosedog.gitlab.io'
},
{
_id: 5e44f141b5d2871371235874,
name: 'Google',
url: 'https://www.google.com'
},
{
_id: 5e44f141b5d2871371235875,
name: 'Facebook',
url: 'https://zh-tw.facebook.com'
}
]

  • 查詢條件為”J.J.’s blogs”:
1
2
3
4
5
6
7
8
9
10
11
12
13
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/jjtest";
 
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
    if (err) throw err;
    var dbo = db.db("jjtest");
    var whereStr = {"name":'J.J.\'s blogs'};
    dbo.collection("site").find(whereStr).toArray(function(err, result) {
        if (err) throw err;
        console.log(result);
        db.close();
    });
});

執行結果如下:

1
2
3
4
5
6
7
8
9
$ node test.js
(node:5011) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
[
{
_id: 5e44f141b5d2871371235873,
name: "J.J.'s blogs",
url: 'morosedog.gitlab.io'
}
]

更新資料

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/jjtest";
 
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
    if (err) throw err;
    var dbo = db.db("jjtest");
    var whereStr = {"name":'J.J.\'s blogs'};
    var updateStr = {$set: { "url" : "https://morosedog.gitlab.io/" }};
    dbo.collection("site").updateOne(whereStr, updateStr, function(err, res) {
        if (err) throw err;
        console.log("資料更新成功");
        db.close();
    });
});

執行結果如下:

1
2
3
$ node test.js
(node:5028) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
資料更新成功

MongoDB客戶端:

1
2
3
4
5
> db.site.find()
{ "_id" : ObjectId("5e44f141b5d2871371235873"), "name" : "J.J.'s blogs", "url" : "https://morosedog.gitlab.io/" }
{ "_id" : ObjectId("5e44f141b5d2871371235874"), "name" : "Google", "url" : "https://www.google.com" }
{ "_id" : ObjectId("5e44f141b5d2871371235875"), "name" : "Facebook", "url" : "https://zh-tw.facebook.com" }
>

更新多筆資料

更新所有符合條件的資料資料可以使用updateMany()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/jjtest";
 
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
    if (err) throw err;
    var dbo = db.db("jjtest");
    var whereStr = {"name":'J.J.\'s blogs'};
    var updateStr = {$set: { "url" : "https://morosedog.gitlab.io/" }};
    dbo.collection("site").updateMany(whereStr, updateStr, function(err, res) {
        if (err) throw err;
         console.log(res.result.nModified + " 條資料被更新");
        db.close();
    });
});

註:更新多筆資料就不特別示範了。

刪除資料

1
2
3
4
5
6
7
8
9
10
11
12
13
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/jjtest";

MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
    if (err) throw err;
    var dbo = db.db("jjtest");
    var whereStr = {"name":'J.J.\'s blogs'};
    dbo.collection("site").deleteOne(whereStr, function(err, obj) {
        if (err) throw err;
        console.log("資料刪除成功");
        db.close();
    });
});

執行結果如下:

1
2
3
$ node test.js
(node:5074) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
資料刪除成功

MongoDB客戶端:

1
2
3
4
5
6
7
8
9
10
11
12
13
> use jjtest
switched to db jjtest
> db.site.find()
{ "_id" : ObjectId("5e44f141b5d2871371235873"), "name" : "J.J.'s blogs", "url" : "https://morosedog.gitlab.io/" }
{ "_id" : ObjectId("5e44f141b5d2871371235874"), "name" : "Google", "url" : "https://www.google.com" }
{ "_id" : ObjectId("5e44f141b5d2871371235875"), "name" : "Facebook", "url" : "https://zh-tw.facebook.com" }
>
>
>
> db.site.find()
{ "_id" : ObjectId("5e44f141b5d2871371235874"), "name" : "Google", "url" : "https://www.google.com" }
{ "_id" : ObjectId("5e44f141b5d2871371235875"), "name" : "Facebook", "url" : "https://zh-tw.facebook.com" }
>

刪除多筆資料

刪除所有符合條件的資料資料可以使用deleteMany()

1
2
3
4
5
6
7
8
9
10
11
12
13
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/jjtest";

MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
    if (err) throw err;
    var dbo = db.db("jjtest");
    var whereStr = {"name":'J.J.\'s blogs'};
    dbo.collection("site").deleteMany(whereStr, function(err, obj) {
        if (err) throw err;
        console.log(obj.result.n + " 條資料被刪除");
        db.close();
    });
});

註:刪除多筆資料就不特別示範了。

刪除集合

使用drop()方法來刪除集合。

1
2
3
4
5
6
7
8
9
10
11
12
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/jjtest";
 
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
    if (err) throw err;
    var dbo = db.db("jjtest");
    dbo.collection("site").drop(function(err, delOK) {
        if (err) throw err;
        if (delOK) console.log("集合已刪除");
        db.close();
    });
});

執行結果如下:

1
2
3
$ node test.js
(node:5086) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
集合已刪除

MongoDB客戶端:

1
2
3
4
5
6
7
8
> use jjtest
switched to db jjtest
> show tables
site
>
>
> show tables
>

排序

使用sort()方法,該方法接受一個參數,規定是升序(1)還是降序(-1)。

1
2
{ type: 1 } // 按 type 字段升序
{ type: -1 } // 按 type 字段降序
  • 在開始之前,請先準備資料,主要是多了type的資料。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/jjtest";
 
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
if (err) throw err;
var dbo = db.db("jjtest");
var myobj = [
{ name: "J.J.'s blogs", url: "morosedog.gitlab.io", type: 1 },
{ name: 'Google', url: 'https://www.google.com', type: 2},
{ name: 'Facebook', url: 'https://zh-tw.facebook.com', type: 3}
];
dbo.collection("site").insertMany(myobj, function(err, res) {
if (err) throw err;
console.log("插入的資料數量為: " + res.insertedCount);
db.close();
});
});

MongoDB客戶端:

1
2
3
4
5
6
7
> use jjtest
switched to db jjtest
> db.site.find()
{ "_id" : ObjectId("5e44f9b0e8a4cb13e7650b40"), "name" : "J.J.'s blogs", "url" : "morosedog.gitlab.io", "type" : 1 }
{ "_id" : ObjectId("5e44f9b0e8a4cb13e7650b41"), "name" : "Google", "url" : "https://www.google.com", "type" : 2 }
{ "_id" : ObjectId("5e44f9b0e8a4cb13e7650b42"), "name" : "Facebook", "url" : "https://zh-tw.facebook.com", "type" : 3 }
>
  • type升序排列。
1
2
3
4
5
6
7
8
9
10
11
12
13
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/jjtest";
 
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
if (err) throw err;
var dbo = db.db("jjtest");
var mysort = { type: 1 };
dbo.collection("site").find().sort(mysort).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});

執行結果如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
$ node test.js
(node:5121) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
[
{
_id: 5e44f9b0e8a4cb13e7650b40,
name: "J.J.'s blogs",
url: 'morosedog.gitlab.io',
type: 1
},
{
_id: 5e44f9b0e8a4cb13e7650b41,
name: 'Google',
url: 'https://www.google.com',
type: 2
},
{
_id: 5e44f9b0e8a4cb13e7650b42,
name: 'Facebook',
url: 'https://zh-tw.facebook.com',
type: 3
}
]
  • type降序排列。
1
2
3
4
5
6
7
8
9
10
11
12
13
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/jjtest";
 
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
if (err) throw err;
var dbo = db.db("jjtest");
var mysort = { type: -1 };
dbo.collection("site").find().sort(mysort).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});

執行結果如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
$ node test.js
(node:5126) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
[
{
_id: 5e44f9b0e8a4cb13e7650b42,
name: 'Facebook',
url: 'https://zh-tw.facebook.com',
type: 3
},
{
_id: 5e44f9b0e8a4cb13e7650b41,
name: 'Google',
url: 'https://www.google.com',
type: 2
},
{
_id: 5e44f9b0e8a4cb13e7650b40,
name: "J.J.'s blogs",
url: 'morosedog.gitlab.io',
type: 1
}
]

查詢分頁

  • 使用limit()方法,該方法只接受一個參數,指定了返回的條數。
1
2
3
4
5
6
7
8
9
10
11
12
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/jjtest";
 
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
    if (err) throw err;
    var dbo = db.db("jjtest");
    dbo.collection("site").find().limit(2).toArray(function(err, result) {
        if (err) throw err;
        console.log(result);
        db.close();
  });
});

執行結果如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$ node test.js
(node:5172) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
[
{
_id: 5e44f9b0e8a4cb13e7650b40,
name: "J.J.'s blogs",
url: 'morosedog.gitlab.io',
type: 1
},
{
_id: 5e44f9b0e8a4cb13e7650b41,
name: 'Google',
url: 'https://www.google.com',
type: 2
}
]
  • 指定跳過的條數,可以使用skip()方法。
1
2
3
4
5
6
7
8
9
10
11
12
13
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/jjtest";
 
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
    if (err) throw err;
    var dbo = db.db("jjtest");
// 跳過前面兩條資料,讀取兩條資料
    dbo.collection("site").find().skip(2).limit(2).toArray(function(err, result) {
        if (err) throw err;
        console.log(result);
        db.close();
  });
});

執行結果如下:

1
2
3
4
5
6
7
8
9
10
$ node test.js
(node:5177) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
[
{
_id: 5e44f9b0e8a4cb13e7650b42,
name: 'Facebook',
url: 'https://zh-tw.facebook.com',
type: 3
}
]

註:礙於太多GIF圖檔,會造成網頁讀取緩慢,所以這邊就不再顯示示範。

補充

  • 關於警告DeprecationWarning:不建議使用當前的URL字符串解析器,並將在以後的版本中將其刪除。
    要使用新的解析器,請將選項{ useNewUrlParser: true , useUnifiedTopology: true}傳遞給MongoClient.connect
1
2
3
4
5
6
7
8
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/jjtest";
 
MongoClient.connect(url, { useNewUrlParser: true , useUnifiedTopology: true}, function(err, db) {
  if (err) throw err;
  console.log("資料庫已建立!");
  db.close();
});

執行結果如下:

1
2
$ node test.js
資料庫已建立!

註:以上參考了
Node.js 连接 MongoDB
MongoDB 教程