Mongodb Visual Studio Code

  



  1. Mongodb In Visual Studio Code
  2. Mongodb Visual Studio Code
  3. Conectar Mongodb Con Visual Studio Code
  4. Mongodb C# Visual Studio Code
  5. Mongodb With Visual Studio Code

Map MongoDB to C# objects; Look at MongoDB aggregation; How to use LINQ with MongoDB; As you already know, C# is a general-purpose language and MongoDB is a general-purpose data platform. Together, C# and MongoDB are a powerful combination. To follow along, I'll be using Visual Studio 2019 on Windows 10 and we will be connecting to a MongoDB. The CosmosDB extension for Visual Studio Code turns your text editor into a killer MongoDB administration tool as well. And that’s great, because the best place to work with your database is in the same place where you write all your code.

Visual Studio Code has great support for working with MongoDB databases, whether your own instance or in Azure with MongoDB Atlas. With the MongoDB for VS Code extension, you can create, manage, and query MongoDB databases from within VS Code.

Install the extension

MongoDB support for VS Code is provided by the MongoDB for VS Code extension. To install the MongoDB for VS Code extension, open the Extensions view by pressing ⇧⌘X (Windows, Linux Ctrl+Shift+X) and search for 'MongoDB' to filter the results. Select the MongoDB for VS Code extension.

Connect to MongoDB

Once you've installed the MongoDB for VS Code extension, you'll notice there is a new MongoDB Activity Bar view. Select the MongoDB view and you'll see the MongoDB Explorer.

To connect to a MongoDB database, select Add Connection and enter the connection details for the database then Connect, the default is a local MongoDB server at mongodb://127.0.0.1:27017. You can also enter a connection string, click the 'connect with a connection string' link and paste the connection string.

Note: Make sure your MongoDB server (mongod.exe) is running if you are connecting to a local MongoDB server.

Once attached, you can work with the MongoDB server, managing MongoDB Databases, Collections, and Documents.

You can expand databases to view their collections with their schema and indexes and you can select individual MongoDB Documents to view their JSON.

You can also attach a MongoDB shell to the active connection, simply by right-clicking on the connection itself.

Note: Make sure the MongoDB shell (mongo or mongosh) is installed and is on your path. In the extension's settings, you can choose which shell you are using.

MongoDB Commands

There are MongoDB specific commands available in the VS Code Command Palette (⇧⌘P (Windows, Linux Ctrl+Shift+P)) as well as through Explorer context menus.

Using Playgrounds

One of the most powerful features of the VS Code MongoDB integration is Mongo Playgrounds. Playgrounds let you create, run, and save MongoDB commands from a VS Code editor. Create a new playground with the MongoDB: Create MongoDB Playground command.

In a playground, you can reference MongoDB entities and commands and you get rich IntelliSense as you type. Playgrounds are useful for prototyping database operations and queries. Execute selected lines in the playground queries with the MongoDB: Run Selected Lines From Playground command.

MongoDB on Azure

You can easily create a MongoDB cluster on Azure for Free with MongoDB Atlas.

Choose Create a New Cluster from the dashboard and choose Azure as the Cloud Provider. Once the cluster is created, connect to using the connection string provided by MongoDB Atlas.

Next steps

  • Azure Extensions - The VS Code Marketplace has hundreds of extensions for Azure and the cloud.
  • Deploying to Azure - Learn step-by-step how to deploy your application to Azure.
  • Working with Docker - Put your application in a Docker container for easy reuse and deployment.

Introduction

Pronounced “C Sharp”, C# is a general purpose programming language developed by Microsoft. C# is an object-oriented programming language useful for creating websites, mobile apps, video games and virtual reality environments. Visual Studio Code is an editor used for creating web and cloud applications. The Microsoft .NET SDK, or Software Development Kit, Framework gives developers the ability to build applications on x64 platforms. This tutorial will cover the steps needed to install Visual Studio Code and the .NET SDK framework for creating a C and MongoDB application.

Prerequisites

  • The .NET Core SDK must be download and installed the local dev machine to create a C and MongoDB application. The best way to compile and run C# is using an IDE with a built-in compiler, such as Visual Studio Code or Mono.

  • The examples in this tutorial assume using VS Code. The interactive installer for VS Code must be downloaded if running MacOS or Windows. For a Linux distro’s package repository, install VS Code via the terminal command line.

Install VS Code

For Windows or MacOS, download the interactive installer for Visual Studio code here and then double click the downloaded package and follow the installation instructions. For MacOS, the archive must be unzipped and then installed in the Visual Studio Code.app file.

Install Visual Studio code on Ubuntu

The VS Code can be installed with the APT-GET repository, if running a Debian flavor of Linux.

If it has not already been done, the first step is to add the apt-transport-https package to the repository with the following command:

sudoapt-get install apt-transport-https

Now update the local repository packages with apt-get update and then install code using the following commands:

Install VS Code

Install the .NET Core

Download the .NET Core SDK framework from Microsoft’s Dotnet website, as shown here:

To be safe, restart the machine once the installation has finsihed.

Install the .NET Core on Linux

For Linux, the .NET Core will have to be installed using terminal commands. If using a Debian flavor of Linux like Ubuntu, execute the following wget command to download the DEB archive:

wget-q https://packages.microsoft.com/config/ubuntu/19.04/packages-microsoft-prod.deb -O packages-microsoft-prod.deb

When finished downloading, be certain to run the following command from the same directory as the .deb package to install Microsoft’s .NET Core:

Install the .NET SDK on Linux

If it has not already been done, update the local APT-GET repository with the sudo apt-get update command and then install the dotnet-sdk-3.1 package by executing the following command:

sudoapt-get install dotnet-sdk-3.1

Install the ASP.NET Core framework with the following command:

Install the .NET SDK with snap

If the snap package manager is installed, the following command can also be used to install the .NET SDK:

sudo snap install dotnet-sdk --classic

Install MongoDB

The MongoDB service must also be installed and running before building a C# app for Mongo in Visual Studio Code.

Mongodb In Visual Studio Code

Install MongoDB on Ubuntu

If running an Ubuntu flavor of Linux, such as Ubuntu 18 or Linux Mint, execute the following wget command to obtain the key for the MongoDB package:

wget-qO - https://www.mongodb.org/static/pgp/server-4.2.asc |sudoapt-key add -

Executing the above command should return a response of OK.

VisualMongodb Visual Studio Code

Mongodb Visual Studio Code

Now use echo to add the repository to Ubuntu’s sources.list.d file:

echo'deb [ arch=amd64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.2 multiverse'|sudotee/etc/apt/sources.list.d/mongodb-org-4.2.list

Finally, install the DEB package for version 4.2 of MongoDB Community Edition by updating the local packages with the following command:

The results should resemble the following:

Now use the following command to start the MongoDB server:

sudo service mongod start

Install MongoDB on macOS

Conectar Mongodb Con Visual Studio Code

Homebrew can be used if building the C# MongoDB app on MacOS.

First, the brew repository must be updated and given a health check with the following brew doctor command:

Once it has finished updating, execute the following brew install command to install MongoDB Community Edition:

brew install mongodb

Now execute the following Homebrew command to start the MongoDB server:

Verify that MongoDB is installed

When MongoDB has finished installing and the service has started, execute the following command to obtaining the version number and verify the service is working:

mongo --version

Install NuGet

Microsoft’s NuGet package manager must also be installed in order for the C# driver for MongoDB to work in the local development environment.

Install the NuGet package manager on Ubuntu

Mongodb C# Visual Studio Code

The NuGet service is installed with the APT repository on Ubuntu. Execute the following command to update the APT packages and then install NuGet:

Install NuGet on macOS with Homebrew

A Mono library, called mono-libgdiplus, must be installed to make the macOS GDI+ (graphics device interface) compatible. Execute the following command to install the Mono library:

brew install mono-libgdiplus

The Nuget package manager can now be installed with the following command:

NOTE: This will be used later to install the C# driver for MongoDB using the nuget command.

Install the C# MongoDB driver

Download the NuGet driver for MongoDB here. Alternatively, the following command can be executed in the project’s VS Code terminal to install the C# driver for MongoDB:

dotnet add package MongoDB.Driver --version 2.10.0

The following nuget command can also be used in a UNIX terminal to install the C# driver for MongoDB on MacOS or Linux:

nuget install mongoDB.Driver && nuget install mongocsharpdriver

The results should resemble the following:

Create a .NET project

Now create a new .NET project folder for the C# and MongoDB application.

Create a new VS Code project folder

Mongodb With Visual Studio Code

Open the Visual Studio Code application and click the VS code folder icon in the left sidebar. A modal pop-up window should appear with the title New Folder and a prompt to name the project, as shown here:

Clicking the blue -kbd-Create-/kbd- button will generate all of the necessary .NET files and dependencies for the C# project.

NOTE: Make sure the name doesn’t have any spaces, underscores (_) or hyphens (-). Typically .NET project names use PascalCase or UpperCamelCase, where the first letter of each word is capitalized.

Install the C# extension for VS Code

Now the VS Code C# extension must be installed in the Code Extension Marketplace. As shown on the below screenshot, click the Extension Marketplace icon in the left-hand sidebar to load the marketplace. Next type c# in the input field to search for the extension. Make sure to install the official Microsoft extension.

Build and restore the .NET project

At this point the project files should be visable in the sidebar. However, the project must be initilized using VS Code’s built-in terminal.

To open the terminal panel, press -kbd-CTRL-/kbd-+-kbd-`-/kbd- to open the terminal panel from the bottom. Alternatively, as shown below, navigate to ‘View’ in the main menu and then click ‘Terminal’ in the drop-down menu.

Use the ‘dotnet’ command to start the project

Now the dotnet command can be used in the VS terminal to initialize the .NET project for the C# and MongoDB application by executing the following command:

The system should return the following response:

Use 'dotnet --help' to see available commands or visit: https://aka.ms/dotnet-cli-docs
Write your first app: https://aka.ms/first-net-core-app

Now the following restore command can be used to restore the project dependencies:

The results should resemble the following:

Finally, execute the following run command to compile and run the C# code for the project:

dotnet run

The console should display a Hello, world response that indicates the application working.

C# code for MongoDB

Delete all of the contents in the Program.cs script. Now paste the following C# code into it so it will return a string containing all of the MongoDB database names:

usingSystem;
usingMongoDB.Driver;
namespace MongoProject
{
class Program
{
staticvoid Main(string[] args)
{
try
{
var connString ='mongodb://127.0.0.1:27017';
MongoClient client =new MongoClient(connString);
// List all the MongoDB databases
var allDatabases = client.ListDatabases().ToList();
Console.WriteLine('MongoDB db array type: '+ allDatabases.GetType());
Console.WriteLine('MongoDB databases:');
Console.WriteLine(string.Join(', ', allDatabases));
}
catch(Exception ex)
{
Console.WriteLine('Error:'+ ex.Message);
}
}
}
}

NOTE: Make sure to modify the above connString variable to match the domain and port of the MongoDB server. Use 127.0.0.1:27017 if running MongoDB on a localhost server using the default MongoDB port of 27017.

Now execute the above code using the following run command:

The project application should return something that resembles the following VS Code in the terminal:

{'name':'admin', 'sizeOnDisk':40960.0, 'empty':false},
{'name':'config', 'sizeOnDisk':110592.0, 'empty':false},
{'name':'local', 'sizeOnDisk':40960.0, 'empty':false}

Conclusion

This tutorial explained the steps required to install Visual Studio Code and the .NET SDK framework for creating a C and MongoDB application. This comprehensive tutorial covered how to install VS Code and how to download and install the .NET Core SDK framework. The article explained how to install MongoDB and confirm the installation, how to install Microsoft’s NuGet and its package manager and how to install the C# MongoDB driver. The tutorial also covered how to create a .NET project and a new VS Code project folder, how to install the C# extension for VS Code, build and restore the .NET project and run the C# code for MongoDB. Remember to be sure to modify the connString variable to match the domain and port of the MongoDB server.

Just the Code

usingSystem;
usingMongoDB.Driver;
namespace MongoProject
{
class Program
{
staticvoid Main(string[] args)
{
try
{
var connString ='mongodb://127.0.0.1:27017';
MongoClient client =new MongoClient(connString);
// List all the MongoDB databases
var allDatabases = client.ListDatabases().ToList();
Console.WriteLine('MongoDB db array type: '+ allDatabases.GetType());
Console.WriteLine('MongoDB databases:');
Console.WriteLine(string.Join(', ', allDatabases));
}
catch(Exception ex)
{
Console.WriteLine('Error:'+ ex.Message);
}
}
}
}