Alex Liang

MongoDB初探及CRUD筆記

由於工作的關係開始使用MongoDB,我註冊官方的MongoDB for Node.js DeveloperMongoDB for DBAS。這一系列文章為上課筆記和心得。

MongoDB是NoSQL的其中一種類別,它是document-base,適合存放文檔類型的database。
而NoSQL主要改善傳統SQL database在join table的操作,在系統scale-out時能降低複雜度及改善效能。

一般來說,NoSQL不需要shema(專案需要加上schema的規則也是可以)採用key-value的存取方式,其格式類似json,以下介紹MongoDB CRUD的操作。

Read

假設本地端己建立一個collection名為movieDetails。其內容格式如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
{
"_id" : ObjectId("569190ca24de1e0ce2dfcd4f"),
"title" : "Once Upon a Time in the West",
"year" : 1968,
"rated" : "PG-13",
"released" : ISODate("1968-12-21T05:00:00Z"),
"runtime" : 175,
"countries" : [
"Italy",
"USA",
"Spain"
],
"genres" : [
"Western"
],
"director" : "Sergio Leone",
"writers" : [
"Sergio Donati",
"Sergio Leone",
"Dario Argento",
"Bernardo Bertolucci",
"Sergio Leone"
],
"actors" : [
"Claudia Cardinale",
"Henry Fonda",
"Jason Robards",
"Charles Bronson"
],
"imdb" : {
"id" : "tt0064116",
"rating" : 8.6,
"votes" : 201283
},
"metacritic" : 80,
"awards" : {
"wins" : 4,
"nominations" : 5,
"text" : "4 wins & 5 nominations."
},
"type" : "movie"
}

如果我要找出上映年份為2000年的電影,那該如何下指令呢?

1
> db.movieDetails.find({year: 2000}).pretty()

find為基本的query指令,{}裡是query條件,而pretty能讓輸出結果像上面那樣編排整齊。
如果query條件不只一個,則使用,分開。要注意的是欄位的型別,例如查詢string型別(例如
title)必需使用單引號包起來

1
> db.movieDetails.find({title: 'Once Upon a Time in the West'}).pretty()

如果要限制query結果的數量可用limit;想依特定欄位排序則使用sort,skip可略過指定的數量的結果,例如

1
> db.movieDetails.find({ year: 1968 }).sort({ runtime: -1 }).skip(10).limit(5)

sort({ runtime: -1 })表示query結果依runtime的值做遞減排序;反之為1
skip(10)是省略前10筆結果;limit(5)表示只顯示5筆結果
要注意的是skip, sort和limit在實際運作時有預設的順序。分別為sort,skip最後才是limit

更多query方式請參考官方文件

Create

建立資料則是使用insertOne或insertMany。

1
> db.movieDetails.insertOne({ title: 'Batman', year: 2008, runtime: 150 })

上例是insertOne簡易的用法。{}裡的語法和find類似,我們可以建立指定的資料。
而insertMany則需要將多筆資料放在array裡:

1
2
3
4
5
> db.movieDetail.insertMany( [
> { title: 'Batman', year: 2008, runtime: 150 },
> { title: 'Taken', year: 2007, runtime: 124 },
> { title: 'Iron Man', year: 2008, runtime: 130 }
> ])

Delete

刪除資料可使用deleteOne, deleteMany和remove。
deleteOne及deleteMany和find一樣,必須給予query條件

1
> db.movieDetails.insertOne({ title: 'Batman' })

假如要刪除collection所有資料,則使用remove

1
> db.movieDetails.remove()

remove也可以只刪除一筆資料,例如

1
> db.movieDetails.remove({ title: 'Batman' }, 1)

只要給予justOne參數為1即可

Update

更新資料可使用updateOne和updateMany。假如加上upsert: true,如果沒找到資料會新增一筆進DB

1
2
3
4
5
6
7
> db.movieDetails.updateOne(
{ title: 'Batman' },
{ title: 'Batman 2' },
{
upsert: true
}
)

上例中,我們將”Batman”資料的title更新為”Batman 2”,假如沒找到Batman這筆資料則新增一筆Batman 2

參考來源:
官方文件