JohnsonMao
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    --- title: MongoDB tags: MongoDB date: 2021/9/6 --- ###### tags: `MongoDB` ###### *date: 2021/9/4* # MongoDB [TOC] ## 前言 在製作自己的專案時,想讓專案更加完整,於是就開始想,既然前端畫面邏輯都自己開發了,現在網路上資源又那麼豐富,未來也有可能朝全端發展,何不自己架設後端 API,給自己串接,還能了解整個網頁的運作邏輯,於是開始自學了後端框架 Express 和資料庫 MongoDB,這裡將會記錄學習 MongoDB 的學習筆記。 ## 介紹 ### 資料庫 - 關聯式資料庫(RDBMS) - 資料具有關聯性 - 表格化、標準化 - 如:MySQL - 非關聯式資料庫(Not only SQL) - 更加彈性化(不一定要使用 SQL) - 如:MongoDB - SQL 是什麼? - SQL 是**結構化查詢語言** - 所有的關聯式資料庫都是用 SQL - 會 SQL 就大致上能快速學會關聯式資料庫(每個資料庫還是有些微的不同) ### MongoDB - 是快速開發 Web 而設計的資料庫 - 極簡、靈活性高 - 存取的是各式各樣的 BSON。 - BSON 就是二進制的 JSON。 - MongodDB 可以有多個資料庫 - database 為資料庫,存放多個集合 - collection 集合,存放多個文件 - document 文件,我們操作的部分 ## MongoDB 安裝 與 啟動 ### 安裝 MongoDB 可以去官網依自己的作業系統下載。 建議安裝版本為偶數結尾(穩定版)。 [官網下載網站](https://docs.mongodb.com/manual/administration/install-community/) ==注意==:安裝建議用使用預設的比較不容易出錯,自訂的話,路徑不能有中文。 ### 設置環境變數 我這裡是安裝 Windows 的 MongoDB 5.0 版本 1. 找到安裝 MongoDB 的資料夾,直到找到裡面的 bin 資料夾 範例:`C:\Program Files\MongoDB\Server\5.0\bin` 2. 開啟電腦的環境變數,對使用者變數裡面的 PATH 編輯,並把剛剛 bin 的路徑新增到 PATH 內(需注意不要動到裡面其他的路徑) 以我 Windows 10 為例: 打開我的電腦 > 開啟設定 > 開啟進階系統設定 > 系統內容進階 tag 內點環境變數 > 對 PATH 進行編輯 3. 在 C:\ 根目錄新增 data 資料夾,裡面新增 db 資料夾。 4. 開啟 CMD 輸入 `Mongod` 啟動服務器後縮小 5. 再開啟另一個 CMD 輸入 `Mongo` 連接資料庫,連接成功 CMD 會出現 `>` ### 開機自動啟動服務器 1. 在 MongoDB 版本那個資料夾新增`mongod.cfg`檔案 如:`C:\Program Files\MongoDB\Server\5.0`新增`mongod.cfg` 2. 在`mongod.cfg`內輸入設定 ```cfg systemLog: destination: file path: c:\data\log\mongod.log # 這裡輸入 log 檔案 storage: dbPath: c:\data\db # 這裡輸入資料要存的位置 net: port: 27017 # 這裡輸入想要的 port 號 ``` 3. 開啟系統管理員身分的 CMD 在 **bin 資料夾** 輸入 `mongod.exe --config` 4. 在 **資料存取位置** 輸入 `god.cfg --install` 5. 接著輸入 `net start MongoDB` 啟動服務器 ### 圖形化工具安裝 除了使用 CMD 來操作 MongoDB 外,也有圖形化工具可以使用 [下載圖形化工具網站](https://www.mongodbmanager.com/download) ## 增刪改查資料庫 使用 `use <database>` 新增並進入資料庫 如:`use test` 當你新增資料時,`<collection>`為你的集合名。 如:`db.students.insert({ name: "毛毛", gender: "男"})` 這時資料庫就會自動新增 students 這個集合, 這個集合裡面有個`{ name: "毛毛", gender: "男"}`的資料, 輸入`show collection` 就可以看到 students 輸入`show dbs`就可以看到資料庫名稱 test 想刪除集合,只要輸入`db.students.drop()`就會刪除集合。 想刪除當前所在的資料庫,只要輸入`db.dropDatabase()` ### 新增資料 `db.<collection>.insert(資料)` 可以新增 JSON 資料,一個資料傳物件,多個資料傳陣列。 新增後如果沒有自訂`_id`值的話,MongoDB 會自動生成 `_id`,確保每個資料都是唯一性。 `db.<collection>.insertOne()` 只能傳一個物件。 `db.<collection>.insertMany()` 只能傳一個陣列。 ### 查詢資料 `db.<collection>.find({條件}, {顯示})` 第一個參數,可以傳物件,當作查詢集合的參考,返回陣列。 如:傳`{}`就會顯示所有資料 第二個參數則是將傳來的結果資料進行過濾顯示。 `db.<collection>.findOne()` 返回第一個查到的物件。 `db.<collection>.find().count()` 返回查詢的數量。(length()一樣) #### **如果想加入條件** 假設想查詢 price > 100 的資料,條件加上 `$gt` 範例:`db.<collection>.find({price: {$gt: 100} })` 假設想查詢 price >= 100 的資料,條件加上 `$gte` 範例:`db.<collection>.find({price: {$gte: 100} })` 假設想查詢 price < 100 的資料,條件加上 `$lt` 範例:`db.<collection>.find({price: {$lt: 100} })` 假設想查詢 90 < price < 100 的資料,條件之間加上`,` 範例:`db.<collection>.find({price: {$lt: 100, $gt: 90} })` 假設想查詢 price < 90 或 price > 100 的資料,條件變成要先設定`$or`,並使用陣列劃分條件 範例:`db.<collection>.find({$or: [{price: {$lt: 90} }, {price: {$gt: 100} }])` 假設想查詢前 10 筆資料,使用 `limit(數量)` 範例:`db.<collection>.find().limit(10)` 假設想查詢第 11 ~ 20 筆資料,使用 `limit(數量)`外,還要使用`skip(跳過幾筆)` 範例:`db.<collection>.find().skip(10).limit(10)` ### 更新資料 `db.<collection>.update(查詢條件, 更新資料)` 透過第一個參數查詢到第一筆資料,第二個參數默認情況下會直接取代原有資料。 #### 修改資料 `db.<collection>.update(查詢條件, { $set: {更新資料} })` 第二個參數增加 $set 修改操作符,就可以合併資料,而不是取代。 `db.<collection>.update(查詢條件, { $unset: {刪除資料} })` 第二個參數改成 $unset 修改操作符,就可以把資料指定屬性刪除。 #### 修改多筆資料 `db.<collection>.updateMany()` update 默認情況只會修改一個資料,可以使用 updateMany 同時修改多筆資料。 `db.<collection>.update(查詢條件, { $set: {更新資料} }, { multi: true })` 透過傳入第三個參數`{ multi: true }`,也可以同時修改多筆資料。 #### 修改的資料是多層陣列或多層物件 如果資料裡面是陣列或物件, 想修改裡面的屬性就要把操作符換成 $push 或 $addToSet 新增 或 $pop 移除, 查詢條件支持用`.`搜尋,但要用**引號**包起來。 $push 與 $addToSet 的差別在於 - $push 會直接添加。 - $addToSet 如果資料內有一樣的資料不會添加,沒有則會添加。 #### 想運算修改資料內的數字 如果資料內物品價格為 10 元 想漲價 10 元,使用`$inc` `db.<collection>.update({查詢物品}, {$inc: {price: 10} })` ### 刪除資料 `db.<collection>.remove(查詢條件)` `db.<collection>.deleteMany(查詢條件)` 刪除符合條件的多筆資料 `db.<collection>.remove(查詢條件, true)` `db.<collection>.deleteOne(查詢條件)` 刪除符合條件的第一筆資料 ### 排列資料庫 資料庫默認情況下是使用`_id`來進行排列,可以使用 `sort({})` 來指定排序,1 為升序, -1 為降序。 如果想讓 price 由小到大升序,請看以下範例: `db.<collection>.find(查詢條件).sort({price: 1})` 如果想讓 price 由大到小降序,請看以下範例: `db.<collection>.find(查詢條件).sort({price: -1})` ### 參考資料 - [Day17 - MongoDB 安裝設定](https://ithelp.ithome.com.tw/articles/10186324) - [MongoDB 入門教學影片](https://www.youtube.com/watch?v=Q9r8guQo58k&list=PLmOn9nNkQxJGX-finJqCSVVZx3gwn4Rga) - [MongoDB MANUAL](https://docs.mongodb.com/manual/)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully