MongoDB 是一個 NoSQL 資料庫(Not only SQL,針對不同於傳統的關聯式資料庫的資料庫管理系統的統稱),一套以文件 (document
) 導向的資料庫管理系統,相較於傳統的關聯式資料庫,非關聯式資料庫的特性讓 MongoDB 在處理巨量資料有更大的支援
MongoDB 會以 BSON 的形式儲存資料(Binary JSON),相較於 JSON 可以儲存的資料類型更多
MongoDB 整體資料結構為:db
-> collection
-> document
我們可以透過指令(The mongo
Shell)的方式用終端機來操作資料庫
collection
需替換為資料庫中 collection 的名稱,例如:db.users.insertOne()
執行新增成功後會為每一筆 document 都新增不同的 _id
例如執行新增多筆資料後會出現
直接執行此指令會將此 collection 中的資料全部列出
若是要查詢特定資料可以在 find()
帶入{ 屬性: 值 }
尋找符合條件的資料
例如:
屬性值可以搭配運算子設定條件:
使用比較運算子設定篩選條件
$eq | 等於 |
---|---|
$ne | 不等於 |
$gt | 大於 |
$lt | 小於 |
$gte | 大於等於 |
$lte | 小於等於 |
$in | 存在某個值 |
$nin | 不存在某個值 |
例:找出此 colletion 中符合 example 屬性值等於 "text"
的資料
使用以下邏輯運算子
$and | 全部條件皆符合 |
---|---|
$or | 符合其中一項條件 |
$nor | 全部條件皆不符合 |
$not | 與條件相反 |
例:找出此 colletion 中符合以下條件之一的資料: status 屬性為 A
,或 qty 值小於 30
也可以帶入正規表達式篩選有符合的文字
例:查詢 example 有包含 text
的資料
insertOne()
insertMany()
新增資料:insertOne、insertMany(章節影片)
db.collection.find()
Query and Projection Operators — MongoDB Manual
MongoDB 簡介(章節影片)
請建立一個 database(名稱可自定義),並建立一個 students
collection
將答案依序列在 HackMD 並將連結貼至回報區
students
collection範例:
students
collection查詢 students
collection 中的所有資料
查詢 students
collection 中符合 group 屬性為 B 的資料 使用 { <field>: <value> } 設定符合的項目
查詢 students
collection 中符合分數在 60 分以上的的資料
查詢 students
collection 中符合分數在 60 分以下或是 group 為 B 的資料
students
collection範例:
students
collection答案:
students
collection 中的所有資料students
collection 中符合 group 屬性為 B 的資料 使用 { <field>: <value> } 設定符合的項目
students
collection 中符合分數在 60 分以上的資料students
collection 中符合分數在 60 分以下或是 group 為 B 的資料Node.js 直播班 - 2022 春季班