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.
- 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.
- 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.
- 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.
- 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.
- 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
- 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 = '
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:
### 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.
- 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.
- 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.
- 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
- 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 = "
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:
### 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.
- 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.
- 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.
- 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.
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>
- 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.");
}
}
}
}
```
- 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.
- 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.
- 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.
- 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.
```xml
- 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();
}
}
}
```
- 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.
- 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.
- 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.
- 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
- 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
var filter = Builders
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:
### 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.
- 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.
- 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.
- 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:
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
- 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
using bsoncxx::builder::basic::kvp; using bsoncxx::builder::basic::make_document;
int main() {
mongocxx::instance instance;
mongocxx::uri uri("
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:
### 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.
- 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.
- 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.
- 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
- 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)
}
```
- 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.
- 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.
- 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.
- 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.
```xml
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.
```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.")
}
} ```
- 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.
- 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.
- 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.
- 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.
```xml
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.
```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()
}
```
- 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.
- 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.
- 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.
- Initialize your application
Before you begin, ensure that you have the following dependencies install
(本文超出站点单文档体积上限,已截断)
