🚀 在 VS Code 中

使用 MongoDB

Visual Studio Code 對於使用 MongoDB 資料庫提供絕佳的支援,無論是您自己的執行個體或是在 Azure with MongoDB Atlas 中。透過 MongoDB for VS Code 擴充功能,您可以從 VS Code 內建立、管理和查詢 MongoDB 資料庫。

安裝擴充功能

VS Code 的 MongoDB 支援是由 MongoDB for VS Code 擴充功能所提供。若要安裝 MongoDB for VS Code 擴充功能,請按下 ⇧⌘X (Windows、Linux Ctrl+Shift+X) 開啟 [擴充功能] 檢視,並搜尋 'MongoDB' 以篩選結果。選取 MongoDB for VS Code 擴充功能。

Select MongoDB for VS Code

連線到 MongoDB

一旦您安裝 MongoDB for VS Code 擴充功能,您會注意到有一個新的 MongoDB 活動列檢視。選取 MongoDB 檢視,您會看到 MongoDB 瀏覽器。

MongoDB explorer

若要連線到 MongoDB 資料庫

  1. 在 MongoDB 檢視中選取 [新增連線]

  2. 接下來,選擇使用連線字串連線或使用進階連線選項

    • 選取 [使用連線字串連線],然後在連線字串快速選取中輸入連線字串。

      本機 MongoDB 的預設連線字串為 mongodb://127.0.0.1:27017

      Database Connection setup

    • 選取 [進階連線設定],輸入連線詳細資料,然後選取 [儲存並連線]。

      Database Connection setup

注意:如果您要連線到本機 MongoDB 伺服器,請確定您的 MongoDB 伺服器 (mongod.exe) 正在執行。

連線後,您可以使用 MongoDB 伺服器,管理 MongoDB 資料庫、集合和文件。

attached MongoDB database

您可以展開資料庫以檢視其集合及其結構描述和索引,並且您可以選取個別的 MongoDB 文件以檢視其 JSON。

open mongodb document

您也可以將 MongoDB Shell 附加到作用中的連線,只需在連線上按一下滑鼠右鍵即可。

MongoDB Connection

注意:請確定 MongoDB Shell (mongomongosh) 已安裝 且在您的路徑中。在擴充功能的設定中,您可以選擇您正在使用的 Shell。

MongoDB 命令

在 VS Code 命令面板 (⇧⌘P (Windows、Linux Ctrl+Shift+P)) 中以及透過 [瀏覽器] 內容功能表,都有可用的 MongoDB 特定命令。

mongodb commands

使用 Playground

VS Code MongoDB 整合最強大的功能之一是 Mongo Playground。Playground 可讓您從 VS Code 編輯器建立、執行和儲存 MongoDB 命令。使用 MongoDB: 建立 MongoDB Playground 命令建立新的 Playground。

new mongo Playground

在 Playground 中,您可以參考 MongoDB 實體和命令,並且在您輸入時獲得豐富的 IntelliSense。Playground 對於原型化資料庫作業和查詢非常有用。使用 MongoDB: 從 Playground 執行選取的行 命令執行 Playground 查詢中選取的行。

mongodb Playground

Run Playground queries

Azure 上的 MongoDB

您可以透過 MongoDB Atlas 在 Azure 上免費輕鬆建立 MongoDB 叢集。

從儀表板選擇 [建立新的叢集],然後選擇 [Azure] 作為雲端提供者。叢集建立完成後,使用 MongoDB Atlas 提供的連線字串連線。

Create Azure Cluster

後續步驟

  • Azure 擴充功能 - Visual Studio Marketplace 擁有數百個適用於 Azure 和雲端的 VS Code 擴充功能。
  • 部署到 Azure - 逐步了解如何將您的應用程式部署到 Azure。
  • 使用 Docker - 將您的應用程式放入 Docker 容器中,以便輕鬆重複使用和部署。