The sample code is a JavaScript server written with Express.js and the native MongoDB API. The user adds data ( 2 text fields), can view data, and delete a single row or all rows. The programming work is done for you, this tutorial focuses on using the local and remote Azure environments successfully from inside Visual Studio Code with Azure. MongoDB provides an extension for Microsoft Visual Studio Code which lets you work with MongoDB and your data directly within your coding environment.
To make developers more productive when working with MongoDB, we built MongoDB for Visual Studio Code, an extension that allows you to quickly connect to MongoDB and MongoDB Atlas and work with your data to build applications right inside your code editor. With the MongoDB Visual Studio Code Plugin you can:
- Connect to a MongoDB or MongoDB Atlas cluster, navigate through your databases and collections, get a quick overview of your schema, and see the documents in your collections;
- Create MongoDB Playgrounds, the fastest way to prototype CRUD operations and MongoDB commands;
- Quickly access the MongoDB Shell, to launch the MongoDB Shell from the command palette and quickly connect to the active cluster.
Getting Started with MongoDB Atlas
Create an Atlas Account
First things first, we will need to set up a MongoDB Atlas account. And don’t worry, you can create an M0 MongoDB Atlas cluster for free. No credit card is required to get started! To get up and running with a free M0 cluster, follow the MongoDB Atlas Getting Started guide, or follow the steps below. First you will need to start at the MongoDB Atlas registration page, and fill in your account information. You can find more information about how to create a MongoDB Atlas account in our documentation
Deploy a Free Tier Cluster
Once you log in, Atlas prompts you to build your first cluster. You need to click “Build a Cluster.” You will then select the Starter Cluster. Starter clusters include the M0, M2, and M5 cluster tiers. These low-cost clusters are suitable for users who are learning MongoDB or developing small proof-of-concept applications.
Atlas supports M0 Free Tier clusters on Amazon Web Services (AWS), Google Cloud Platform (GCP), and Microsoft Azure. Atlas displays only the regions that support M0 Free Tier and M2/M5 Shared tier clusters.
Once you deploy your cluster, it can take up to 10 minutes for your cluster to provision and become ready to use.
Add Your Connection IP Address to Your IP Access List
You must add your IP address to the IP access list before you can connect to your cluster. To add your IP address to the IP access list. This is important, as it ensures that only you can access the cluster in the cloud from your IP address. You also have the option of allowing access from anywhere, though this means that anyone can have network access to your cluster. This is a potential security risk if your password and other credentials leak. From your Clusters view, click the Connect button for your cluster.
Configure your IP access list entry
Click Add Your Current IP Address.
Create a Database User for Your Cluster
For security purposes, you must create a database user to access your cluster. Enter the new username and password. You’ll then have the option of selecting user privileges, including admin, read/write access, or read-only access. From your Clusters view, click the Connect button for your cluster.
In the Create a MongoDB User step of the dialog, enter a Username and a Password for your database user. You’ll use this username and password combination to access data on your cluster.
For information on configuring additional database users on your cluster, see Configure Database Users.
Install MongoDB for Visual Studio Code
Next, we are going to connect to our new MongoDB Atlas database cluster using the Visual Studio Code MongoDB Plugin. To install MongoDB for Visual Studio Code, simply search for it in the Extensions list directly inside Visual Studio Code or head to the “MongoDB for Visual Studio Code” homepage in the Visual Studio Code Marketplace.
Connect Your MongoDB Data
MongoDB for Visual Studio Code can connect to MongoDB standalone instances or clusters on MongoDB Atlas or self-hosted. Once connected, you can browse databases, collections, and read-only views directly from the tree view.
For each collection, you will see a list of sample documents and a quick overview of the schema. This is very useful as a reference while writing queries and aggregations.
Once installed there will be a new MongoDB tab that we can use to add our connections by clicking “Add Connection”. If you’ve used MongoDB Compass before, then the form should be familiar. You can enter your connection details in the form, or use a connection string. I went with the latter as my database is hosted on MongoDB Atlas.
To obtain your connection string, navigate to your “Clusters” page and select “Connect”.
Choose the “Connect using MongoDB Compass” option and copy the connection string. Make sure to add your username and password in their respective places before entering the string in Visual Studio Code.
Then paste this string into Visual Studio Code.
Once you’ve connected successfully, you should see an alert. At this point, you can explore the data in your cluster, as well as your schemas.
Navigate Your Data
Once you connect to your deployment using MongoDB for Visual Studio Code, use the left navigation to:
- Explore your databases, collections, read-only views, and documents.
- Create new databases and collections.
- Drop databases and collections.
Databases and Collections
When you expand an active connection, MongoDB for Visual Studio Code shows the databases in that deployment. Click a database to view the collections it contains.
View Collection Documents and Schema
When you expand a collection, MongoDB for Visual Studio Code displays that collection’s document count next to the Documents label in the navigation panel.
Mongodb With Visual Studio Code
When you expand a collection’s documents, MongoDB for Visual Studio Code lists the _id
of each document in the collection. Click an _id
value to open that document in Visual Studio Code and view its contents.
Alternatively, right-click a collection and click View Documents to view all the collection’s documents in an array.
Opening collection documents provides a read-only view of your data. To modify your data using MongoDB for Visual Studio Code, use a JavaScript Playground or launch a shell by right-clicking your active deployment in the MongoDB view in the Activity Bar.
Schema
Your collection’s schema defines the fields and data types within the collection. Due to MongoDB’s flexible schema model, different documents in a collection may contain different fields, and data types may vary within a field. MongoDB can enforce schema validation to ensure your collection documents have the same shape.
When you expand a collection’s schema, MongoDB for Visual Studio Code lists the fields which appear in that collection’s documents. If a field exists in all documents and its type is consistent throughout the collection, MongoDB for Visual Studio Code displays an icon indicating that field’s data type.
Create a New Database
When you create a new database, then you must populate it with an initial collection. To create a new database:
- Hover over the connection for the deployment where you want your database to exist.
- Click the Plus icon that appears.
- In the prompt, enter a name for your new database.
- Press the enter key.
- Enter a name for the first collection in your new database.
- Press the enter key.
Create a New Collection
To create a new collection:
- Hover over the database where you want your collection to exist.
- Click the Plus icon that appears.
- In the prompt, enter a name for your new collection.
- Press the enter key to confirm your new collection.
Explore Your Data with Playgrounds
MongoDB Playgrounds are the most convenient way to prototype and execute CRUD operations and other MongoDB commands directly inside Visual Studio Code. Use JavaScript environments to interact your data. Prototype queries, run aggregations, and more.
- Prototype your queries, aggregations, and MongoDB commands with MongoDB syntax highlighting and intelligent autocomplete for MongoDB shell API, MongoDB operators, and for database, collection, and field names.
- Run your playgrounds and see the results instantly. Click the play button in the tab bar to see the output.
- Save your playgrounds in your workspace and use them to document how your application interacts with MongoDB
- Build aggregations quickly with helpful and well-commented stage snippets
Open the Visual Studio Code Command Palette.
To open a playground and begin interacting with your data, open Visual Studio Code and press one of the following key combinations:
- Control + Shift + P on Windows or Linux.
- Command + Shift + P on macOS.
The Command Palette provides quick access to commands and keyboard shortcuts.
Find and run the “Create MongoDB Playground” command.
Use the Command Palette search bar to search for commands. All commands related to MongoDB for Visual Studio Code are prefaced with MongoDB:.
When you run the MongoDB: Create MongoDB Playground command, MongoDB for Visual Studio Code opens a playground pre-configured with a few commands.
Run a Playground
To run a playground, click the Play Button in Visual Studio Code’s top navigation bar.
You can use a MongoDB Playground to perform CRUD (create, read, update, and delete) operations on documents in a collection on a connected deployment. Use the MongoDB CRUD Operators and shell methods to interact with your databases in MongoDB Playgrounds.
Perform CRUD Operations
Let’s run through the default MongoDB Playground template that’s created when you initialize a new Playground. In the default template, it executes the following:
use('mongodbVSCodePlaygroundDB')
switches to themongodbVSCodePlaygroundDB
database.- db.sales.drop() drops the sales collection. So the playground will start from a clean slate.
- Inserts eight documents into the mongodbVSCodePlaygroundDB.sales collection.
- Since the collection was dropped, the insert operations will create the collection and insert the data.
- For a detailed description of this method’s parameters, see insertOne() in the MongoDB Manual.
- Runs a query to read all documents sold on April 4th, 2014.
- For a detailed description of this method’s parameters, see find() in the MongoDB Manual.
When you press the Play Button, this operation outputs the following document to the Output view in Visual Studio Code:
You can learn more about the basics of MQL and CRUD operations in the post, Getting Started with Atlas and the MongoDB Query Language (MQL).
Run Aggregation Pipelines
Let’s run through the last statement of the default MongoDB Playground template. You can run aggregation pipelines on your collections in MongoDB for Visual Studio Code. Aggregation pipelines consist of stages that process your data and return computed results.
Common uses for aggregation include:
- Grouping data by a given expression.
- Calculating results based on multiple fields and storing those results in a new field.
- Filtering data to return a subset that matches a given criteria.
- Sorting data.
When you run an aggregation, MongoDB for Visual Studio Code conveniently outputs the results directly within Visual Studio Code.
This pipeline performs an aggregation in two stages:
- The $match stage filters the data such that only sales from the year 2014 are passed to the next stage.
- The $group stage groups the data by item. The stage adds a new field to the output called totalSaleAmount, which is the culmination of the item’s price and quantity.
When you press the Play Button, this operation outputs the following documents to the Output view in Visual Studio Code:
See Run Aggregation Pipelines for more information on running the aggregation pipeline from the MongoDB Playground.
Terraform snippet for MongoDB Atlas
Vs Code Mongodb
If you use Terraform to manage your infrastructure, MongoDB for Visual Studio Code helps you get started with the MongoDB Atlas Provider. We aren’t going to cover this feature today, but if you want to learn more, be sure to check out Create an Atlas Cluster from a Template using Terraform, from the MongoDB manual.
Summary
There you have it! MongoDB for Visual Studio Code Extension allows you to connect to your MongoDB instance and enables you to interact in a way that fits into your native workflow and development tools. You can navigate and browse your MongoDB databases and collections, and prototype queries and aggregations for use in your applications.
Visual Studio Code Mongodb
If you are a Visual Studio Code user, getting started with MongoDB for Visual Studio Code is easy:
- Install the extension from the marketplace;
- Get a free Atlas cluster if you don’t have a MongoDB server already;
- Connect to it and start building a playground.
You can find more information about MongoDB for Visual Studio Code and all its features in the documentation. Alt delete for mac.
If you have any questions on MongoDB for Visual Studio Code, you can join in the discussion at the MongoDB Community Forums, and you can share feature requests using the MongoDB Feedback Engine.
When you’re ready to try out the MongoDB Visual Studio Code plugin for yourself, check out MongoDB Atlas, MongoDB’s fully managed database-as-a-service. Atlas is the easiest way to get started with MongoDB and has a generous, forever-free tier.
Related Links
Check out the following resources for more information:
MongoDB for VS Code is currently available as a Preview in the Visual StudioMarketplace. The product, its features, and the correspondingdocumentation may change during the Preview stage.
This page outlines how to use the Atlas template for Terraform filesincluded with the MongoDB Extension for Visual Studio Code to createShared Tier Atlas clusters.
After loading the template, you configure the cluster and providedetails about your Atlas account. You then use Terraformcommands to plan, apply, and destroy your Atlas cluster.
Prerequisites¶
Before you use the Atlas template for Terraform filesincluded with the MongoDB Extension for Visual Studio Code, you must:
- Have an Atlas account.
- Have an Atlas organization.
- Have an API key in an organization with the
Organization Owner
orOrganization Project Creator
role.
Procedures¶
Create an Atlas Terraform File using the Template¶
Use the Atlas template for Terraform files included with the MongoDB for VS Codeto configure an Atlas cluster:
In Visual Studio Code, create a new file.¶
Operating System | Method | Actions |
---|---|---|
Any | Visual Studio Code Menu | File > New File |
MacOS | Keyboard Shortcut | Press Command + N |
Windows and Linux | Keyboard Shortcut | Press Control + N |
Save the file. Name it main.tf
.¶
main.tf
is the recommended filename for the entry point to aTerraform module.
Conectar Mongodb Con Visual Studio Code
In the main.tf
file, type atlas
, then press the Enter or Return key.¶
The MongoDB Extension for VSCode populates the file with an exampleconfiguration using the MongoDB AtlasTerraform provider to create a Shared Tier Atlas cluster.
Update the Atlas Terraform configuration to configure your cluster.¶
The cursor moves to select the value of the name
argument of themongodbatlas_project
resource.
Provide values for the following arguments to configure your cluster:
Press the Tab key to select to the next argument inthe template that you should update.
Attribute | Value |
---|---|
.name | Name of the Atlas project that this configuration creates. |
.name | Name of the Atlas cluster that this configuration creates. |
.backing_provider_name | Provider on which the Atlas cluster that this configurationcreates is hosted. Choose one of the following accepted values:
|
.provider_region_name | Region to which the Atlas cluster that this configurationcreates is deployed. Ensure that the region you chose supportsAtlas clusters of the instance size you want to deploy. By default the template provisions Shared Tier clusters: For details about the instance sizes that each provider andregion supports, see the following sections in the Atlasdocumentation: |
.provider_instance_size_name | Instance size of the Atlas cluster that this configurationcreates. Either:
For details about the instance sizes that each provider andregion supports, see the following sections in the Atlasdocumentation: |
.disk_size_gbs | Disk size of the Atlas cluster that this configurationcreates. Ensure that you provide a value that is equal to orless than the maximum disk size for the instance size youchose.
For details about the disk sizes that each provider supportsfor each instance size, see the following sections in theAtlas documentation: |
Update the local
variables.¶
The local
variables contain sensitive information. Do notcheck these values in to a repository that is available publicly.
Provide values for the following local
variables:
Variable | Value |
---|---|
mongodb_atlas_api_pub_key | Atlas public API key. |
mongodb_atlas_api_pri_key | Atlas private API key. |
mongodb_atlas_org_id | Atlas organization ID in which you want to create aproject. |
mongodb_atlas_database_username | Username of the MongoDB database user that Atlas createsfor your cluster. |
mongodb_atlas_database_user_password | Password for the MongoDB database user named inmongodb_atlas_database_username . |
mongodb_atlas_whitelistip | IP address or CIDR block from which your Atlas cluster isaccessible. |
To maximize security, consider taking the following steps:
Define the
local
Examples of automator for mac. variables in an input variablesfile.- Exclude the input variables file from your repository. Forexample, add the filename to the
.gitignore
file for yourrepository. Reference variables from the input variables file in the
main.tf
file by prefacing them withvars.
.
Azure Data Studio Mongodb
Add optional configuration options to the main.tf
file.¶
For a complete list of supported configuration options, see theMongoDB Atlas Terraform Provider documentation.
Shared Tier Atlas clusters don't support all configurationsavailable with the MongoDB Atlas Terraform provider. For a list ofunsupported configurations, see the Atlas documentation.
Mongodb C# Visual Studio Code
Save the main.tf
file.¶
Create the Atlas Cluster using Terraform¶
After you create a Terraform file using the template, create theAtlas cluster:
Navigate to the directory in which you saved your main.tf
file.¶
Run the terraform init
command to install the required providers.¶
The following output indicates that the MongoDB AtlasTerraform Provider is installed and ready for use:
Run the terraform plan
command to view what happens when you apply the configuration.¶
The following output shows what happens when you apply the Terraform configuration:

Proceed to the next step if the information is correct.
Run the terraform apply
command to create an Atlas cluster from the Terraform configuration.¶
Type yes
when prompted to confirm that you want to apply theconfiguration.
The terraform apply
command might take several minutes tocomplete.
The following output indicates that your Atlas cluster is created.You can create a connection to thisdeployment using the MongoDB for VS Code with the displayed connection strings:
Delete the Atlas Cluster using Terraform¶
Deleting a cluster destroys databases, collections, and documentsstored on it and all other resources defined in the Terraformconfiguration in which you configured the cluster.
Proceed with caution.
To delete the Atlas cluster:
Navigate to the directory in which you saved your main.tf
file.¶
Run the terraform destroy
command to install the required providers.¶
Type yes
Mercalli v2 for mac. when prompted to confirm that you want to destroy theresources defined in the configuration.
The terraform destroy
command might take several minutes tocomplete.
The following output indicates that the Atlas cluster and allassociated resources are deleted:

© MongoDB, Inc 2008-present. MongoDB, Mongo, and the leaf logo are registered trademarks of MongoDB, Inc.
require()
to Include External ModulesReference →