# MongoDB 學習筆記 ###### tags: `SQL` `MongoDB` `學習紀錄` * [鐵人賽文章參考網址](https://ithelp.ithome.com.tw/users/20089358/ironman/1064) * [尚硅谷參考影片](https://www.youtube.com/watch?v=Q9r8guQo58k&list=PLmOn9nNkQxJGX-finJqCSVVZx3gwn4Rga) * [用 Docker 玩轉 MongoDB](https://ithelp.ithome.com.tw/articles/10201657) * [在 Laravel 中使用 MongoDB](https://learnku.com/articles/2560/using-mongodb-in-laravel) * 非關係型資料庫(NoSQL) * ex : MongoDB、Redis... * 文檔型資料庫 * 類似JSON結構 * BSON : 二進制JSON * BSON(中文發音:逼森)是Binary JSON的簡稱,是MongoDB用來儲存文件(document)資料及遠端程序呼叫(remote procedure calls)的資料格式。 * BSON是二進位編碼(binary encoded)的序列化(serialization)JSON資料格式。BSON其特性與JSON相同,並進一步擴展了JSON原本不支援的資料型態(data type),例如BSON支援date,binData,long等型態。 * MongoDB的BSON支援的資料型態請參考BSON Types。 * BSON除了支援比JSON更多的資料型態外,MongoDB也利用BSON二進制的特性來達到更好的查詢,轉譯及傳輸效率,也就是效能比較好。 * 簡單說BSON就是比較威的JSON。 * [參考網址](https://matthung0807.blogspot.com/2019/08/mongodb-bson.html) ## 結構 * ![](https://i.imgur.com/N0gngZa.png) * database * 可存放collection * collection * 類似array * 可存放document * document * 存儲和操作的內容都是document * 在MongoDB中,databese & collection都不需要手動創建 * 當我們創建document時,如果document所在的database & collection不存在的話會自動創建database & collection ## 基本指令 * show dbs * show databases * 顯示當前的所有databases * use databaseName * 進入到指定的database * db * 顯示當前所在的database * show collections * 顯示當前的所有collections ## CRUD操作 * [docs](https://docs.mongodb.com/manual/crud/) * [線上MongoDB練習用Shell](https://docs.mongodb.com/manual/tutorial/insert-documents/) * ![](https://i.imgur.com/8rAaGoa.png) * db.<collectionName\>.insert(bsonData) * 向collectionName插入一個document * 向collectionName插入多個document,要用array[bsonData,bsonData...]的類型 * 插入時沒指定_id的話MongoDB會自動增加 * 有指定_id的話就不會自動增加了,但需確保唯一性 * db.<collectionName\>.find() * 查詢當前collectionName中的所有document * ![](https://i.imgur.com/gDbdKmx.png) * [新手村CRUD---搜尋之find與搜尋操作符號](https://ithelp.ithome.com.tw/articles/10185439) * [find與搜尋操作符號-黑色好看版](https://mark-lin.com/posts/20160908/) * ## document的關係 * 一對一(one to one) * 一對多(one to many) * 多對多(many to many) ## 正規化的疑問 * [MongoDB的設計---正規與反正規化的戰爭](https://ithelp.ithome.com.tw/articles/10186327)