Important
The atlas deployments commands are deprecated as of Atlas CLI version 1.52.0. Use atlas local commands for local deployments and atlas clusters commands for cloud deployments. We updated this guide to use the new commands.
In this guide, you will learn how to create a MongoDB Atlas deployment locally or in the cloud. Then, you will learn how to create an application that connects to your deployment. To learn how to install MongoDB Community or MongoDB Enterprise editions on your own infrastructure, see the Install MongoDB guide.
Create a MongoDB Atlas Deployment
This section shows how to set up a local or cloud MongoDB Atlas deployment and connect to the deployment by using the MongoDB Shell.
Install dependencies
Before you begin this tutorial, you must install the following dependencies in your development environment:
Atlas CLI: Command-line interface that allows you to manage your deployments from the terminal
MongoDB Shell: Interactive tool that connects to a deployment and provides database operation support
Docker: Platform that allows you to run software within containers, including local MongoDB deployments
Select the tab corresponding to your operating system to view the commands that install these required development tools.
Run the following commands to install the dependencies by using the Homebrew package manager. If you do not have Homebrew, you can install it by following the instructions on the Homebrew website.
brew install mongodb-atlas brew install --cask docker
Run the following commands to install the dependencies by using the Chocolatey package manager. If you do not have Chocolatey, you can install it by following the instructions on the Chocolatey website.
choco install mongodb-atlas choco install docker-desktop
For other ways to install the Atlas CLI, see Atlas CLI install page.
Note
Docker Desktop
The preceding commands install the Docker Desktop application. After the installation completes, ensure that you create a Docker account and start the application.
Set up a fully-featured deployment
Run the following command and follow the prompts in the shell to deploy a cluster. If you do not have an Atlas account, the following command prompts you to create one.
This command creates a single-member replica set in a container that runs on your local machine.
atlas local setup myDeployment \ --mdbVersion 8.0 --port <port number> --connectWith connectionString
Note
Replace the <port number> placeholder with the port you want to use. The default port is 27017, but you can specify a different port if 27017 is not available.
The command outputs the following information:
Deployment created! Connection string: "<connection string URI>"
Save the connection string URI for use in a future step.
This command creates a free cluster on MongoDB Atlas.
atlas setup --clusterName myDeployment \ --provider AWS --region us-east-1 --skipSampleData \ --username <database username> --password <database user password> \ --connectWith skip --force
Note
Replace the following placeholder values to create a new database user with atlasAdmin privileges in your deployment:
<database username>: Specify a username for your new database user<database user password>: Specify a password for your new database user
The command outputs the following information:
Cluster created. Your connection string: "<connection string URI>"
Save the connection string URI for use in a future step.
Connect to your deployment
You can connect to your deployment with the MongoDB Shell (mongosh) by running the following command:
atlas local connect myDeployment --connectWith mongosh
atlas clusters connect myDeployment --username <database username> \ --password <database user password> --connectWith mongosh
Note
Replace the <database username> and <database user password> placeholders with the username and password you created for your database user.
After connecting, you can run the following command to test your connection:
show dbs
The command returns a list of databases in your deployment.
Congratulations! You have successfully set up your MongoDB Atlas deployment and connected to it. To learn more about how to interact with your deployment by using the MongoDB Shell, see the MongoDB Shell documentation.
In the next section, you will learn how to create an application that connects to your deployment and interacts with data.
Create Your First MongoDB Application
To connect to your MongoDB Atlas deployment in an application, you can use one of the official MongoDB client libraries.
Select your preferred programming language from the following dropdown menu to learn how to connect to your MongoDB Atlas deployment in that language.
Tip
Before running the steps in this section, ensure that you exit the MongoDB Shell by running the exit command.
Load sample data
You can run the following commands to load sample data into your deployment:
Run the following commands from your terminal to install the MongoDB Database Tools:
brew tap mongodb/brew brew trust mongodb/brew brew install mongodb-database-tools
Then, run the following commands to load the sample data:
curl https://atlas-education.s3.amazonaws.com/sampledata.archive -o sampledata.archive mongorestore --archive=sampledata.archive --port <port number>
Note
Replace the <port number> placeholder with the port number of your deployment. Your port number can be found in Docker Desktop.
atlas clusters sampleData load myDeployment
Initialize your application
Run the following commands in your terminal to create a new directory and a file for your application. The command also initializes npm in the directory and installs the Node.js driver.
mkdir node-quickstart cd node-quickstart touch index.js npm init -y npm install mongodb
mkdir node-quickstart cd node-quickstart type nul > index.js npm init -y npm install mongodb
Create your application
Copy and paste the following code into index.js. This code connects to your cluster and queries your sample data.
import { MongoClient } from 'mongodb'; async function runGetStarted() { // Replace the uri string with your connection string const uri = '<connection string URI>'; const client = new MongoClient(uri); try { const database = client.db('sample_mflix'); const movies = database.collection('movies'); // Queries for a movie that has a title value of 'Back to the Future' const query = { title: 'Back to the Future' }; const movie = await movies.findOne(query); console.log(movie); } finally { await client.close(); } } runGetStarted().catch(console.dir);
Add your connection string
In your application file, replace the <connection string URI> placeholder with your connection string. The connection string has the following format:
mongodb://localhost:<port number>/?directConnection=true
Replace the <port number> placeholder with the port number of your local deployment. Your port number can be found in Docker Desktop.
mongodb+srv://<database user>:<database password>@<cluster address>
Replace the following placeholder values:
<database user>: The database username you specified when creating your deployment.<database password>: The password for the database user.<cluster address>: The SRV address for your cluster. You can view your cluster address in the connection string you saved after creating your deployment, or by runningatlas clusters connectionStrings describe myDeploymentin your terminal and copying the text after themongodb+srv://prefix.
Run your application
In your project directory, run the following command to start the application:
node index.js
The application output contains details about the retrieved movie document:
{ _id: ..., plot: 'A young man is accidentally sent 30 years into the past...', genres: [ 'Adventure', 'Comedy', 'Sci-Fi' ], ... title: 'Back to the Future', ... }
Next Steps
To learn more about your MongoDB deployment, see the following resources:
To access free courses for beginners and more advanced MongoDB users, visit the MongoDB University.
Load sample data
You can run the following commands to load sample data into your deployment:
Run the following commands from your terminal to install the MongoDB Database Tools:
brew tap mongodb/brew brew trust mongodb/brew brew install mongodb-database-tools
Then, run the following commands to load the sample data:
curl https://atlas-education.s3.amazonaws.com/sampledata.archive -o sampledata.archive mongorestore --archive=sampledata.archive --port <port number>
Note
Replace the <port number> placeholder with the port number of your deployment. Your port number can be found in Docker Desktop.
atlas clusters sampleData load myDeployment
Initialize your application
Ensure you have the following dependencies installed in your development environment:
Run the following commands in your shell to create a new directory and a file for your application. The commands also install the Python driver in a virtual environment.
mkdir pymongo-quickstart cd pymongo-quickstart touch quickstart.py python3 -m venv venv source venv/bin/activate python3 -m pip install pymongo
mkdir pymongo-quickstart cd pymongo-quickstart type nul > quickstart.py python -m venv venv .\venv\Scripts\activate python -m pip install pymongo
Create your application
Copy and paste the following code into quickstart.py. This code connects to your cluster and queries your sample data.
from pymongo import MongoClient import json uri = "<connection string URI>" client = MongoClient(uri) try: database = client.get_database("sample_mflix") movies = database.get_collection("movies") # Queries for a movie that has the title 'Back to the Future' query = { "title": "Back to the Future" } movie = movies.find_one(query) print(json.dumps(movie, indent=4, default=str)) client.close() except Exception as e: raise Exception("Unable to find the document due to the following error: ", e)
Add your connection string
In your application file, replace the <connection string URI> placeholder with your connection string. The connection string has the following format:
mongodb://localhost:<port number>/?directConnection=true
Replace the <port number> placeholder with the port number of your local deployment. Your port number can be found in Docker Desktop.
mongodb+srv://<database user>:<database password>@<cluster address>
Replace the following placeholder values:
<database user>: The database username you specified when creating your deployment.<database password>: The password for the database user.<cluster address>: The SRV address for your cluster. You can view your cluster address in the connection string you saved after creating your deployment, or by runningatlas clusters connectionStrings describe myDeploymentin your terminal and copying the text after themongodb+srv://prefix.
Run your application
From your project directory, run the following command to start the application:
python3 quickstart.py
The output includes details of the retrieved movie document:
{ _id: ..., plot: 'A young man is accidentally sent 30 years into the past...', genres: [ 'Adventure', 'Comedy', 'Sci-Fi' ], ... title: 'Back to the Future', ... }
Next Steps
To learn more about your MongoDB deployment, see the following resources:
To access free courses for beginners and more advanced MongoDB users, visit the MongoDB University.
Load sample data
You can run the following commands to load sample data into your deployment:
Run the following commands from your terminal to install the MongoDB Database Tools:
brew tap mongodb/brew brew trust mongodb/brew brew install mongodb-database-tools
Then, run the following commands to load the sample data:
curl https://atlas-education.s3.amazonaws.com/sampledata.archive -o sampledata.archive mongorestore --archive=sampledata.archive --port <port number>
Note
Replace the <port number> placeholder with the port number of your deployment. Your port number can be found in Docker Desktop.
atlas clusters sampleData load myDeployment
Download and install
Before you begin this tutorial, ensure that you install the following dependencies:
JDK version 8 or later
Integrated development environment (IDE), such as IntelliJ IDEA or Eclipse
In your IDE, create a new Maven project. Add the Bill of Materials (BOM) for MongoDB JVM artifacts and the Java driver to your pom.xml file.
<dependencyManagement> <dependencies> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-bom</artifactId> <version>5.5.1</version> <type>pom</type> <scope>import</scope> </dependency> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-sync</artifactId> </dependency> </dependencies> </dependencyManagement>
Create your application
In your project directory, create a new Java class file called Quickstart.java. Copy and paste the following code into that file. This code connects to your cluster and queries your sample data.
import static com.mongodb.client.model.Filters.eq; import org.bson.Document; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; public class QuickStart { public static void main(String[] args) { // Replace the placeholder with your MongoDB deployment's connection string String uri = "<connection string uri>"; try (MongoClient mongoClient = MongoClients.create(uri)) { MongoDatabase database = mongoClient.getDatabase("sample_mflix"); MongoCollection<Document> collection = database.getCollection("movies"); Document doc = collection.find(eq("title", "Back to the Future")).first(); if (doc != null) { System.out.println(doc.toJson()); } else { System.out.println("No matching documents found."); } } } }
Add your connection string
In your application file, replace the <connection string URI> placeholder with your connection string. The connection string has the following format:
mongodb://localhost:<port number>/?directConnection=true
Replace the <port number> placeholder with the port number of your local deployment. Your port number can be found in Docker Desktop.
mongodb+srv://<database user>:<database password>@<cluster address>
Replace the following placeholder values:
<database user>: The database username you specified when creating your deployment.<database password>: The password for the database user.<cluster address>: The SRV address for your cluster. You can view your cluster address in the connection string you saved after creating your deployment, or by runningatlas clusters connectionStrings describe myDeploymentin your terminal and copying the text after themongodb+srv://prefix.
Run your application
Run your application from your IDE or in your shell. The output contains details about the retrieved movie document:
{ "_id": ..., "plot": "A young man is accidentally sent 30 years into the past...", "genres": ["Adventure", "Comedy", "Sci-Fi"], ... "title": "Back to the Future", ... }
Next Steps
To learn more about your MongoDB deployment, see the following resources:
To access free courses for beginners and more advanced MongoDB users, visit the MongoDB University.
Load sample data
You can run the following commands to load sample data into your deployment:
Run the following commands from your terminal to install the MongoDB Database Tools:
brew tap mongodb/brew brew trust mongodb/brew brew install mongodb-database-tools
Then, run the following commands to load the sample data:
curl https://atlas-education.s3.amazonaws.com/sampledata.archive -o sampledata.archive mongorestore --archive=sampledata.archive --port <port number>
Note
Replace the <port number> placeholder with the port number of your deployment. Your port number can be found in Docker Desktop.
atlas clusters sampleData load myDeployment
Download and install
Before you begin this tutorial, ensure that you install the following dependencies:
JDK version 8 or later
Integrated development environment (IDE), such as IntelliJ IDEA or Eclipse
In your IDE, create a new Maven project. Add the Bill of Materials (BOM) for MongoDB JVM artifacts and the Java Reactive Streams driver driver to your pom.xml file.
<dependencyManagement> <dependencies> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-bom</artifactId> <version>5.5.1</version> <type>pom</type> <scope>import</scope> </dependency> <dependency> <groupId>io.projectreactor</groupId> <artifactId>reactor-bom</artifactId> <version>2023.0.7</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>io.projectreactor</groupId> <artifactId>reactor-core</artifactId> </dependency> <dependency> <groupId>io.projectreactor</groupId> <artifactId>reactor-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-reactivestreams</artifactId> </dependency> </dependencies>
Create your application
In your project, create a new Java file in the Java package named QueryDatabase. Copy and paste the following code into the QueryDatabase file:
import com.mongodb.*; import com.mongodb.reactivestreams.client.MongoCollection; import org.bson.Document; import reactor.core.publisher.Mono; import com.mongodb.reactivestreams.client.MongoClient; import com.mongodb.reactivestreams.client.MongoClients; import com.mongodb.reactivestreams.client.MongoDatabase; import static com.mongodb.client.model.Filters.eq; public class QueryDatabase { public static void main(String[] args) { // Replace the placeholder with your Atlas connection string String uri = "<connection string URI>"; // Construct a ServerApi instance using the ServerApi.builder() method ServerApi serverApi = ServerApi.builder() .version(ServerApiVersion.V1) .build(); MongoClientSettings settings = MongoClientSettings.builder() .applyConnectionString(new ConnectionString(uri)) .serverApi(serverApi) .build(); // Create a new client and connect to the server try (MongoClient mongoClient = MongoClients.create(settings)) { MongoDatabase database = mongoClient.getDatabase("sample_mflix"); MongoCollection<Document> movies = database.getCollection("movies"); Mono.from(movies.find(eq("title", "Back to the Future"))) .doOnSuccess(i -> System.out.println(i)) .doOnError(err -> System.out.println("Error: " + err.getMessage())) .block(); } } }
Add your connection string
In your application file, replace the <connection string URI> placeholder with your connection string. The connection string has the following format:
mongodb://localhost:<port number>/?directConnection=true
Replace the <port number> placeholder with the port number of your local deployment. Your port number can be found in Docker Desktop.
mongodb+srv://<database user>:<database password>@<cluster address>
Replace the following placeholder values:
<database user>: The database username you specified when creating your deployment.<database password>: The password for the database user.<cluster address>: The SRV address for your cluster. You can view your cluster address in the connection string you saved after creating your deployment, or by runningatlas clusters connectionStrings describe myDeploymentin your terminal and copying the text after themongodb+srv://prefix.
Next Steps
To learn more about your MongoDB deployment, see the following resources:
To access free courses for beginners and more advanced MongoDB users, visit the MongoDB University.
Load sample data
You can run the following commands to load sample data into your deployment:
Run the following commands from your terminal to install the MongoDB Database Tools:
brew tap mongodb/brew brew trust mongodb/brew brew install mongodb-database-tools
Then, run the following commands to load the sample data:
curl https://atlas-education.s3.amazonaws.com/sampledata.archive -o sampledata.archive mongorestore --archive=sampledata.archive --port <port number>
Note
Replace the <port number> placeholder with the port number of your deployment. Your port number can be found in Docker Desktop.
atlas clusters sampleData load myDeployment
Create your application
Copy and paste the following code into the Program.cs file in your application:
using MongoDB.Bson; using MongoDB.Bson.IO; using MongoDB.Driver; var connectionString = Environment.GetEnvironmentVariable("MONGODB_URI"); if (connectionString == null) { Console.WriteLine("You must set your 'MONGODB_URI' environment variable. To learn how to set it, see https://www.mongodb.com/docs/drivers/csharp/current/get-started/create-connection-string"); Environment.Exit(0); } var client = new MongoClient(connectionString); var collection = client.GetDatabase("sample_mflix").GetCollection<BsonDocument>("movies"); var filter = Builders<BsonDocument>.Filter.Eq("title", "Back to the Future"); var document = collection.Find(filter).First(); Console.WriteLine(document.ToJson(new JsonWriterSettings { Indent = true }));
Add your connection string
Set your MONGODB_URI environment variable to your connection string, which has the following format:
mongodb://localhost:<port number>/?directConnection=true
Replace the <port number> placeholder with the port number of your local deployment. Your port number can be found in Docker Desktop.
mongodb+srv://<database user>:<database password>@<cluster address>
Replace the following placeholder values:
<database user>: The database username you specified when creating your deployment.<database password>: The password for the database user.<cluster address>: The SRV address for your cluster. You can view your cluster address in the connection string you saved after creating your deployment, or by runningatlas clusters connectionStrings describe myDeploymentin your terminal and copying the text after themongodb+srv://prefix.
Run your application
From your project directory, run the following command to start the application:
dotnet run csharp-quickstart.csproj
The application output contains details about the retrieved movie document:
{ _id: ..., plot: 'A young man is accidentally sent 30 years into the past...', genres: [ 'Adventure', 'Comedy', 'Sci-Fi' ], ... title: 'Back to the Future', ... }
Next Steps
To learn more about your MongoDB deployment, see the following resources:
To access free courses for beginners and more advanced MongoDB users, visit the MongoDB University.
Load sample data
You can run the following commands to load sample data into your deployment:
Run the following commands from your terminal to install the MongoDB Database Tools:
brew tap mongodb/brew brew trust mongodb/brew brew install mongodb-database-tools
Then, run the following commands to load the sample data:
curl https://atlas-education.s3.amazonaws.com/sampledata.archive -o sampledata.archive mongorestore --archive=sampledata.archive --port <port number>
Note
Replace the <port number> placeholder with the port number of your deployment. Your port number can be found in Docker Desktop.
atlas clusters sampleData load myDeployment
Download and install
Before you begin this tutorial, ensure you have the following dependencies installed in your development environment:
Compiler that supports C++17, such as GCC, Clang, or Visual Studio
CMake v3.15 or later
To download the latest version of the C++ driver from the mongo-cxx-driver Github repository, run the following commands in your shell from your root directory:
curl -OL https://github.com/mongodb/mongo-cxx-driver/releases/download/r4.1.1/mongo-cxx-driver-r4.1.1.tar.gz tar -xzf mongo-cxx-driver-r4.1.1.tar.gz cd mongo-cxx-driver-r4.1.1/build
Then, run following command from your mongo-cxx-driver-r4.1.1/build directory to configure your driver for installation:
cmake .. \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_CXX_STANDARD=17
'C:\<path>\cmake.exe' .. \ -G "Visual Studio <version> <year>" -A "x64" \ -DCMAKE_CXX_STANDARD=17 \ -DCMAKE_INSTALL_PREFIX=C:\mongo-cxx-driver \
Finally, run the following command to build and install the driver:
cmake --build . sudo cmake --build . --target install
cmake --build . --config RelWithDebInfo cmake --build . --target install --config RelWithDebInfo
Create your application
Create a new directory for your project and a file named quickstart.cpp. Copy and paste the following code into quickstart.cpp. This code connects to your cluster and queries your sample data.
using bsoncxx::builder::basic::kvp; using bsoncxx::builder::basic::make_document; int main() { mongocxx::instance instance; mongocxx::uri uri("<connection string URI>"); mongocxx::client client(uri); auto db = client["sample_mflix"]; auto collection = db["movies"]; auto result = collection.find_one(make_document(kvp("title", "The Shawshank Redemption"))); if (result) { std::cout << bsoncxx::to_json(*result) << std::endl; } else { std::cout << "No result found" << std::endl; } }
Add your connection string
In your application file, replace the <connection string URI> placeholder with your connection string. The connection string has the following format:
mongodb://localhost:<port number>/?directConnection=true
Replace the <port number> placeholder with the port number of your local deployment. Your port number can be found in Docker Desktop.
mongodb+srv://<database user>:<database password>@<cluster address>
Replace the following placeholder values:
<database user>: The database username you specified when creating your deployment.<database password>: The password for the database user.<cluster address>: The SRV address for your cluster. You can view your cluster address in the connection string you saved after creating your deployment, or by runningatlas clusters connectionStrings describe myDeploymentin your terminal and copying the text after themongodb+srv://prefix.
Run your application
In your shell, run the following commands to compile and run the application:
c++ --std=c++17 quickstart.cpp $(pkg-config --cflags --libs libmongocxx) -o ./app.out ./app.out
Tip
MacOS users might see the following error after running the preceding commands:
dyld[54430]: Library not loaded: @rpath/libmongocxx._noabi.dylib
To resolve this error, use the -Wl,-rpath linker option to set the @rpath, as shown in the following code:
c++ --std=c++17 quickstart.cpp -Wl,-rpath,/usr/local/lib/ $(pkg-config --cflags --libs libmongocxx) -o ./app.out ./app.out
The application output contains details about the retrieved movie document:
{ _id: ..., plot: 'A young man is accidentally sent 30 years into the past...', genres: [ 'Adventure', 'Comedy', 'Sci-Fi' ], ... title: 'Back to the Future', ... }
Next Steps
To learn more about your MongoDB deployment, see the following resources:
To access free courses for beginners and more advanced MongoDB users, visit the MongoDB University.
Load sample data
You can run the following commands to load sample data into your deployment:
Run the following commands from your terminal to install the MongoDB Database Tools:
brew tap mongodb/brew brew trust mongodb/brew brew install mongodb-database-tools
Then, run the following commands to load the sample data:
curl https://atlas-education.s3.amazonaws.com/sampledata.archive -o sampledata.archive mongorestore --archive=sampledata.archive --port <port number>
Note
Replace the <port number> placeholder with the port number of your deployment. Your port number can be found in Docker Desktop.
atlas clusters sampleData load myDeployment
Initialize your application
Run the following commands in your shell to create a new directory and initialize a Go application. The command also installs the Go driver.
mkdir go-quickstart cd go-quickstart go mod init go-quickstart go get go.mongodb.org/mongo-driver/v2/mongo touch main.go
mkdir go-quickstart cd go-quickstart go mod init go-quickstart go get go.mongodb.org/mongo-driver/v2/mongo type nul > main.go
Create your application
Copy and paste the following code into your main.go file. This code connects to your cluster and queries your sample data.
package main import ( "context" "encoding/json" "fmt" "log" "os" "go.mongodb.org/mongo-driver/v2/bson" "go.mongodb.org/mongo-driver/v2/mongo" "go.mongodb.org/mongo-driver/v2/mongo/options" ) func main() { uri := os.Getenv("MONGODB_URI") docs := "www.mongodb.com/docs/drivers/go/current/" if uri == "" { log.Fatal("Set your 'MONGODB_URI' environment variable. " + "See: " + docs + "usage-examples/#environment-variable") } client, err := mongo.Connect(options.Client(). ApplyURI(uri)) if err != nil { panic(err) } defer func() { if err := client.Disconnect(context.TODO()); err != nil { panic(err) } }() coll := client.Database("sample_mflix").Collection("movies") title := "Back to the Future" var result bson.M err = coll.FindOne(context.TODO(), bson.M{"title": title}). Decode(&result) if err == mongo.ErrNoDocuments { fmt.Printf("No document was found with the title %s\n", title) return } if err != nil { panic(err) } jsonData, err := json.MarshalIndent(result, "", " ") if err != nil { panic(err) } fmt.Printf("%s\n", jsonData) }
Add your connection string
Set your MONGODB_URI environment variable to your connection string, which has the following format:
mongodb://localhost:<port number>/?directConnection=true
Replace the <port number> placeholder with the port number of your local deployment. Your port number can be found in Docker Desktop.
mongodb+srv://<database user>:<database password>@<cluster address>
Replace the following placeholder values:
<database user>: The database username you specified when creating your deployment.<database password>: The password for the database user.<cluster address>: The SRV address for your cluster. You can view your cluster address in the connection string you saved after creating your deployment, or by runningatlas clusters connectionStrings describe myDeploymentin your terminal and copying the text after themongodb+srv://prefix.
Next Steps
To learn more about your MongoDB deployment, see the following resources:
To access free courses for beginners and more advanced MongoDB users, visit the MongoDB University.
Load sample data
You can run the following commands to load sample data into your deployment:
Run the following commands from your terminal to install the MongoDB Database Tools:
brew tap mongodb/brew brew trust mongodb/brew brew install mongodb-database-tools
Then, run the following commands to load the sample data:
curl https://atlas-education.s3.amazonaws.com/sampledata.archive -o sampledata.archive mongorestore --archive=sampledata.archive --port <port number>
Note
Replace the <port number> placeholder with the port number of your deployment. Your port number can be found in Docker Desktop.
atlas clusters sampleData load myDeployment
Download and install
Before you begin this tutorial, ensure that you install the following dependencies:
Kotlin installed and running on JDK 1.8 or later
Integrated development environment (IDE), such as IntelliJ IDEA or Eclipse
Create a new Maven project in your IDE. Add the Bill of Materials (BOM) for MongoDB JVM artifacts and the Kotlin Coroutine driver dependency to your pom.xml file. This code also adds a serialization package to enable the driver to convert between Kotlin objects and BSON.
<dependencyManagement> <dependencies> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-bom</artifactId> <version>5.5.1</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-sync</artifactId> </dependency> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-kotlin-sync-driver</artifactId> </dependency> <dependency> <groupId>org.mongodb</groupId> <artifactId>bson-kotlinx</artifactId> </dependency> </dependencies>
After you configure your dependencies, ensure that they are available to your project by running the dependency manager and refreshing the project in your IDE.
Create your application
Create a file called GetStarted.kt in your project. Copy and paste the following code into the file. This code connects to your cluster and queries your sample data.
import com.mongodb.client.model.Filters.eq import com.mongodb.kotlin.client.MongoClient // Create data class to represent a MongoDB document data class Movie(val title: String, val year: Int, val directors: List<String>) fun main() { // Replace the placeholder with your MongoDB deployment's connection string val uri = "<connection string URI>" val mongoClient = MongoClient.create(uri) val database = mongoClient.getDatabase("sample_mflix") val collection = database.getCollection<Movie>("movies") // Find a document with the specified title val doc = collection.find(eq(Movie::title.name, "Before Sunrise")).firstOrNull() if (doc != null) { // Print the matching document println(doc) } else { println("No matching documents found.") } }
Add your connection string
In your application file, replace the <connection string URI> placeholder with your connection string. The connection string has the following format:
mongodb://localhost:<port number>/?directConnection=true
Replace the <port number> placeholder with the port number of your local deployment. Your port number can be found in Docker Desktop.
mongodb+srv://<database user>:<database password>@<cluster address>
Replace the following placeholder values:
<database user>: The database username you specified when creating your deployment.<database password>: The password for the database user.<cluster address>: The SRV address for your cluster. You can view your cluster address in the connection string you saved after creating your deployment, or by runningatlas clusters connectionStrings describe myDeploymentin your terminal and copying the text after themongodb+srv://prefix.
Next Steps
To learn more about your MongoDB deployment, see the following resources:
To access free courses for beginners and more advanced MongoDB users, visit the MongoDB University.
Load sample data
You can run the following commands to load sample data into your deployment:
Run the following commands from your terminal to install the MongoDB Database Tools:
brew tap mongodb/brew brew trust mongodb/brew brew install mongodb-database-tools
Then, run the following commands to load the sample data:
curl https://atlas-education.s3.amazonaws.com/sampledata.archive -o sampledata.archive mongorestore --archive=sampledata.archive --port <port number>
Note
Replace the <port number> placeholder with the port number of your deployment. Your port number can be found in Docker Desktop.
atlas clusters sampleData load myDeployment
Download and install
Before you begin this tutorial, ensure that you install the following dependencies:
Kotlin installed and running on JDK 1.8 or later
Integrated development environment (IDE), such as IntelliJ IDEA or Eclipse
Create a new Maven project in your IDE. Add the Bill of Materials (BOM) for MongoDB JVM artifacts and the Kotlin Coroutine driver dependency to your pom.xml file. This code also adds a serialization package to enable the driver to convert between Kotlin objects and BSON.
<dependencyManagement> <dependencies> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-bom</artifactId> <version>5.5.1</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-kotlin-coroutine-driver</artifactId> </dependency> <dependency> <groupId>org.mongodb</groupId> <artifactId>bson-kotlinx</artifactId> </dependency> </dependencies>
After you configure your dependencies, ensure that they are available to your project by running the dependency manager and refreshing the project in your IDE.
Create your application
Create a file called GetStarted.kt in your project. Copy and paste the following code into the file. This code connects to your cluster and queries your sample data.
import com.mongodb.client.model.Filters.eq import com.mongodb.kotlin.client.coroutine.MongoClient import io.github.cdimascio.dotenv.dotenv import kotlinx.coroutines.flow.firstOrNull import kotlinx.coroutines.runBlocking import org.bson.Document fun main() { // Replace the placeholder with your MongoDB deployment's connection string val uri = <connection string URI> val mongoClient = MongoClient.create(uri) val database = mongoClient.getDatabase("sample_mflix") val collection = database.getCollection<Document>("movies") runBlocking { val doc = collection.find(eq("title", "Back to the Future")).firstOrNull() if (doc != null) { println(doc.toJson()) } else { println("No matching documents found.") } } mongoClient.close() }
Add your connection string
In your application file, replace the <connection string URI> placeholder with your connection string. The connection string has the following format:
mongodb://localhost:<port number>/?directConnection=true
Replace the <port number> placeholder with the port number of your local deployment. Your port number can be found in Docker Desktop.
mongodb+srv://<database user>:<database password>@<cluster address>
Replace the following placeholder values:
<database user>: The database username you specified when creating your deployment.<database password>: The password for the database user.<cluster address>: The SRV address for your cluster. You can view your cluster address in the connection string you saved after creating your deployment, or by runningatlas clusters connectionStrings describe myDeploymentin your terminal and copying the text after themongodb+srv://prefix.
Next Steps
To learn more about your MongoDB deployment, see the following resources:
To access free courses for beginners and more advanced MongoDB users, visit the MongoDB University.
Load sample data
You can run the following commands to load sample data into your deployment:
Run the following commands from your terminal to install the MongoDB Database Tools:
brew tap mongodb/brew brew trust mongodb/brew brew install mongodb-database-tools
Then, run the following commands to load the sample data:
curl https://atlas-education.s3.amazonaws.com/sampledata.archive -o sampledata.archive mongorestore --archive=sampledata.archive --port <port number>
Note
Replace the <port number> placeholder with the port number of your deployment. Your port number can be found in Docker Desktop.
atlas clusters sampleData load myDeployment
Initialize your application
Before you begin, ensure that you have the following dependencies installed:
Run the following commands in your shell to create a new directory and a file for your application. The command also installs the PHP driver.
mkdir php-get-started cd php-get-started touch getstarted.php pie install mongodb/mongodb-extension composer require mongodb/mongodb
mkdir php-get-started cd php-get-started type nul > getstarted.php pie install mongodb/mongodb-extension composer require mongodb/mongodb
Create your application
Copy and paste the following code into getstarted.php. This code connects to your cluster and queries your sample data.
require __DIR__ . '/../vendor/autoload.php'; $uri = getenv('MONGODB_URI') ?: throw new RuntimeException( 'Set the MONGODB_URI environment variable to your Atlas URI', ); $client = new MongoDB\Client($uri); $collection = $client->sample_mflix->movies; $filter = ['title' => 'The Shawshank Redemption']; $result = $collection->findOne($filter); if ($result) { echo json_encode($result, JSON_PRETTY_PRINT); } else { echo 'Document not found'; }
Add your connection string
Set your MONGODB_URI environment variable to your connection string, which has the following format:
mongodb://localhost:<port number>/?directConnection=true
Replace the <port number> placeholder with the port number of your local deployment. Your port number can be found in Docker Desktop.
mongodb+srv://<database user>:<database password>@<cluster address>
Replace the following placeholder values:
<database user>: The database username you specified when creating your deployment.<database password>: The password for the database user.<cluster address>: The SRV address for your cluster. You can view your cluster address in the connection string you saved after creating your deployment, or by runningatlas clusters connectionStrings describe myDeploymentin your terminal and copying the text after themongodb+srv://prefix.
Next Steps
To learn more about your MongoDB deployment, see the following resources:
To access free courses for beginners and more advanced MongoDB users, visit the MongoDB University.
Load sample data
You can run the following commands to load sample data into your deployment:
Run the following commands from your terminal to install the MongoDB Database Tools:
brew tap mongodb/brew brew trust mongodb/brew brew install mongodb-database-tools
Then, run the following commands to load the sample data:
curl https://atlas-education.s3.amazonaws.com/sampledata.archive -o sampledata.archive mongorestore --archive=sampledata.archive --port <port number>
Note
Replace the <port number> placeholder with the port number of your deployment. Your port number can be found in Docker Desktop.
atlas clusters sampleData load myDeployment
Initialize your application
Before you begin developing, ensure that you have Ruby version 2.5 or later installed.
Run the following commands in your shell to create your project directory and your application file.
mkdir ruby-get-started cd ruby-get-started touch get_started.rb
mkdir ruby-get-started cd ruby-get-started type NUL > get_started.rb
Add the following code to the get_started.rb file to add the Ruby driver with the Bundler dependency management tool:
require 'bundler/inline' gemfile do source 'https://rubygems.org' gem 'mongo' end
Create your application
Copy and paste the following code into the get_started.rb file. This code connects to your cluster and queries the sample data:
uri = '<connection string URI>' begin client = Mongo::Client.new(uri) database = client.use('sample_mflix') movies = database[:movies] # Queries for a movie that has the title 'Back to the Future' query = { title: 'Back to the Future' } movie = movies.find(query).first # Prints the movie document puts movie ensure client&.close end
Add your connection string
In your application file, replace the <connection string URI> placeholder with your connection string. The connection string has the following format:
mongodb://localhost:<port number>/?directConnection=true
Replace the <port number> placeholder with the port number of your local deployment. Your port number can be found in Docker Desktop.
mongodb+srv://<database user>:<database password>@<cluster address>
Replace the following placeholder values:
<database user>: The database username you specified when creating your deployment.<database password>: The password for the database user.<cluster address>: The SRV address for your cluster. You can view your cluster address in the connection string you saved after creating your deployment, or by runningatlas clusters connectionStrings describe myDeploymentin your terminal and copying the text after themongodb+srv://prefix.
Run your application
In your project directory, run the following command to start the application:
ruby quickstart.rb
The application output contains details about the retrieved movie document:
{"_id"=>BSON::ObjectId('...'), "plot"=>"A young man is accidentally sent 30 years into the past in a time-traveling DeLorean invented by his friend, Dr. Emmett Brown, and must make sure his high-school-age parents unite in order to save his own existence.", ... "title"=>"Back to the Future", ...
Next Steps
To learn more about your MongoDB deployment, see the following resources:
To access free courses for beginners and more advanced MongoDB users, visit the MongoDB University.
Load sample data
You can run the following commands to load sample data into your deployment:
Run the following commands from your terminal to install the MongoDB Database Tools:
brew tap mongodb/brew brew trust mongodb/brew brew install mongodb-database-tools
Then, run the following commands to load the sample data:
curl https://atlas-education.s3.amazonaws.com/sampledata.archive -o sampledata.archive mongorestore --archive=sampledata.archive --port <port number>
Note
Replace the <port number> placeholder with the port number of your deployment. Your port number can be found in Docker Desktop.
atlas clusters sampleData load myDeployment
Initialize your application
Before you begin, ensure you have Rust 1.71.1 or later, and Cargo, the Rust package manager, installed in your development environment.
For information about how to install Rust and Cargo, see the official Rust guide on downloading and installing Rust.
Initialize your application
Run the following commands in your shell to create a new Rust project:
cargo new rust-get-started cd rust-get-started
Then, add the following code to your Cargo.toml file to install the necessary dependencies:
[dependencies] serde = "1.0.188" futures = "0.3.28" tokio = {version = "1.32.0", features = ["full"]} [dependencies.mongodb] version = "3.2.4"
Create your Rust application
Replace the contents of src/main.rs with the following code. This code connects to your cluster and queries the sample data.
use mongodb::{ bson::{Document, doc}, Client, Collection }; async fn main() -> mongodb::error::Result<()> { // Replace the placeholder with your Atlas connection string let uri = "<connection string URI>"; // Create a new client and connect to the server let client = Client::with_uri_str(uri).await?; // Get a handle on the movies collection let database = client.database("sample_mflix"); let my_coll: Collection<Document> = database.collection("movies"); // Find a movie based on the title value let my_movie = my_coll.find_one(doc! { "title": "The Perils of Pauline" }).await?; // Print the document println!("Found a movie:\n{:#?}", my_movie); Ok(()) }
Add your connection string
In your application file, replace the <connection string URI> placeholder with your connection string. The connection string has the following format:
mongodb://localhost:<port number>/?directConnection=true
Replace the <port number> placeholder with the port number of your local deployment. Your port number can be found in Docker Desktop.
mongodb+srv://<database user>:<database password>@<cluster address>
Replace the following placeholder values:
<database user>: The database username you specified when creating your deployment.<database password>: The password for the database user.<cluster address>: The SRV address for your cluster. You can view your cluster address in the connection string you saved after creating your deployment, or by runningatlas clusters connectionStrings describe myDeploymentin your terminal and copying the text after themongodb+srv://prefix.
Run your Rust application
In your project directory, run the following command to start the application:
cargo run
The application output contains details about the retrieved movie document:
Found a movie: Some( Document({ "_id": ObjectId(...), "title": String( "The Perils of Pauline", ), "plot": String( "Young Pauline is left a lot of money ...", ), "runtime": Int32( 199, ), "cast": Array([ String( "Pearl White", ), String( "Crane Wilbur", ), ... ]), }), )
Next Steps
To learn more about your MongoDB deployment, see the following resources:
To access free courses for beginners and more advanced MongoDB users, visit the MongoDB University.