Explore Developer Center's New Chatbot! MongoDB AI Chatbot can be accessed at the top of your navigation to answer all your MongoDB questions.

Join us at AWS re:Invent 2024! Learn how to use MongoDB for AI use cases.
MongoDB Developer
MongoDB
plus
Sign in to follow topics
MongoDB Developer Centerchevron-right
Developer Topicschevron-right
Productschevron-right
MongoDBchevron-right

How To Use The MongoDB Visual Studio Code Plugin

Joe Karlsson11 min read • Published Jan 18, 2022 • Updated May 31, 2022
MongoDB
Facebook Icontwitter iconlinkedin icon
Rate this tutorial
star-empty
star-empty
star-empty
star-empty
star-empty
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 MongoDB for Visual Studio Code 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
Screenshot showing the MongoDB Atlas Website.

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.
Image showing available cluster types
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.
Image highlighting Free and 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.
Screenshot highlighting allow list entry screen.

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.
Screenshot highlighting cluster connect button.
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.
Screeenshot of adding new user information.
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.
Add new MongoDB connection
Connect to MongoDB
To obtain your connection string, navigate to your "Clusters" page and select "Connect".
Connect to MongoDB Cluster
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.
Connection Method
Copy Connection String
Then paste this string into Visual Studio Code.
Enter connection string
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.
Connected Successfully
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.
Screenshot showing deployment navigation

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.
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.
Screenshot showing deployment navigation
Alternatively, right-click a collection and click View Documents to view all the collection's documents in an array.
Screenshot showing deployment navigation
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.
Screenshot showing schema navigation in VS Code

Create a New Database

When you create a new database, you must populate it with an initial collection. To create a new database:
  1. Hover over the connection for the deployment where you want your database to exist.
  2. Click the Plus icon that appears.
  3. In the prompt, enter a name for your new database.
  4. Press the enter key.
  5. Enter a name for the first collection in your new database.
  6. Press the enter key.
Screenshot showing how to create a new database in VS Code. A red box highlights the plus button next to your cluster name,.

Create a New Collection

To create a new collection:
  1. Hover over the database where you want your collection to exist.
  2. Click the Plus icon that appears.
  3. In the prompt, enter a name for your new collection.
  4. Press the enter key to confirm your new collection.
Screenshot showing how to create a new collection in VS Code. A red box highlights the plus button next to your database name.

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.
Screenshot showing how to open up the command palette in VS Code. A red box highlights the ommand palette.

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.
Screenshot showing the 'Connect to MongoDB' page within the MongoDB Visual Studio Code plugin.

Run a Playground

To run a playground, click the Play Button in Visual Studio Code's top navigation bar.
Screenshot showing how to run a playground, a red box highlights 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:
  1. use('mongodbVSCodePlaygroundDB') switches to the mongodbVSCodePlaygroundDB database.
  2. db.sales.drop() drops the sales collection, so the playground will start from a clean slate.
  3. Inserts eight documents into the mongodbVSCodePlaygroundDB.sales collection.
    1. Since the collection was dropped, the insert operations will create the collection and insert the data.
    2. For a detailed description of this method's parameters, see insertOne() in the MongoDB Manual.
  4. Runs a query to read all documents sold on April 4th, 2014.
    1. For a detailed description of this method's parameters, see find() in the MongoDB Manual.
1// MongoDB Playground
2// To disable this template go to Settings \| MongoDB \| Use Default Template For Playground.
3// Make sure you are connected to enable completions and to be able to run a playground.
4// Use Ctrl+Space inside a snippet or a string literal to trigger completions.
5
6// Select the database to use.
7use('mongodbVSCodePlaygroundDB');
8
9// The drop() command destroys all data from a collection.
10// Make sure you run it against proper database and collection.
11db.sales.drop();
12
13// Insert a few documents into the sales collection.
14db.sales.insertMany([
15 { '_id' : 1, 'item' : 'abc', 'price' : 10, 'quantity' : 2, 'date' : new Date('2014-03-01T08:00:00Z') },
16 { '_id' : 2, 'item' : 'jkl', 'price' : 20, 'quantity' : 1, 'date' : new Date('2014-03-01T09:00:00Z') },
17 { '_id' : 3, 'item' : 'xyz', 'price' : 5, 'quantity' : 10, 'date' : new Date('2014-03-15T09:00:00Z') },
18 { '_id' : 4, 'item' : 'xyz', 'price' : 5, 'quantity' : 20, 'date' : new Date('2014-04-04T11:21:39.736Z') },
19 { '_id' : 5, 'item' : 'abc', 'price' : 10, 'quantity' : 10, 'date' : new Date('2014-04-04T21:23:13.331Z') },
20 { '_id' : 6, 'item' : 'def', 'price' : 7.5, 'quantity': 5, 'date' : new Date('2015-06-04T05:08:13Z') },
21 { '_id' : 7, 'item' : 'def', 'price' : 7.5, 'quantity': 10, 'date' : new Date('2015-09-10T08:43:00Z') },
22 { '_id' : 8, 'item' : 'abc', 'price' : 10, 'quantity' : 5, 'date' : new Date('2016-02-06T20:20:13Z') },
23]);
24
25// Run a find command to view items sold on April 4th, 2014.
26db.sales.find({
27 date: {
28 $gte: new Date('2014-04-04'),
29 $lt: new Date('2014-04-05')
30 }
31});
When you press the Play Button, this operation outputs the following document to the Output view in Visual Studio Code:
1{
2 acknowleged: 1,
3 insertedIds: {
4 '0': 2,
5 '1': 3,
6 '2': 4,
7 '3': 5,
8 '4': 6,
9 '5': 7,
10 '6': 8,
11 '7': 9
12 }
13}
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:
  1. The $match stage filters the data such that only sales from the year 2014 are passed to the next stage.
  2. 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.
1// Run an aggregation to view total sales for each product in 2014.
2const aggregation = [
3 { $match: {
4 date: {
5 $gte: new Date('2014-01-01'),
6 $lt: new Date('2015-01-01')
7 }
8 } },
9 { $group: {
10 _id : '$item', totalSaleAmount: {
11 $sum: { $multiply: [ '$price', '$quantity' ] }
12 }
13 } },
14];
15
16db.sales.aggregate(aggregation);
When you press the Play Button, this operation outputs the following documents to the Output view in Visual Studio Code:
1[
2 {
3 _id: 'abc',
4 totalSaleAmount: 120
5 },
6 {
7 _id: 'jkl',
8 totalSaleAmount: 20
9 },
10 {
11 _id: 'xyz',
12 totalSaleAmount: 150
13 }
14]
See Run Aggregation Pipelines for more information on running the aggregation pipeline from the MongoDB Playground.

Terraform snippet for MongoDB Atlas

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, check out Create an Atlas Cluster from a Template using Terraform, from the MongoDB manual.
Screenshot showing the Terraform capabilities of the MongoDB VS Code Plugin.

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.
If you are a Visual Studio Code user, getting started with MongoDB for Visual Studio Code is easy:
  1. Get a free Atlas cluster if you don't have a MongoDB server already;
  2. 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.
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.
Check out the following resources for more information:

Facebook Icontwitter iconlinkedin icon
Rate this tutorial
star-empty
star-empty
star-empty
star-empty
star-empty
Related
Quickstart

Getting Started With MongoDB and Starlette


Jul 12, 2024 | 5 min read
News & Announcements

MongoDB 3.6: Here to SRV you with easier replica set connections


Sep 23, 2022 | 4 min read
Article

Building a Flask and MongoDB App with Azure Container Apps


Apr 02, 2024 | 8 min read
Tutorial

Modernize Your Insurance Data Models With MongoDB Relational Migrator


Jun 03, 2024 | 14 min read
Table of Contents