使用 MongoDB
Visual Studio Code 非常適合用於處理 MongoDB 資料庫,無論是您自己的執行個體,還是 Azure 上搭配 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] 擴充功能。
連接到 MongoDB
安裝 MongoDB for VS Code 擴充功能後,您會注意到新的 [MongoDB] 活動列檢視。選取 [MongoDB] 檢視,您就會看到 MongoDB 瀏覽器。
若要連接到 MongoDB 資料庫
-
在 [MongoDB] 檢視中選取 [新增連線]
-
接下來,選擇使用連線字串連線,或使用進階連線選項
-
選取 [使用連線字串連線],然後在連線字串快速選取中輸入連線字串。
本機 MongoDB 的預設連線字串為
mongodb://127.0.0.1:27017
。 -
選取 [進階連線設定],輸入連線詳細資料,然後選取 [儲存並連線]。
-
注意:如果您要連線到本機 MongoDB 伺服器,請確定您的 MongoDB 伺服器 (mongod.exe) 正在執行。
連接後,您就可以使用 MongoDB 伺服器,管理 MongoDB 資料庫、集合和文件。
您可以展開資料庫以檢視其集合及其結構描述和索引,而且您可以選取個別的 MongoDB 文件以檢視其 JSON。
您也可以將 MongoDB Shell 連接到作用中的連線,只需在連線上按一下滑鼠右鍵即可。
注意:請確定 MongoDB Shell (
mongo
或mongosh
) 已安裝且位於您的路徑中。在擴充功能的設定中,您可以選擇要使用的 Shell。
MongoDB 命令
VS Code [命令選擇區] (⇧⌘P (Windows、Linux Ctrl+Shift+P)) 以及透過 [檔案總管] 內容功能表提供特定的 MongoDB 命令。
使用 Playground
VS Code MongoDB 整合最強大的功能之一是 Mongo Playground。[Playground] 可讓您從 VS Code 編輯器建立、執行和儲存 MongoDB 命令。使用 [MongoDB: 建立 MongoDB Playground] 命令建立新的 Playground。
在 Playground 中,您可以參考 MongoDB 實體和命令,並在輸入時取得豐富的 IntelliSense。[Playground] 適用於原型化資料庫作業和查詢。使用 [MongoDB: 從 Playground 執行選取的行] 命令,執行 Playground 查詢中選取的行。
Azure 上的 MongoDB
您可以使用 MongoDB Atlas 在 Azure 上輕鬆免費建立 MongoDB 叢集。
從儀表板選擇 [建立新的叢集],然後選擇 [Azure] 作為雲端提供者。叢集建立完成後,使用 MongoDB Atlas 提供的連線字串進行連線。
後續步驟
- Azure 擴充功能 - Visual Studio Marketplace 提供數百種適用於 Azure 和雲端的 VS Code 擴充功能。
- 部署至 Azure - 逐步了解如何將應用程式部署至 Azure。
- 使用 Docker - 將您的應用程式放入 Docker 容器中,以便輕鬆重複使用和部署。