初識 MongoDB — 簡介

Mindy Huang
4 min readJul 20, 2021

什麼是 MongoDB?

MongoDB 是一個文檔導向的資料庫管理系統,由 C++ 語言編寫。他是目前最流行的 NoSQL 資料庫之一,並且完全開源。

MongoDB 提出文檔(Document), 集合(Collection) 的概念。如果要用關聯式資料庫的觀念來理解的話:

MongoDB 的特色

  • 物件導向:使用 BSON 作為資料模型結構 (類似 JSON 格式)
  • 更靈活的資料儲存方式:沒有固定的 Schema,且能儲存多層級的資料。
  • 即時查詢能力:保留傳統的索引 (Index) 功能 (底層是 B-Tree)
  • 分散式儲存: 支援多個儲存引擎,能將資料分散其他伺服器,共同分擔。

Collection (集合)

Collection 是一個 MongoDB document 的群組。相當於關聯式資料庫的 Table。

可以不事先定義欄位 (Schema-Free)

一般的關連式資料庫,開 Table 必須定義欄位 (大小、型別、名稱等)。
但 Collection 可以不用事先定義,每筆document可以有不等數量的欄位,而存在同一個collection內。

Document (文檔)

  • 一個 Document 相當於資料表中的一筆紀錄
  • 他的基本結構就是 key-value pair

Document 範例

{
_id: ObjectId(7df78ad8902c)
title: 'MongoDB Overview',
description: 'MongoDB is no sql database',
by: 'tutorials point',
url: 'http://www.tutorialspoint.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100,
comments: [
{
user:'user1',
message: 'My first comment',
dateCreated: new Date(2011,1,20,2,15),
like: 0
},
{
user:'user2',
message: 'My second comments',
dateCreated: new Date(2011,1,25,7,45),
like: 5
}
]
}

_id

每一個 Doument 必定會有一個最基本的特殊欄位 “_id”

  • 在所屬的 Collection 底下,_id 為唯一值。
  • _id 長度為 12,由 16 進位數字組成
  • 其結構為 [timestamp][machine_id][process_id][increment]
  • timestamp: 當前時間 (4byte)
  • machine_id: 機器 id (3byte)
  • process_id: 伺服器的 process id (2 byte)
  • increment number: 簡單的遞增數字 (3byte)

參考資源:

https://kknews.cc/zh-tw/code/g954yvm.html
https://www.tutorialspoint.com/mongodb/index.htm
https://kknews.cc/code/lqneyng.html
https://dotblogs.com.tw/sungnoone/2012/01/11/65274

--

--