MongoDB for VS Code

repository·main·Indexed 18 days ago

https://github.com/mongodb-js/vscode

An extension for VS Code that allows developers to connect to MongoDB and Atlas instances, navigate databases and collections, and inspect schemas. It features MongoDB Playgrounds for prototyping CRUD operations and aggregations, AI-powered assistance via the @MongoDB GitHub Copilot participant, and specialized editors for documents, aggregations, and indexes.

Tokens
6.7K
Snippets
18
Records
28
Agent score
63%

What's inside MongoDB for VS Code

  1. Use MongoDB Editors in VS Code

    main

    The MongoDB extension provides specialized editors for interacting with MongoDB entities directly within your workspace. These editors allow you to view and manipulate data without leaving VS Code. Supported editors include:

    • DocumentEditor: For viewing and editing individual documents.
    • AggregationEditor: For building and testing aggregation pipelines.
    • CollectionEditor: For managing and viewing collections.
    • IndexEditor: For managing database indexes.
    • CodeLenses: Interactive UI elements that appear above code or entities to provide quick actions.
  2. Understand the MongoDB for VS Code Tree View components

    main

    The MongoDB for VS Code extension uses a hierarchical tree view to allow you to navigate and manage your MongoDB data. The tree view is composed of several specialized items that represent different levels of your data infrastructure and connection state:

    • base tree view: The root container for the MongoDB explorer.
    • connection item: Represents an active connection to a MongoDB deployment.
    • deployment item: Represents a specific deployment (e.g., a cluster or standalone instance).
    • instance item: Represents a specific instance within a deployment.
    • database item: Represents a database within an instance.
    • collection item: Represents a collection within a database.
    • index item: Represents an index within a collection.
    • document item: Represents an individual document within a collection.
    • saved query item: Represents a query that has been saved for reuse.
  3. Locate VS Code settings files for MCP configuration

    main

    If you are configuring the MongoDB MCP server manually, you can apply settings to either your global User configuration or your specific Workspace configuration.

    User Configuration (Global)

    Applies to all workspaces. Use this for sensitive credentials like apiClientId.

    • Windows: %APPDATA%\Code\User\settings.json
    • macOS: ~/Library/Application Support/Code/User/settings.json
    • Linux: ~/.config/Code/User/settings.json

    Workspace Configuration (Project-specific)

    Applies only to the current project. Use this for project-specific permissions like readOnly: false.

    • Path: .vscode/settings.json (within your project root)

    Note: After making manual changes, reload the VS Code window or run the MongoDB: Start MCP Server command for changes to take effect.

  4. Debug the MongoDB Language Server

    main

    The MongoDB Language Server runs as a separate Node.js process from the VS Code client. To debug the different components, use the following methods:

    Debugging the Client

    Debugging the client is standard for VS Code extensions. Set a breakpoint in your client code and press F5 to debug the extension.

    Debugging the Server

    Because the server runs in a separate process started by the LanguageClient, you must attach a debugger to the running server.

    1. Switch to the Run view in VS Code.
    2. Select the launch configuration Extension + Server Inspector.
    3. Press F5.

    This configuration will launch both the extension and the Server Inspector simultaneously.

  5. Enable intelligent autocomplete in snippets and strings

    main

    By default, VS Code prevents code completion inside snippets and string literals. To enable intelligent autocomplete (like database name completions for use('dbName')) within the MongoDB extension, you must adjust your global editor settings.

    To enable autocomplete in strings: Set editor.quickSuggestions as follows:

    "editor.quickSuggestions": {
      "other": true,
      "comments": false,
      "strings": true
    }

    To enable autocomplete in snippets: Set editor.suggest.snippetsPreventQuickSuggestions to false. This allows snippet completions (e.g., $match, $addFields) and field completion based on the document schema during db.collection.aggregate() expressions.

    "editor.quickSuggestions": {
      "other": true,
      "comments": false,
      "strings": true
    }
  6. Use MongoDB Playgrounds to prototype queries

    main

    MongoDB Playgrounds allow you to prototype and execute CRUD operations, queries, and aggregations directly within VS Code. They provide syntax highlighting and intelligent autocomplete for the MongoDB Shell API, BSON types, MongoDB Query API, system variables, and database/collection/field names.

    To use a playground:

    1. Ensure you are connected to a MongoDB server or cluster (autocomplete and execution require an active connection).
    2. Write your MongoDB commands in the playground file.
    3. Click the play button in the tab bar to execute the commands and see the results instantly.
    4. You can edit documents returned by your playground directly.
    5. Save the playground file alongside your application code for documentation and easy testing.
    // Example playground content
    db.collection('users').find({ status: 'active' });
    
    db.collection('orders').aggregate([
      { $match: { amount: { $gt: 100 } } },
      { $group: { _id: '$customer_id', total: { $sum: '$amount' } } }
    ]);
  7. Configure MongoDB MCP Server credentials

    main

    To unlock Atlas-specific tools (like retrieving performance metrics or managing database users), you must provide Atlas Service Account credentials. The MCP server authenticates against the Atlas Admin API using a Client ID and Client Secret.

    How to obtain credentials

    1. Sign in to MongoDB Atlas and open your organization.
    2. Navigate to Access ManagerService AccountsCreate Service Account.
    3. Assign the minimum required roles (e.g., Organization Read Only).
    4. Copy the Client ID and generate a Client Secret (save it immediately as it is only shown once).
    5. Important: Add your IP address to the Service Account's API Access List to prevent authentication errors.

    Security Best Practice

    Never commit these values to version control. Store them in your User Settings rather than your workspace .vscode/settings.json to prevent accidental exposure.

    "mdb.mcp.apiClientId": "<your-client-id>",
    "mdb.mcp.apiClientSecret": "<your-client-secret>"
  8. Install MongoDB for VS Code from source

    main

    To build and install the extension locally, clone the repository and use pnpm.

    Standard installation:

    pnpm install
    pnpm run local-install

    Windows installation:

    pnpm install
    pnpm run .
    ode_modules\.bin\vsce.cmd package
    code --install-extension ./mongodb-vscode-*.vsix

    Note: If the code command is not found, use the VS Code Command Palette to select 'Install code command in $PATH'.

    pnpm install
    pnpm run local-install
  9. Use the MongoDB Copilot Participant in Chat

    main

    If you have the GitHub Copilot extension installed, you can use the MongoDB Participant to interact with your clusters using natural language via GitHub Copilot Chat.

    How to use it:

    1. In the chat input field, enter @MongoDB to start a conversation with the participant.
    2. Type / to see available commands:
      • /docs: Finds answers to coding-related questions in the official MongoDB documentation.
      • /query: Generates MongoDB queries or aggregations from natural language. It uses your schema to reduce hallucinations and provides actions to open the code in a playground or run it directly.
      • /schema: Analyzes and returns information about a collection's schema.

    Tip: You can enable mdb.useSampleDocsInCopilot in settings to send sample field values to the /query command for better accuracy.

    @MongoDB /query Find all users who signed up in the last 30 days
  10. Configure MongoDB for VS Code settings

    main

    You can customize the extension behavior via VS Code settings. Key configuration options include:

    SettingDescription
    mdb.shellThe MongoDB shell to use (mongosh or the legacy mongo). Default: mongosh
    mdb.defaultDocumentDisplayNameOrdered array of fields used for file names when displaying a document (e.g., ["name","title","_id"]).
    mdb.defaultLimitNumber of documents to fetch when viewing a collection. Default: 10
    mdb.documentViewAndEditFormatFormat for showing documents and playground results. Default: shell
    mdb.confirmRunAllWhether to show a confirmation before running playground commands. Default: true
    mdb.confirmDeleteDocumentWhether to show a confirmation before deleting a document in the tree view. Default: true
    mdb.sendTelemetryOpt-in/out of diagnostic and telemetry collection. Default: true
    mdb.useSampleDocsInCopilotEnable sending sample field values to the @MongoDB /query command. Default: false
  11. How MongoDB Playground evaluation works

    main

    To prevent one playground from blocking another, the extension follows these principles:

    1. Isolation: Every playground evaluation is assigned its own Node.js worker thread.
    2. Lifecycle: Each thread is responsible for exactly one evaluation and terminates once the result is returned or an error occurs.
    3. Concurrency: Multiple playgrounds can be run simultaneously because each runs in its own thread.
    4. Cancellation: If a user cancels a running operation, the extension terminates the specific worker thread associated with that playground to stop all JavaScript execution immediately.
    5. Connection Integrity: Using separate threads ensures that the NodeDriverServiceProvider connection remains up-to-date and that multiple runs do not interfere with each other's state.
  12. Control MCP server write permissions with mdb.mcp.readOnly

    main

    The mdb.mcp.readOnly setting determines whether the connected agent can perform write operations against your database.

    • true (Default): Only read and metadata operations are available. create, update, and delete operations are disabled. This is recommended for production environments.
    • false: Allows the agent to perform write operations.

    Recommendation: Use workspace-level settings (.vscode/settings.json) when you need to enable write access for a specific project, keeping your global user settings read-only.

    "mdb.mcp.readOnly": true