tutorial
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: linux_macos, windows, vib, json-editor, maven, gradle, fts-vs, data-explorer -->
MongoDB Search Quick Start
Get started with MongoDB Search by creating a search index, running a query, and processing the results. Select your deployment type, interface, and language to view the appropriate procedure.
MongoDB Search is an embedded full-text search feature that gives you a seamless, scalable experience for building relevance-based app features. This quick start describes how to get started in the following steps:
-
Create a MongoDB Search index on a sample collection.
-
Build a MongoDB Search query to search the collection. You will learn how to:
-
Run a basic query to search for a term in a field
-
Use an operator to refine your search
-
Add a search option to process your results
Time required: 15 minutes
Note:
This tutorial includes examples for a selection of clients. For all supported clients, see the [Indexes](https://www.mongodb.com/docs/search/indexes/manage-indexes.md#std-label-fts-manage-indexes and [Queries](https://www.mongodb.com/docs/search/query/query-ref.md#std-label-ref-query-management pages.
MongoDB Search is an embedded full-text search feature that gives you a seamless, scalable experience for building relevance-based app features. This quick start describes how to get started in the following steps:
-
Create a MongoDB Search index on a sample collection.
-
Build a MongoDB Search query to search the collection. You will learn how to:
-
Run a basic query to search for a term in a field
-
Use an operator to refine your search
-
Add a search option to process your results
Time required: 15 minutes
Note:
This tutorial includes examples for a selection of clients. For all supported clients, see the [Indexes](https://www.mongodb.com/docs/search/indexes/manage-indexes.md#std-label-fts-manage-indexes and [Queries](https://www.mongodb.com/docs/search/query/query-ref.md#std-label-ref-query-management pages.
MongoDB Search is an embedded full-text search feature that gives you a seamless, scalable experience for building relevance-based app features. This quick start demonstrates how to get started in the following steps:
- Deploy MongoDB Search in Docker.
For more details on deploying by using a tarball, see [Install and Deploy MongoDB Search on Linux.](https://www.mongodb.com/docs/search/self-managed/current/installation/linux.md#std-label-mongot-deployment-on-linux
-
Load sample data into a MongoDB cluster.
-
Create a MongoDB Search index on a sample collection.
-
Build a MongoDB Search query to search the collection.
Time required: 20 minutes
Note:
The resulting set up of this quick start is not secure. For more information on securing your deployment, see [Security for Self-Managed Deployments.](https://www.mongodb.com/docs/manual/administration/security-checklist.md#std-label-security-checklist
Architecture
This tutorial creates the following architecture:
-
A MongoDB Community Edition Server (
mongod) with a single node replica set on port 27017 -
A MongoDB Search (
mongot) search engine component on port 27028 -
Persistant data volumes on both ports
-
Pre-loaded sample data
Note:
For a production deployment, MongoDB recommends that you use a replica set with at least three members.
Before You Begin
Before you begin, you must complete the following prerequisites:
-
Download Docker v4.40 or later
-
Download Docker Compose
-
Download the
curlcommand -
Download
mongoshlocally or have access to it through Docker
Set Up Your Cluster
Set up your Atlas cluster.
Create a free Atlas account or sign in to an existing account.
If you don't yet have an Atlas cluster, create a free M0 cluster. To learn more about creating an Atlas cluster, see [Create a Cluster.](https://www.mongodb.com/docs/atlas/tutorial/create-new-cluster.md#std-label-create-new-cluster
IMPORTANT: If you are working with an existing cluster, you must have [Project Data Access Admin](https://www.mongodb.com/docs/atlas/reference/user-roles.md#mongodb-authrole-Project-Data-Access-Admin or higher [access](https://www.mongodb.com/docs/atlas/access/manage-project-access.md#std-label-who-can-access-project to your Atlas project.
If you create a new cluster, you have the necessary permissions by default.
You can create only one M0 Free cluster per [project.](https://www.mongodb.com/docs/atlas/atlas-ui-authorization.md#std-label-atlas-ui-auth-projects
Load the sample dataset.
If you haven't yet loaded the [sample dataset](https://www.mongodb.com/docs/vector-search/tutorials/quick-start.md#std-label-vector-search-quickstart-sample-data for this quick start onto your cluster, [load](https://www.mongodb.com/docs/atlas/import/load-sample-data.md#std-label-load-sample-data the sample_mflix sample database onto your cluster.
If you already loaded the sample_mflix dataset, check.
Loading the sample dataset can take several minutes to complete.
In the left sidebar, click Search & Vector Search. Choose your cluster from the Select data source menu and click Go to Atlas Search.
Install the dependencies.
Install the Atlas CLI.
If you use [Homebrew](https://brew.sh/#install, you can run the following command in your terminal:
brew install mongodb-atlas
For installation instructions on other operating systems, see Install the Atlas CLI
Install Docker.
Docker requires a network connection for pulling and caching MongoDB images.
-
For MacOS or Windows, install [Docker Desktop v4.31+.](https://docs.docker.com/desktop/release-notes/#4310
-
For Linux, install Docker Engine v27.0+.
-
For RHEL, you can also use Podman v5.0+.
Install the MongoDB Database Tools.
You must install the MongoDB Command Line Database Tools to access the mongorestore command, which you'll use to load the sample data.
Set up your local Atlas deployment.
If you don't have an existing Atlas account, run atlas setup in your terminal or create a new account.
Run atlas deployments setup and follow the prompts to create a local deployment. When prompted to connect to the deployment, select skip.
For detailed instructions, see [Create a Local Atlas Deployment.](https://www.mongodb.com/docs/atlas/cli/current/atlas-cli-deploy-local/#create-a-local-atlas-deployment-1
Load the sample data.
Run the following command in your terminal to download the sample data:
curl https://atlas-education.s3.amazonaws.com/sampledata.archive -o sampledata.archive
Run the following command to load the data into your deployment, replacing <port-number> with the port where you're hosting the deployment:
mongorestore --archive=sampledata.archive --port=<port-number>
- Pull the
mongotDocker image.
To pull the mongot Docker image, run the following command:
shell
docker pull mongodb/mongodb-community-search:latest
To verify the image is on your Docker Desktop, run the following command:
shell
docker image ls mongodb/mongodb-community-search
- Create a Docker network.
To create a docker network for inter-container communication between the database and search containers, run the following command:
shell
docker network create search-community
- Download the MongoDB Docker image.
To download the MongoDB Docker image, run the following command:
shell
docker pull mongodb/mongodb-community-server:latest
Note:
You must have a minimum of MongoDB 8.3+ to use MongoDB Search with an on-prem deployment. For more information, see MongoDB Search Compatibility.
For additional details on installing MongoDB with Docker, see Install MongoDB Community with Docker.
- Create a
mongotsync-user password file.
Create a password file for mongot to connect to mongod. Select your operating system and run the command:
### Linux/MacOS
Replace <mongot_password> with your password and run the following command to create a file called passwordFile in your current directory:
shell
echo -n "<mongot_password>" > passwordFile
chmod 400 passwordFile
Note:
The -n flag prevents a trailing newline.
- Create your mongod configuration file.
To create your configuration file, save the following code to mongod.conf or your preferred location.
```yaml # MongoDB Configuration File
# Network configuration net: port: 27017 bindIpAll: true # Equivalent to --bind_ip_all
# Replica set configuration
replication:
replSetName: rs0
# Search configuration parameters
setParameter:
# Server parameters to advise mongod of mongot availability for search index management and querying
searchIndexManagementHostAndPort: mongot-community.search-community:27028
mongotHost: mongot-community.search-community:27028
skipAuthenticationToSearchIndexManagementServer: false
useGrpcForSearch: true
searchTLSMode: disabled
```
- Start your
mongod.
To start the mongod:
-
Replace
</path/to/data/db>with the path to the local directory for the mounted volume. -
Replace
</path/to/mongod.conf>with the path to the configuration file you created above. -
On Windows, replace the backslash (
\) at the end of each line with the line continuation character for your shell. Command Prompt uses a caret (^), and PowerShell uses a backtick.
shell
docker run --rm \
--name mongod \
-v </path/to/mongod.conf>:/etc/mongod.conf:ro \
-v </path/to/data/db>:/data/db \
-p 27017:27017 \
--network search-community \
mongodb/mongodb-community-server:latest \
--config /etc/mongod.conf \
--replSetMember=mongod.search-community:27017
- In a new shell, start
mongosh.
Run the following command to connect to the mongod instance you started on port 27017:
shell
docker exec -it mongod mongosh --port 27017
- Create a user for the
mongotprocess on your MongoDB deployment.
mongot must be able to connect to your MongoDB deployment through a user with the [searchCoordinator](https://www.mongodb.com/docs/manual/reference/built-in-roles.md#mongodb-authrole-searchCoordinator role.
Run the following command to connect to the admin database:
javascript
use admin
To create a user with the searchCoordinator role:
-
Replace
<mongot_username>with a username for yourmongotuser. -
Replace
<mongot_password>with the password that you specified in yourpasswordFilein step 4. -
Run the following command:
javascript
db.createUser(
{
user: "<mongot_username>",
pwd: "<mongot_password>",
roles: [ "searchCoordinator" ]
}
)
For more information on creating users, see [Create a User on Self-Managed Deployments.](https://www.mongodb.com/docs/manual/tutorial/create-users.md#std-label-create-users
- Specify your search configuration options.
You can configure mongot with a YAML configuration file. You must specify the username that you specified in the previous step as the syncSource.replicaSet.scramAuth.username. You must also specify the passwordFile that you created in the previous step as the syncSource.replicaSet.scramAuth.passwordFile.
For more information on mongot configuration options, see [mongot Options.](https://www.mongodb.com/docs/manual/reference/configuration-options.md#std-label-mongot-configuration-options
For example, you can adapt the settings to your local configuration as shown below:
```yaml # mongot.conf syncSource: replicaSet: hostAndPort: "mongod.search-community:27017" scramAuth: username: "mongotUser" passwordFile: "/passwordFile" authSource: "admin" tls: enabled: false replicationReader: readPreference: "secondaryPreferred"
storage: dataPath: "/data/mongot"
server: grpc: address: "mongot-community.search-community:27028" tls: mode: "disabled"
metrics: enabled: true address: "mongot-community.search-community:9946"
healthCheck: address: "mongot-community.search-community:8080"
logging: verbosity: INFO ```
Save your file to mongot.config or your preferred file location.
Both containers run on the same search-community Docker network.
-
Start the mongot process.
To start the Search in Community binary (
mongot), select your operating system and run the command:Linux/MacOS
-
Replace
</path/to/data/mongot>with the path to the local directory for the mounted volume to storemongotdata. -
Replace
</path/to/mongot.conf>with the path to themongotconfiguration file that you created in the previous step. -
Replace
</path/to/passwordFile>with the path to the password file that you created.
shell docker run --rm \ --name mongot-community \ -v </path/to/data/mongot>:/data/mongot \ -v </path/to/mongot.conf>:/mongot-community/config.default.yml \ -v </path/to/passwordFile>:/passwordFile:ro \ --network search-community \ -p 8080:8080 \ -p 9946:9946 \ mongodb/mongodb-community-search:latestThis command:
-
Mounts the volume.
-
Mounts a configuration file from a local volume.
-
Specifies the port range.
-
Exposes the metrics port.
-
Starts the container on the
search-communityDocker network with a container namedmongot-community.
-
-
Verify the health of the
mongotprocess.To verify, send a request by using a HTTP (HyperText Transport Protocol) client or
curlto the/healthendpoint. For example, send acurlrequest similar to the following sample request:shell curl localhost:8080/healthThe endpoint returns one of the following in the response:
SERVING, if themongotprocess is running
mongotmight not serve queries as it doesn't check the status of the indexes, which must be inReadystate to serve queries.NOT_SERVING, if themongotprocess isn't running
For more information, see [Verify Your mongot Connection.](https://www.mongodb.com/docs/search/self-managed/current/connection/verify-connection.md#std-label-mongot-verify-connection
Define and Create a MongoDB Search Index
What is a Search Index?
A MongoDB Search index is a data structure that categorizes data in an easily searchable format. It maps terms with documents that contain those terms to enable fast retrieval of documents at query-time.
You must configure a MongoDB Search index to query data using MongoDB Search. We recommend that you index the fields that you regularly use to sort or filter your data.
To learn more, see [Supported Clients.](https://www.mongodb.com/docs/search/indexes/manage-indexes.md#std-label-fts-manage-indexes
In this section, you create a MongoDB Search index on the sample [movies](https://www.mongodb.com/docs/manual/sample-data/sample-mflix.md#std-label-mflix-movies collection.
-
When the sample data finishes loading, click Create Search Index.
-
Make the following selections on the page and then click Next.
| Search Type | Select the MongoDB Search index type. |
|---|---|
| Index Name and Data Source | Specify the following information: Index Name: default; Database and Collection:sample_mflix; movies |
| Configuration Method | For a guided experience, select Visual Editor.To edit the raw index definition, select JSON Editor. |
- Define the index.
The following index definition dynamically indexes the fields in the movies collection.
### Visual Editor
Review the “default” index definition for the movies collection.
-
Click Create Search Index.
-
Wait for the index to finish building.
The index should take about one minute to build. While it is building, the Status column reads Build in
Progress. When it is finished building, the Status column reads Active.
1) Connect to the cluster using [mongosh](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh.
Open [mongosh](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh in a terminal window and connect to your Atlas cluster. For detailed instructions on connecting, see [Connect via mongosh.](https://www.mongodb.com/docs/atlas/mongo-shell-connection.md#std-label-connect-mongo-shell
2) Switch to the database that contains the collection for which you want to create the index.
Example:
shell
use sample_mflix
Output:
shell
switched to db sample_mflix
3) Run the [db.collection.createSearchIndex()](https://www.mongodb.com/docs/manual/reference/method/db.collection.createSearchIndex.md#mongodb-method-db.collection.createSearchIndex method to create the index.
shell
db.movies.createSearchIndex(
"default",
{ mappings: { dynamic: true } }
)
Output:
text
default
- Connect to your cluster via MongoDB Compass.
Open Compass and connect to your cluster. For detailed instructions, see [Connect to a Cluster via Compass.](https://www.mongodb.com/docs/atlas/compass-connection.md#std-label-atlas-connect-via-compass
- Specify the database and collection.
On the Database screen, click the sample_mflix database, then click the movies collection.
- Create the MongoDB Search index.
Click the Indexes tab, then select Search Indexes.
Click Create Index to open the index creation dialog box.
Specify a name for the index.
Your MongoDB Search index is named default by default. If you keep this name, then your index will be the default Search index for any MongoDB Search query that does not specify a different index option in its [operators](https://www.mongodb.com/docs/search/query/operators-collectors/overview.md#std-label-fts-operators. If you are creating multiple indexes, we recommend that you maintain a consistent, descriptive naming convention across your indexes.
Specify the JSON (Javascript Object Notation) MongoDB Search index definition.
json
{
"mappings": {
"dynamic": true|false,
"fields": {
"<field-name>": {
"type": "string",
"analyzer": "<atlas-search-analyzer>",
"searchAnalyzer": "<atlas-search-analyzer>",
"indexOptions": "docs|freqs|positions|offsets",
"store": true|false,
"ignoreAbove": <integer>,
"similarity": { "type": "bm25|boolean|stableTfl" },
"multi": { <string-field-definition> },
"norms": "include|omit"
}
}
}
}
Click Create Search Index.
1) Set up and initialize the .NET/C# project.
text
# Create a new directory and initialize the project
mkdir atlas-search-quickstart && cd atlas-search-quickstart
dotnet new console
text
# Add the MongoDB .NET/C# Driver to your project
dotnet add package MongoDB.Driver
For more detailed installation instructions, see the MongoDB .NET/C# Driver documentation.
2) Define the index.
Paste the following code into the Program.cs file.
```csharp using MongoDB.Bson; using MongoDB.Driver;
// connect to your Atlas deployment
var uri = "
var client = new MongoClient(uri);
var db = client.GetDatabase("sample_mflix");
var collection = db.GetCollection
// define your MongoDB Search index var index = new CreateSearchIndexModel( "default", new BsonDocument { { "mappings", new BsonDocument { { "dynamic", true } } } });
var result = collection.SearchIndexes.CreateOne(index); Console.WriteLine(result);
```
Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.
To learn more about finding your connection string, see [Connect to a Cluster via Client Libraries.](https://www.mongodb.com/docs/atlas/driver-connection.md#std-label-connect-via-driver
Note:
For a local or self-managed deployment, your connection string should use the following format:
text
mongodb://localhost:<port-number>/?directConnection=true
To learn more, see [Connection Strings.](https://www.mongodb.com/docs/manual/reference/connection-string.md#std-label-mongodb-uri
3) Create the index.
shell
dotnet run Program.cs
Output:
text
default
- Set up and initialize the Go module.
text
# Create a new directory and initialize the project
mkdir atlas-search-quickstart && cd atlas-search-quickstart
go mod init atlas-search-quickstart
text
# Add the MongoDB Go Driver to your project
go get go.mongodb.org/mongo-driver/v2/mongo
For more detailed installation instructions, see the [MongoDB Go Driver documentation.](https://www.mongodb.com/docs/drivers/go/current/get-started.md#std-label-go-get-started
- Define the index.
Paste the following code into a file named create-index.go.
```go package main
import ( "context" "log"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)
func main() { ctx := context.Background()
// Replace the placeholder with your Atlas connection string
const uri = "<connection-string>"
// Connect to your Atlas cluster
clientOptions := options.Client().ApplyURI(uri)
client, err := mongo.Connect(clientOptions)
if err != nil {
log.Fatalf("failed to connect to the server: %v", err)
}
defer func() { _ = client.Disconnect(ctx) }()
// Set the namespace
coll := client.Database("<database-name>").Collection("<collection-name>")
// Define a simple MongoDB Search index
indexName := "<index-name>"
// Create the default definition for search index
definition := bson.D{{"mappings", bson.D{{"dynamic", true}}}}
indexModel := mongo.SearchIndexModel{
Definition: definition,
Options: options.SearchIndexes().SetName(indexName),
}
// Create the index
searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, indexModel)
if err != nil {
log.Fatalf("failed to create the search index: %v", err)
}
log.Println("New search index named " + searchIndexName + " is building.")
}
```
Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.
To learn more about finding your connection string, see [Connect to a Cluster via Client Libraries.](https://www.mongodb.com/docs/atlas/driver-connection.md#std-label-connect-via-driver
Note:
For a local or self-managed deployment, your connection string should use the following format:
text
mongodb://localhost:<port-number>/?directConnection=true
To learn more, see [Connection Strings.](https://www.mongodb.com/docs/manual/reference/connection-string.md#std-label-mongodb-uri
- Create the index.
shell
go run create-index.go
Output:
text
New search index named default is building.
1) Add the Java driver version 4.11 or higher as a dependency in your Java project.
Select one of the following tabs, depending on your package manager:
### Maven
If you are using Maven, add the following dependencies to the dependencies array in your project's pom.xml file:
xml
<dependencies>
<!-- MongoDB Java Sync Driver v4.11.0 or later -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>[4.11.0,)</version> </dependency> </dependencies> 2) Run your package manager to install the dependencies to your project. For more detailed installation instructions and version compatibility, see the [MongoDB Java Driver documentation.](https://www.mongodb.com/docs/drivers/java/sync/current/quick-start/#std-label-add-mongodb-dependency
3) Define the index.
Paste the following example into a file named CreateIndex.java.
```java import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document;
public class CreateIndex {
public static void main(String[] args) {
// connect to your Atlas cluster
String uri = “
try (MongoClient mongoClient = MongoClients.create(uri)) {
// set namespace
MongoDatabase database = mongoClient.getDatabase(“<databaseName>”);
MongoCollection<Document> collection = database.getCollection(“<collectionName>”);
Document index = new Document(“mappings”,
new Document(“dynamic”, true));
collection.createSearchIndex(“<index-name>”, index);
}
}
}
```
Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.
To learn more about finding your connection string, see [Connect to a Cluster via Client Libraries.](https://www.mongodb.com/docs/atlas/driver-connection.md#std-label-connect-via-driver
Note:
For a local or self-managed deployment, your connection string should use the following format:
text
mongodb://localhost:<port-number>/?directConnection=true
To learn more, see [Connection Strings.](https://www.mongodb.com/docs/manual/reference/connection-string.md#std-label-mongodb-uri
4) Compile and run the file to create the index.
shell
javac CreateIndex.java
java CreateIndex
- Install the MongoDB Kotlin Coroutine Driver.
Create a new Kotlin project and install the [MongoDB Kotlin Coroutine Driver documentation.](https://www.mongodb.com/docs/drivers/kotlin/coroutine/current/getting-started.md#std-label-kotlin-quickstart
- Define the index.
Create a file named CreateIndex.kt. Copy and paste the following code into the file.
```kotlin import com.mongodb.MongoException import com.mongodb.client.model.SearchIndexModel import com.mongodb.client.model.SearchIndexType import com.mongodb.kotlin.client.coroutine.MongoClient import kotlinx.coroutines.runBlocking import org.bson.Document
fun main() {
// Replace the placeholder with your MongoDB deployment's connection string
val uri = “
Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.
To learn more about finding your connection string, see [Connect to a Cluster via Client Libraries.](https://www.mongodb.com/docs/atlas/driver-connection.md#std-label-connect-via-driver
Note:
For a local or self-managed deployment, your connection string should use the following format:
text
mongodb://localhost:<port-number>/?directConnection=true
To learn more, see [Connection Strings.](https://www.mongodb.com/docs/manual/reference/connection-string.md#std-label-mongodb-uri
- Run the
CreateIndex.ktfile in your IDE.
1) Initialize your Node.js project.
text
# Create a new directory and initialize the project
mkdir atlas-search-quickstart && cd atlas-search-quickstart
npm init -y
text
# Add the MongoDB Node.js Driver to your project
npm install mongodb
For detailed installation instructions, see the MongoDB Node Driver documentation.
2) Define the index.
Paste the following code into a file named create-index.js.
```javascript const { MongoClient } = require(“mongodb”);
// connect to your Atlas deployment
const uri =
“
const client = new MongoClient(uri);
async function run() { try {
// set namespace
const database = client.db(“sample_mflix”);
const collection = database.collection(“movies”);
// define your MongoDB Search index
const index = {
name: “default”,
definition: {
/* search index definition fields */
“mappings”: {
“dynamic”: true
}
}
}
// run the helper method
const result = await collection.createSearchIndex(index);
console.log(result);
} finally {
await client.close();
}
}
run().catch(console.dir);
```
Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.
To learn more about finding your connection string, see [Connect to a Cluster via Client Libraries.](https://www.mongodb.com/docs/atlas/driver-connection.md#std-label-connect-via-driver
Note:
For a local or self-managed deployment, your connection string should use the following format:
text
mongodb://localhost:<port-number>/?directConnection=true
To learn more, see [Connection Strings.](https://www.mongodb.com/docs/manual/reference/connection-string.md#std-label-mongodb-uri
3) Create the index.
shell
node create-index.js
Output:
text
default
- Install the MongoDB Python Driver.
sh
pip install pymongo
For detailed installation instructions, see [MongoDB Python Driver (PyMongo).](https://www.mongodb.com/docs/languages/python/pymongo-driver/get-started.md#std-label-pymongo-get-started-download-and-install
- Define the index.
Paste the following code into a file named create_index.py.
```python from pymongo import MongoClient from pymongo.operations import SearchIndexModel
# connect to your Atlas deployment
uri = “
# set namespace database = client[“sample_mflix”] collection = database[“movies”]
# define your MongoDB Search index search_index_model = SearchIndexModel( definition={ “mappings”: { “dynamic”: True }, }, name=“default”, )
# create the index result = collection.create_search_index(model=search_index_model) print(result)
```
Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.
To learn more about finding your connection string, see [Connect to a Cluster via Client Libraries.](https://www.mongodb.com/docs/atlas/driver-connection.md#std-label-connect-via-driver
Note:
For a local or self-managed deployment, your connection string should use the following format:
text
mongodb://localhost:<port-number>/?directConnection=true
To learn more, see [Connection Strings.](https://www.mongodb.com/docs/manual/reference/connection-string.md#std-label-mongodb-uri
- Create the index.
shell
python create_index.py
Output:
text
default
1) Initialize your Rust project.
text
# Create a new Rust project
cargo new atlas-search-quickstart && cd atlas-search-quickstart
Add the following dependencies to your Cargo.toml file:
```text [dependencies] serde = “1.0” futures = “0.3” tokio = {version = “1.0”, features = [“full”]}
[dependencies.mongodb] version = “3.0” ```
For detailed installation instructions, see the [MongoDB Rust Driver Download and Install](https://www.mongodb.com/docs/drivers/rust/current/get-started.md#std-label-rust-quick-start-download-and-install guide.
2) Define the index.
Paste the following code into src/main.rs.
```rust use mongodb::bson::{doc, Document}; use mongodb::{Client, Collection, SearchIndexModel, SearchIndexType};
#[tokio::main]
async fn main() -> mongodb::error::Result<()> {
// Connects to your Atlas deployment
let uri =
“
let client = Client::with_uri_str(uri).await?;
// Sets the namespace
let collection: Collection<Document> = client
.database(“sample_mflix”)
.collection(“movies”);
// Defines your MongoDB Search index
let index = doc! {
“mappings”: doc! {
“dynamic”: true
}
};
let idx_model = SearchIndexModel::builder()
.definition(index)
.name(“search_idx”.to_string())
.index_type(SearchIndexType::Search)
.build();
// Runs the helper method
let result = collection.create_search_index(idx_model).await?;
println!(“{}”, result);
Ok(())
}
```
Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.
To learn more about finding your connection string, see [Connect to a Cluster via Client Libraries.](https://www.mongodb.com/docs/atlas/driver-connection.md#std-label-connect-via-driver
Note:
For a local or self-managed deployment, your connection string should use the following format:
text
mongodb://localhost:<port-number>/?directConnection=true
To learn more, see [Connection Strings.](https://www.mongodb.com/docs/manual/reference/connection-string.md#std-label-mongodb-uri
3) Create the index.
shell
cargo run
Output:
text
search_idx
- Connect to the cluster using [
mongosh](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh.
Open [mongosh](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh in a terminal window and connect to your Atlas cluster. For detailed instructions on connecting, see [Connect via mongosh.](https://www.mongodb.com/docs/atlas/mongo-shell-connection.md#std-label-connect-mongo-shell
- Switch to the database that contains the collection for which you want to create the index.
Example:
shell
use sample_mflix
Output:
shell
switched to db sample_mflix
- Run the [
db.collection.createSearchIndex()](https://www.mongodb.com/docs/manual/reference/method/db.collection.createSearchIndex.md#mongodb-method-db.collection.createSearchIndex method to create the index.
shell
db.movies.createSearchIndex(
“default”,
{ mappings: { dynamic: true } }
)
Output:
text
default
1) Connect to your cluster via MongoDB Compass.
Open Compass and connect to your cluster. For detailed instructions, see [Connect to a Cluster via Compass.](https://www.mongodb.com/docs/atlas/compass-connection.md#std-label-atlas-connect-via-compass
2) Specify the database and collection.
On the Database screen, click the sample_mflix database, then click the movies collection.
3) Create the MongoDB Search index.
Click the Indexes tab, then select Search Indexes.
Click Create Index to open the index creation dialog box.
Specify a name for the index.
Your MongoDB Search index is named default by default. If you keep this name, then your index will be the default Search index for any MongoDB Search query that does not specify a different index option in its [operators](https://www.mongodb.com/docs/search/query/operators-collectors/overview.md#std-label-fts-operators. If you are creating multiple indexes, we recommend that you maintain a consistent, descriptive naming convention across your indexes.
Specify the JSON (Javascript Object Notation) MongoDB Search index definition.
json
{
“mappings”: {
“dynamic”: true|false,
“fields”: {
“<field-name>”: {
“type”: “string”,
“analyzer”: “<atlas-search-analyzer>”,
“searchAnalyzer”: “<atlas-search-analyzer>”,
“indexOptions”: “docs|freqs|positions|offsets”,
“store”: true|false,
“ignoreAbove”: <integer>,
“similarity”: { “type”: “bm25|boolean|stableTfl” },
“multi”: { <string-field-definition> },
“norms”: “include|omit”
}
}
}
}
Click Create Search Index.
- Set up and initialize the .NET/C# project.
text
# Create a new directory and initialize the project
mkdir atlas-search-quickstart && cd atlas-search-quickstart
dotnet new console
text
# Add the MongoDB .NET/C# Driver to your project
dotnet add package MongoDB.Driver
For more detailed installation instructions, see the MongoDB .NET/C# Driver documentation.
- Define the index.
Paste the following code into the Program.cs file.
```csharp using MongoDB.Bson; using MongoDB.Driver;
// connect to your Atlas deployment
var uri = “
var client = new MongoClient(uri);
var db = client.GetDatabase(“sample_mflix”);
var collection = db.GetCollection
// define your MongoDB Search index var index = new CreateSearchIndexModel( “default”, new BsonDocument { { “mappings”, new BsonDocument { { “dynamic”, true } } } });
var result = collection.SearchIndexes.CreateOne(index); Console.WriteLine(result);
```
Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.
To learn more about finding your connection string, see [Connect to a Cluster via Client Libraries.](https://www.mongodb.com/docs/atlas/driver-connection.md#std-label-connect-via-driver
Note:
For a local or self-managed deployment, your connection string should use the following format:
text
mongodb://localhost:<port-number>/?directConnection=true
To learn more, see [Connection Strings.](https://www.mongodb.com/docs/manual/reference/connection-string.md#std-label-mongodb-uri
- Create the index.
shell
dotnet run Program.cs
Output:
text
default
1) Set up and initialize the Go module.
text
# Create a new directory and initialize the project
mkdir atlas-search-quickstart && cd atlas-search-quickstart
go mod init atlas-search-quickstart
text
# Add the MongoDB Go Driver to your project
go get go.mongodb.org/mongo-driver/v2/mongo
For more detailed installation instructions, see the [MongoDB Go Driver documentation.](https://www.mongodb.com/docs/drivers/go/current/get-started.md#std-label-go-get-started
2) Define the index.
Paste the following code into a file named create-index.go.
```go package main
import ( “context” “log”
“go.mongodb.org/mongo-driver/v2/bson”
“go.mongodb.org/mongo-driver/v2/mongo”
“go.mongodb.org/mongo-driver/v2/mongo/options”
)
func main() { ctx := context.Background()
// Replace the placeholder with your Atlas connection string
const uri = “<connection-string>”
// Connect to your Atlas cluster
clientOptions := options.Client().ApplyURI(uri)
client, err := mongo.Connect(clientOptions)
if err != nil {
log.Fatalf(“failed to connect to the server: %v”, err)
}
defer func() { _ = client.Disconnect(ctx) }()
// Set the namespace
coll := client.Database(“<database-name>”).Collection(“<collection-name>”)
// Define a simple MongoDB Search index
indexName := “<index-name>”
// Create the default definition for search index
definition := bson.D{{“mappings”, bson.D{{“dynamic”, true}}}}
indexModel := mongo.SearchIndexModel{
Definition: definition,
Options: options.SearchIndexes().SetName(indexName),
}
// Create the index
searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, indexModel)
if err != nil {
log.Fatalf(“failed to create the search index: %v”, err)
}
log.Println(“New search index named ” + searchIndexName + “ is building.”)
}
```
Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.
To learn more about finding your connection string, see [Connect to a Cluster via Client Libraries.](https://www.mongodb.com/docs/atlas/driver-connection.md#std-label-connect-via-driver
Note:
For a local or self-managed deployment, your connection string should use the following format:
text
mongodb://localhost:<port-number>/?directConnection=true
To learn more, see [Connection Strings.](https://www.mongodb.com/docs/manual/reference/connection-string.md#std-label-mongodb-uri
3) Create the index.
shell
go run create-index.go
Output:
text
New search index named default is building.
- Add the Java driver version 4.11 or higher as a dependency in your Java project.
Select one of the following tabs, depending on your package manager:
### Maven
If you are using Maven, add the following dependencies to the dependencies array in your project's pom.xml file:
xml
<dependencies>
<!-- MongoDB Java Sync Driver v4.11.0 or later -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>[4.11.0,)</version> </dependency> </dependencies> 2. Run your package manager to install the dependencies to your project. For more detailed installation instructions and version compatibility, see the [MongoDB Java Driver documentation.](https://www.mongodb.com/docs/drivers/java/sync/current/quick-start/#std-label-add-mongodb-dependency
- Define the index.
Paste the following example into a file named CreateIndex.java.
```java import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document;
public class CreateIndex { public static void main(String[] args) { // c
(本文超出站点单文档体积上限,已截断)
