MongoDB 入門

Python 中的 MongoDB 入門

Filip Schouwenaars

Machine Learning Researcher

資料無所不在!

到處都是資料

Python 中的 MongoDB 入門

範例:學生選課資料

student_id name course_code title
1 Amina CS101 Intro to Coding
1 Amina MATH201 Algebra Basics
2 Luca CS101 Intro to Coding
Python 中的 MongoDB 入門

如何儲存資料

Students

student_id name
1 Amina
2 Luca
Python 中的 MongoDB 入門

如何儲存資料

Students

student_id name
1 Amina
2 Luca

Courses

course_code title
CS101 Intro to Coding
MATH201 Algebra Basics
Python 中的 MongoDB 入門

如何儲存資料

Students

student_id name
1 Amina
2 Luca

Enrollments

student_id course_code
1 CS101
1 MATH201
2 CS101

Courses

course_code title
CS101 Intro to Coding
MATH201 Algebra Basics

關聯式模型

  • 由關聯式資料庫採用
  • 例:MySQL、PostgreSQL
Python 中的 MongoDB 入門

當關聯式資料庫力有未逮時

 

  • 很適合結構化且一致的資料
  • 那複雜、多變的資料呢?
  • 需要更多資料表來放額外細節
  • 規模變大就更難管理

示意圖

Python 中的 MongoDB 入門

走進 MongoDB

 

  • 以文件為主,而非資料表
  • 彈性高:每筆紀錄可不同
  • 不需嚴格綱要(schema)
  • 輕鬆儲存巢狀結構資料

Python 中的 MongoDB 入門

BSON:特別的 JSON 變體

 

  • BSON = Binary JSON
  • 類似但更快、更有效率
  • 具備額外型別,如 Date、Binary
  • MongoDB 在底層使用 BSON

Python 中的 MongoDB 入門

連線到 MongoDB

from pymongo import MongoClient

# 建立用戶端(localhost) client = MongoClient()
# 建立用戶端(遠端伺服器) client2 = MongoClient("mongodb+srv://usr:[email protected]")
Python 中的 MongoDB 入門

一起來練習吧!

Python 中的 MongoDB 入門

Preparing Video For Download...