Voyage AI joins MongoDB to power more accurate and trustworthy AI applications on Atlas.

Explore o novo chatbot do Developer Center! O MongoDB AI chatbot pode ser acessado na parte superior da sua navegação para responder a todas as suas perguntas sobre o MongoDB .

5 Diferentes maneiras de implantar um banco de dados gratuito com o MongoDB Atlas

Nic Raboy5 min read • Published Dec 17, 2021 • Updated Feb 03, 2023
Facebook Icontwitter iconlinkedin icon
Classifique este início rápido
star-empty
star-empty
star-empty
star-empty
star-empty
You might have already known that MongoDB offers a free tier through M0 clusters on MongoDB Atlas, but did you know that there are numerous ways to deploy depending on your infrastructure needs? To be clear, there's no wrong way to deploy a MongoDB Atlas cluster, but there could be an easier way to fit your operations needs.
Neste artigo, vamos dar uma rápida olhada nas várias maneiras de você implantar um MongoDB Atlas cluster usando ferramentas como Terraform, CloudFormation, CLIs e um simples apontar e clicar.

Usando a IU da Web do Atlas para implantar um cluster

If you're a fan of point and click deployments like I am, the web UI for MongoDB Atlas will probably fit your needs. Let's take a quick look at how to deploy a new cluster with a database using the UI found within the MongoDB Cloud Dashboard.
Within the Databases tab for your account, if you don't have any databases or clusters, you'll be presented with the opportunity to build one using the "Build a Database" button.
Create a New MongoDB Atlas Cluster on the Web
Criar um novo MongoDB Atlas cluster na web
Como estamos mantendo as coisas gratuitas neste artigo, vamos escolher a opção " Shared " quando apresentada na próxima tela. Se você acha que precisa de mais alguma coisa, não deixe que eu pare você!
Depois de selecionar "Compartilhado" nas opções, você poderá criar um novo cluster selecionando primeiro seu provedor de serviços de cloud e região.
MongoDB Atlas Cloud Service Provider
MongoDB Atlas Cloud Service Provider
Você pode usar os padrões ou selecionar um provedor ou região que preferir usar. Sua escolha não tem impacto em como você trabalhará com seu cluster. No entanto, escolher um provedor e um local que corresponda aos seus outros serviços pode gerar melhorias de desempenho.
Depois de selecionar o botão " Create Cluster ", seu cluster será implantado. Isso pode levar alguns minutos, dependendo do tamanho do cluster.
Cluster Dashboard in MongoDB Atlas
Painel do Cluster no MongoDB Atlas
At this point, you can continue exploring Atlas, create a database or two, and be on your way to creating great applications. A good next step after deploying your cluster would be adding entries to your access list. You can learn how to do that here.
Digamos que você prefira uma abordagem mais orientada por CLI.

Usando o MongoDB CLI para implantar um cluster

A MongoDB CLI pode ser útil se você quiser fazer sistemas baseados em script ou se preferir fazer tudo a partir da linha de comando.
To install the MongoDB CLI, check out the installation documentation and follow the instructions. You'll also need to have a MongoDB Cloud account created.
If this is your first time using the MongoDB CLI, check out the configuration documentation to learn how to add your credentials and other information.
Para este exemplo, usaremos a funcionalidade de início rápido que a CLI oferece. Na CLI, execute o seguinte:
1mongocli atlas quickstart
Usando a abordagem de início rápido, você receberá uma série de perguntas sobre como deseja que seu Atlas cluster seja configurado. Isso inclui a criação de usuários, regras de acesso à rede e outras informações.
To see some of the other options for the CLI, check out the documentation.

Usando a API Atlas Admin para implantar um cluster

Uma opção semelhante ao uso da CLI para criar clusters MongoDB Atlas é usar a API Atlas Admin. Uma diferença aqui é que você não precisa baixar ou instalar nenhuma CLI específica e, em vez disso, pode usar solicitações HTTP para realizar o trabalho usando qualquer coisa capaz de fazer solicitações HTTP.
Considere a seguinte solicitação HTTP, por exemplo, uma que ainda pode ser executada no prompt de comando:
1curl --location --request POST 'https://cloud.mongodb.com/api/atlas/v1.0/groups/{GROUP_ID}/clusters?pretty=true' \
2--user "{PUBLIC_KEY}:{PRIVATE_KEY}" --digest \
3--header 'Content-Type: application/json' \
4--data-raw '{
5 "name": "MyCluster",
6 "providerSettings": {
7 "providerName": "AWS",
8 "instanceSizeName": "M10",
9 "regionName": "US_EAST_1"
10 }
11}'
The above cURL request is a trimmed version, containing just the required parameters, taken from the Atlas Admin API documentation. You can try the above example after switching the GROUP_ID, PUBLIC_KEY, and PRIVATE_KEY placeholders with those found in your Atlas dashboard. The GROUP_ID is the project id representing where you'd like to create your cluster. The PUBLIC_KEY and PRIVATE_KEY are the keys for a particular project with proper permissions for creating clusters.
The same cURL components can be executed in a programming language or even a tool like Postman. The Atlas Admin API is not limited to just cURL using a command line.
Embora você possa usar a API de administração do Atlas para criar usuários, aplicar regras de acesso e semelhantes, seriam necessárias algumas solicitações HTTP diferentes em comparação com o que vimos com a CLI, pois a CLI foi projetada para facilitar esses tipos de interações .
For information on the other optional fields that can be used in the request, refer to the documentation.

Usando o Terraform HashiCorp para implantar um cluster

Há uma chance de que sua organização já esteja usando uma solução de infraestrutura como código (IaC), como o Terraform. A grande novidade é que temos um provedor de Terraform para o MongoDB Atlas que permite criar um banco de dados Atlas gratuito e fácil.
Veja a seguinte configuração do Terraform:
1locals {
2 mongodb_atlas_api_pub_key = "PUBLIC_KEY"
3 mongodb_atlas_api_pri_key = "PRIVATE_KEY"
4 mongodb_atlas_org_id = "ORG_ID"
5 mongodb_atlas_project_id = "PROJECT_ID"
6}
7
8terraform {
9 required_providers {
10 mongodbatlas = {
11 source = "mongodb/mongodbatlas"
12 version = "1.1.1"
13 }
14 }
15}
16
17provider "mongodbatlas" {
18 public_key = local.mongodb_atlas_api_pub_key
19 private_key = local.mongodb_atlas_api_pri_key
20}
21
22resource "mongodbatlas_cluster" "my_cluster" {
23 project_id = local.mongodb_atlas_project_id
24 name = "terraform"
25
26 provider_name = "TENANT"
27 backing_provider_name = "AWS"
28 provider_region_name = "US_EAST_1"
29 provider_instance_size_name = "M0"
30}
31
32output "connection_strings" {
33 value = mongodbatlas_cluster.my_cluster.connection_strings.0.standard_srv
34}
If you added the above configuration to a main.tf file and swapped out the information at the top of the file with your own, you could execute the following commands to deploy a cluster with Terraform:
1terraform init
2terraform plan
3terraform apply
The configuration used in this example was taken from the Terraform template accessible within the Visual Studio Code Extension for MongoDB. However, if you'd like to learn more about Terraform with MongoDB, check out the official provider information within the Terraform Registry.

Usando Amazon Web Services CloudFormation para distribuir um cluster

Se todos os seus aplicativos estiverem hospedados na AWS, você pode querer usar o CloudFormation, outra solução do IaC.
If you're interested in a script-like configuration for CloudFormation, Cloud Product Manager Jason Mimick wrote a thorough tutorial titled Comece a usar o MongoDB Atlas e o AWS CloudFormation. However, like I mentioned earlier, I'm a fan of a point and click solution.
A point and click solution can be accomplished with AWS CloudFormation! Navigate to the MongoDB Atlas on AWS page and click "How to Deploy."
You'll have a few options, but the simplest option is to launch the Quick Start for deploying without VPC peering.
MongoDB Atlas with AWS CloudFormation Quick Start
Início rápido do MongoDB Atlas com AWS CloudFormation
As próximas etapas envolvem seguir um assistente de configuração e implantação de quatro partes.
A primeira etapa consiste em selecionar um modelo de configuração.
MongoDB Atlas with AWS CloudFormation Quick Start
Início rápido do MongoDB Atlas com AWS CloudFormation
A menos que você conheça o CloudFormation, os padrões devem funcionar bem.
A segunda etapa do assistente de configuração é para definir as informações de configuração para MongoDB Atlas. Foi o que foi visto em outras partes deste artigo.
MongoDB Atlas with AWS CloudFormation Quick Start
Início rápido do MongoDB Atlas com AWS CloudFormation
Replace the fields with your own information, including the public key, private key, and organization id to be used with CloudFormation. Once more, these values can be found and configured within your MongoDB Atlas Dashboard.
MongoDB Atlas with AWS CloudFormation Quick Start
Início rápido do MongoDB Atlas com AWS CloudFormation
O estágio final do assistente de configuração é definir as permissões. Para este artigo, tudo na fase final ficará com as informações padrão fornecidas, mas sinta-se à vontade para usar as suas próprias.
Depois de revisar a configuração do CloudFormation, você pode prosseguir para a implementação, que pode levar alguns minutos.
Como mencionei, se preferir não passar por esse assistente, você também pode explorar uma abordagem mais scriptada usando o CloudFormation e a AWS CLI.

Conclusão

Você acabou de receber uma introdução a algumas das maneiras de distribuir clusters do MongoDB Atlas. Como mencionei anteriormente, não há uma maneira errada, mas pode haver uma maneira melhor, dependendo de como você já está gerenciando sua infraestrutura.
If you get stuck with your MongoDB Atlas deployment, navigate to the MongoDB Community Forums for some help!

Facebook Icontwitter iconlinkedin icon
Classifique este início rápido
star-empty
star-empty
star-empty
star-empty
star-empty
Relacionado
Tutorial

Construindo com padrões: o Padrão Outlier


May 16, 2022 | 3 min read
Tutorial

Codificação com Mark: abstraindo junções e subconjuntos em Python


Mar 19, 2024 | 11 min read
Tutorial

Orquestrando o MongoDB e BigQuery para excelência em aprendizado de máquina com as bibliotecas PyMongoArrow e BigQuery Pandas


Feb 08, 2024 | 4 min read
Tutorial

The 5-Minute Guide to Working with ESG Data on MongoDB


Aug 24, 2023 | 11 min read