get-started

For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt

<!-- Tab options on this page. Append to the .md URL to filter: ?tabs=<id,...> select specific tabs (e.g. ?tabs=nodejs,shell) ?allTabs=true include every tab (no param) default: one tab per tabset

Available tabs: other tabs: macos, windows, local, cloud, configure-mac-linux, configure-windows -->

Get Started

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.

  1. 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.

### macOS

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.

shell brew install mongodb-atlas brew install --cask docker

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.

  1. 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.

### Local Deployment

This command creates a single-member replica set in a container that runs on your local machine.

shell 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:

bash Deployment created! Connection string: "<connection string URI>"

Save the connection string URI for use in a future step.

  1. Connect to your deployment

You can connect to your deployment with the MongoDB Shell (mongosh) by running the following command:

### Local Deployment

shell atlas local connect myDeployment --connectWith mongosh

After connecting, you can run the following command to test your connection:

shell 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.

  1. Load sample data

You can run the following commands to load sample data into your deployment:

### Local Deployment

Run the following commands from your terminal to install the MongoDB Database Tools:

bash brew tap mongodb/brew brew trust mongodb/brew brew install mongodb-database-tools

Then, run the following commands to load the sample data:

bash 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.

  1. 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.

### macOS

shell mkdir node-quickstart cd node-quickstart touch index.js npm init -y npm install mongodb

  1. Create your application

Copy and paste the following code into index.js. This code connects to your cluster and queries your sample data.

```javascript import { MongoClient } from 'mongodb';

async function runGetStarted() { // Replace the uri string with your connection string const 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);

```

  1. 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:

### Local Deployment

shell 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.

  1. Run your application

In your project directory, run the following command to start the application:

shell node index.js

The application output contains details about the retrieved movie document:

none { _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.

  1. Load sample data

You can run the following commands to load sample data into your deployment:

### Local Deployment

Run the following commands from your terminal to install the MongoDB Database Tools:

bash brew tap mongodb/brew brew trust mongodb/brew brew install mongodb-database-tools

Then, run the following commands to load the sample data:

bash 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.

  1. 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.

### macOS

shell mkdir pymongo-quickstart cd pymongo-quickstart touch quickstart.py python3 -m venv venv source venv/bin/activate python3 -m pip install pymongo

  1. Create your application

Copy and paste the following code into quickstart.py. This code connects to your cluster and queries your sample data.

```python from pymongo import MongoClient import json

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)

```

  1. 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:

### Local Deployment

shell 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.

  1. Run your application

From your project directory, run the following command to start the application:

shell python3 quickstart.py

The output includes details of the retrieved movie document:

none { _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.

  1. Load sample data

You can run the following commands to load sample data into your deployment:

### Local Deployment

Run the following commands from your terminal to install the MongoDB Database Tools:

bash brew tap mongodb/brew brew trust mongodb/brew brew install mongodb-database-tools

Then, run the following commands to load the sample data:

bash 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.

  1. Download and install

Before you begin this tutorial, ensure that you install the following dependencies:

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.

xml <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>

  1. 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.

```java 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.");
           }
       }
   }

}

```

  1. 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:

### Local Deployment

shell 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.

  1. Run your application

Run your application from your IDE or in your shell. The output contains details about the retrieved movie document:

```json { "_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.

  1. Load sample data

You can run the following commands to load sample data into your deployment:

### Local Deployment

Run the following commands from your terminal to install the MongoDB Database Tools:

bash brew tap mongodb/brew brew trust mongodb/brew brew install mongodb-database-tools

Then, run the following commands to load the sample data:

bash 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.

  1. Download and install

Before you begin this tutorial, ensure that you install the following dependencies:

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.

```xml org.mongodb mongodb-driver-bom 5.5.1 pom import io.projectreactor reactor-bom 2023.0.7 pom import

io.projectreactor reactor-core io.projectreactor reactor-test test org.mongodb mongodb-driver-reactivestreams ```

  1. 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:

```java 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 = "";

       // 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();
       }
   }

}

```

  1. 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:

### Local Deployment

shell 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.

  1. Run your application

Run your application from your IDE or in your shell. The output contains details about the retrieved movie document:

none { _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.

  1. Load sample data

You can run the following commands to load sample data into your deployment:

### Local Deployment

Run the following commands from your terminal to install the MongoDB Database Tools:

bash brew tap mongodb/brew brew trust mongodb/brew brew install mongodb-database-tools

Then, run the following commands to load the sample data:

bash 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.

  1. Initialize your application

Run the following commands in your shell to create a new directory and a file for your application. The command also installs the .NET/C# driver.

shell mkdir csharp-quickstart cd csharp-quickstart dotnet new console dotnet add package MongoDB.Driver

  1. Create your application

Copy and paste the following code into the Program.cs file in your application:

```csharp 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("movies");

var filter = Builders.Filter.Eq("title", "Back to the Future");

var document = collection.Find(filter).First();

Console.WriteLine(document.ToJson(new JsonWriterSettings { Indent = true }));

```

  1. Add your connection string

Set your MONGODB_URI environment variable to your connection string, which has the following format:

### Local Deployment

shell 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.

  1. Run your application

From your project directory, run the following command to start the application:

shell dotnet run csharp-quickstart.csproj

The application output contains details about the retrieved movie document:

none { _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.

  1. Load sample data

You can run the following commands to load sample data into your deployment:

### Local Deployment

Run the following commands from your terminal to install the MongoDB Database Tools:

bash brew tap mongodb/brew brew trust mongodb/brew brew install mongodb-database-tools

Then, run the following commands to load the sample data:

bash 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.

  1. Download and install

Before you begin this tutorial, ensure you have the following dependencies installed in your development environment:

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:

bash 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:

### macOS

bash cmake .. \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_CXX_STANDARD=17

Finally, run the following command to build and install the driver:

### macOS

bash cmake --build . sudo cmake --build . --target install

  1. 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.

```cpp #include #include #include

#include #include #include #include #include

using bsoncxx::builder::basic::kvp; using bsoncxx::builder::basic::make_document;

int main() { mongocxx::instance instance; mongocxx::uri 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;
   }

} ```

  1. 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:

### Local Deployment

shell 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.

  1. Run your application

In your shell, run the following commands to compile and run the application:

bash 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:

bash 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:

bash 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:

none { _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.

  1. Load sample data

You can run the following commands to load sample data into your deployment:

### Local Deployment

Run the following commands from your terminal to install the MongoDB Database Tools:

bash brew tap mongodb/brew brew trust mongodb/brew brew install mongodb-database-tools

Then, run the following commands to load the sample data:

bash 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.

  1. 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.

### macOS

shell mkdir go-quickstart cd go-quickstart go mod init go-quickstart go get go.mongodb.org/mongo-driver/v2/mongo touch main.go

  1. 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.

```go 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)

}

```

  1. Add your connection string

Set your MONGODB_URI environment variable to your connection string, which has the following format:

### Local Deployment

shell 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.

  1. Run your application

In your project directory, run the following command to start the application:

shell go run main.go

none { _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.

  1. Load sample data

You can run the following commands to load sample data into your deployment:

### Local Deployment

Run the following commands from your terminal to install the MongoDB Database Tools:

bash brew tap mongodb/brew brew trust mongodb/brew brew install mongodb-database-tools

Then, run the following commands to load the sample data:

bash 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.

  1. Download and install

Before you begin this tutorial, ensure that you install the following dependencies:

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.

```xml org.mongodb mongodb-driver-bom 5.5.1 pom import

org.mongodb mongodb-driver-sync org.mongodb mongodb-kotlin-sync-driver org.mongodb bson-kotlinx ```

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.

  1. 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.

```kotlin 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)

fun main() { // Replace the placeholder with your MongoDB deployment's connection string val 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.")
   }

} ```

  1. 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:

### Local Deployment

shell 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.

  1. Run your application

Run your application from your IDE or in your shell. The output contains details about the retrieved movie document.

none Document{{_id=..., plot=A young man and woman ..., genres=[Drama, Romance], ...}}

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.

  1. Load sample data

You can run the following commands to load sample data into your deployment:

### Local Deployment

Run the following commands from your terminal to install the MongoDB Database Tools:

bash brew tap mongodb/brew brew trust mongodb/brew brew install mongodb-database-tools

Then, run the following commands to load the sample data:

bash 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.

  1. Download and install

Before you begin this tutorial, ensure that you install the following dependencies:

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.

```xml org.mongodb mongodb-driver-bom 5.5.1 pom import

org.mongodb mongodb-kotlin-coroutine-driver org.mongodb bson-kotlinx ```

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.

  1. 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.

```kotlin 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()

}

```

  1. 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:

### Local Deployment

shell 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.

  1. Run your application

Run your application from your IDE or in your shell. The output contains details about the retrieved movie document.

none { _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.

  1. Load sample data

You can run the following commands to load sample data into your deployment:

### Local Deployment

Run the following commands from your terminal to install the MongoDB Database Tools:

bash brew tap mongodb/brew brew trust mongodb/brew brew install mongodb-database-tools

Then, run the following commands to load the sample data:

bash 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.

  1. Initialize your application

Before you begin, ensure that you have the following dependencies install

(本文超出站点单文档体积上限,已截断)