For AI agents: a documentation index is available at https://www.mongodb.com/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.

Use MongoDB Search and Vector Search

If you installed MongoDBSearch resource successfully, you can create MongoDB Search and Vector Search indexes as the mdb-user and run MongoDB Search and Vector Search queries using the indexes. This page describes how to load sample data, create MongoDB Search and Vector Search indexes for the data, and run MongoDB Search and Vector Search queries against the data.

To use MongoDB Search and Vector Search, you must have the following:

1

To set the environment variables for use in the subsequent steps in this procedure, copy the following, set the values for the environment variables, and then load the environment variables:

# The env vars here are all commented out because this snippets module# is reusable across different MongoDB deployments and all the necessary variables# should be already defined there. # set it to the context name of the k8s cluster#export K8S_CTX="<local cluster context>"# the following namespace will be used to deploy mongodb tools pod#export MDB_NS="mongodb" # regular user performing restore and search queries on sample mflix database# the user should be able to restore database using mongorestore#export MDB_USER_PASSWORD="mdb-user-password-CHANGE-ME" # name of MongoDB or MongoDBCommunity resource in case it's deployed in the same cluster# user only for the connection string in MDB_CONNECTION_STRING env var below#export MDB_RESOURCE_NAME="mdbc-rs" # default connection string if MongoDB database is deployed using the operator#export MDB_CONNECTION_STRING="mongodb://mdb-user:${MDB_USER_PASSWORD}@${MDB_RESOURCE_NAME}-0.${MDB_RESOURCE_NAME}-svc.${MDB_NS}.svc.cluster.local:27017/?replicaSet=${MDB_RESOURCE_NAME}"
2

Deploy a pod named mongodb-tools-pod to run MongoDB client tools like mongosh and mongorestore from within the Kubernetes cluster. Running a pod inside the cluster simplifies connectivity to mongodb without neeeding to expose the database externally.

The following command deploys a pod named mongodb-tools-pod that runs a MongoDB Community Server image. The pod is kept running with a sleep infinity command to allow you to use kubectl exec to run MongoDB client tools.

kubectl apply -n "${MDB_NS}" --context "${K8S_CTX}" -f - <<EOFapiVersion: v1kind: Podmetadata: name: mongodb-tools-pod labels: app: mongodb-toolsspec: containers: - name: mongodb-tools image: mongodb/mongodb-community-server:${MDB_VERSION}-ubi8 command: ["/bin/bash", "-c"] args: ["sleep infinity"] restartPolicy: NeverEOF echo "Waiting for the mongodb-tools to be ready..."kubectl --context "${K8S_CTX}" -n "${MDB_NS}" wait \ --for=condition=Ready pod/mongodb-tools-pod --timeout=60s
3

Import the sample_mflix database, which contains the following collections:

Collection Name
Description

comments

Contains comments associated with specific movies.

embedded_movies

Contains details on movies in the Western, Action, and Fantasy genres from the movies collection with the following additional fields:

  • plot_embedding_voyage_3_large - Contains 2048d embeddings created from the plot field using Voyage AI's voyage-3-large embedding model and converted to binData for efficient storage and retrieval.

  • plot_embedding - Contains 1536d embeddings created from the plot field using OpenAI's text-embedding-ada-002 embedding model and converted to binData for efficient storage and retrieval.

movies

Contains movie information, including release year, director, and reviews.

sessions

Metadata field. Contains users' JSON Web Tokens.

theaters

Contains locations of movie theaters.

users

Contains user information.

The following command downloads the sample dataset and uses mongorestore to load the data into the sample_mflix database in your MongoDB deployment, connecting as the mdb-user.

kubectl exec -n "${MDB_NS}" --context "${K8S_CTX}" \ mongodb-tools-pod -- /bin/bash -eu -c "$(cat <<EOFecho "Downloading sample database archive..."curl https://atlas-education.s3.amazonaws.com/sample_mflix.archive \ -o /tmp/sample_mflix.archiveecho "Restoring sample database"mongorestore \ --archive=/tmp/sample_mflix.archive \ --verbose=1 \ --drop \ --nsInclude 'sample_mflix.*' \ --uri="${MDB_CONNECTION_STRING}"EOF)"
4

You can create a MongoDB Search or a Vector Search index. You must create a MongoDB Search index to run $search and $searchMeta queries and Vector Search index to run $vectorSearch queries.

  • MongoDB Search provides flexible index definitions that support dynamic and static field mappings, various analyzers (standard, language-specific, custom), and features like synonyms and faceted search. To learn more, see Define Your Index.

  • Vector Search provides simple index definition that supports querying vector embeddings in your data based on semantic similarity by using ANN and ENN search algorithm. To learn more, see Define Vector Search Index.

  1. Copy, paste, and run the following command in your terminal to create a MongoDB Search or a Vector Search index.

    The command uses kubectl exec to run mongosh in the mongodb-tools-pod. It connects to the sample_mflix db.<collection>.createSearchIndex() method to create an index.

    The following command creates a MongoDB Search index named default with dynamic mappings on the movies collection. Dynamic mapping automatically indexes all dynamically indexable field types.

    kubectl exec --context "${K8S_CTX}" -n "${MDB_NS}" mongodb-tools-pod -- \ mongosh --quiet \ "${MDB_CONNECTION_STRING}" \ --eval "use sample_mflix" \ --eval 'db.movies.createSearchIndex("default", { mappings: { dynamic: true } });'
  2. Wait for index creation to complete.

    Index creation is an asynchronous process. Run the following script to wait for 60 seconds for the index creation to complete.

    # Currently it's not possible to check the status of search indexes, we need to just waitecho "Sleeping to wait for search indexes to be created"sleep 60

    Alternatively, run the following command to retrieve the list of indexes for the collection.

    kubectl exec --context "${K8S_CTX}" -n "${MDB_NS}" mongodb-tools-pod -- \ mongosh --quiet "${MDB_CONNECTION_STRING}" \ --eval "use sample_mflix" \ --eval 'db.runCommand({"listSearchIndexes": "movies"});'
5

After the index creation is successful, you can run MongoDB Search or Vector Search queries using the index. You can also combine MongoDB Search with Vector Search. To learn more about running MongoDB Search queries, see Define Your Query. To learn more about Vector Search queries, see Run Vector Search ANN and ENN Queries.

The following script defines the aggregation pipeline query criteria and uses the kubectl exec command to load mongosh to execute the query.

The following query searches the plot field for movie plots that contain the term baseball. It excludes movies in the comedy and romance genres.

mdb_script=$(cat <<'EOF'use sample_mflix;db.movies.aggregate([ { $search: { "compound": { "must": [ { "text": { "query": "baseball", "path": "plot" } }], "mustNot": [ { "text": { "query": ["Comedy", "Romance"], "path": "genres" } } ] }, "sort": { "released": -1 } } }, { $limit: 3 }, { $project: { "_id": 0, "title": 1, "plot": 1, "genres": 1, "released": 1 } }]);EOF) kubectl exec --context "${K8S_CTX}" -n "${MDB_NS}" \ mongodb-tools-pod -- /bin/bash -eu -c "$(cat <<EOFecho '${mdb_script}' > /tmp/mdb_script.jsmongosh --quiet "${MDB_CONNECTION_STRING}" < /tmp/mdb_script.jsEOF)"
mdbc-rs [primary] test> switched to db sample_mflixmdbc-rs [primary] sample_mflix> ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... [ { plot: 'A sports agent stages an unconventional recruitment strategy to get talented Indian cricket players to play Major League Baseball.', genres: [ 'Biography', 'Drama', 'Sport' ], title: 'Million Dollar Arm', released: ISODate('2014-05-16T00:00:00.000Z') }, { plot: 'A Taiwanese high school baseball team travels to Japan in 1931 to compete in a national tournament.', genres: [ 'Biography', 'Drama', 'History' ], title: 'Kano', released: ISODate('2014-02-27T00:00:00.000Z') }, { plot: "12-year-old Josh is a mixed race boy and a promising baseball player. He is abused by his mother's boyfriend Byrd, and neglected by his mother Debbie. He forges his own path in life when ...", genres: [ 'Drama' ], title: 'Calloused Hands', released: ISODate('2013-03-03T00:00:00.000Z') }]mdbc-rs [primary] sample_mflix>

To learn more about creating indexes and running search queries, see: