quick-start
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, windows-2, vib, jsoneditor, cloud, local, maven, gradle, Asynchronous API, Synchronous API, async, sync -->
MongoDB Vector Search Quick Start Tutorial
Important:
Automated Embeddings is available as a Preview feature. The feature and the corresponding documentation might change at any time during the Preview period. Do not use this feature in your production environment. We do not use any customer data from this feature to train our models at this time. To learn more, see Preview Features.
About This Task
This quick start describes how to load sample documents that contain vector embeddings into your cluster, create a MongoDB Vector Search index on those embeddings, and then perform semantic search to return documents that are similar to your query.
Time required: 15 minutes
Objectives
In this quick start, you complete the following steps:
-
Create an index definition for the
sample_mflix.embedded_moviescollection that indexes theplot_embedding_voyage_3_largefield as thevectortype. Theplot_embedding_voyage_3_largefield contains embeddings created using Voyage AI'svoyage-3-largeembedding model. The index definition specifies2048vector dimensions and measures similarity usingdotProduct. -
Run a MongoDB Vector Search query that searches the sample
sample_mflix.embedded_moviescollection. The query uses the [$vectorSearch](https://www.mongodb.com/docs/vector-search/query/aggregation-stages/vector-search-stage.md#mongodb-pipeline-pipe.-vectorSearch stage to search theplot_embedding_voyage_3_largefield, which contains embeddings created using Voyage AI'svoyage-3-largeembedding model. The query searches theplot_embedding_voyage_3_largefield using vector embeddings for the string time travel. It considers up to150nearest neighbors, and returns10documents in the results.
To learn more, see [Learning Summary.](https://www.mongodb.com/docs/vector-search/tutorials/quick-start.md#std-label-avs-qs-learning-summary
This quick start describes how to create a local Atlas deployment with sample data loaded into the deployment, create a MongoDB Vector Search index for the sample data, and then perform semantic search to return documents that are similar to your query.
Time required: 15 minutes
Objectives
In this quick start, you complete the following steps:
- Deploy Atlas locally via Atlas CLI with sample data loaded.
To create a local Atlas deployment using Docker commands, see [Create a Local Atlas Deployment with Docker.](https://www.mongodb.com/docs/atlas/cli/atlas-cli-deploy-docker.md#std-label-atlas-cli-deploy-docker
-
Create an index definition for the
sample_mflix.embedded_moviescollection that indexes theplot_embedding_voyage_3_largefield as thevectortype. Theplot_embedding_voyage_3_largefield contains embeddings created using Voyage AI'svoyage-3-largeembedding model. The index definition specifies2048vector dimensions and measures similarity usingdotProduct. -
Run a MongoDB Vector Search query that searches the sample
sample_mflix.embedded_moviescollection. The query uses the [$vectorSearch](https://www.mongodb.com/docs/vector-search/query/aggregation-stages/vector-search-stage.md#mongodb-pipeline-pipe.-vectorSearch stage to search theplot_embedding_voyage_3_largefield, which contains embeddings created using Voyage AI'svoyage-3-largeembedding model. The query searches theplot_embedding_voyage_3_largefield using vector embeddings for the string time travel. It considers up to150nearest neighbors, and returns10documents in the results.
To learn more, see [Learning Summary.](https://www.mongodb.com/docs/vector-search/tutorials/quick-start.md#std-label-avs-qs-learning-summary
Before You Begin
Before you begin, you must download the following:
-
Docker
-
Atlas CLI v5.3.1 or later
-
[
mongosh](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh
This quick start demonstrates how to deploy MongoDB Search and MongoDB Vector Search in Docker, load sample data into the MongoDB cluster, create a MongoDB Vector Search index for the sample data, and run vector search queries against the sample data.
Time required: 20 minutes
Objectives
The quick start walks you through the following steps:
- Deploy MongoDB and
mongotin Docker.
For more details on deploying by using a tarball or as an image in Docker, see [Install MongoDB Community and MongoDB Search.](https://www.mongodb.com/docs/manual/administration/install-community.md#std-label-install-mdb-community-edition
- Load sample data, create a vector search index, and run vector search queries on your local deployment.
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 download the following:
-
Docker v4.40 or higher
-
Docker Compose
-
curlcommand -
mongoshlocally or have access to it through Docker
This quick start describes how to load sample documents that contain text data into your cluster, create a MongoDB Vector Search index on a text field in the collection to automatically generate embeddings for the text data at index time and query time, and then perform semantic search to return documents that are similar to your query.
Time required: 15 minutes
Objectives
In this quick start, you complete the following steps:
-
Create an index definition for the
sample_mflix.moviescollection that indexes thefullplotfield as theautoEmbedtype. The index definition specifiesvoyage-4as the model to use for generating embeddings for thefullplotfield. -
Run a MongoDB Vector Search query that searches the sample
sample_mflix.moviescollection. The query uses the [$vectorSearch](https://www.mongodb.com/docs/vector-search/query/aggregation-stages/vector-search-stage.md#mongodb-pipeline-pipe.-vectorSearch stage to search thefullplotfield. The query performs a semantic search for the phrasejourney through the country sideusing the embedding generated at query time using thevoyage-4embedding model. It considers up to100nearest neighbors, and returns10documents in the results.
To learn more, see [Learning Summary.](https://www.mongodb.com/docs/vector-search/tutorials/quick-start.md#std-label-avs-qs-learning-summary
This quick start describes how to create a local Atlas deployment with sample data loaded into the deployment, create a MongoDB Vector Search index for the sample data, and then perform semantic search to return documents that are similar to your query.
Time required: 15 minutes
Objectives
In this quick start, you complete the following steps:
- Deploy Atlas locally via Atlas CLI with sample data loaded.
To create a local Atlas deployment using Docker commands, see [Create a Local Atlas Deployment with Docker.](https://www.mongodb.com/docs/atlas/cli/atlas-cli-deploy-docker.md#std-label-atlas-cli-deploy-docker
-
Create an index definition for the
sample_mflix.moviescollection that indexes thefullplotfield as theautoEmbedtype. The index definition specifiesvoyage-4as the embedding model to use for generating embeddings for thefullplotfield. -
Run a MongoDB Vector Search query that searches the sample
sample_mflix.moviescollection. The query uses the [$vectorSearch](https://www.mongodb.com/docs/vector-search/query/aggregation-stages/vector-search-stage.md#mongodb-pipeline-pipe.-vectorSearch stage to search thefullplotfield for the movies semantically similar to the query string journey through the country side. It considers up to100nearest neighbors and returns10documents in the results.
To learn more, see [Learning Summary.](https://www.mongodb.com/docs/vector-search/tutorials/quick-start.md#std-label-avs-qs-learning-summary
Before You Begin
Before you begin, you must have the following:
-
Docker
-
Atlas CLI v5.3.1 or later
-
[
mongosh](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh -
Voyage AI API (Application Programming Interface) keys created from the Atlas UI
To learn more about creating a Voyage AI API (Application Programming Interface) key from the Atlas UI, see [Manage Voyage AI Model API Keys.](https://www.mongodb.com/docs/voyageai/management/api-keys.md#std-label-voyage-api-keys
Note:
Local Atlas deployment doesn't support Voyage AI API (Application Programming Interface) keys created directly from Voyage AI.
This quick start demonstrates how to deploy MongoDB Search and MongoDB Vector Search in Docker, load sample data into the MongoDB cluster, create a vector search index for the sample data, and run vector search queries against the sample data.
Time required: 20 minutes
Objectives
The quick start walks you through the following steps:
- Deploy MongoDB and
mongotin Docker.
For more details on deploying by using a tarball or as an image in Docker, see [Install MongoDB Community and MongoDB Search.](https://www.mongodb.com/docs/manual/administration/install-community.md#std-label-install-mdb-community-edition
- Load sample data, create a vector search index, and run vector search queries on your local deployment.
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 higher
-
Download Docker Compose
-
Download the
curlcommand -
Download
mongoshlocally or have access to it through Docker -
Create Voyage AI API (Application Programming Interface) keys from the [Atlas UI](https://www.mongodb.com/docs/voyageai/management/api-keys.md#std-label-voyage-api-keys or directly from Voyage AI
We recommend two separate keys to enable MongoDB Vector Search to [automatically generate embeddings](https://www.mongodb.com/docs/vector-search/crud-embeddings/automated-embedding.md#std-label-avs-auto-embeddings at index- and query-time.
Note:
Your provider endpoint for generating embeddings depends on whether you create the API (Application Programming Interface) key from the Atlas UI or directly from Voyage AI.
Set Up 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.
1) Run the Atlas CLI command to create a local Atlas deployment with sample data loaded into the deployment.
javascript
MONGODB_ATLAS_LOCAL_PREVIEW=true atlas local setup --loadSampleData true --force
Output:
javascript
"Installing first class plugin atlas-local-plugin"
"Plugin mongodb/atlas-local-cli successfully installed"
[1/4] [✅] Pulling the latest version of the MongoDB image...
[2/4] [✅] Creating the deployment...
[3/4] [✅] Starting the deployment...
[4/4] [✅] Waiting for the deployment to be healthy...
{"outcome":"setup","deployment_name":"local7816","mongodb_version":"8.2.5","port":53211,"load_sample_data":true,"connect_result":{"connect_outcome":"skipped"}}
2) Connect to your local Atlas deployment.
To connect, run the following command after replacing <deployment_name> with the name of your local Atlas deployment.
shell
atlas local connect --connectWith mongosh <deployment_name>
- Pull the MongoDB Search Docker image and the latest MongoDB Community Edition image.
To download the mongot Docker image and the latest MongoDB Community Edition image, run the following command:
shell
docker pull mongodb/mongodb-community-server:latest && docker pull mongodb/mongodb-community-search:latest
Note:
You must have a minimum of MongoDB 8.2.0 to use MongoDB Search with a self-managed deployment. For more information, see [MongoDB Search Compatibility.](https://www.mongodb.com/docs/search/deployment/feature-compatibility.md#std-label-fts-feature-availability
- Download an archive of sample data.
To download the sample data, run the following command:
shell
curl https://atlas-education.s3.amazonaws.com/sampledata.archive -o sampledata.archive
- Create your password file.
Create a password file for mongot to connect to mongod.
Important:
Do not include trailing new lines in your password file. mongot rejects password files that contain trailing newlines.
Select your operating system and run the command to create your password file:
### Linux/MacOS
shell
echo -n "mongotPassword" > pwfile
chmod 400 pwfile
Note:
The -n flag prevents a trailing newline.
Note:
-
If you change the
mongotpassword, you must also update the password value in theinit-mongo-shscript. -
Most text editors automatically add newlines to files when you edit files manually.
-
Set up your configuration files.
Create the following configuration files in your project folder and paste the provided code for each file:
##### docker-compose.yml
```shell services: mongod: image: mongodb/mongodb-community-server:latest container_name: mongod-community command: >- mongod --config /etc/mongod.conf --replSetMember=mongod.search-community:27017 ports: - 27017:27017 extra_hosts: - "host.docker.internal:host-gateway" volumes: - mongod_data:/data/db - ./mongod.conf:/etc/mongod.conf:ro - ./sampledata.archive:/sampledata.archive - ./init-mongo.sh:/docker-entrypoint-initdb.d/init-mongo.sh:ro networks: - search-community
mongot:
image: mongodb/mongodb-community-search:latest
entrypoint:
- /mongot-community/mongot
- --config=/mongot-community/config.default.yml
- --internalListAllIndexesForTesting=true
container_name: mongot-community-pupr
networks:
- search-community
volumes:
- mongot_data:/data/mongot
- ./mongot.conf:/mongot-community/config.default.yml
- ./pwfile:/mongot-community/pwfile:ro
depends_on:
- mongod
ports:
- 27028:27028 # Query server port from config
- 9946:9946 # Metrics port from config
volumes: mongod_data: mongot_data:
networks: search-community: name: search-community external: true # Use an external network if it exists. Comment this line if you want to create a new network. ```
##### init-mongo.sh
Note:
If you specified a custom password in your password file, update the mongotPassword in the init-mongo.sh file to your custom password.
The mongotUser in this file is only in use for the mongod to authorize mongot through the searchCoordinator role.
```shell #!/bin/bash set -e
echo "Starting MongoDB initialization..." sleep 2
# Create user using local connection (no port specification needed) echo "Creating user..." mongosh --eval " const adminDb = db.getSiblingDB('admin'); try { adminDb.createUser({ user: 'mongotUser', pwd: 'mongotPassword', roles: [{ role: 'searchCoordinator', db: 'admin' }] }); print('User mongotUser created successfully'); } catch (error) { if (error.code === 11000) { print('User mongotUser already exists'); } else { print('Error creating user: ' + error); } } "
# Check for existing data echo "Checking for existing sample data..." if mongosh --quiet --eval "db.getSiblingDB('sample_airbnb').getCollectionNames().includes('listingsAndReviews')" | grep -q "true"; then echo "Sample data already exists. Skipping restore." else echo "Sample data not found. Running mongorestore..." if [ -f "/sampledata.archive" ]; then mongorestore --archive=/sampledata.archive echo "Sample data restored successfully." else echo "Warning: sampledata.archive not found" fi fi
echo "MongoDB initialization completed." ```
##### mongod.conf
Note:
If you deploy mongot in a production environment, MongoDB recommends that you enable security and configure TLS. For more information about mongod security settings, see [Self-Managed Security.](https://www.mongodb.com/docs/manual/core/self-managed-security.md#std-label-self-managed-security
```shell # mongod.conf storage: dbPath: /data/db
net: port: 27017 bindIp: 0.0.0.0
setParameter: searchIndexManagementHostAndPort: mongot.search-community:27028 mongotHost: mongot.search-community:27028 skipAuthenticationToSearchIndexManagementServer: false useGrpcForSearch: true
replication: replSetName: rs0 ```
##### mongot.conf
shell
syncSource:
replicaSet:
hostAndPort: "mongod.search-community:27017"
username: "mongotUser"
passwordFile: "/mongot-community/pwfile"
authSource: "admin"
tls: false
readPreference: "primaryPreferred"
storage:
dataPath: "data/mongot"
server:
grpc:
address: "mongot.search-community:27028"
tls:
mode: "disabled"
metrics:
enabled: true
address: "mongot.search-community:9946"
healthCheck:
address: "mongot.search-community:8080"
logging:
verbosity: INFO
- Set up the Docker environment.
To create the Docker network, run the following command:
shell
docker network create search-community
- Start
mongodandmongot.
Use the following steps to launch both services:
Launch mongod and mongot:
shell
docker compose up -d
Wait for both services to fully initialize.
To monitor the logs of both services, run the following command:
shell
docker compose logs -f
The initialization is complete when the logs return MongoDB
initialization completed.
1) Run the Atlas CLI command to create a local Atlas deployment with sample data loaded into the deployment.
To create a local Atlas deployment, run the following command after replacing <voyage_api_key> with the Voyage AI API (Application Programming Interface) key created from the Atlas UI.
javascript
MONGODB_ATLAS_LOCAL_PREVIEW=true MONGODB_ATLAS_LOCAL_VOYAGE_API_KEY=<voyage_api_key> atlas local setup --loadSampleData true --force
Output:
javascript
"Installing first class plugin atlas-local-plugin"
"Plugin mongodb/atlas-local-cli successfully installed"
[1/4] [✅] Pulling the latest version of the MongoDB image...
[2/4] [✅] Creating the deployment...
[3/4] [✅] Starting the deployment...
[4/4] [✅] Waiting for the deployment to be healthy...
{"outcome":"setup","deployment_name":"local7816","mongodb_version":"8.2.5","port":53211,"load_sample_data":true,"connect_result":{"connect_outcome":"skipped"}}
2) Connect to your local Atlas deployment.
To connect, run the following command after replacing <deployment_name> with the name of your local Atlas deployment.
shell
atlas local connect --connectWith mongosh <deployment_name>
- 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
Create a Vector Search Index
In this section, you create a MongoDB Vector Search index on sample data that you load into your cluster:
-
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 Vector Search index type. |
|---|---|
| How do you want to set up your vector data? | Select one of the following: Automated Embedding if you want MongoDB to generate and manage vector embeddings for your text fields.; Bring your own embeddings if you have already generated vector embeddings for your data. Choose Bring your own embeddings. |
| Index Name and Data Source | Specify the following information: Index Name: autoembed_index; Database and Collection:sample_mflix; embedded_movies |
| Configuration Method | For a guided experience, select Visual Editor.To edit the raw index definition, select JSON Editor. |
- Define the index.
### Visual Editor
Atlas automatically detects fields that contain vector embeddings, as well as their corresponding dimensions. For the sample_mflix.movies collection, the plot_embedding field displays.
To configure the index, do the following:
Select Dot Product from the Similarity Method dropdown.
Click the Advanced dropdown menu and select Scalar to [automatically quantize](https://www.mongodb.com/docs/vector-search/about/vector-quantization.md#std-label-avs-automatic-quantization the embeddings in the field.
This index definition:
-
Indexes the
plot_embedding_voyage_3_largefield as thevector[type.](https://www.mongodb.com/docs/vector-search/indexes/vector-search-type.md#std-label-avs-types-vectorThis field contains [vector embeddings](https://www.mongodb.com/docs/vector-search/index.md#std-term-vector-embeddings that represent the summary of a movie's plot.
-
Specifies
2048[vector dimensions.](https://www.mongodb.com/docs/vector-search/index.md#std-term-vector -
Measures [similarity](https://www.mongodb.com/docs/vector-search/indexes/vector-search-type.md#std-label-avs-similarity-functions using
dotProductsimilarity. -
Enables [automatic](https://www.mongodb.com/docs/vector-search/about/vector-quantization.md#std-label-avs-automatic-quantization
quantizationof the vectors. -
Click Next.
-
Click Create Vector Search Index.
The index should take about one minute to build. When your vector index 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.
In a terminal window, run atlas deployments connect and follow the prompts to connect to your local Atlas deployment via [mongosh](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh. For detailed instructions on connecting, see [Manage a Local Atlas Deployment.](https://www.mongodb.com/docs/atlas/cli/current/atlas-cli-deploy-local/#manage-a-local-atlas-deployment
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.
shell
db.embedded_movies.createSearchIndex(
"vector_index",
"vectorSearch",
{
"fields": [
{
"type": "vector",
"path": "plot_embedding_voyage_3_large",
"numDimensions": 2048,
"similarity": "dotProduct",
"quantization": "scalar"
}
]
}
);
This index definition:
-
Indexes the
plot_embedding_voyage_3_largefield as thevector[type.](https://www.mongodb.com/docs/vector-search/indexes/vector-search-type.md#std-label-avs-types-vectorThis field contains [vector embeddings](https://www.mongodb.com/docs/vector-search/index.md#std-term-vector-embeddings that represent the summary of a movie's plot.
-
Specifies
2048[vector dimensions.](https://www.mongodb.com/docs/vector-search/index.md#std-term-vector -
Measures [similarity](https://www.mongodb.com/docs/vector-search/indexes/vector-search-type.md#std-label-avs-similarity-functions using
dotProductsimilarity. -
Enables [automatic](https://www.mongodb.com/docs/vector-search/about/vector-quantization.md#std-label-avs-automatic-quantization
quantizationof the vectors. -
Install the MongoDB C Driver.
For detailed installation instructions, refer to the MongoDB C Driver documentation.
- Create a new directory called
query-quick-start.
bash
mkdir query-quick-start
- Enter the directory, and create a
CMakeLists.txtfile.
bash
cd query-quick-start
touch CMakeLists.txt
Copy and paste the following lines into the CMakeLists.txt file:
```console cmake_minimum_required(VERSION 3.30)
project(atlas-vector-search-quick-start)
# Specify the minimum version for creating a vector index. find_package (mongoc-1.0 1.28.0 REQUIRED)
add_executable(atlas-vector-search-quick-start vector_index.c )
target_link_libraries (atlas-vector-search-quick-start PRIVATE mongo::mongoc_shared) ```
- Define the index.
Create a file named vector_index.c. Copy and paste the following code into the file.
```c
#include
int main(void) { mongoc_client_t client; mongoc_collection_t collection; bson_error_t error; char database_name[] = "sample_mflix"; char collection_name[] = "embedded_movies"; char index_name[] = "vector_index";
mongoc_init();
// Replace the placeholder with your connection string
client = mongoc_client_new("<connection-string>");
// Connect to your cluster
collection = mongoc_client_get_collection (client, database_name, collection_name);
bson_t cmd;
// Create search index command.
{
char *cmd_str = bson_strdup_printf (
BSON_STR ({
"createSearchIndexes" : "%s",
"indexes" : [{
"definition": {
"fields": [{
"type": "vector",
"path": "plot_embedding_voyage_3_large",
"numDimensions": 2048,
"similarity": "dotProduct",
"quantization": "scalar"
}]
},
"name": "%s",
"type": "vectorSearch"
}]
}),
collection_name, index_name);
if (!bson_init_from_json(&cmd, cmd_str, -1, &error)) {
printf("Failed to initialize BSON: %s\n", error.message);
bson_free(cmd_str);
return 1;
}
bson_free (cmd_str);
}
if (!mongoc_collection_command_simple (collection, &cmd, NULL /* read_prefs */, NULL /* reply */, &error)) {
bson_destroy (&cmd);
printf ("Failed to run createSearchIndexes: %s", error.message);
return 1;
} else {
printf ("New search index named %s is building.\n", index_name);
bson_destroy (&cmd);
}
// Polling for index status
printf("Polling to check if the index is ready. This may take up to a minute.\n");
int queryable = 0;
while (!queryable) {
const char *pipeline_str = "{\"pipeline\": [{\"$listSearchIndexes\": {}}]}";
bson_t pipeline;
if (!bson_init_from_json(&pipeline, pipeline_str, -1, &error)) {
printf("Failed to initialize pipeline BSON: %s\n", error.message);
break; // Exit the loop on error
}
mongoc_cursor_t *cursor = mongoc_collection_aggregate(collection, MONGOC_QUERY_NONE, &pipeline, NULL, NULL);
const bson_t *got;
// Check if the cursor returns any documents
int found_index = 0;
while (mongoc_cursor_next(cursor, &got)) {
bson_iter_t iter;
if (bson_iter_init(&iter, got) && bson_iter_find(&iter, "name")) {
const char *name = bson_iter_utf8(&iter, NULL);
if (strcmp(name, index_name) == 0) {
found_index = 1; // Index found
bson_iter_find(&iter, "queryable");
queryable = bson_iter_bool(&iter);
break; // Exit the loop since we found the index
}
}
}
if (mongoc_cursor_error(cursor, &error)) {
printf("Failed to run $listSearchIndexes: %s\n", error.message);
break; // Exit the loop on error
}
if (!found_index) {
printf("Index %s not found yet. Retrying...\n", index_name);
}
bson_destroy(&pipeline);
mongoc_cursor_destroy(cursor);
sleep(5); // Sleep for 5 seconds before checking again
}
if (queryable) {
printf("%s is ready for querying.\n", index_name);
} else {
printf("Error occurred or index not found.\n");
}
// Cleanup
mongoc_collection_destroy(collection);
mongoc_client_destroy(client);
mongoc_cleanup();
return 0;
} ```
This index definition:
-
Indexes the
plot_embedding_voyage_3_largefield as thevector[type.](https://www.mongodb.com/docs/vector-search/indexes/vector-search-type.md#std-label-avs-types-vectorThis field contains [vector embeddings](https://www.mongodb.com/docs/vector-search/index.md#std-term-vector-embeddings that represent the summary of a movie's plot.
-
Specifies
2048[vector dimensions.](https://www.mongodb.com/docs/vector-search/index.md#std-term-vector -
Measures [similarity](https://www.mongodb.com/docs/vector-search/indexes/vector-search-type.md#std-label-avs-similarity-functions using
dotProductsimilarity. -
Enables [automatic](https://www.mongodb.com/docs/vector-search/about/vector-quantization.md#std-label-avs-automatic-quantization
quantizationof the vectors.
This code also includes a polling mechanism to check if the index is ready to use.
- Specify the
<connectionString>.
Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.
### Atlas Cluster
Your connection string should use the following format:
text
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net
IMPORTANT: Ensure that your connection string includes your database user's credentials. 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
- Create and enter the
/builddirectory:
bash
mkdir build && cd build
- Prepare the project.
bash
cmake ../
- Build the app.
bash
cmake --build .
- Execute the app to create the index.
bash
./atlas-vector-search-quick-start
Output:
```sh New search index named vector_index is building. Polling to check if the index is ready. This may take up to a minute. vector_index is ready for querying.
```
1) Install the MongoDB C++ Driver.
For detailed installation instructions, refer to the MongoDB C++ Driver documentation.
2) Create a new directory called query-quick-start.
bash
mkdir query-quick-start
3) Enter the directory, and create a CMakeLists.txt file.
bash
cd query-quick-start
touch CMakeLists.txt
Copy and paste the following lines into the CMakeLists.txt file:
```console cmake_minimum_required(VERSION 3.30)
project(query_quick_start)
set(CMAKE_CXX_STANDARD 17)
# You must use mongocxx driver version 3.11.0 or later to # create a vector index. find_package(mongocxx REQUIRED) find_package(bsoncxx REQUIRED)
add_executable(query_quick_start vector_index.cpp )
target_link_libraries(query_quick_start PRIVATE mongo::mongocxx_shared) target_link_libraries(query_quick_start PRIVATE mongo::bsoncxx_shared) ```
4) Define the index.
Create a file named vector_index.cpp. Copy and paste the following code into the file.
```cpp #include <bsoncxx/builder/basic/document.hpp> #include <iostream> #include <mongocxx/client.hpp> #include <mongocxx/instance.hpp> #include <mongocxx/search_index_view.hpp> #include <mongocxx/uri.hpp> #include <thread>
using bsoncxx::builder::basic::kvp; using bsoncxx::builder::basic::make_array; using bsoncxx::builder::basic::make_document;
int main() { try { mongocxx::instance inst{};
// Replace the placeholder with your connection string
const auto uri = mongocxx::uri{"<connection-string>"};
// Connect to your cluster
mongocxx::client conn{uri};
auto db = conn["sample_mflix"];
auto collection = db["embedded_movies"];
auto siv = collection.search_indexes();
std::string name = "vector_index";
auto type = "vectorSearch";
auto definition = make_document(
kvp("fields",
make_array(make_document(
kvp("type", "vector"), kvp(
(本文超出站点单文档体积上限,已截断)
