MongoDB Quick Notes

Mac

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$ brew update # 更新 brew
$ brew install mongodb # 安裝 MongoDB
$ brew upgrade mongodb # 更新 MongoDB
$ mongod # 啟動 MongoDB Server
$ mongo # 連線到 localhost:27017/test ,不需帳密。
* 27017 預設 port
* 28017 Web 界面 MongoDB Server 資訊類似 PHP Admin 。

<!--more-->

$ mkdir -p /data/db # 建立資料庫儲存的目錄。
$ chown `id -u` /data/db # 授權當前使用者目錄權限。
$ id -u # 列出當前使用者 uid
$ sudo plutil -p /var/db/dslocal/nodes/Default/users/[YourAccount].plist # OSX 底下的 /etc/shadow 。
$ mongod --dbpath /data/db # 設定資料庫資料目錄。

基本對照

SQL MongoDB
database database
table collection
row(record) documents
column field(key)
value value

Mongo shell

  • db 當前使用的資料庫。
  • show dbs 資料庫列表。
  • show collections 資料表清單。
  • use [dbname] 切換使用目標資料庫。
  • db.getSlibingDB('dbname') 取得資料庫參考物件。
  • db.dropDatabase() # 移除資料庫。
  • db.addUser( { user: "<user>", pwd: "<password>", roles: [<roles>] } ) # 加入使用者
  • db.auth('id', 'pwd') # 登入認證身份。
  • printjson(obj) 將物件以 JSON 格式輸出。
  • db.createCollection(name, {capped: <Boolean>, autoIndexId: <Boolean>, size: <number>, max <number>} ) # 建立集合,主要的功能是用來開固定式集合,固定式集合不能刪除 Row,但可以移除整個資料表,一旦 capped 設為 true 就要指定 size,但如果要限制則必須在指定 max 。一旦超出 max 舊的資料就會被覆寫。
  • db.collection.drop() # 移除資料表。
  • db.collection.ensureIndex({name: [1|-1]}) # 建立索引
  • db.collection.getIndexes() # 取得索引
  • db.collection.dropIndex({name: 1}) # 移除索引

其他資料
snapshot
Performance
Munin
Indexes
B+Tree
Distributed System
Aggregate
SQL 到 MongoDB 對應表
Basic toturial