How To Use The MongoDB Visual Studio Code Plugin
Rate this tutorial
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.
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
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.
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.
Click Add Your Current IP Address.
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.
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.
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.
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.
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.
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.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.
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.
When you create a new database, 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.
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.
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
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.
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.
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.
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.
- Runs a query to read all documents sold on April 4th, 2014.
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. 7 use('mongodbVSCodePlaygroundDB'); 8 9 // The drop() command destroys all data from a collection. 10 // Make sure you run it against proper database and collection. 11 db.sales.drop(); 12 13 // Insert a few documents into the sales collection. 14 db.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. 26 db.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).
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 // Run an aggregation to view total sales for each product in 2014. 2 const 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 16 db.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.
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.
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:
- 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: