---
tags: Node.js 直播班 - 2022 春季班
---
# 🏅 Day 4
## MongoDB 基本操作: 修改、刪除
### 修改
#### 修改單筆資料
`updateOne()` 第一個參數透過設定符合的屬性找出要修改的資料,若第一個參數帶入空物件 `{}`,則會選取全部資料的第一筆資料,第二個參數放入要修改的屬性,需先加上 `$set` 物件,並在此物件中帶入要修改的物件屬性
第二個參數可選擇帶入 `$currentDate` 屬性,會再修改資料成功後顯示出最新修改的時間
```javascript=
db.collection.updateOne(
{
example: "text"
},
{
$set: {
example: "texttext"
},
$currentDate: {
lastModified: true
}
}
)
```
#### 修改多筆資料
```javascript=
db.collection.updateMany(
{
example: /text/
},
{
$set: {
example: "texttext"
},
$currentDate: {
lastModified: true
}
}
)
```
### 刪除
#### 刪除一筆資料
只刪除一筆符合條件的資料
```javascript=
db.collection.deleteOne(
{
example: /text/
}
)
```
#### 刪除多筆資料
```javascript=
db.collection.deleteMany(
{
example: /text/
}
)
```
#### 刪除全部資料
```javascript=
db.collection.deleteMany({})
```
### 參考資源
[db.collection.updateOne() — MongoDB Manual](https://www.mongodb.com/docs/v4.4/reference/method/db.collection.updateOne/#mongodb-method-db.collection.updateOne)
[db.collection.updateMany() — MongoDB Manual](https://www.mongodb.com/docs/v4.4/reference/method/db.collection.updateMany/#mongodb-method-db.collection.updateMany)
[db.collection.deleteOne() — MongoDB Manual](https://www.mongodb.com/docs/v4.4/reference/method/db.collection.deleteOne/#mongodb-method-db.collection.deleteOne)
[db.collection.deleteMany() — MongoDB Manual](https://www.mongodb.com/docs/v4.4/reference/method/db.collection.deleteMany/#mongodb-method-db.collection.deleteMany)
[更新資料 \- updateOne、updateMany](https://courses.hexschool.com/courses/1670869/lectures/38579075)(章節影片)
[刪除資料 \- deleteOne、deleteMany](https://courses.hexschool.com/courses/1670869/lectures/38579077)(章節影片)
[尋找資料 \- find 關鍵字搜尋](https://courses.hexschool.com/courses/1670869/lectures/38579080)(章節影片)
### 題目(將答案寫在 HackMD 並提交至回報區)
若尚未做前一天的每日任務,需先建立一個 database(名稱可自定義),並建立一個 `students` collection
將以下資料新增至 `students` collection(若已做完前一天的每日任務,可繼續沿用已建立的 `students` collection)
```json
{
"studentName": "Riley Parker",
"group": "A",
"score": 83,
"isPaid": false
},
{
"studentName": "Brennan Miles",
"group": "C",
"score": 72,
"isPaid": false
},
{
"studentName": "Mia Diaz",
"group": "B",
"score": 98,
"isPaid": true
},
{
"studentName": "Caroline morris",
"group": "B",
"score": 55,
"isPaid": false
},
{
"studentName": "Beverly Stewart",
"group": "B",
"score": 60,
"isPaid": false
}
```
將答案依序列在自己的 HackMD 並將連結貼至回報區
```
範例:
1. ...
2. ...
3. ...
4. ...
```
1. 指定其中一個 `_id` ,並將該筆 document 的 `group` 改為 `D`
```
db.students.updateOne({id:'625e326f63341de57ecc22d8'},{$set:{'group':'D'}})
```
2. 將 `group` 為 `B` 的多筆 document 的 `isPaid` 改為 `true`
```
db.students.updateMany({'group':'B'},{$set:{'isPaid':true}})
```
3. 將 `studentName` 包含關鍵字 `Brennan` 的 document 刪除
```
db.students.deleteMany({'studentName':/Brennan/})
```
4. 將 `isPaid` 為 `true` 的多筆 document 刪除
```
db.students.deleteMany({'isPaid':true})
```