<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: MongoDB</title>
    <description>The latest articles on DEV Community by MongoDB (mongodb).</description>
    <link>https://dev.to/mongodb</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Forganization%2Fprofile_image%2F140%2F9639a040-3c27-4b99-b65a-85e100016d3c.png</url>
      <title>DEV Community: MongoDB</title>
      <link>https://dev.to/mongodb</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/mongodb"/>
    <language>en</language>
    <item>
      <title>Build a Music Recommender With Mongoose and MongoDB Vector Search</title>
      <dc:creator>Jordan Smith</dc:creator>
      <pubDate>Tue, 01 Dec 2026 14:39:02 +0000</pubDate>
      <link>https://dev.to/mongodb/build-a-music-recommender-with-mongoose-and-mongodb-vector-search-4n5a</link>
      <guid>https://dev.to/mongodb/build-a-music-recommender-with-mongoose-and-mongodb-vector-search-4n5a</guid>
      <description>&lt;p&gt;In the age of AI, the way that search works has changed. A traditional keyword search that only matches words in the search term is no longer sufficient for modern applications. Instead, let’s take a look at a relatively new method called &lt;em&gt;semantic search&lt;/em&gt;, which searches based on meaning rather than keywords.&lt;/p&gt;

&lt;p&gt;In this tutorial, you’ll learn how to use MongoDB Vector Search with Mongoose by building a music recommender. You’ll type a description of a “&lt;em&gt;vibe&lt;/em&gt;,” like “upbeat road trip with the windows down,” and get back a ranked list of songs that fit the feeling. Along the way, you’ll define a Mongoose schema and model for documents with vector embeddings, create a vector search index, and query it with &lt;code&gt;$vectorSearch&lt;/code&gt;, using Voyage AI on MongoDB to generate the query embeddings.&lt;/p&gt;

&lt;p&gt;This is a follow-up to &lt;a href="https://dev.to/mongodb/building-a-vibe-based-music-recommender-with-mongodb-and-voyage-ai-a0m"&gt;another music recommender tutorial&lt;/a&gt; I posted, which builds the same app with the native MongoDB Node.js Driver. You don’t need to have read it to follow along. Let’s get into it!&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;In This Tutorial&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;By the end of this tutorial, you’ll know how to:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Define a Mongoose schema and model for documents that store vector embeddings
&lt;/li&gt;
&lt;li&gt;Create a vector search index from a Mongoose model
&lt;/li&gt;
&lt;li&gt;Embed a natural-language query with Voyage AI
&lt;/li&gt;
&lt;li&gt;Run &lt;code&gt;$vectorSearch&lt;/code&gt; queries through a Mongoose model and return ranked results
&lt;/li&gt;
&lt;li&gt;Connect it all to a simple Express app&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;How It Actually Works&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Before we write any code, let’s go through a quick overview of how the search functionality in this app actually works.&lt;/p&gt;

&lt;p&gt;The key to all of this is vector embeddings. A vector embedding is a way of representing text (or other data like images or audio) as an array of numbers, or a vector. Data with similar semantic meanings produces similar vectors, so you can compare all of your vectors mathematically to find data that’s similar in meaning.&lt;/p&gt;

&lt;p&gt;Here’s how it works in this app:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Every song in our sample collection has an LLM-generated “vibe description.” This is a 2-3 sentence description of what the song “feels” like to listen to. Vector embeddings were generated from these descriptions using Voyage AI and are stored with the songs.
&lt;/li&gt;
&lt;li&gt;When a user types a search query, it is converted into a vector using the same Voyage AI embedding model.
&lt;/li&gt;
&lt;li&gt;We use MongoDB Vector Search, through a Mongoose model, to find the songs in the collection whose vectors are closest to the query vector.
&lt;/li&gt;
&lt;li&gt;The results are returned to the user, ranked by how closely their vectors match the query vector.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Where Mongoose Fits In&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Mongoose sits on top of the MongoDB Node.js driver and adds a schema layer, a model for each collection, and connection management. It doesn’t change how vector search works, and it doesn’t generate embeddings for you. Here’s what it does handle in this app:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Schema and model:&lt;/strong&gt; We define what a song looks like, including the &lt;code&gt;embedding&lt;/code&gt; field that holds its vector, and Mongoose validates every song before it’s written to the database.
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Connection:&lt;/strong&gt; Mongoose manages one connection that every model in the app shares.
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Index creation:&lt;/strong&gt; The model has a method for creating the vector search index.
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Querying:&lt;/strong&gt; We run the &lt;code&gt;$vectorSearch&lt;/code&gt; aggregation stage through the model, and Mongoose sends it to MongoDB.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Full Project Code&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;If you want to see the full project with all of the code already written, you can find it in the &lt;a href="https://github.com/mongodb-developer/song-vibe-recommendations/tree/main/Mongoose" rel="noopener noreferrer"&gt;&lt;code&gt;Mongoose&lt;/code&gt; directory&lt;/a&gt; of the GitHub repository. Everything you need is in that directory, including the sample data and the front end. I’ll explain all the elements throughout this tutorial, and you can clone the repository and follow along as well.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Prerequisites&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Before getting started, you’ll need a few things in place:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Node.js&lt;/strong&gt; (v20.19 or later) installed on your machine. This is the minimum version that &lt;a href="https://mongoosejs.com/docs/migrating_to_9.html" rel="noopener noreferrer"&gt;Mongoose 9&lt;/a&gt; supports.
&lt;/li&gt;
&lt;li&gt;A &lt;strong&gt;MongoDB Atlas&lt;/strong&gt; account with a free cluster
&lt;/li&gt;
&lt;li&gt;A &lt;strong&gt;Voyage AI&lt;/strong&gt; API key - you can get one from the &lt;a href="https://www.mongodb.com/docs/voyageai/management/api-keys/?utm_campaign=devrel&amp;amp;utm_source=third-party-content&amp;amp;utm_medium=cta&amp;amp;utm_content=buildrel-mongoose-music&amp;amp;utm_term=hugh.murray" rel="noopener noreferrer"&gt;MongoDB Atlas UI&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You don’t need to be a Mongoose expert, but it helps to be comfortable with the basic idea of defining a schema and creating a model from it. We’ll explain the Mongoose-specific parts as we go.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Project Setup&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;With that out of the way, let’s get going with the actual code.&lt;/p&gt;

&lt;p&gt;Start by creating a new project directory and initializing it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;mkdir music-recommender-mongoose
&lt;span class="nb"&gt;cd&lt;/span&gt; music-recommender-mongoose
npm init -y
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then install the dependencies:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;npm install express mongoose voyageai dotenv
npm install --save-dev typescript tsx @types/node @types/express
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Mongoose bundles the MongoDB Node.js driver, so you don’t need to install the &lt;code&gt;mongodb&lt;/code&gt; package separately.&lt;/p&gt;

&lt;p&gt;This tutorial uses TypeScript, so create a &lt;code&gt;tsconfig.json&lt;/code&gt; file in the root of your project:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nl"&gt;"compilerOptions"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nl"&gt;"target"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"ES2020"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nl"&gt;"module"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"commonjs"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nl"&gt;"lib"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"ES2020"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nl"&gt;"strict"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nl"&gt;"esModuleInterop"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nl"&gt;"resolveJsonModule"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nl"&gt;"outDir"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"./dist"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nl"&gt;"rootDir"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"./"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nl"&gt;"skipLibCheck"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nl"&gt;"include"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"seed/**/*"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"src/**/*"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nl"&gt;"exclude"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"node_modules"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"dist"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then add two scripts to the &lt;code&gt;scripts&lt;/code&gt; section of your &lt;code&gt;package.json&lt;/code&gt; file. One starts the app, and the other seeds the database:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="nl"&gt;"scripts"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nl"&gt;"dev"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"tsx src/server.ts"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nl"&gt;"seed"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"tsx seed/seed.ts"&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Create a &lt;code&gt;.env&lt;/code&gt; file in the root of your project with the following variables:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight conf"&gt;&lt;code&gt;&lt;span class="na"&gt;MONGODB_URI&lt;/span&gt;&lt;span class="o"&gt;=&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Your&lt;/span&gt; &lt;span class="nc"&gt;MongoDB&lt;/span&gt; &lt;span class="nc"&gt;Connection&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="na"&gt;MONGODB_DATABASE&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;song_vibe_search&lt;/span&gt;

&lt;span class="na"&gt;VOYAGE_API_KEY&lt;/span&gt;&lt;span class="o"&gt;=&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Your&lt;/span&gt; &lt;span class="nc"&gt;Voyage&lt;/span&gt; &lt;span class="no"&gt;AI&lt;/span&gt; &lt;span class="no"&gt;API&lt;/span&gt; &lt;span class="nc"&gt;Key&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, you’ll need the sample data for the app.&lt;/p&gt;

&lt;p&gt;The sample data is a small sample of 500 songs from the &lt;a href="https://freemusicarchive.org/" rel="noopener noreferrer"&gt;Free Music Archive&lt;/a&gt; with pre-generated “vibe descriptions” and embeddings, so we won’t need to generate any ourselves in this tutorial. You can download it by copying the &lt;a href="https://github.com/mongodb-developer/song-vibe-recommendations/tree/main/Mongoose/seed/data" rel="noopener noreferrer"&gt;data directory&lt;/a&gt; from the &lt;code&gt;Mongoose/seed&lt;/code&gt; directory of the GitHub repository for this tutorial.&lt;/p&gt;

&lt;p&gt;Create a directory called &lt;code&gt;seed&lt;/code&gt; in the root of your project and place the &lt;code&gt;data&lt;/code&gt; directory inside it, so that the songs are in &lt;code&gt;seed/data/songs.json&lt;/code&gt;. Our seed script will live in this same directory, and we’ll write it later in the tutorial.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Defining the Song Model&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;The first Mongoose-specific piece of this app is the model. A model is how Mongoose represents a collection in your code. You describe the shape of your documents with a schema, and Mongoose gives you a model that you use to write to and read from that collection.&lt;/p&gt;

&lt;p&gt;In the root of your project, create a new directory called &lt;code&gt;src&lt;/code&gt; and create a new file called &lt;code&gt;song.ts&lt;/code&gt; in that directory. This file holds our schema, our model, and the functions that connect to and disconnect from the database.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Setting up imports and constants&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;First, we need to set our imports, load our environment variables, and define a few constants. Paste the following code into &lt;code&gt;song.ts&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;dotenv&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="s2"&gt;"dotenv"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;path&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="s2"&gt;"path"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;mongoose&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nc"&gt;Schema&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;InferSchemaType&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="s2"&gt;"mongoose"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="c1"&gt;// Load the .env file from the project root, regardless of where the script is run from.&lt;/span&gt;
&lt;span class="n"&gt;dotenv&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;config&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;path&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;path&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;resolve&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;__dirname&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"../.env"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="no"&gt;MONGODB_URI&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;process&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;env&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;MONGODB_URI&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="no"&gt;MONGODB_URI&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nb"&gt;Error&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="s2"&gt;"Missing MONGODB_URI in environment. Ensure that you have created a .env file and added your connection string."&lt;/span&gt;
  &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="no"&gt;DB_NAME&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;process&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;env&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;MONGODB_DATABASE&lt;/span&gt; &lt;span class="o"&gt;??&lt;/span&gt; &lt;span class="s2"&gt;"song_vibe_search"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="no"&gt;COLLECTION_NAME&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"songs"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="no"&gt;VECTOR_INDEX&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"vibe_vector_index"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This code loads the &lt;code&gt;.env&lt;/code&gt; file from the root of the project, no matter where the script is run from, and makes sure the connection string is present. It also defines three constants that we’ll use throughout the app: the database name, the collection name, and the name of the vector search index that we’ll create in the next section.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Defining the schema&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Now it’s time to define what a song looks like. Paste the following code into &lt;code&gt;song.ts&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="n"&gt;songSchema&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Schema&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
  &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;title&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="kd"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;required&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;artist&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="kd"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;required&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;album&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="kd"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="k"&gt;default&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;""&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;fma_track_id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="kd"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;Number&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;required&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;fma_url&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="kd"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;required&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;play_count&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="kd"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;Number&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;required&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;genre_top&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="kd"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="k"&gt;default&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;""&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;genres&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="kd"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;String&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="k"&gt;default&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;vibe_description&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="kd"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;required&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;embedding&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="kd"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;Number&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;required&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="c1"&gt;// 1024 dimensions (voyage-4-lite)&lt;/span&gt;
    &lt;span class="n"&gt;seeded_at&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="kd"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;Date&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="k"&gt;default&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;Date&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;now&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;collection&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="no"&gt;COLLECTION_NAME&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;versionKey&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;false&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The most important field for vector search is &lt;code&gt;embedding&lt;/code&gt;. It’s an array of numbers, and for the &lt;code&gt;voyage-4-lite&lt;/code&gt; model that we’re using, it contains 1024 of them. This is the field that our vector search index will point to. A plain array of numbers is what Voyage AI returns, so that’s what we’ll store. MongoDB also supports a more compact binary format for vectors, which you can read about in the &lt;a href="https://mongoosejs.com/docs/atlas-vector-search.html" rel="noopener noreferrer"&gt;Mongoose guide to vector search&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The rest of the schema describes the song’s metadata. Fields marked &lt;code&gt;required&lt;/code&gt; must be present or Mongoose will reject the document when we try to save it, and fields with a &lt;code&gt;default&lt;/code&gt; are filled in automatically when they’re missing. This is one of the benefits of using Mongoose: if a song is missing its &lt;code&gt;embedding&lt;/code&gt;, we’ll find out when we insert it, instead of when search quietly leaves it out of the results.&lt;/p&gt;

&lt;p&gt;The second argument to &lt;code&gt;Schema&lt;/code&gt; is an options object. We use two options here:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;collection: COLLECTION_NAME&lt;/code&gt; — By default, Mongoose derives a collection name from the model name. Setting it explicitly makes sure our songs always go into the &lt;code&gt;songs&lt;/code&gt; collection.
&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;versionKey: false&lt;/code&gt; — Mongoose normally adds a &lt;code&gt;__v&lt;/code&gt; field to every document to track changes to arrays. We don’t modify songs after they’re inserted, so we turn it off to keep our documents clean.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Mongoose’s default behavior is also to ignore any fields that aren’t in the schema when saving. That means that if you adapt this tutorial to your own data, you’ll need to add every field you want to keep to the schema.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Creating the model&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Paste the following code into &lt;code&gt;song.ts&lt;/code&gt; to create the type and the model:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;type&lt;/span&gt; &lt;span class="nc"&gt;Song&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;InferSchemaType&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="k"&gt;typeof&lt;/span&gt; &lt;span class="n"&gt;songSchema&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="c1"&gt;// Reuse the model if it is already registered (avoids OverwriteModelError on reload).&lt;/span&gt;
&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nc"&gt;SongModel&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;
  &lt;span class="n"&gt;mongoose&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;models&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Song&lt;/span&gt; &lt;span class="o"&gt;??&lt;/span&gt; &lt;span class="n"&gt;mongoose&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;model&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Song"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;songSchema&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The first line uses &lt;code&gt;InferSchemaType&lt;/code&gt; to generate a TypeScript type from the schema, so we don’t have to write a separate interface for a song and keep the two in sync. The second creates the model, which is what we’ll use to insert songs, create our index, and run our search. If a model named &lt;code&gt;Song&lt;/code&gt; has already been registered, which can happen when a script reloads, we reuse it. Otherwise, Mongoose throws an &lt;code&gt;OverwriteModelError&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Connecting to MongoDB&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;The last thing we need in this file is a way to connect to the database. Paste the following code into &lt;code&gt;song.ts&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;connectDB&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;appName&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"devrel-tutorial-javascript-music-recommender"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;Promise&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="k"&gt;void&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="n"&gt;mongoose&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;connect&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="no"&gt;MONGODB_URI&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;dbName&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="no"&gt;DB_NAME&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;appName&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;disconnectDB&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;Promise&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="k"&gt;void&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="n"&gt;mongoose&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;disconnect&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Where you would create a &lt;code&gt;MongoClient&lt;/code&gt; with the native driver, Mongoose gives you a single connection that all of your models share. You call &lt;code&gt;mongoose.connect()&lt;/code&gt; once when your app starts, and every model uses that connection automatically. We pass the database name separately with the &lt;code&gt;dbName&lt;/code&gt; option because our connection string doesn’t include one, and we pass an &lt;code&gt;appName&lt;/code&gt; that identifies our app in MongoDB’s logs. When the app shuts down, &lt;code&gt;mongoose.disconnect()&lt;/code&gt; closes the connection cleanly.&lt;/p&gt;

&lt;p&gt;With our model defined, we’re ready to put some data in it.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Seeding the Database&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Now we’ll write the script that loads the sample data into MongoDB and creates the vector search index. Create a new file called &lt;code&gt;seed.ts&lt;/code&gt; in the &lt;code&gt;seed&lt;/code&gt; directory. We’ll build it up in a few pieces.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Setting up the seed script&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;First, paste in the imports and a couple of helpers:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;fs&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="s2"&gt;"fs"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;path&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="s2"&gt;"path"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;mongoose&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="s2"&gt;"mongoose"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nc"&gt;SongModel&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Song&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="no"&gt;VECTOR_INDEX&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="no"&gt;DB_NAME&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="no"&gt;COLLECTION_NAME&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;connectDB&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;disconnectDB&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="s2"&gt;"../src/song"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="c1"&gt;// Pre-built dataset (500 songs with vibe descriptions and Voyage AI embeddings).&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="no"&gt;DATA_FILE&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;path&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;resolve&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;__dirname&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"data/songs.json"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Notice that the script imports &lt;code&gt;SongModel&lt;/code&gt; and our connection functions from the file we just wrote. The &lt;code&gt;DATA_FILE&lt;/code&gt; constant points to the pre-built dataset that we copied into the seed directory earlier.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Creating the vector search index&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;This is the most important part of the seed script. Before MongoDB can run a vector search, it needs to know the shape of our &lt;code&gt;embedding&lt;/code&gt; field so it can build the right index structure. Paste the following code into &lt;code&gt;seed.ts&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;createVectorSearchIndex&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;Promise&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="k"&gt;void&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nb"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"\nCreating Vector Search index..."&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

  &lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nc"&gt;SongModel&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;createSearchIndex&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="no"&gt;VECTOR_INDEX&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
      &lt;span class="kd"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"vectorSearch"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
      &lt;span class="n"&gt;definition&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;fields&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
          &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="kd"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"vector"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="n"&gt;path&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"embedding"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="n"&gt;numDimensions&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1024&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="n"&gt;similarity&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"cosine"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
          &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
      &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nb"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sb"&gt;`  Index "${VECTOR_INDEX}" created. It may take a moment to become active.`&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;catch&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;err&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;any&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;err&lt;/span&gt;&lt;span class="o"&gt;?&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;message&lt;/span&gt;&lt;span class="o"&gt;?&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;includes&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"already exists"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="nb"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sb"&gt;`  Index "${VECTOR_INDEX}" already exists — skipping.`&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="n"&gt;err&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The model’s &lt;code&gt;createSearchIndex()&lt;/code&gt; method creates an Atlas Search or Vector Search index on the model’s collection. We set &lt;code&gt;type: "vectorSearch"&lt;/code&gt; to get a vector search index, and the &lt;code&gt;definition&lt;/code&gt; describes the vector field with the following parameters:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;type: "vector"&lt;/code&gt; — Marks this field as a vector field.
&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;path: "embedding"&lt;/code&gt; — The field in our documents that holds the vectors. This matches the &lt;code&gt;embedding&lt;/code&gt; field in our schema.
&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;numDimensions: 1024&lt;/code&gt; — This must match the output size of your embedding model. Voyage AI’s &lt;code&gt;voyage-4-lite&lt;/code&gt; model produces 1024-dimensional vectors by default. If you’re using a different model, you should be able to find the number of dimensions in the documentation for your model.
&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;similarity: "cosine"&lt;/code&gt; — This is the distance metric used to compare vectors. Cosine similarity works well for text embeddings because it measures the angle between vectors rather than their raw distance, which makes it robust to differences in text length.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The &lt;code&gt;try/catch&lt;/code&gt; makes the script safe to run more than once. If the index already exists, we skip it instead of failing.&lt;/p&gt;

&lt;p&gt;An alternative approach is to define the index on the schema itself by using &lt;code&gt;songSchema.searchIndex()&lt;/code&gt;, and then call &lt;code&gt;SongModel.createSearchIndexes()&lt;/code&gt; to create it. That keeps the index definition next to the fields it indexes. You can read more about this approach in the &lt;a href="https://mongoosejs.com/docs/atlas-vector-search.html" rel="noopener noreferrer"&gt;Mongoose guide to vector search&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Inserting the songs&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Finally, paste the following code to complete the script:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;Promise&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="k"&gt;void&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nb"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"=== Song Vibe Search - Seeding Pipeline (Mongoose) ===\n"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="nb"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sb"&gt;`Target database  : ${DB_NAME}`&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="nb"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sb"&gt;`Target collection: ${COLLECTION_NAME}`&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

  &lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nb"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"\nConnecting to MongoDB..."&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nf"&gt;connectDB&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"devrel-github-javascript-music-recommender-seed"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nb"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Connected."&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="c1"&gt;// Make sure the collection exists before creating the search index on it.&lt;/span&gt;
    &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nc"&gt;SongModel&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;createCollection&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="n"&gt;existingCount&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nc"&gt;SongModel&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;countDocuments&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;existingCount&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="nb"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sb"&gt;`\nCollection already contains ${existingCount} documents — skipping insert.`&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="nb"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sb"&gt;`\nLoading pre-built dataset from ${DATA_FILE}...`&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
      &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="n"&gt;raw&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;JSON&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;parse&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;fs&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;readFileSync&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="no"&gt;DATA_FILE&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"utf-8"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Omit&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Song&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"seeded_at"&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;_id&lt;/span&gt;&lt;span class="o"&gt;?:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nv"&gt;$oid&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
      &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

      &lt;span class="c1"&gt;// songs.json is an Extended JSON export, so _id is { "$oid": "..." }. Convert it to a real ObjectId.&lt;/span&gt;
      &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="n"&gt;documents&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;raw&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;map&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;doc&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;doc&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;_id&lt;/span&gt;&lt;span class="o"&gt;?&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nv"&gt;$oid&lt;/span&gt; &lt;span class="o"&gt;?&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;_id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="n"&gt;mongoose&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Types&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;ObjectId&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;_id&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nv"&gt;$oid&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="n"&gt;seeded_at&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nb"&gt;Date&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
      &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

      &lt;span class="nb"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sb"&gt;`Inserting ${documents.length} documents into MongoDB...`&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
      &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nc"&gt;SongModel&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;insertMany&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;documents&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
      &lt;span class="nb"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"  Done."&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="c1"&gt;// Always runs — safe to call when the index already exists.&lt;/span&gt;
    &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nf"&gt;createVectorSearchIndex&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="n"&gt;finalCount&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nc"&gt;SongModel&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;countDocuments&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nb"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sb"&gt;`\n=== Seeding complete ===`&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nb"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sb"&gt;`Documents in '${COLLECTION_NAME}': ${finalCount}`&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;catch&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;err&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nb"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;error&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"\nSeeding failed:"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;err&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nb"&gt;process&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;exit&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;finally&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nf"&gt;disconnectDB&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nb"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"\nMongoDB connection closed."&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This function does a few things. After connecting, it calls &lt;code&gt;SongModel.createCollection()&lt;/code&gt; to make sure the &lt;code&gt;songs&lt;/code&gt; collection exists before we create a search index on it. Then it checks whether the collection already has documents by using &lt;code&gt;countDocuments()&lt;/code&gt;, so running the script a second time doesn’t insert duplicates.&lt;/p&gt;

&lt;p&gt;If the collection is empty, the script loads the pre-built dataset from &lt;code&gt;songs.json&lt;/code&gt;. This file is an Extended JSON export, which means each &lt;code&gt;_id&lt;/code&gt; is stored as &lt;code&gt;{ "$oid": "..." }&lt;/code&gt;, so we convert it into a real &lt;code&gt;ObjectId&lt;/code&gt; by using &lt;code&gt;mongoose.Types.ObjectId&lt;/code&gt; before inserting. Then &lt;code&gt;SongModel.insertMany()&lt;/code&gt; inserts all of the songs. This is where our schema comes into play: Mongoose validates every document against it, applies defaults, and rejects any document that is missing a required field, such as &lt;code&gt;embedding&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Whether it inserts the songs or skips them because they’re already there, the script ends by creating the vector search index. The &lt;code&gt;finally&lt;/code&gt; block closes the connection when the script completes.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Running the seed script&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;With everything in place, run the following command to connect to your cluster, insert the seed data, and create the vector search index:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;npm run seed
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This creates a new database called &lt;code&gt;song_vibe_search&lt;/code&gt; and a new collection called &lt;code&gt;songs&lt;/code&gt;. The &lt;code&gt;songs&lt;/code&gt; collection contains 500 documents, each representing a song with a “vibe description” and an embedding vector. It also creates a vector search index on the &lt;code&gt;embedding&lt;/code&gt; field.&lt;/p&gt;

&lt;p&gt;After the script finishes, the index can take a minute or so to build. You can check its status on the Search &amp;amp; Vector Search page for your cluster in the Atlas UI, and you should wait until it shows as active before searching. You can also check from code by calling &lt;code&gt;SongModel.listSearchIndexes()&lt;/code&gt; and looking for &lt;code&gt;queryable: true&lt;/code&gt; on the index.&lt;/p&gt;

&lt;p&gt;Now that we have our data and our vector search index, we are ready to build the main application.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Implementing Vector Search&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;In the &lt;code&gt;src&lt;/code&gt; directory, create a new file called &lt;code&gt;search.ts&lt;/code&gt;. This is where we will implement the search logic that powers our recommendations.&lt;/p&gt;

&lt;p&gt;First, we need to set our imports, our interfaces and constants, and load our Voyage AI key. Paste the following code into &lt;code&gt;search.ts&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;dotenv&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="s2"&gt;"dotenv"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;path&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="s2"&gt;"path"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nc"&gt;SongModel&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="no"&gt;VECTOR_INDEX&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;connectDB&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;disconnectDB&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="s2"&gt;"./song"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nc"&gt;VoyageAIClient&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="s2"&gt;"voyageai"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="c1"&gt;// Load the .env file from the project root, regardless of where the script is run from.&lt;/span&gt;
&lt;span class="n"&gt;dotenv&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;config&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;path&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;path&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;resolve&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;__dirname&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"../.env"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="no"&gt;VOYAGE_API_KEY&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;process&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;env&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;VOYAGE_API_KEY&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="no"&gt;VOYAGE_API_KEY&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nb"&gt;Error&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="s2"&gt;"Missing VOYAGE_API_KEY in environment. Ensure that you have created a .env file and added your Voyage AI key."&lt;/span&gt;
  &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="no"&gt;VECTOR_INDEX&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;connectDB&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;disconnectDB&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="n"&gt;voyage&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;VoyageAIClient&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;apiKey&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="no"&gt;VOYAGE_API_KEY&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;environment&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"https://ai.mongodb.com/v1"&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="no"&gt;EMBEDDING_MODEL&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"voyage-4-lite"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="no"&gt;NUM_RESULTS&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="no"&gt;NUM_CANDIDATES&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;interface&lt;/span&gt; &lt;span class="nc"&gt;SearchResult&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="n"&gt;title&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;string&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="n"&gt;artist&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;string&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="n"&gt;genre_top&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;string&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="n"&gt;genres&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;string&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="n"&gt;score&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;number&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;interface&lt;/span&gt; &lt;span class="nc"&gt;SearchResponse&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="n"&gt;results&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;SearchResult&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="n"&gt;queryVector&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;number&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Notice that we pass an &lt;code&gt;environment&lt;/code&gt; option to the Voyage AI client. It points the client at MongoDB’s Voyage AI endpoint, which is where API keys created in the MongoDB Atlas UI work. That’s why the prerequisites had you create your key through Atlas rather than directly on the Voyage AI platform. We’re also using the &lt;code&gt;voyage-4-lite&lt;/code&gt; model, which is the same model that generated the embeddings in our sample data.&lt;/p&gt;

&lt;p&gt;The model and connection functions come from the &lt;code&gt;song.ts&lt;/code&gt; file that we wrote earlier. We re-export the connection functions so the server, which we’ll build shortly, can import everything it needs from this one file.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;SearchResult&lt;/code&gt; interface is worth a closer look. It describes the shape of what our search returns, which is a subset of the full song document: only the fields that we show to the user, plus a similarity score. We define it separately from the &lt;code&gt;Song&lt;/code&gt; type because of how Mongoose handles aggregation, which we’ll see in a moment.&lt;/p&gt;

&lt;p&gt;If you’re unfamiliar with vector search, some of the constants above may not make sense quite yet, but we’ll explain them more as they’re used.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Embedding the query&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;When a user submits a search, the first thing we need to do is embed that query by using the same Voyage AI model that was used to embed our song descriptions. Paste the following code into &lt;code&gt;search.ts&lt;/code&gt; to create a search function and embed the query. Note the comment that shows where we will add the vector search query code in the next step.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;searchSongs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;query&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;string&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;Promise&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;SearchResponse&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="c1"&gt;// Embed the user's query by using Voyage AI.&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="n"&gt;embedResponse&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="n"&gt;voyage&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;embed&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="no"&gt;EMBEDDING_MODEL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;input&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;query&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;inputType&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"query"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="n"&gt;queryVector&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;embedResponse&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;embedding&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

  &lt;span class="c1"&gt;// vector search query code here&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This code specifies a few things. First, we specify the embedding model to use (in our case, we pass in the constant that we set earlier). We then pass the actual user query as an array to the &lt;code&gt;input&lt;/code&gt; parameter. Finally, we specify the &lt;code&gt;inputType&lt;/code&gt; as “&lt;code&gt;query&lt;/code&gt;”. Voyage AI distinguishes between the following two types of input:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;"document"&lt;/code&gt; — used when embedding data that gets saved into your database (the song vibe descriptions, in our case)
&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;"query"&lt;/code&gt; — used when embedding a search query at runtime&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Using the right input type improves retrieval quality. It’s a small but important thing to keep in mind when implementing vector search applications.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Searching with the model&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Now that we have our query embedded, it’s time to use it to search for similar songs. Replace the &lt;code&gt;// vector search query code here&lt;/code&gt; comment inside the function with the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;  &lt;span class="c1"&gt;// Run $vectorSearch against the songs collection through the Mongoose model.&lt;/span&gt;
  &lt;span class="c1"&gt;// Model.aggregate() sends the pipeline to MongoDB unchanged (Mongoose does not&lt;/span&gt;
  &lt;span class="c1"&gt;// cast it), so ranking and scores match the native driver.&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="n"&gt;results&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nc"&gt;SongModel&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;aggregate&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;SearchResult&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="nv"&gt;$vectorSearch&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;index&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="no"&gt;VECTOR_INDEX&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="n"&gt;path&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"embedding"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="n"&gt;queryVector&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="n"&gt;numCandidates&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="no"&gt;NUM_CANDIDATES&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="n"&gt;limit&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="no"&gt;NUM_RESULTS&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
      &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="nv"&gt;$project&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;_id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="n"&gt;title&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="n"&gt;artist&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="n"&gt;genre_top&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="n"&gt;genres&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="n"&gt;score&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nv"&gt;$meta&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"vectorSearchScore"&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
      &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;results&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;queryVector&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There’s no special Mongoose method for vector search. Instead, we use the &lt;code&gt;$vectorSearch&lt;/code&gt; stage of the &lt;a href="https://www.mongodb.com/docs/manual/core/aggregation-pipeline/?utm_campaign=devrel&amp;amp;utm_source=third-party-content&amp;amp;utm_medium=other" rel="noopener noreferrer"&gt;aggregation pipeline&lt;/a&gt; and run it by calling &lt;code&gt;aggregate()&lt;/code&gt; on our model. Mongoose passes the pipeline to MongoDB as written, without casting or validating it against the schema, and returns plain JavaScript objects instead of Mongoose documents. That’s why we pass &lt;code&gt;SearchResult&lt;/code&gt; as the type parameter to &lt;code&gt;aggregate()&lt;/code&gt;: it tells TypeScript what shape to expect, since the results have been reshaped by the &lt;code&gt;$project&lt;/code&gt; stage. Because Mongoose aggregations can be awaited directly, we don’t need to convert the results into an array ourselves.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;$vectorSearch&lt;/code&gt; stage takes the following parameters:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;index&lt;/code&gt; — The name of the vector search index we created during seeding
&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;path&lt;/code&gt; — The field in the document that holds the embedding (in this case, named &lt;code&gt;"embedding"&lt;/code&gt;).
&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;queryVector&lt;/code&gt; — The vector we just generated from the user’s query.
&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;numCandidates&lt;/code&gt; — How many candidate documents to consider before ranking. A higher number means the search will be more thorough but slower.
&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;limit&lt;/code&gt; — How many results to return.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;After the search stage, a &lt;code&gt;$project&lt;/code&gt; stage shapes our output, with &lt;code&gt;{ $meta: "vectorSearchScore" }&lt;/code&gt; pulling in the similarity score for each result — a number between 0 and 1, where higher means more similar.&lt;/p&gt;

&lt;p&gt;And that’s all we need for our search functionality! Next, we’ll build out a simple server with an endpoint to call this function.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Building the Server&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Create a new file called &lt;code&gt;server.ts&lt;/code&gt; in the &lt;code&gt;src&lt;/code&gt; directory. This is where we will create any endpoints we might need. In this tutorial, we will create a single endpoint to search for songs.&lt;/p&gt;

&lt;p&gt;To start, paste the following code into &lt;code&gt;server.ts&lt;/code&gt;, which specifies the imports and sets up an Express server:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="s2"&gt;"dotenv/config"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;express&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="s2"&gt;"express"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;path&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="s2"&gt;"path"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;connectDB&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;disconnectDB&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;searchSongs&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="s2"&gt;"./search"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="n"&gt;app&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;express&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="no"&gt;PORT&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;process&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;env&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;PORT&lt;/span&gt; &lt;span class="o"&gt;??&lt;/span&gt; &lt;span class="mi"&gt;3000&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="n"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;use&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;express&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;json&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="n"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;use&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;express&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;static&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;path&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;join&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;__dirname&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"../public"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Notice that the server imports &lt;code&gt;connectDB&lt;/code&gt; and &lt;code&gt;disconnectDB&lt;/code&gt; instead of a database client, and that it never touches the model directly. All of the database logic stays in &lt;code&gt;song.ts&lt;/code&gt; and &lt;code&gt;search.ts&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Now, we’ll create our POST route that calls the &lt;code&gt;searchSongs&lt;/code&gt; function we created earlier. Paste the following code into &lt;code&gt;server.ts&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="n"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;post&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"/api/search"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;req&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;query&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;req&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;body&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

  &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="n"&gt;query&lt;/span&gt; &lt;span class="o"&gt;||&lt;/span&gt; &lt;span class="k"&gt;typeof&lt;/span&gt; &lt;span class="n"&gt;query&lt;/span&gt; &lt;span class="o"&gt;!==&lt;/span&gt; &lt;span class="s2"&gt;"string"&lt;/span&gt; &lt;span class="o"&gt;||&lt;/span&gt; &lt;span class="n"&gt;query&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;trim&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="s2"&gt;""&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;status&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;400&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;json&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;error&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"A search query is required."&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;

  &lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="n"&gt;results&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;queryVector&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;results&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;queryVector&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nf"&gt;searchSongs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;query&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;trim&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;catch&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;err&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nb"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;error&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Search failed:"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;err&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;status&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;500&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;json&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;error&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"Search failed. Please try again."&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;

  &lt;span class="nb"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sb"&gt;`\nSearch: "${query.trim()}"`&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="nb"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sb"&gt;`Results (${results.length}):`&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="n"&gt;results&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;forEach&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt;
    &lt;span class="nb"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sb"&gt;`  ${i + 1}. ${r.title} — ${r.artist} (score: ${r.score.toFixed(3)})`&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

  &lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;json&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;results&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the preceding code, the function first checks that the query is valid. Then it sends the query to our &lt;code&gt;searchSongs()&lt;/code&gt; function and returns the results. If there is an error, it returns an error message. We also log each search and its results to the terminal, which is a handy way to see the similarity scores while you experiment.&lt;/p&gt;

&lt;p&gt;The last thing we need to do is write the code that actually starts the server and handles signals to close the connection cleanly on shutdown. Paste the following code into &lt;code&gt;server.ts&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;startServer&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nf"&gt;connectDB&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="nb"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Connected to MongoDB Atlas."&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

  &lt;span class="n"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;listen&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="no"&gt;PORT&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nb"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sb"&gt;`Server running at http://localhost:${PORT}`&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

  &lt;span class="nb"&gt;process&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;on&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"SIGINT"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nf"&gt;disconnectDB&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nb"&gt;process&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;exit&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

  &lt;span class="nb"&gt;process&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;on&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"SIGTERM"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nf"&gt;disconnectDB&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nb"&gt;process&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;exit&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nf"&gt;startServer&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The server waits for &lt;code&gt;connectDB()&lt;/code&gt; to finish before it starts listening for requests, and it calls &lt;code&gt;disconnectDB()&lt;/code&gt; to close Mongoose’s connection when the process is told to stop.&lt;/p&gt;

&lt;p&gt;Now that we have our server set up, let’s create a simple front end to interact with it.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Building the Front End&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Since the purpose of this tutorial is the search functionality itself, we’ll keep the front end simple. It doesn’t know or care that Mongoose is behind it, because it only talks to our server through an API. That’s one of the nice things about keeping your database logic behind an endpoint.&lt;/p&gt;

&lt;p&gt;To add it to your project, copy the public directory from the &lt;a href="https://github.com/mongodb-developer/song-vibe-recommendations/tree/main/Mongoose" rel="noopener noreferrer"&gt;&lt;code&gt;Mongoose&lt;/code&gt; directory&lt;/a&gt; of the GitHub repository and paste it into the root of your project. It’s important to keep the name as &lt;code&gt;public&lt;/code&gt;, since our server is already set up to serve files from this directory. If you want a line-by-line walkthrough of the HTML, CSS, and JavaScript, you can find it in our original music recommender tutorial, which builds the same front end.&lt;/p&gt;

&lt;p&gt;The only thing you need to know to follow along is how the page talks to the server. When you submit a search, the page sends a &lt;code&gt;POST&lt;/code&gt; request to &lt;code&gt;/api/search&lt;/code&gt; with a JSON body that contains your query:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nl"&gt;"query"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"upbeat road trip with the windows down"&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The server responds with a &lt;code&gt;results&lt;/code&gt; array, which the page renders as a list of cards:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nl"&gt;"results"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="nl"&gt;"title"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"Song Title"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
      &lt;span class="nl"&gt;"artist"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"Artist Name"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
      &lt;span class="nl"&gt;"genre_top"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"Rock"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
      &lt;span class="nl"&gt;"genres"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"Rock"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"Indie-Rock"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
      &lt;span class="nl"&gt;"score"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;0.87&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
  &lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Each card shows the title, artist, and genres, along with a match percentage calculated from the score and a link to search for the song on YouTube.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Running the App&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;At this point, you should have everything set up. Make sure you have already run the &lt;code&gt;npm run seed&lt;/code&gt; command from earlier in the tutorial and that your vector search index is active.&lt;/p&gt;

&lt;p&gt;Then, run the following command to start the server:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;npm run dev
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Open &lt;a href="http://localhost:3000" rel="noopener noreferrer"&gt;http://localhost:3000&lt;/a&gt; and try a few searches, such as:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;“melancholy rainy afternoon”
&lt;/li&gt;
&lt;li&gt;“high energy workout, aggressive beats”
&lt;/li&gt;
&lt;li&gt;“peaceful background music for focusing”&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You should see the results ranked by similarity score, with a link to YouTube so you can listen to the songs (if they’re uploaded there). You’ll also see each search and its scores printed in the terminal where the server is running. In a real application, you would want to serve the audio files or link directly to a streaming service, but for the sample data we’re using here, searching YouTube is the only free option without license limitations. If you want to expand on this with different music, check out APIs for streaming services like Spotify.&lt;/p&gt;

&lt;p&gt;If your searches come back empty, the most likely cause is that the vector search index is still building or doesn’t exist yet. Check its status in the Atlas UI, and make sure the name in your code (&lt;code&gt;vibe_vector_index&lt;/code&gt;) matches the name of the index.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Next Steps&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;And that’s the basics! You’ve now built a working music recommender that uses Mongoose, MongoDB Vector Search, and Voyage AI to find songs based on their “vibe.” There are lots of ways you can expand on this as well. Here are a few that build on what you’ve learned:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Filter your results.&lt;/strong&gt; &lt;code&gt;$vectorSearch&lt;/code&gt; accepts a &lt;code&gt;filter&lt;/code&gt; option that narrows the search to documents that match a condition, such as songs from a particular genre. To use it, add the field to your index definition as a &lt;code&gt;filter&lt;/code&gt; field, like &lt;code&gt;{ type: "filter", path: "genre_top" }&lt;/code&gt;, and update or recreate the index. Then add &lt;code&gt;filter: { genre_top: "Rock" }&lt;/code&gt; to the &lt;code&gt;$vectorSearch&lt;/code&gt; stage.
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Define your index on the schema.&lt;/strong&gt; As we mentioned in the seeding section, Mongoose lets you define search indexes with &lt;code&gt;schema.searchIndex()&lt;/code&gt;, which keeps your index definitions in version control right next to your schema.
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Store vectors more compactly.&lt;/strong&gt; MongoDB supports a binary vector format that takes up less space than an array of numbers. The &lt;a href="https://mongoosejs.com/docs/atlas-vector-search.html" rel="noopener noreferrer"&gt;Mongoose guide to vector search&lt;/a&gt; shows how to use it.
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Let Atlas generate your embeddings.&lt;/strong&gt; With MongoDB automated embedding, MongoDB Atlas can generate embeddings for you, so your application doesn’t have to call an embedding API. The same Mongoose guide covers how to set it up.
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Expand the data and features.&lt;/strong&gt; You could search on other metadata or even implement user profiles so that you can create personalized playlists and recommendations based on their likes, dislikes, and listening habits.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To use your own music instead of the sample data, you’ll need to generate vibe descriptions and embeddings for it. Our original music recommender tutorial walks through that process using Gemini and Voyage AI.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Conclusion&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;You have now built a fully functional application that uses Mongoose, MongoDB Vector Search, and Voyage AI to recommend music based on its general “vibes.” You defined a Mongoose schema and model for documents with embeddings, created a vector search index from the model, and ran &lt;code&gt;$vectorSearch&lt;/code&gt; queries through it. While this app is pretty simple and provides only basic functionality, you can easily use it as a baseline to build much more sophisticated applications.&lt;/p&gt;

&lt;p&gt;Hopefully, this gives you some insight into just how well MongoDB Vector Search works with Mongoose. If you want to learn more, check out the &lt;a href="https://mongoosejs.com/docs/atlas-vector-search.html" rel="noopener noreferrer"&gt;Mongoose documentation on vector search&lt;/a&gt; and &lt;a href="https://www.mongodb.com/docs/vector-search/?utm_campaign=devrel&amp;amp;utm_source=third-party-content&amp;amp;utm_medium=cta&amp;amp;utm_content=buildrel-mongoose-music&amp;amp;utm_term=hugh.murray" rel="noopener noreferrer"&gt;our documentation&lt;/a&gt;, or leave a comment letting me know how you’d like to see this expanded on!&lt;/p&gt;

</description>
      <category>ai</category>
      <category>mongodb</category>
      <category>mongoose</category>
      <category>webdev</category>
    </item>
    <item>
      <title>How to Know When to Scale Your MongoDB Atlas Cluster - Part 3: Turning benchmark results into a scaling strategy</title>
      <dc:creator>Tim Kelly</dc:creator>
      <pubDate>Wed, 25 Nov 2026 13:17:43 +0000</pubDate>
      <link>https://dev.to/mongodb/how-to-know-when-to-scale-your-mongodb-atlas-cluster-part-3-turning-benchmark-results-into-a-12g6</link>
      <guid>https://dev.to/mongodb/how-to-know-when-to-scale-your-mongodb-atlas-cluster-part-3-turning-benchmark-results-into-a-12g6</guid>
      <description>&lt;p&gt;Welcome back to How to Know When to Scale Your MongoDB Atlas Cluster. In Part 1, we chose a starting Atlas tier based on what we expected our application to need. In part 2, we learned how to benchmark our tiers against our workloads, and interpret the results. In this part, we are going to focus on turning everything we've learned into a scaling strategy.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Turning benchmark results into a scaling strategy&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;We've seen how MongoDB Atlas responds to increasing workloads and how to investigate the resources that might be limiting performance. But benchmarking is only the starting point. The real challenge is turning those results into informed scaling decisions in production.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Establishing your performance baseline&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Start by defining the performance your application needs to maintain, including acceptable &lt;strong&gt;p95 and p99 latency&lt;/strong&gt;, expected throughput, and sufficient headroom for traffic spikes.&lt;/p&gt;

&lt;p&gt;In our M10 benchmark, we sustained 1,000 operations per second while keeping p95 latency below 200 ms. At 1,500 operations per second, throughput continued increasing, but latency exceeded our target.&lt;/p&gt;

&lt;p&gt;This gives us a useful performance baseline, but it doesn't mean we should operate at 1,000 operations per second continuously. Instead, we should plan for additional headroom and validate sustained capacity through longer tests.&lt;/p&gt;

&lt;p&gt;Remember that &lt;strong&gt;benchmark results aren't permanent capacity guarantees&lt;/strong&gt;. Changes to your dataset, queries, indexes, and traffic patterns can all affect how much work your cluster can handle.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Knowing when to take action&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Use your benchmark results as a reference when evaluating production performance:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;What you observe&lt;/th&gt;
&lt;th&gt;Recommended action&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Throughput increases, latency remains stable&lt;/td&gt;
&lt;td&gt;Continue monitoring&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;High CPU and deteriorating latency&lt;/td&gt;
&lt;td&gt;Investigate expensive queries and test a larger tier&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Cache pressure and increasing disk reads&lt;/td&gt;
&lt;td&gt;Evaluate working-set size and memory requirements&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Excessive documents examined&lt;/td&gt;
&lt;td&gt;Optimize queries and indexes&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Growing operation queues and plateauing throughput&lt;/td&gt;
&lt;td&gt;Investigate resource saturation&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Healthy performance but increasing demand&lt;/td&gt;
&lt;td&gt;Plan ahead and benchmark the next tier&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;These observations aren't automatic triggers to scale. They're signals that help us decide &lt;strong&gt;what to investigate before making a change&lt;/strong&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Monitoring and planning ahead&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Use &lt;a href="https://www.mongodb.com/docs/atlas/monitoring-alerts/?utm_campaign=devrel&amp;amp;utm_source=third-party-content&amp;amp;utm_medium=cta&amp;amp;utm_content=buildrel-when-to-scale-mdb-cluster&amp;amp;utm_term=hugh.murray" rel="noopener noreferrer"&gt;Atlas Alerts&lt;/a&gt; to monitor resource utilization and notify you when performance approaches concerning levels. Rather than relying on arbitrary thresholds or reacting to isolated spikes, use your benchmark results and production behaviour to establish alerts that reflect sustained pressure on your cluster.&lt;/p&gt;

&lt;p&gt;For eligible dedicated clusters, &lt;a href="https://www.mongodb.com/docs/atlas/cluster-autoscaling-compute-core/?utm_campaign=devrel&amp;amp;utm_source=third-party-content&amp;amp;utm_medium=cta&amp;amp;utm_content=buildrel-when-to-scale-mdb-cluster&amp;amp;utm_term=hugh.murray" rel="noopener noreferrer"&gt;Atlas Compute Auto-Scaling&lt;/a&gt; can help accommodate changing resource demands within configured limits. However, scaling takes time, and auto-scaling won't resolve inefficient queries or eliminate the need for capacity planning.&lt;/p&gt;

&lt;p&gt;As your application grows, monitor throughput and latency trends, revisit your performance targets, and repeat your benchmarks when the workload changes significantly.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Conclusion: Measure, don't guess&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;So, how do you know when it's time to scale your MongoDB Atlas cluster?&lt;/p&gt;

&lt;p&gt;There's no universal queries-per-second threshold that tells you when to upgrade. Every application has different query patterns, data volumes, concurrency requirements, and performance expectations.&lt;/p&gt;

&lt;p&gt;As we've seen, &lt;strong&gt;benchmarking isn't simply about finding the maximum throughput your cluster can handle&lt;/strong&gt;. It's about understanding how your workload behaves under increasing demand, identifying bottlenecks, and determining whether additional resources would actually improve performance.&lt;/p&gt;

&lt;p&gt;Before scaling, investigate your queries, indexes, and resource utilization. Establish a performance baseline, monitor how your application behaves as traffic grows, and test larger configurations when necessary.&lt;/p&gt;

&lt;p&gt;You can get started with my &lt;a href="https://github.com/timotheekelly/mongodb-locust-load-tester" rel="noopener noreferrer"&gt;MongoDB Locust Load Tester&lt;/a&gt; or build your own benchmarking environment. Whichever approach you choose, &lt;strong&gt;reproduce your application's workload as closely as possible&lt;/strong&gt;. The more representative your benchmark, the more useful its results will be.&lt;/p&gt;

&lt;p&gt;Ultimately, the right cluster isn't the one that handles the most queries per second. It's the one that reliably meets your application's performance requirements without unnecessary infrastructure costs.&lt;/p&gt;

</description>
      <category>mongodb</category>
      <category>performance</category>
      <category>database</category>
      <category>cloud</category>
    </item>
    <item>
      <title>How to Know When to Scale Your MongoDB Atlas Cluster - Part 2: Benchmarking Your Workload with Locust</title>
      <dc:creator>Tim Kelly</dc:creator>
      <pubDate>Wed, 25 Nov 2026 13:17:37 +0000</pubDate>
      <link>https://dev.to/mongodb/how-to-know-when-to-scale-your-mongodb-atlas-cluster-part-2-benchmarking-your-workload-with-3fk5</link>
      <guid>https://dev.to/mongodb/how-to-know-when-to-scale-your-mongodb-atlas-cluster-part-2-benchmarking-your-workload-with-3fk5</guid>
      <description>&lt;p&gt;Welcome back to &lt;em&gt;How to Know When to Scale Your MongoDB Atlas Cluster&lt;/em&gt;. In Part 1, we chose a starting Atlas tier based on what we expected our application to need. Now let’s put that choice to the test. How much traffic can the cluster handle before requests start taking longer than our application can tolerate?&lt;/p&gt;

&lt;p&gt;We’ll use a load tester I built with Locust to run the same read-heavy workload against Flex, M10, and M30, increasing the load in stages. At each stage, we’ll measure how much work each cluster completes and whether p95 latency stays below our example target of 200 ms. Then we’ll use Atlas metrics to investigate what happens as response times climb.&lt;/p&gt;

&lt;p&gt;The load tester is an unofficial project you can configure to match your application’s mix of reads, writes, and aggregations. If you already have a benchmarking tool, you can use it and follow along with the same approach to measuring performance and interpreting the results.&lt;/p&gt;

&lt;h2&gt;
  
  
  Understanding the metrics
&lt;/h2&gt;

&lt;p&gt;A benchmark tells us how our MongoDB cluster performs under load, but understanding &lt;em&gt;why&lt;/em&gt; performance changes requires looking at the underlying resource metrics.&lt;/p&gt;

&lt;p&gt;In MongoDB Atlas, navigate to your cluster's &lt;strong&gt;Metrics&lt;/strong&gt; tab, set the time range to match your benchmark, and select the relevant replica set node. We'll focus on six metrics:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fxdy8wtss1d8wbubcjqfu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fxdy8wtss1d8wbubcjqfu.png" alt="MongoDB Atlas metrics chart" width="800" height="495"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Metric&lt;/th&gt;
&lt;th&gt;What to watch for&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Operations per second&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Throughput plateauing despite increasing demand.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Normalized CPU utilization&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Sustained high utilization accompanied by rising latency.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Operation queues&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Operations accumulating as concurrency increases.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;WiredTiger cache&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Increasing eviction pressure or pages being read into cache.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Disk IOPS and latency&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Growing disk activity accompanied by slower operations.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Query targeting&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Excessive documents or index keys examined relative to results returned.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;These metrics are most useful when examined together. High CPU utilization isn't necessarily a problem if throughput continues increasing and latency remains acceptable. However, high CPU alongside growing operation queues and deteriorating response times could indicate compute saturation.&lt;/p&gt;

&lt;p&gt;Similarly, increased disk activity might suggest that the working set no longer fits comfortably in memory, but it could also result from inefficient queries scanning unnecessary documents.&lt;/p&gt;

&lt;p&gt;Before upgrading, investigate whether the workload itself can be improved. Atlas's &lt;strong&gt;Query Profiler&lt;/strong&gt;, &lt;strong&gt;Performance Advisor&lt;/strong&gt;, and MongoDB's &lt;code&gt;explain()&lt;/code&gt; command can help identify expensive queries and indexing opportunities.&lt;/p&gt;

&lt;p&gt;We'll also measure &lt;strong&gt;p95 and p99 latency&lt;/strong&gt; using our load-testing tool, since averages can hide slow operations that affect application performance. And remember, a throughput plateau doesn't necessarily mean MongoDB is responsible — the application, network, connection pool, or load generator could also be the bottleneck.&lt;/p&gt;

&lt;p&gt;Ultimately, &lt;strong&gt;we're not looking for a cluster where every metric stays low&lt;/strong&gt;. We want one that sustains our workload, meets our latency requirements, and maintains sufficient headroom for unexpected demand.&lt;/p&gt;

&lt;p&gt;With that in mind, let's put these metrics to work.&lt;/p&gt;

&lt;h2&gt;
  
  
  Benchmarking your MongoDB workload with Locust
&lt;/h2&gt;

&lt;p&gt;Now that we understand which metrics to monitor, let's see how they behave under increasing load.&lt;/p&gt;

&lt;p&gt;For this experiment, I'll use my &lt;a href="https://github.com/timotheekelly/mongodb-locust-load-tester" rel="noopener noreferrer"&gt;MongoDB Locust Load Tester&lt;/a&gt; to generate a controlled workload against MongoDB Atlas. By gradually increasing the operation rate and comparing application latency with Atlas resource metrics, we can identify where performance begins to deteriorate and investigate whether scaling would help.&lt;/p&gt;

&lt;p&gt;The goal isn't to establish a universal queries-per-second limit for a particular cluster tier. It's to demonstrate &lt;strong&gt;how to benchmark a MongoDB workload against defined performance requirements&lt;/strong&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;The scenario: Can our cluster support the expected workload?&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Imagine an application currently running on Atlas Free. It's performed well with a small audience, but we're preparing to open it to the public and need to understand whether a dedicated cluster will provide sufficient capacity.&lt;/p&gt;

&lt;p&gt;For this experiment, we'll use an &lt;strong&gt;M10 cluster&lt;/strong&gt; and the load tester's &lt;code&gt;read_heavy&lt;/code&gt; profile. This simulates primarily indexed lookups and range queries, alongside a smaller proportion of writes and aggregations.&lt;/p&gt;

&lt;p&gt;The benchmark uses a &lt;strong&gt;2 GB dataset&lt;/strong&gt;, although the actively accessed working set may be considerably smaller.&lt;/p&gt;

&lt;p&gt;We'll also establish a performance requirement: our application must maintain &lt;strong&gt;p95 latency below 200 ms&lt;/strong&gt;. This is an illustrative application target, not a MongoDB-recommended threshold.&lt;/p&gt;

&lt;p&gt;Our objective is to determine how the workload behaves as demand increases, identify where it stops meeting that requirement, and investigate the underlying bottlenecks.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Prerequisites&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Before we get started, here's what you'll need:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Python 3.12 or later&lt;/strong&gt;, with &lt;code&gt;pip&lt;/code&gt; available to install the benchmark dependencies.
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;A MongoDB Atlas cluster&lt;/strong&gt; configured for testing. I'll use M10 for this experiment. If you need help creating a cluster, see &lt;a href="https://www.mongodb.com/docs/atlas/getting-started/?utm_campaign=devrel&amp;amp;utm_source=third-party-content&amp;amp;utm_medium=cta&amp;amp;utm_content=buildrel-when-to-scale-mdb-cluster&amp;amp;utm_term=hugh.murray" rel="noopener noreferrer"&gt;Get Started with Atlas&lt;/a&gt;.
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;A MongoDB database user&lt;/strong&gt; with the permissions required to create and populate the benchmark dataset, and network access configured to allow connections from your load generator.
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;MongoDB Atlas Administration API credentials&lt;/strong&gt;, if you want to collect Atlas resource metrics alongside Locust results. The benchmark can run without them, but database-side analysis will be more limited.
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Docker, Google Cloud CLI (&lt;code&gt;gcloud&lt;/code&gt;), and &lt;code&gt;kubectl&lt;/code&gt;&lt;/strong&gt;, if you want to reproduce the distributed benchmark using Google Kubernetes Engine (GKE). These aren't required for local testing.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Use a dedicated test cluster rather than a deployment serving production traffic.&lt;/strong&gt; The benchmark creates synthetic data and deliberately increases demand until performance deteriorates.&lt;/p&gt;

&lt;p&gt;You can experiment with Atlas Free, but its shared-resource limits make it unsuitable for reproducing the dedicated-cluster results in this tutorial. If testing Free, use the &lt;code&gt;tiny&lt;/code&gt; dataset preset (256 MB) rather than &lt;code&gt;small&lt;/code&gt; (2 GB), and review the workload safety limits in &lt;code&gt;config/base.yaml&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Setting up the benchmark&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Start by cloning the repository and installing its dependencies:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;git clone https://github.com/mongodb-developer/mongodb-locust-load-tester.git
&lt;span class="nb"&gt;cd&lt;/span&gt; mongodb-locust-load-tester

python -m pip install -r requirements.txt
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, copy the example environment configuration:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;cp .env.example .env
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Configure the connection string and any Atlas API credentials required by your environment, then verify that the cluster is defined correctly in &lt;code&gt;tiers.yaml&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;This workload is entirely configurable. Feel free to adjust document size, nesting depth, or weights for the different database operations to better represent your workload. Anything you need to change can be found in the &lt;code&gt;/config&lt;/code&gt; directory.&lt;/p&gt;

&lt;p&gt;The repository includes several workload profiles and dataset sizes, allowing you to adjust the experiment to reflect your application's requirements.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Running a local benchmark&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;The simplest way to get started is to run Locust locally using &lt;code&gt;benchmarks.orchestrator&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;python -m benchmarks.orchestrator \
    --tier M10 \
    --profile read_heavy \
    --volume small \
    --offered-load-stages 10,25,50,75,100,150,200 \
    --offered-load-stage-time 60s \
    --report
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This runs a smaller exploratory benchmark, increasing the target operation rate from 10 to 200 operations per second.&lt;/p&gt;

&lt;p&gt;The main configuration options are:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Flag&lt;/th&gt;
&lt;th&gt;Purpose&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;--tier M10&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Selects the configured Atlas cluster&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;--profile read_heavy&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Defines the mix of MongoDB operations&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;--volume small&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Uses the 2 GB dataset preset&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;--offered-load-stages&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Defines the target operation rates for successive stages&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;--offered-load-stage-time 60s&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Runs each stage for 60 seconds&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;--skip-seed&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Reuses an existing dataset&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;--report&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Generates reports and charts&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Running locally is useful for exploring workload behavior, validating your configuration, and investigating queries.&lt;/p&gt;

&lt;p&gt;However, &lt;strong&gt;the results presented in this tutorial were not generated on my laptop&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;For the full experiment, I increased the offered load to 2,000 operations per second using distributed Locust workers on Google Kubernetes Engine.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Setting up distributed load generation with GKE&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;As offered load increases, the load generator itself can become a bottleneck. A single process may struggle to maintain the requested operation rate, making it difficult to distinguish database limitations from limitations in the testing environment.&lt;/p&gt;

&lt;p&gt;To reduce this risk, I used &lt;strong&gt;Google Kubernetes Engine (GKE) with eight Locust worker pods&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;To reproduce this setup, you'll need a running GKE cluster, the Google Cloud CLI authenticated to your project, and &lt;code&gt;kubectl&lt;/code&gt; configured to access the cluster.&lt;/p&gt;

&lt;p&gt;Verify your current Kubernetes context:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;kubectl config current-context
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Your GKE nodes must also be able to pull images from Artifact Registry, and the cluster must have network connectivity to MongoDB Atlas. This includes configuring the Atlas network access list for the load generators' outbound addresses and ensuring the relevant Kubernetes workloads can access the required MongoDB credentials.&lt;/p&gt;

&lt;p&gt;We'll package the benchmark application into a container image and push it to Google Artifact Registry.&lt;/p&gt;

&lt;p&gt;First, create a Docker repository and configure authentication:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;gcloud artifacts repositories create locust-bench \
    --repository-format=docker \
    --location=&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;region&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;

gcloud auth configure-docker &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;region&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;-docker.pkg.dev
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, build and push the image:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;docker build --platform linux/amd64 \
    -t &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;region&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;-docker.pkg.dev/&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;project-id&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;/locust-bench/locust-mongo-bench:latest .

docker push &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;region&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;-docker.pkg.dev/&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;project-id&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;/locust-bench/locust-mongo-bench:latest
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;--platform linux/amd64&lt;/code&gt; flag ensures the image is compatible with amd64 GKE nodes, which is particularly important when building on an Apple Silicon Mac. If your GKE node pool uses another architecture, build for that architecture instead.&lt;/p&gt;

&lt;p&gt;With the image available in Artifact Registry, we can run the distributed benchmark using &lt;code&gt;benchmarks.orchestrator_k8s&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;It accepts the same workload configuration as the local orchestrator, with additional options for the container image and number of workers:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;python -m benchmarks.orchestrator_k8s \
    --image &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;region&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;-docker.pkg.dev/&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;project-id&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;/locust-bench/locust-mongo-bench:latest \
    --tier M10 \
    --profile read_heavy \
    --volume small \
    --workers 8 \
    --offered-load-stages 10,25,50,75,100,150,200,300,500,750,1000,1500,2000 \
    --offered-load-stage-time 60s \
    --report
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;This is the command used to generate the benchmark results presented in this tutorial.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The eight workers distribute load generation across Kubernetes pods, reducing the likelihood that a single process limits throughput. However, distributed load generation doesn't guarantee unlimited capacity. We still need to verify that the workers can sustain the requested operation rate.&lt;/p&gt;

&lt;p&gt;If a benchmark fails or terminates unexpectedly, inspect &lt;code&gt;results/&amp;lt;profile&amp;gt;/&amp;lt;volume&amp;gt;/&amp;lt;tier&amp;gt;/k8s_debug.txt&lt;/code&gt;. The orchestrator captures Kubernetes job status, pod information, and logs to help diagnose failures.&lt;/p&gt;

&lt;p&gt;The 60-second stages are sufficient for an exploratory benchmark, but they aren't a substitute for longer, repeated tests when planning production capacity.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Understanding the results&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Benchmark outputs are written to:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;results/&amp;lt;profile&amp;gt;/&amp;lt;volume&amp;gt;/&amp;lt;tier&amp;gt;/&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The main files are &lt;code&gt;run_metadata.json&lt;/code&gt;, &lt;code&gt;locust_stats_history.csv&lt;/code&gt;, and &lt;code&gt;atlas_metrics.json&lt;/code&gt;, containing execution metadata, Locust performance measurements, and collected Atlas resource metrics.&lt;/p&gt;

&lt;p&gt;To summarize the results by load stage, run:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;python -m benchmarks.analyze_saturation \
    --profile read_heavy \
    --volume small \
    --tier M10
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The analysis distinguishes three throughput measurements:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Metric&lt;/th&gt;
&lt;th&gt;Meaning&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Offered&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;The target operation rate requested by the benchmark&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Started&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;The rate at which the load generator actually begins operations&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Achieved&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;The rate of completed operations, including failures&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;We'll examine these alongside p95 latency, error rates, and Atlas resource utilization.&lt;/p&gt;

&lt;p&gt;When offered, started, and achieved throughput remain close together, the benchmark is keeping pace with the requested load.&lt;/p&gt;

&lt;p&gt;If started throughput falls behind, the generator isn't maintaining the requested rate. This could indicate insufficient load-generator capacity, but slow database operations can also keep simulated users occupied, preventing them from starting additional work.&lt;/p&gt;

&lt;p&gt;Similarly, a difference between started and achieved throughput requires investigation into in-flight operations, completion times, and the measurement window before we can identify a bottleneck.&lt;/p&gt;

&lt;p&gt;We'll focus primarily on the Atlas primary node because the default MongoDB read preference directs reads to the primary, while writes are also processed there. Averaging utilization across less-active secondary nodes could obscure pressure on the node handling most of our workload.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Two problems that nearly invalidated the benchmark&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;My initial results were considerably worse than expected. Even at 10 operations per second, some requests were taking more than a minute to complete. Before blaming the cluster, I investigated the workload and the benchmarking tool itself.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The first problem was an expensive aggregation.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Breaking down latency by operation type revealed that &lt;code&gt;AGGREGATE&lt;/code&gt; operations were taking between 47 and 270+ seconds.&lt;/p&gt;

&lt;p&gt;The query filtered documents by &lt;code&gt;category&lt;/code&gt;, so I added an index and inspected the execution plan using &lt;code&gt;explain()&lt;/code&gt;. MongoDB switched from a collection scan to an &lt;code&gt;IXSCAN&lt;/code&gt;, but the aggregation still took nearly eight seconds because the subsequent &lt;code&gt;$group&lt;/code&gt; stage remained expensive.&lt;/p&gt;

&lt;p&gt;For this synthetic workload, I changed the aggregation to process a bounded subset of documents, applying &lt;code&gt;$match&lt;/code&gt;, &lt;code&gt;$sort&lt;/code&gt;, and &lt;code&gt;$limit&lt;/code&gt; before &lt;code&gt;$group&lt;/code&gt;, supported by a compound index on &lt;code&gt;(category, seq)&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;This changes the aggregation's semantics&lt;/strong&gt;, since grouping a limited subset isn't equivalent to grouping all matching documents. It was appropriate for this synthetic workload, but wouldn't be suitable for an application requiring complete aggregation results. The sort also needs a unique ordering to select a deterministic subset.&lt;/p&gt;

&lt;p&gt;With these changes, isolated aggregation latency dropped to approximately &lt;strong&gt;280 ms&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The second problem was in the benchmarking tool itself.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Even after fixing the aggregation, achieved throughput consistently matched the &lt;em&gt;previous&lt;/em&gt; stage's offered load.&lt;/p&gt;

&lt;p&gt;The analyzer was calculating stage boundaries from when Kubernetes received the benchmark job, rather than when Locust actually began generating traffic. Pod scheduling, image pulls, and worker startup introduced a delay of almost an entire load stage.&lt;/p&gt;

&lt;p&gt;I corrected the analyzer to infer stage boundaries from observed simulated-user counts, improving measurement alignment. Explicit stage-transition timestamps would be more reliable in future iterations.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Both problems could have led to an unnecessary scaling decision.&lt;/strong&gt; One came from an inefficient workload; the other from inaccurate measurement. Before deciding that MongoDB needs more resources, make sure you're measuring the workload correctly.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;The corrected benchmark results&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;With those issues addressed, I reran the benchmark against M10.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F0u19by98jgrokwdex325.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F0u19by98jgrokwdex325.png" alt="M10 achieved throughput vs offered load" width="800" height="489"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fyov4t5ucu14mnawa9syo.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fyov4t5ucu14mnawa9syo.png" alt="M10 p95 latency vs offered load" width="800" height="489"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Offered ops/s&lt;/th&gt;
&lt;th&gt;Started ops/s&lt;/th&gt;
&lt;th&gt;Achieved ops/s&lt;/th&gt;
&lt;th&gt;p95 latency&lt;/th&gt;
&lt;th&gt;Errors&lt;/th&gt;
&lt;th&gt;Primary CPU&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;10&lt;/td&gt;
&lt;td&gt;10.0&lt;/td&gt;
&lt;td&gt;10.0&lt;/td&gt;
&lt;td&gt;65.4 ms&lt;/td&gt;
&lt;td&gt;0.0%&lt;/td&gt;
&lt;td&gt;2.0%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;25&lt;/td&gt;
&lt;td&gt;25.0&lt;/td&gt;
&lt;td&gt;25.0&lt;/td&gt;
&lt;td&gt;69.6 ms&lt;/td&gt;
&lt;td&gt;0.0%&lt;/td&gt;
&lt;td&gt;2.2%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;50&lt;/td&gt;
&lt;td&gt;49.8&lt;/td&gt;
&lt;td&gt;49.8&lt;/td&gt;
&lt;td&gt;64.6 ms&lt;/td&gt;
&lt;td&gt;0.0%&lt;/td&gt;
&lt;td&gt;3.2%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;75&lt;/td&gt;
&lt;td&gt;75.0&lt;/td&gt;
&lt;td&gt;75.0&lt;/td&gt;
&lt;td&gt;68.6 ms&lt;/td&gt;
&lt;td&gt;0.0%&lt;/td&gt;
&lt;td&gt;4.4%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;100&lt;/td&gt;
&lt;td&gt;99.6&lt;/td&gt;
&lt;td&gt;99.6&lt;/td&gt;
&lt;td&gt;61.4 ms&lt;/td&gt;
&lt;td&gt;0.0%&lt;/td&gt;
&lt;td&gt;5.0%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;150&lt;/td&gt;
&lt;td&gt;149.9&lt;/td&gt;
&lt;td&gt;149.9&lt;/td&gt;
&lt;td&gt;65.3 ms&lt;/td&gt;
&lt;td&gt;0.0%&lt;/td&gt;
&lt;td&gt;7.0%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;200&lt;/td&gt;
&lt;td&gt;200.0&lt;/td&gt;
&lt;td&gt;200.2&lt;/td&gt;
&lt;td&gt;64.7 ms&lt;/td&gt;
&lt;td&gt;0.0%&lt;/td&gt;
&lt;td&gt;8.7%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;300&lt;/td&gt;
&lt;td&gt;300.0&lt;/td&gt;
&lt;td&gt;300.2&lt;/td&gt;
&lt;td&gt;77.5 ms&lt;/td&gt;
&lt;td&gt;0.0%&lt;/td&gt;
&lt;td&gt;12.3%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;500&lt;/td&gt;
&lt;td&gt;498.0&lt;/td&gt;
&lt;td&gt;498.0&lt;/td&gt;
&lt;td&gt;103.6 ms&lt;/td&gt;
&lt;td&gt;0.0%&lt;/td&gt;
&lt;td&gt;17.7%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;750&lt;/td&gt;
&lt;td&gt;750.0&lt;/td&gt;
&lt;td&gt;750.3&lt;/td&gt;
&lt;td&gt;144.7 ms&lt;/td&gt;
&lt;td&gt;0.0%&lt;/td&gt;
&lt;td&gt;25.9%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;1,000&lt;/td&gt;
&lt;td&gt;1,000.3&lt;/td&gt;
&lt;td&gt;1,000.1&lt;/td&gt;
&lt;td&gt;138.9 ms&lt;/td&gt;
&lt;td&gt;0.0%&lt;/td&gt;
&lt;td&gt;33.6%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;1,500&lt;/td&gt;
&lt;td&gt;1,496.3&lt;/td&gt;
&lt;td&gt;1,501.3&lt;/td&gt;
&lt;td&gt;449.0 ms&lt;/td&gt;
&lt;td&gt;0.0%&lt;/td&gt;
&lt;td&gt;54.4%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;2,000&lt;/td&gt;
&lt;td&gt;883.2&lt;/td&gt;
&lt;td&gt;863.9&lt;/td&gt;
&lt;td&gt;4,240.8 ms&lt;/td&gt;
&lt;td&gt;0.1%&lt;/td&gt;
&lt;td&gt;N/A&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;&lt;em&gt;CPU values represent the primary node's normalized CPU utilization. No CPU measurement was available for the final stage on this first run.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Up to &lt;strong&gt;1,000 operations per second&lt;/strong&gt;, the benchmark maintains its requested throughput with no reported errors. More importantly, p95 latency remains below our illustrative 200 ms target, while normalized CPU utilization rises from approximately 2% to 34%.&lt;/p&gt;

&lt;p&gt;At &lt;strong&gt;1,500 operations per second&lt;/strong&gt;, throughput still keeps pace with the offered load, but p95 latency jumps to 449 ms, exceeding our application's performance requirement.&lt;/p&gt;

&lt;p&gt;At &lt;strong&gt;2,000 offered operations per second&lt;/strong&gt;, performance deteriorates sharply. The generator performs only 883 operations per second, achieves approximately 864 completions per second, and has a p95 latency exceeding four seconds.&lt;/p&gt;

&lt;p&gt;This demonstrates an important distinction: &lt;strong&gt;the point at which throughput breaks down isn't necessarily the point where an application should scale&lt;/strong&gt;. Our application already breached its latency requirement at 1,500 operations per second, despite maintaining the requested throughput.&lt;/p&gt;

&lt;p&gt;These results establish that the tested configuration handled 1,000 operations per second within our latency target during the exploratory benchmark. However, the 60-second stages don't establish long-term capacity, and we haven't tested the range between 1,000 and 1,500 operations per second.&lt;/p&gt;

&lt;p&gt;CPU utilization alone doesn't explain the deterioration either. At 1,500 operations per second, normalized CPU reached only 54.4%. To investigate further, we need to examine what was happening inside MongoDB.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Investigating the throughput collapse&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;To understand the performance deterioration, I examined additional historical metrics from MongoDB Atlas, focusing on operation execution times, disk activity, WiredTiger read tickets, and operation queues.&lt;/p&gt;

&lt;p&gt;The most revealing measurements were &lt;strong&gt;&lt;code&gt;TICKETS_AVAILABLE_READS&lt;/code&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;code&gt;GLOBAL_LOCK_CURRENT_QUEUE_READERS&lt;/code&gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;WiredTiger uses execution tickets to regulate concurrent operations, while MongoDB's global lock queue metrics track operations waiting for lock acquisition. Although these measure different forms of contention, examining them together helps identify when operations begin accumulating.&lt;/p&gt;

&lt;p&gt;For most of the benchmark, approximately &lt;strong&gt;47 read tickets remained available&lt;/strong&gt;, with no queued readers. As demand increased, available tickets fell sharply.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fw8y428zeqnr7ib0zue24.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fw8y428zeqnr7ib0zue24.png" alt="M10 read tickets available vs readers queued" width="800" height="489"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;At the same time, queued readers increased from zero to &lt;strong&gt;14, 14, and eventually 39&lt;/strong&gt; across the final three reported minutes.&lt;/p&gt;

&lt;p&gt;This provides evidence of substantial concurrency pressure: &lt;strong&gt;read execution capacity was exhausted while operations began accumulating in queues&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;However, ticket exhaustion doesn't necessarily explain what originally caused operations to slow down. Longer-running operations can occupy execution capacity for longer, creating additional contention.&lt;/p&gt;

&lt;p&gt;Other Atlas metrics revealed further evidence of performance degradation:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F3gapa4o436d2tvh8orbt.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F3gapa4o436d2tvh8orbt.png" alt="Operation execution time" width="800" height="194"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Operation execution times:&lt;/strong&gt; Average read execution time increased substantially, eventually approaching eight seconds.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Faq7t88n6r8cqnc1vh4xh.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Faq7t88n6r8cqnc1vh4xh.png" alt="Disk Latency graph" width="800" height="198"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Disk performance:&lt;/strong&gt; Primary read latency increased to approximately 8–10 ms, alongside elevated read IOPS.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fcbnyb4j5mrrxpnjvaifk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fcbnyb4j5mrrxpnjvaifk.png" alt="Operation queue graph" width="800" height="214"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Operation queues:&lt;/strong&gt; Atlas's total operation queue later peaked at approximately 450.
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;WiredTiger cache:&lt;/strong&gt; Cache fill ratio generally remained around 77–80%, without a sustained increase suggesting cache-fill saturation.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;These measurements show that &lt;strong&gt;read execution, storage activity, and concurrency pressure all deteriorated during the benchmark&lt;/strong&gt;. They don't establish a single root cause, but they give us a much clearer picture than CPU utilization or throughput alone.&lt;/p&gt;

&lt;p&gt;Importantly, the application had already exceeded its latency requirement at 1,500 operations per second, before the final throughput collapse. That remains our first reason to investigate scaling, regardless of which resource ultimately limited throughput.&lt;/p&gt;

&lt;h3&gt;
  
  
  What does this mean for scaling?
&lt;/h3&gt;

&lt;p&gt;For our hypothetical application, the benchmark demonstrates that the tested M10 configuration can handle substantial throughput while meeting our latency requirement, but only within the workload and test conditions we've measured.&lt;/p&gt;

&lt;p&gt;At 1,500 operations per second, the application no longer meets its latency target. At the final stage, we also observe read-ticket exhaustion and growing read queues alongside a sharp throughput decline.&lt;/p&gt;

&lt;p&gt;That gives us a much more useful starting point for deciding what to investigate next.&lt;/p&gt;

&lt;p&gt;We could repeat the experiment with smaller load increments between 1,000 and 1,500 operations per second, extend the measurement windows, and compare the results against a larger cluster.&lt;/p&gt;

&lt;p&gt;We should also remember that this benchmark represents only one workload profile and dataset. A larger working set could increase cache pressure and disk reads, while additional writes, more complex aggregations, or larger documents could introduce different constraints.&lt;/p&gt;

&lt;p&gt;The load tester's &lt;code&gt;balanced&lt;/code&gt; and &lt;code&gt;cpu_intensive&lt;/code&gt; profiles, along with configurable document sizes, offer a starting point for exploring these scenarios.&lt;/p&gt;

&lt;p&gt;We haven't discovered a universal QPS limit for M10. We've demonstrated how to benchmark a particular MongoDB workload, identify where it stops meeting its performance requirements, and use Atlas metrics to investigate why.&lt;/p&gt;

&lt;h2&gt;
  
  
  Try a larger cluster: Benchmarking doesn't have to be expensive
&lt;/h2&gt;

&lt;p&gt;If your benchmark suggests that your current cluster is approaching its limits, the next step is to test whether a larger tier actually improves performance.&lt;/p&gt;

&lt;p&gt;MongoDB Atlas bills dedicated clusters by the hour, prorated for partial hours, so experimenting with a larger tier doesn't require a long-term commitment.&lt;/p&gt;

&lt;p&gt;In our M10 benchmark, p95 latency exceeded our 200 ms target at 1,500 operations per second. Rather than assuming an M30 would solve the problem, we could provision a temporary cluster and repeat the experiment, which is exactly what we do below.&lt;/p&gt;

&lt;p&gt;For a meaningful comparison, keep the &lt;strong&gt;dataset, indexes, workload, offered load, region, and test duration consistent&lt;/strong&gt;. Allow both clusters to warm up, and ensure the load generator isn't limiting throughput.&lt;/p&gt;

&lt;p&gt;Compare throughput, p95/p99 latency, and resource utilization to see whether the larger tier provides a meaningful improvement. If performance barely changes, the bottleneck may lie elsewhere.&lt;/p&gt;

&lt;p&gt;Once you're finished, &lt;a href="https://www.mongodb.com/docs/atlas/terminate-cluster/?utm_campaign=devrel&amp;amp;utm_source=third-party-content&amp;amp;utm_medium=cta&amp;amp;utm_content=buildrel-when-to-scale-mdb-cluster&amp;amp;utm_term=hugh.murray" rel="noopener noreferrer"&gt;delete the temporary cluster&lt;/a&gt; to avoid unnecessary charges.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;A few dollars spent benchmarking could prevent a much more expensive scaling decision.&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Comparing performance across Atlas tiers
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F2ldaer65s33ws83r344m.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F2ldaer65s33ws83r344m.png" alt="Achieved throughput vs Offered load across all tested tiers" width="800" height="480"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;A larger cluster should handle more traffic, but the interesting question is how much more, and what happens when it reaches its limit. We ran the same read-heavy workload against Flex, M10, and M30, ramping traffic from 10 to 2,000 requests per second on each, to see not just how much each could sustain, but where and why it broke down.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Flex hit a hard, early ceiling.&lt;/strong&gt; It ran cleanly up to 300 requests per second. At 500, it broke: a 4.2 percent error rate and p95 latency over 10 seconds. Beyond that point, extra demand bought almost nothing. Even offered 2,000 requests per second, Flex only processed around 600–640, with errors climbing to 8.7 percent. While this is somewhat above its published ~500 ops/sec limit, the 500-stage figures may include some spillover from adjacent stages, since stage windows are inferred from simulated-user counts. Atlas doesn’t expose process-level metrics for Flex, so we can’t isolate the exact mechanism, only that this is a firm practical ceiling.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;M10 looked fine on CPU, right up until it wasn’t.&lt;/strong&gt; Throughput tracked offered load almost perfectly up to 1,500 requests per second with zero errors, although p95 latency had already reached 449 ms, well past our 200 ms target. Over the same range, primary CPU climbed steadily from about 1.5 to 50.7 percent, a reassuring, proportional curve. At 2,000 requests per second, performance collapsed: achieved throughput fell to 864 req/s, p95 jumped to 4,240 ms, and errors appeared, while CPU barely moved, reaching 54.4 percent. What did change was WiredTiger’s read tickets, which were exhausted as operations queued for the storage engine, alongside slower reads and higher disk read latency. M10 wasn’t obviously short on processing power. The evidence points to concurrency pressure, and CPU alone didn’t reveal it.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;M30 never hit a throughput limit in this benchmark.&lt;/strong&gt; At 2,000 requests per second it was still error-free, with p95 around 215-220 ms (just over our 200 ms target) and CPU at just 21.5 percent, less than half what M10 was using when it failed. That doesn’t mean M30 has no ceiling, only that this workload wasn’t demanding enough to find it. &lt;/p&gt;

&lt;h3&gt;
  
  
  What the metrics tell us
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fva0057y654s984bdo4uv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fva0057y654s984bdo4uv.png" alt="p95 latency vs offered load across all tiers tested" width="800" height="480"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Throughput says how much work completes; latency says what users actually feel. Flex’s p95 reached 10-13 seconds at its worst once overloaded. M10 stayed under about 150 ms through 1,000 req/s, crossed 200 ms by 1,500, and collapsed at 2,000. M30 never exceeded ~220ms. A cluster can keep completing hundreds of operations a second while delivering latency no user would accept.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fmh7y75wnp6wtnzv3f6ly.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fmh7y75wnp6wtnzv3f6ly.png" alt="Primary CPU vs offered load across all tiers tested" width="800" height="480"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;At the same offered load, M10 was at 54.4 per cent CPU and already failing; M30 was at 21.5 per cent and fine. CPU tells you computational demand, not whether something else downstream is actually the limiting factor.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F8m9cvp6t0vuxz6gkllud.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F8m9cvp6t0vuxz6gkllud.png" alt="Read tickets available vs readers queued on M10" width="800" height="489"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The ticket and queue metrics show why: as M10 approached its limit, available read tickets fell and queued readers rose, operations arriving faster than the storage engine could admit them. That’s the kind of bottleneck CPU alone won’t reveal, and why it’s worth watching ticket and queue metrics alongside latency and disk behaviour.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;In this benchmark, M10 was still keeping up with the offered load at 1,500 requests per second, but p95 latency had already reached 449 ms. By 2,000 requests per second, throughput had dropped sharply, available WiredTiger read tickets were exhausted, and operations were queuing while primary CPU sat at about 54%. M30 completed the highest load stage without errors, with p95 latency around 215–220 ms, slightly above our target.&lt;/p&gt;

&lt;p&gt;For your own application, start with the latency you need at peak traffic and benchmark with a representative mix of queries, data, and indexes. If the cluster misses that target, use Atlas metrics to decide what to investigate. When you’re considering a larger tier, rerun the same test and compare how much headroom it gives you at the latency your application needs.&lt;/p&gt;

&lt;p&gt;Now that we have seen how to choose your starting tier, and how to benchmark your application, in Part 3 we will look at how to turn these results into a scaling strategy.&lt;/p&gt;

</description>
      <category>mongodb</category>
      <category>performance</category>
      <category>locust</category>
      <category>database</category>
    </item>
    <item>
      <title>How to Know When to Scale Your MongoDB Atlas Cluster - Part 1: What Size Cluster Do You Need for Your App?</title>
      <dc:creator>Tim Kelly</dc:creator>
      <pubDate>Wed, 25 Nov 2026 13:17:21 +0000</pubDate>
      <link>https://dev.to/mongodb/how-to-know-when-to-scale-your-mongodb-atlas-cluster-part-1-what-size-cluster-do-you-need-for-3ee6</link>
      <guid>https://dev.to/mongodb/how-to-know-when-to-scale-your-mongodb-atlas-cluster-part-1-what-size-cluster-do-you-need-for-3ee6</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;"I'm running an M10 cluster. How many queries per second can it handle?"&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;It's a reasonable question, but the answer is everyone's favourite: it depends.&lt;/p&gt;

&lt;p&gt;There's no magic queries-per-second (QPS) threshold that tells you when to scale your MongoDB Atlas cluster. An application performing 1,000 indexed lookups per second will place very different demands on a cluster than one executing 1,000 complex aggregations. Dataset size, memory usage, concurrency, and latency requirements all influence how much traffic a cluster can handle.&lt;/p&gt;

&lt;p&gt;So rather than asking how many queries an M10 can execute, a better question is:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;"How do I know when my current cluster is no longer sufficient for my workload?"&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The same workload details that determine when you need to scale also help you choose where to start. In Part 1, we’ll use them to pick an initial Atlas tier. Later in the series, we’ll diagnose bottlenecks and benchmark larger tiers against a representative workload.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to choose your starting Atlas tier?
&lt;/h2&gt;

&lt;p&gt;If you're unsure how your application will perform, starting with a larger cluster for additional headroom and scaling down once you understand your workload can be reasonable. Atlas supports scaling dedicated clusters up or down, including automatic compute scaling for eligible configurations, although &lt;a href="https://www.mongodb.com/docs/atlas/scale-cluster/?utm_campaign=devrel&amp;amp;utm_source=third-party-content&amp;amp;utm_medium=cta&amp;amp;utm_content=buildrel-when-to-scale-mdb-cluster&amp;amp;utm_term=hugh.murray" rel="noopener noreferrer"&gt;certain restrictions apply&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Here's a quick overview of where the different tiers fit:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Tier&lt;/th&gt;
&lt;th&gt;Starting price (USD)&lt;/th&gt;
&lt;th&gt;When it makes sense&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Free&lt;/td&gt;
&lt;td&gt;$0&lt;/td&gt;
&lt;td&gt;Learning, experimenting, small prototypes&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Flex&lt;/td&gt;
&lt;td&gt;$8–$30 per 30 days, based on usage&lt;/td&gt;
&lt;td&gt;Development, testing, and low-traffic production workloads that fit within Flex limits&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;M10&lt;/td&gt;
&lt;td&gt;From $0.08/hour&lt;/td&gt;
&lt;td&gt;Low-traffic workloads that need dedicated resources or features unavailable on Flex&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;M30&lt;/td&gt;
&lt;td&gt;$0.54/hour in MongoDB’s AWS example&lt;/td&gt;
&lt;td&gt;Production workloads with sustained traffic or higher compute and memory requirements&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;&lt;em&gt;Dedicated cluster prices vary by cloud provider, region, and configuration. See &lt;a href="https://www.mongodb.com/pricing/?utm_campaign=devrel&amp;amp;utm_source=third-party-content&amp;amp;utm_medium=cta&amp;amp;utm_content=buildrel-when-to-scale-mdb-cluster&amp;amp;utm_term=hugh.murray" rel="noopener noreferrer"&gt;Atlas pricing&lt;/a&gt; for current costs.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Start with your expected launch workload. How much data and index space will you need? Which requests hit the database most often, and how many reads or writes does each one generate? What does peak traffic look like, and how quickly do those requests need to finish? Use your storage and feature requirements to narrow the tier choices, then run a representative workload against the tier you’re considering. If it meets your latency target at expected peak load with room to spare, you have a starting point you can justify.&lt;/p&gt;

&lt;h3&gt;
  
  
  When is an Atlas Free cluster enough?
&lt;/h3&gt;

&lt;p&gt;Atlas Free is a good starting point for learning MongoDB, experimenting, and building small prototypes. It runs on shared infrastructure, with 512 MB of storage and a limit of 100 read and write operations per second. It allows 10 GB of inbound traffic and 10 GB of outbound traffic per rolling seven-day period. Atlas Free has no automated backups, and Atlas pauses the cluster after 30 days without a connection.&lt;/p&gt;

&lt;p&gt;These limits are reasonable for prototypes and applications with minimal traffic, but Free isn't suitable for benchmarking dedicated cluster performance. Its shared resources and throughput restrictions won't reflect how an M10 or M30 behaves under the same workload.&lt;/p&gt;

&lt;p&gt;See the &lt;a href="https://www.mongodb.com/docs/atlas/reference/free-shared-limitations/?utm_campaign=devrel&amp;amp;utm_source=third-party-content&amp;amp;utm_medium=cta&amp;amp;utm_content=buildrel-when-to-scale-mdb-cluster&amp;amp;utm_term=hugh.murray" rel="noopener noreferrer"&gt;Atlas Free Cluster Limitations&lt;/a&gt; for details.&lt;/p&gt;

&lt;h3&gt;
  
  
  When should you choose Flex?
&lt;/h3&gt;

&lt;p&gt;Atlas Flex offers usage-based pricing, daily snapshots, and up to 5 GB of storage. Atlas limits Flex to 500 read and write operations per second.&lt;/p&gt;

&lt;p&gt;The operation limits for Free and Flex tell you when Atlas throttles database traffic. To estimate how much application traffic either tier can serve within your latency target, measure how many database operations each request generates and how expensive those operations are.&lt;/p&gt;

&lt;p&gt;Flex can be a good fit for smaller production applications. However, if you're consistently approaching its limits or need more predictable performance and monitoring, it's worth considering a dedicated cluster.&lt;/p&gt;

&lt;p&gt;See the &lt;a href="https://www.mongodb.com/docs/atlas/reference/flex-limitations/?utm_campaign=devrel&amp;amp;utm_source=third-party-content&amp;amp;utm_medium=cta&amp;amp;utm_content=buildrel-when-to-scale-mdb-cluster&amp;amp;utm_term=hugh.murray" rel="noopener noreferrer"&gt;Atlas Flex Limitations&lt;/a&gt; for details.&lt;/p&gt;

&lt;h3&gt;
  
  
  When do M10 and M20 make sense?
&lt;/h3&gt;

&lt;p&gt;M10 is the entry point for dedicated Atlas clusters. M10 and M20 both use burstable infrastructure and can suit low-traffic production applications that need dedicated resources, more detailed monitoring, or features unavailable on Flex.&lt;/p&gt;

&lt;p&gt;M10 and M20 throughput depends on your queries, dataset, concurrency, and available resources. If you’re testing either tier, run your representative workload long enough to see how it performs under sustained load as well as during short bursts.&lt;/p&gt;

&lt;p&gt;See the &lt;a href="https://www.mongodb.com/docs/atlas/reference/limitations/?utm_campaign=devrel&amp;amp;utm_source=third-party-content&amp;amp;utm_medium=cta&amp;amp;utm_content=buildrel-when-to-scale-mdb-cluster&amp;amp;utm_term=hugh.murray#atlas-cluster-tier-limits" rel="noopener noreferrer"&gt;Atlas Cluster Tier Limits&lt;/a&gt; for configuration details.&lt;/p&gt;

&lt;h3&gt;
  
  
  When should you consider M30?
&lt;/h3&gt;

&lt;p&gt;MongoDB recommends M30 or larger for production deployments and calls out M10 and M20 as options for low-traffic applications. Consider starting with M30 if you expect sustained traffic, heavier queries, or a workload that needs more memory. If you’re choosing between M20 and M30, benchmark both with representative data and indexes, and compare application latency at your expected peak load.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Choosing a tier is only the starting point. To know when it's time to scale, we need to measure how our application performs under load and identify what's actually limiting it.&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Where to go from here
&lt;/h2&gt;

&lt;p&gt;Start with an Atlas tier that fits your expected workload, storage needs, and feature requirements. Then estimate your peak traffic and set a p95 latency target. Those two numbers give you a concrete way to test whether the tier can handle the load you expect.&lt;/p&gt;

&lt;p&gt;In Part 2, we’ll use Locust to run the same read-heavy workload against Flex, M10, and M30, increasing the load in stages. We’ll see when each tier crosses our p95 latency target and use Atlas metrics to investigate what happens as load builds.&lt;/p&gt;

</description>
      <category>mongodb</category>
      <category>performance</category>
      <category>database</category>
      <category>cloud</category>
    </item>
    <item>
      <title>Fraud Detection with Feast and MongoDB</title>
      <dc:creator>Abigail Afi Gbadago</dc:creator>
      <pubDate>Mon, 16 Nov 2026 22:17:22 +0000</pubDate>
      <link>https://dev.to/mongodb/fraud-detection-with-feast-and-mongodb-49ib</link>
      <guid>https://dev.to/mongodb/fraud-detection-with-feast-and-mongodb-49ib</guid>
      <description>&lt;p&gt;When building ML systems, you may need the exact same feature definitions, such as a user's recent transaction patterns computed in two very different contexts. At training time, you need historical features assembled correctly, without accidentally mixing past and future data (point-in-time correctness). At serving time, when a transaction happens, you need the current value of those same features computed and returned in milliseconds, not seconds. &lt;/p&gt;

&lt;p&gt;Most teams achieve this by running three separate databases: the application's primary database, a dedicated low-latency online store for serving, and a separate data warehouse for offline training retrieval. Feast, combined with MongoDB, solves this by defining features once and serving them consistently in both contexts. MongoDB can act as both Feast’s online and offline store, removing the need for separate systems.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://feast.dev/" rel="noopener noreferrer"&gt;Feast&lt;/a&gt; is the leading open-source feature store for machine learning, which MongoDB supports as an online and offline store. This enables machine learning teams to serve features at low latency and generate point-in-time-correct training datasets directly against MongoDB.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;This tutorial only configures MongoDB as Feast's online store; the offline store uses a local Parquet file (&lt;code&gt;offline_store: type: file&lt;/code&gt; in &lt;code&gt;feature_store.yaml&lt;/code&gt;). MongoDB can also serve as Feast's offline store to fully realize the single-cluster, ETL-free architecture described above.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In this tutorial, we will build a fraud detection pipeline using MongoDB as Feast’s online store with the Django MongoDB Backend. &lt;br&gt;
Specifically, you will learn:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;How to use the Django MongoDB backend to model and persist transactions in MongoDB&lt;/li&gt;
&lt;li&gt;How to use Feast as a feature store, with a local Parquet file as the offline store&lt;/li&gt;
&lt;li&gt;How to use MongoDB as Feast's online store for low-latency lookups&lt;/li&gt;
&lt;li&gt;How to build a statistical model (a z-score on transaction amount) to identify potentially fraudulent transactions in real time&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In the end, you will use &lt;code&gt;user_id&lt;/code&gt; to fetch a user's most recent materialized features from MongoDB (online store) using Feast and return whether that transaction looks fraudulent or not.&lt;/p&gt;

&lt;p&gt;There are two ways to follow this tutorial.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Option A: &lt;a href="https://github.com/mongodb-developer/feast-mongodb-fraud-detection" rel="noopener noreferrer"&gt;Clone the GitHub repo&lt;/a&gt;  containing the finished code from this tutorial, set it up using the repo's &lt;a href="https://github.com/mongodb-developer/feast-mongodb-fraud-detection#fraud-detection-with-feast--mongodb" rel="noopener noreferrer"&gt;README&lt;/a&gt;, and explore it on your own. &lt;/li&gt;
&lt;li&gt;Option B: Start the project from scratch by following the steps below.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
  
  
  Outline
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Prerequisites&lt;/li&gt;
&lt;li&gt;Create a project folder and virtual environment&lt;/li&gt;
&lt;li&gt;Create the Django project and Django app&lt;/li&gt;
&lt;li&gt;Generate synthetic financial data&lt;/li&gt;
&lt;li&gt;Define the Transaction model&lt;/li&gt;
&lt;li&gt;Load the synthetic data into MongoDB&lt;/li&gt;
&lt;li&gt;Scaffold the feature repository with Feast&lt;/li&gt;
&lt;li&gt;Define the Transaction features&lt;/li&gt;
&lt;li&gt;Configure Feast to use MongoDB&lt;/li&gt;
&lt;li&gt;Train a fraud model&lt;/li&gt;
&lt;li&gt;Materialize features into MongoDB&lt;/li&gt;
&lt;li&gt;View the materialized features in MongoDB Atlas&lt;/li&gt;
&lt;li&gt;Produce real-time predictions&lt;/li&gt;
&lt;li&gt;Conclusion and next steps&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
  
  
  Prerequisites
&lt;/h2&gt;

&lt;p&gt;Before starting, make sure you have:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Python 3.12+&lt;/li&gt;
&lt;li&gt;A &lt;a href="https://www.mongodb.com/docs/atlas/tutorial/create-new-cluster/?utm_campaign=devrel&amp;amp;utm_source=third-party-content&amp;amp;utm_medium=cta&amp;amp;utm_content=buildrel-feast-implementation-devto&amp;amp;utm_term=abigail.gbadago" rel="noopener noreferrer"&gt;MongoDB Atlas cluster&lt;/a&gt;; a local Atlas deployment (connection string &lt;code&gt;mongodb://localhost:27017/?directConnection=true&lt;/code&gt;) also works.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Once these prerequisites are complete, the next step is to create your project folder.&lt;/p&gt;
&lt;h2&gt;
  
  
  Create a project and virtual environment
&lt;/h2&gt;

&lt;p&gt;Create an empty folder for your project and &lt;code&gt;cd&lt;/code&gt; into it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;mkdir fraud_detection
&lt;span class="nb"&gt;cd&lt;/span&gt; fraud_detection
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;From the project root, create a virtual environment:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;python3 -m venv .venv
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then activate it. &lt;/p&gt;

&lt;p&gt;On macOS/Linux:&lt;/p&gt;

&lt;p&gt;Run &lt;code&gt;source .venv/bin/activate&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;On Windows:&lt;/p&gt;

&lt;p&gt;Run &lt;code&gt;.venv\Scripts\activate&lt;/code&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Install dependencies
&lt;/h3&gt;

&lt;p&gt;Create a &lt;code&gt;requirements.txt&lt;/code&gt; file at the root of the project with the following contents:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# requirements.txt
django-mongodb-backend==6.0.4
python-dotenv==1.2.4
feast==0.67.0
pymongo==4.19.0
pandas==2.3.3
numpy==2.5.4
pyarrow==26.0.0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;django-mongodb-backend&lt;/code&gt; 6.0.x installs Django 6.0, which matches the 6.0.x project template used in the next step. &lt;/p&gt;

&lt;p&gt;Then install everything:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;pip install -r requirements.txt
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Create Django Project and Django App
&lt;/h2&gt;

&lt;p&gt;From your project's root directory, run the following command to create a new Django project from the MongoDB project template. The &lt;code&gt;.&lt;/code&gt; after the project name tells Django to create the project in the current directory instead of a new nested folder.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;django-admin startproject fraud_detection . --template https://github.com/mongodb-labs/django-mongodb-project/archive/refs/heads/6.0.x.zip 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The template adds a &lt;code&gt;README.md&lt;/code&gt;, but it doesn’t overwrite your &lt;code&gt;requirements.txt&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Create the &lt;strong&gt;transactions&lt;/strong&gt; app
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;python manage.py startapp transactions
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Register the app in &lt;code&gt;fraud_detection/settings.py&lt;/code&gt; by adding &lt;code&gt;transactions&lt;/code&gt; to the end of the existing &lt;code&gt;INSTALLED_APPS&lt;/code&gt; list. The template already has the other entries:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="no"&gt;INSTALLED_APPS&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
    &lt;span class="s1"&gt;'fraud_detection.apps.MongoAdminConfig'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="s1"&gt;'fraud_detection.apps.MongoAuthConfig'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="s1"&gt;'fraud_detection.apps.MongoContentTypesConfig'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="s1"&gt;'django.contrib.sessions'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="s1"&gt;'django.contrib.messages'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="s1"&gt;'django.contrib.staticfiles'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="s1"&gt;'django_mongodb_backend'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="s1"&gt;'transactions'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Configure environment variables
&lt;/h3&gt;

&lt;p&gt;Create a &lt;code&gt;.gitignore&lt;/code&gt; file at the root of the project so that secrets and generated files are not added when you push.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#.gitignore
.env
.venv/
__pycache__/
*.pyc
data/transactions.parquet
training/model_params.json
feature_repo/feature_repo/data/registry.db
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then create a &lt;code&gt;.env&lt;/code&gt; file at the root of the project with your own values.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# .env
SECRET_KEY='&amp;lt;your-secret-key&amp;gt;'
MONGODB_URI='mongodb+srv://&amp;lt;username&amp;gt;:&amp;lt;password&amp;gt;@&amp;lt;cluster&amp;gt;.mongodb.net/?retryWrites=true&amp;amp;w=majority'
DB_NAME='fraud_detection'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;NB: Keep the single quotes.&lt;/p&gt;

&lt;p&gt;For &lt;code&gt;SECRET_KEY&lt;/code&gt;, copy the value Django generated in &lt;code&gt;settings.py&lt;/code&gt; when you ran &lt;code&gt;startproject&lt;/code&gt;, or generate a new one:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;python -c &lt;span class="s2"&gt;"from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Django hardcodes the secret key in &lt;code&gt;settings.py&lt;/code&gt; by default, but we move it into &lt;code&gt;.env&lt;/code&gt; to keep it out of version control, since it's used to sign session cookies, CSRF tokens, and other security-sensitive data.&lt;/p&gt;

&lt;p&gt;Now, update &lt;code&gt;fraud_detection/settings.py&lt;/code&gt; to read the secret key and the database configuration from the environment instead of hardcoding them. Make the following changes and leave the rest of the file as is.&lt;/p&gt;

&lt;p&gt;At the top of the file, add the imports and the &lt;code&gt;load_dotenv()&lt;/code&gt; call:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;os&lt;/span&gt;
&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;dotenv&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;load_dotenv&lt;/span&gt;

&lt;span class="nf"&gt;load_dotenv&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Replace the hardcoded &lt;code&gt;SECRET_KEY = '...'&lt;/code&gt; line with:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="no"&gt;SECRET_KEY&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;os&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getenv&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'SECRET_KEY'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the existing &lt;code&gt;DATABASES&lt;/code&gt; setting, replace the &lt;code&gt;HOST&lt;/code&gt; and &lt;code&gt;NAME&lt;/code&gt; values:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="no"&gt;DATABASES&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="s1"&gt;'default'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="s1"&gt;'ENGINE'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s1"&gt;'django_mongodb_backend'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="s1"&gt;'HOST'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;os&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getenv&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"MONGODB_URI"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="s1"&gt;'NAME'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;os&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getenv&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"DB_NAME"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Generate synthetic financial data
&lt;/h2&gt;

&lt;p&gt;Since we don't have a real transaction feed, we'll generate a small synthetic dataset with a handful of users, categories, and locations, plus a small percentage of inflated-amount "fraudulent" transactions.&lt;/p&gt;

&lt;p&gt;First, create a &lt;code&gt;data/&lt;/code&gt; directory at the root of the project (alongside &lt;code&gt;manage.py&lt;/code&gt;) to hold this script and the generated file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;mkdir data
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then create &lt;code&gt;data/generate_transactions.py&lt;/code&gt; with the following contents:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="s2"&gt;"""Generates random transactions data for the Feast + MongoDB tutorial."""&lt;/span&gt;

&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;pathlib&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nc"&gt;Path&lt;/span&gt;

&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;pandas&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;pd&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;numpy&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;np&lt;/span&gt;

&lt;span class="no"&gt;TRANSACTIONS_PARQUET_FILE&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Path&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;__file__&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;resolve&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="s2"&gt;"transactions.parquet"&lt;/span&gt;

&lt;span class="n"&gt;random_generator&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;random&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;default_rng&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;seed&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;42&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="no"&gt;N&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="no"&gt;FRAUD_RATE&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;50&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mf"&gt;0.02&lt;/span&gt;

&lt;span class="n"&gt;df&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;pd&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;DataFrame&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="s2"&gt;"user_id"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;random_generator&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;integers&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;9&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="no"&gt;N&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="s2"&gt;"transaction_id"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"txn_{i:04d}"&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="no"&gt;N&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="s2"&gt;"amount"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;random_generator&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;lognormal&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;mean&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mf"&gt;3.5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;sigma&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mf"&gt;0.6&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="no"&gt;N&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;round&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="s2"&gt;"category"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;random_generator&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;choice&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"food"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"utilities"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"entertainment"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"travel"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"shopping"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="no"&gt;N&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="s2"&gt;"location"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;random_generator&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;choice&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"Accra"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"Lagos"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"New York"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"London"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"Paris"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;size&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="no"&gt;N&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="c1"&gt;# Timezone-aware: Django runs with USE_TZ = True, and Feast expects UTC.&lt;/span&gt;
    &lt;span class="s2"&gt;"event_timestamp"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;pd&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Timestamp&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"2026-07-01"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;tz&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"UTC"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;pd&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;to_timedelta&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;random_generator&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;integers&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;30&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="mi"&gt;24&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="mi"&gt;60&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="no"&gt;N&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;unit&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"m"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;sort_values&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"event_timestamp"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;reset_index&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;drop&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="c1"&gt;# Choose a fraud row from each user's most recent transactions&lt;/span&gt;
&lt;span class="n"&gt;latest_per_user&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;df&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;groupby&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"user_id"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;tail&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;fraud_indices&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;latest_per_user&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;sample&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="nb"&gt;max&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;round&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="no"&gt;N&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="no"&gt;FRAUD_RATE&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;random_state&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;42&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;index&lt;/span&gt;
&lt;span class="n"&gt;df&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"is_fraudulent"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;False&lt;/span&gt;
&lt;span class="n"&gt;df&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;loc&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;fraud_indices&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"is_fraudulent"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;
&lt;span class="c1"&gt;# Inflate the amount for fraudulent transactions&lt;/span&gt;
&lt;span class="n"&gt;df&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;loc&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;fraud_indices&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"amount"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;*=&lt;/span&gt; &lt;span class="n"&gt;random_generator&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;uniform&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;fraud_indices&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;   

&lt;span class="n"&gt;df&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"created_timestamp"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;df&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"event_timestamp"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

&lt;span class="n"&gt;df&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;to_parquet&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="no"&gt;TRANSACTIONS_PARQUET_FILE&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;index&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;False&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"Wrote {len(df)} transactions to parquet file, {df['is_fraudulent'].sum()} of which are fraudulent."&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Feast requires an &lt;code&gt;event_timestamp&lt;/code&gt; column (when the fact occurred) and, since we're using a &lt;code&gt;FileSource&lt;/code&gt;, a &lt;code&gt;created_timestamp&lt;/code&gt; column (when the row was written) for tie-breaking. The timestamps are timezone-aware (UTC) because Django runs with &lt;code&gt;USE_TZ = True&lt;/code&gt; and Feast works in UTC. &lt;/p&gt;

&lt;p&gt;Run the script from the project root:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;python data/generate_transactions.py
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The expected output should be &lt;code&gt;Wrote 50 transactions to parquet file, 1 of which are fraudulent.&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This writes &lt;code&gt;data/transactions.parquet&lt;/code&gt;, which is used both to load data into MongoDB via the Django ORM and as Feast's offline store for training.&lt;/p&gt;

&lt;h2&gt;
  
  
  Define the Transaction model
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;transactions/models.py&lt;/code&gt; defines the Django model that maps to the &lt;code&gt;transactions&lt;/code&gt; collection in MongoDB:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;django&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;db&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;models&lt;/span&gt;

&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Transaction&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;models&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Model&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;transaction_id&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;models&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;CharField&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;max_length&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;64&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;unique&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;user_id&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;models&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;IntegerField&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;amount&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;models&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;DecimalField&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;max_digits&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;decimal_places&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;category&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;models&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;CharField&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;max_length&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;location&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;models&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;CharField&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;max_length&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;timestamp&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;models&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;DateTimeField&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;is_fraudulent&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;models&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;BooleanField&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;default&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;False&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Meta&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;db_table&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;'transactions'&lt;/span&gt;
        &lt;span class="n"&gt;indexes&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
            &lt;span class="n"&gt;models&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Index&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;fields&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'user_id'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="n"&gt;models&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Index&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;fields&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'timestamp'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="p"&gt;]&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__str__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"Transaction {self.transaction_id} - Amount: {self.amount} - Fraudulent: {self.is_fraudulent}"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;user_id&lt;/code&gt; is an &lt;code&gt;IntegerField&lt;/code&gt; so that it matches the Feast entity's &lt;code&gt;INT64&lt;/code&gt; type and the &lt;code&gt;&amp;lt;int:user_id&amp;gt;&lt;/code&gt; URL parameter we will define later. It is also indexed because the app looks up transactions by user.&lt;/p&gt;

&lt;h3&gt;
  
  
  Generate and run the migration
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;python manage.py makemigrations transactions
python manage.py migrate
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Load the synthetic data into MongoDB
&lt;/h2&gt;

&lt;p&gt;Create the folders for the custom management command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;mkdir -p transactions/management/commands
touch transactions/management/__init__.py
touch transactions/management/commands/__init__.py
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;transactions/management/commands/load_transactions.py&lt;/code&gt; is a custom management command that reads &lt;code&gt;data/transactions.parquet&lt;/code&gt; and bulk-inserts the rows into MongoDB through the Django ORM:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;decimal&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nc"&gt;Decimal&lt;/span&gt;

&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;pandas&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;pd&lt;/span&gt;
&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;django&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;conf&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;settings&lt;/span&gt;
&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;django&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;core&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;management&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;base&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nc"&gt;BaseCommand&lt;/span&gt;
&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;transactions&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;models&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nc"&gt;Transaction&lt;/span&gt;

&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Command&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;BaseCommand&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="nb"&gt;help&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"Loading transaction data from data/transactions.parquet into the database via Django ORM"&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;add_arguments&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;parser&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;parser&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;add_argument&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="s2"&gt;"--path"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="n"&gt;default&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;settings&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;BASE_DIR&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="s2"&gt;"data"&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="s2"&gt;"transactions.parquet"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="nb"&gt;help&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"Path to the Parquet file containing transaction data"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;handle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;**&lt;/span&gt;&lt;span class="n"&gt;options&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;df&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;pd&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;read_parquet&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;options&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"path"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;transactions&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
            &lt;span class="nc"&gt;Transaction&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
                &lt;span class="n"&gt;user_id&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"user_id"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="n"&gt;transaction_id&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"transaction_id"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="n"&gt;amount&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="nc"&gt;Decimal&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"{row['amount']:.2f}"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="n"&gt;category&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"category"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="n"&gt;location&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"location"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="n"&gt;timestamp&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"event_timestamp"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="n"&gt;is_fraudulent&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kt"&gt;bool&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"is_fraudulent"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;df&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;to_dict&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"records"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;]&lt;/span&gt;

        &lt;span class="nc"&gt;Transaction&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;objects&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;all&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;delete&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="nc"&gt;Transaction&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;objects&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;bulk_create&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;transactions&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stdout&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;write&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;style&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;SUCCESS&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
                &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;" Loaded {len(transactions)} transactions into MDB database."&lt;/span&gt;
            &lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A few details to note:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;amount&lt;/code&gt; is converted to a &lt;code&gt;Decimal&lt;/code&gt; with two decimal places to match the &lt;code&gt;DecimalField&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Existing transactions are deleted before inserting, so you can re-run the command after regenerating the data without hitting the unique constraint on &lt;code&gt;transaction_id&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;The default &lt;code&gt;--path&lt;/code&gt; is built from &lt;code&gt;settings.BASE_DIR&lt;/code&gt; so that the command will find the Parquet file no matter which directory you run it from.
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Then run it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;python manage.py load_transactions
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Scaffold the feature repository with Feast
&lt;/h2&gt;

&lt;p&gt;Before we go ahead to define features, we need to initialize a Feast project. From the root of your directory, run:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;feast init feature_repo
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This generates a demo Feast project in &lt;code&gt;feature_repo/feature_repo/&lt;/code&gt;. Alongside the &lt;code&gt;feature_store.yaml&lt;/code&gt; configuration file, it includes three things you won't need for this tutorial:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;feature_definitions.py&lt;/code&gt;: example feature definitions for the demo dataset&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;test_workflow.py&lt;/code&gt;: a script that runs through the demo end to end&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;data/driver_stats.parquet&lt;/code&gt; and &lt;code&gt;data/driver_quality_labels.parquet&lt;/code&gt;: sample data for the demo&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Delete these files, but keep the &lt;code&gt;data/&lt;/code&gt; folder, since Feast stores its registry there. You'll replace the demo definitions with your own &lt;code&gt;features.py&lt;/code&gt; (below) and update &lt;code&gt;feature_store.yaml&lt;/code&gt; as shown in "Configure Feast to use MongoDB".&lt;br&gt;
&lt;code&gt;feast init&lt;/code&gt; also creates &lt;code&gt;feature_repo/README.md&lt;/code&gt; and &lt;code&gt;feature_repo/.gitignore&lt;/code&gt;. You can delete them or leave them; they don’t affect anything.&lt;/p&gt;
&lt;h2&gt;
  
  
  Define the Transaction features
&lt;/h2&gt;

&lt;p&gt;Feast needs its own definitions of the entity and features, independent of the Django model, because it reads directly from the Parquet file rather than through the Django ORM. These live in &lt;code&gt;feature_repo/feature_repo/features.py&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;datetime&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;timedelta&lt;/span&gt;
&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;pathlib&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nc"&gt;Path&lt;/span&gt;
&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;feast&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nc"&gt;Entity&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;FeatureView&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Field&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;FileSource&lt;/span&gt;
&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;feast&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;types&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nc"&gt;Float32&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;
&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;feast&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;value_type&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nc"&gt;ValueType&lt;/span&gt;

&lt;span class="c1"&gt;# An entity is the key used to look up features; here, it is the user_id&lt;/span&gt;
&lt;span class="n"&gt;user&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Entity&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"user_id"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;join_keys&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"user_id"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;value_type&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="nc"&gt;ValueType&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;INT64&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="c1"&gt;# Feast reads the Parquet file directly; it does not go through the Django ORM.&lt;/span&gt;
&lt;span class="no"&gt;TRANSACTIONS_PARQUET_FILE&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="nc"&gt;Path&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;__file__&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;resolve&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;parents&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="s2"&gt;"data"&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="s2"&gt;"transactions.parquet"&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="n"&gt;transaction_source&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;FileSource&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"transaction_source"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;path&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="no"&gt;TRANSACTIONS_PARQUET_FILE&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;timestamp_field&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"event_timestamp"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;created_timestamp_column&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"created_timestamp"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="n"&gt;transaction_features&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;FeatureView&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"transaction_features"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;entities&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;user&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;ttl&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="nf"&gt;timedelta&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;days&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;365&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;schema&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;
        &lt;span class="nc"&gt;Field&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"amount"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;dtype&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="nc"&gt;Float32&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="nc"&gt;Field&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"category"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;dtype&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="nc"&gt;Field&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"location"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;dtype&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;source&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;transaction_source&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;user&lt;/code&gt; is the &lt;strong&gt;entity&lt;/strong&gt;: the key (&lt;code&gt;user_id&lt;/code&gt;) that features are looked up by.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;transaction_source&lt;/code&gt; points Feast to the generated Parquet file. &lt;code&gt;timestamp_field&lt;/code&gt; tells Feast which column holds the event time used for point-in-time joins, and &lt;code&gt;created_timestamp_column&lt;/code&gt; breaks ties when two rows share the same event time.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;transaction_features&lt;/code&gt; is the &lt;strong&gt;feature view&lt;/strong&gt; that ties the entity, the source, and the individual fields (&lt;code&gt;amount&lt;/code&gt;, &lt;code&gt;category&lt;/code&gt;, &lt;code&gt;location&lt;/code&gt;) together.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Configure Feast to use MongoDB
&lt;/h2&gt;

&lt;p&gt;Feast's project configuration lives in &lt;code&gt;feature_repo/feature_repo/feature_store.yaml&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;&lt;span class="na"&gt;project&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;fraud_detection&lt;/span&gt;
&lt;span class="na"&gt;registry&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;data/registry.db&lt;/span&gt;
&lt;span class="na"&gt;provider&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;local&lt;/span&gt;

&lt;span class="na"&gt;offline_store&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
  &lt;span class="na"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;file&lt;/span&gt;

&lt;span class="na"&gt;online_store&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
  &lt;span class="na"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;mongodb&lt;/span&gt;
  &lt;span class="na"&gt;connection_string&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;${MONGODB_URI}&lt;/span&gt;
  &lt;span class="na"&gt;database_name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;${DB_NAME}&lt;/span&gt;

&lt;span class="na"&gt;entity_key_serialization_version&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;offline_store.type: file&lt;/code&gt; tells Feast to use the local Parquet file for historical/training queries.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;online_store.type: mongodb&lt;/code&gt; tells Feast to use MongoDB for low-latency online lookups, using the same &lt;a href="https://www.mongodb.com/docs/atlas/connect-to-database-deployment/?interface=atlas-cli#connect-to-your-cloud-cluster" rel="noopener noreferrer"&gt;&lt;code&gt;MONGODB_URI&lt;/code&gt; connection string&lt;/a&gt; and &lt;code&gt;DB_NAME&lt;/code&gt; database as Django.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Feast substitutes &lt;code&gt;${MONGODB_URI}&lt;/code&gt; and &lt;code&gt;${DB_NAME}&lt;/code&gt; from the process environment. Unlike Django, the &lt;code&gt;feast&lt;/code&gt; CLI does &lt;strong&gt;not&lt;/strong&gt; read your &lt;code&gt;.env&lt;/code&gt; file (it never imports &lt;code&gt;settings.py&lt;/code&gt;), so export the variables into your shell first. &lt;/p&gt;

&lt;p&gt;On macOS/Linux, from the project root:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;set&lt;/span&gt; -a&lt;span class="o"&gt;;&lt;/span&gt; &lt;span class="nb"&gt;source&lt;/span&gt; .env&lt;span class="o"&gt;;&lt;/span&gt; &lt;span class="nb"&gt;set&lt;/span&gt; +a
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you skip this, Feast won’t raise an error about missing variables. It leaves &lt;code&gt;${MONGODB_URI}&lt;/code&gt; and &lt;code&gt;${DB_NAME}&lt;/code&gt; as literal text, and the next command fails with a confusing error such as &lt;code&gt;pymongo.errors.InvalidName: database names cannot contain the character '$'&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;On Windows, set them in your shell instead, for example &lt;code&gt;$env:MONGODB_URI="..."&lt;/code&gt; and &lt;code&gt;$env:DB_NAME="..."&lt;/code&gt; in PowerShell. Run all of the following &lt;code&gt;feast&lt;/code&gt; and Python commands from this same shell.&lt;/p&gt;

&lt;p&gt;From the project root, register the entity and feature view with Feast:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;cd&lt;/span&gt; feature_repo/feature_repo
feast apply
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This creates or updates &lt;code&gt;data/registry.db&lt;/code&gt; with your entity and feature view definitions.&lt;/p&gt;

&lt;h2&gt;
  
  
  Train a fraud model
&lt;/h2&gt;

&lt;p&gt;Return to the root after &lt;code&gt;feast apply&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;cd&lt;/span&gt; ../..
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;From the project root, create a &lt;code&gt;training/&lt;/code&gt; folder to contain the training script and the model parameters it produces:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;mkdir training
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;training/train_model.py&lt;/code&gt; pulls point-in-time-correct historical features from Feast's offline store and derives the parameters for a simple z-score model:&lt;/p&gt;

&lt;p&gt;A &lt;a href="https://en.wikipedia.org/wiki/Standard_score" rel="noopener noreferrer"&gt;z-score&lt;/a&gt; measures how many standard deviations a value sits from the mean. Transaction amounts are right-skewed (a few large purchases, many small ones), so we compute the z-score on log(amount), which is roughly normally distributed. The mean and standard deviation are fit on legitimate transactions only and transactions with log-amounts more than 2 standard deviations above the mean are flagged as potentially fraudulent.&lt;/p&gt;

&lt;p&gt;For each row in &lt;code&gt;entity_df&lt;/code&gt;, &lt;code&gt;get_historical_features()&lt;/code&gt; looks backward from that row's timestamp and finds the most recent feature value available at that point in time, which is what makes the result point-in-time-correct.&lt;/p&gt;

&lt;p&gt;If no feature value exists within the &lt;code&gt;ttl&lt;/code&gt; window before a given timestamp, that row comes back with nulls instead of a stale, overly-old value. Shortening the &lt;code&gt;ttl&lt;/code&gt; makes the lookup stricter, as only recent data will be added; lengthening it allows older values to still be considered valid.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="s2"&gt;"""
Retrieves point-in-time training data from Feast’s offline store, then
“trains” a z-score model on it.
The model parameters are written to training/model_params.json so that the
Django view reads them instead of having to copy them in by hand.
"""&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;json&lt;/span&gt;
&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;pathlib&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nc"&gt;Path&lt;/span&gt;

&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;numpy&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;np&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;pandas&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;pd&lt;/span&gt;
&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;feast&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nc"&gt;FeatureStore&lt;/span&gt;

&lt;span class="no"&gt;BASE_DIR&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Path&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;__file__&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;resolve&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;
&lt;span class="no"&gt;TRANSACTIONS_PARQUET_FILE&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="no"&gt;BASE_DIR&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="s2"&gt;"data"&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="s2"&gt;"transactions.parquet"&lt;/span&gt;
&lt;span class="no"&gt;PARAMS_PATH&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Path&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;__file__&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;resolve&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="s2"&gt;"model_params.json"&lt;/span&gt;
&lt;span class="n"&gt;store&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;FeatureStore&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;repo_path&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="no"&gt;BASE_DIR&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="s2"&gt;"feature_repo"&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="s2"&gt;"feature_repo"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;transactions_df&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;pd&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;read_parquet&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="no"&gt;TRANSACTIONS_PARQUET_FILE&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;


&lt;span class="c1"&gt;# Extra entity_df columns (here, the is_fraudulent label) are passed through to the result unchanged.&lt;/span&gt;
&lt;span class="n"&gt;entity_df&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;transactions_df&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"user_id"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"event_timestamp"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"is_fraudulent"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;copy&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;training_df&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;store&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get_historical_features&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="n"&gt;entity_df&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;entity_df&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;features&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;
        &lt;span class="s2"&gt;"transaction_features:amount"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="s2"&gt;"transaction_features:category"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="s2"&gt;"transaction_features:location"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;to_df&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;training_df&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;head&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"\nPulled {len(training_df)} rows of training data."&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="c1"&gt;# --- The “model”: mean and standard deviation of log(amount) ---&lt;/span&gt;
&lt;span class="c1"&gt;# Amounts are right-skewed (lognormal), so the z-score is computed on &lt;/span&gt;
&lt;span class="c1"&gt;# log(amount), which is roughly normal. The baseline is fit on legitimate&lt;/span&gt;
&lt;span class="c1"&gt;# transactions only, so fraud doesn’t inflate its own threshold.&lt;/span&gt;
&lt;span class="c1"&gt;# A transaction is flagged if its log-amount is more than 2 standard&lt;/span&gt;
&lt;span class="c1"&gt;# deviations ABOVE the mean (one-sided: unusually small amounts aren’t flagged).&lt;/span&gt;


&lt;span class="n"&gt;legit_log_amounts&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;np&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;training_df&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;loc&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="o"&gt;~&lt;/span&gt;&lt;span class="n"&gt;training_df&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"is_fraudulent"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"amount"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="no"&gt;TRAIN_MEAN_LOG_AMOUNT&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kt"&gt;float&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;legit_log_amounts&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;mean&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="no"&gt;TRAIN_STD_LOG_AMOUNT&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kt"&gt;float&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;legit_log_amounts&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;std&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="no"&gt;PARAMS_PATH&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;write_text&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="n"&gt;json&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;dumps&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="s2"&gt;"mean_log_amount"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="no"&gt;TRAIN_MEAN_LOG_AMOUNT&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="s2"&gt;"std_log_amount"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="no"&gt;TRAIN_STD_LOG_AMOUNT&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="s2"&gt;"z_score_threshold"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;2.0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="n"&gt;indent&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="s2"&gt;"\n"&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"\nFit on {len(legit_log_amounts)} legitimate transactions."&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Trained model parameters:"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"TRAIN_MEAN_LOG_AMOUNT = {TRAIN_MEAN_LOG_AMOUNT}"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"TRAIN_STD_LOG_AMOUNT = {TRAIN_STD_LOG_AMOUNT}"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"\nWrote parameters to {PARAMS_PATH}"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;From the project root, run:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;python training/train_model.py
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With the seeded data, you should see &lt;code&gt;Fit on 49 legitimate transactions.&lt;/code&gt; , &lt;code&gt;TRAIN_MEAN_LOG_AMOUNT = 3.5326…&lt;/code&gt;, and &lt;code&gt;TRAIN_STD_LOG_AMOUNT = 0.4687…&lt;/code&gt;. &lt;br&gt;
The script writes these values to &lt;code&gt;training/model_params.json&lt;/code&gt;, which the Django view reads at request time. &lt;code&gt;training/model_params.json&lt;/code&gt; is already in your &lt;code&gt;.gitignore&lt;/code&gt;; it's regenerated each time you train.&lt;/p&gt;
&lt;h2&gt;
  
  
  Materialize features into MongoDB
&lt;/h2&gt;

&lt;p&gt;"Materializing" pushes the latest feature values for each entity from the offline store to the online store (MongoDB), which is what serves low-latency lookups at request time. &lt;/p&gt;

&lt;p&gt;From the project root, run:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;cd&lt;/span&gt; feature_repo/feature_repo
feast materialize 2020-01-01T00:00:00 2026-09-01T00:00:00
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The end date must be after the most recent &lt;code&gt;event_timestamp&lt;/code&gt; in your data (30 July 2026 for seeded data).&lt;br&gt;
You should see output similar to the following along with a progress bar:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Materializing 1 feature view from 2020-01-01 00:00:00+00:00 to 2026-09-01 00:00:00+00:00 into the mongodb online store.

transaction_features:
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can confirm the features landed in MongoDB by using Feast to read them back. &lt;/p&gt;

&lt;p&gt;Create &lt;code&gt;feature_repo/feature_repo/test_online_features.py&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="s2"&gt;"""
Confirms Feast can read materialized features back out of MongoDB
via get_online_features()
"""&lt;/span&gt;

&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;pathlib&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nc"&gt;Path&lt;/span&gt;

&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;feast&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nc"&gt;FeatureStore&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;store&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;FeatureStore&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;repo_path&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Path&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;__file__&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;resolve&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="n"&gt;entity_rows&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"user_id"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

    &lt;span class="n"&gt;online_features&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;store&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get_online_features&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="n"&gt;features&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;
            &lt;span class="s2"&gt;"transaction_features:amount"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="s2"&gt;"transaction_features:category"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="s2"&gt;"transaction_features:location"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="n"&gt;entity_rows&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;entity_rows&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;to_dict&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;online_features&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;


&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;__name__&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="s2"&gt;"__main__"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The work is wrapped in &lt;code&gt;main()&lt;/code&gt; behind an &lt;code&gt;if __name__ == "__main__":&lt;/code&gt; guard because &lt;code&gt;feast apply&lt;/code&gt; imports every Python file in the feature repository. Without the guard, this script would query the online store every time you run &lt;code&gt;feast apply&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;You are still in &lt;code&gt;feature_repo/feature_repo&lt;/code&gt;, so run the following command and return to the project root:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;python test_online_features.py
&lt;span class="nb"&gt;cd&lt;/span&gt; ../..
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You should see something like this:&lt;br&gt;
&lt;code&gt;{'user_id': [2], 'amount': [28.079999923706055], 'category': ['entertainment'], 'location': ['London']}&lt;/code&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The online store holds each entity's latest value only, not full history, so a flagged transaction won't necessarily surface if newer transactions have since materialized over it. Re-run &lt;code&gt;feast materialize&lt;/code&gt; whenever new transactions are generated and loaded.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;
  
  
  View the materialized features in MongoDB Atlas
&lt;/h2&gt;

&lt;p&gt;After connecting to your MongoDB Atlas cluster, open your cluster and browse collections.&lt;br&gt;
Select the database you set as &lt;code&gt;DB_NAME&lt;/code&gt; in &lt;code&gt;.env&lt;/code&gt; (the same database used by Django and by &lt;code&gt;database_name&lt;/code&gt; in &lt;code&gt;feature_store.yaml&lt;/code&gt;).&lt;br&gt;
Open the &lt;code&gt;fraud_detection_latest&lt;/code&gt; collection. Feast names it &lt;code&gt;&amp;lt;project&amp;gt;_latest&lt;/code&gt;, and its MongoDB online store keeps one document per entity holding only the most recent materialized feature values.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F4qeprcjfh2o94k200af6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F4qeprcjfh2o94k200af6.png" alt="Materialized features in the fraud_detection_latest collection, one document per user" width="799" height="495"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Materialized features in the fraud_detection_latest collection, one document per user. User 6’s document holds the fraudulent amount (143.044…).&lt;/p&gt;
&lt;h2&gt;
  
  
  Produce real-time predictions
&lt;/h2&gt;

&lt;p&gt;Back in the Django app, &lt;code&gt;transactions/feast_client.py&lt;/code&gt; wraps the Feast online lookup:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;django&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;conf&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;settings&lt;/span&gt;
&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;feast&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nc"&gt;FeatureStore&lt;/span&gt;

&lt;span class="no"&gt;FEATURE_REPO_PATH&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;settings&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;BASE_DIR&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="s2"&gt;"feature_repo"&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="s2"&gt;"feature_repo"&lt;/span&gt;
&lt;span class="n"&gt;_store&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;FeatureStore&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;repo_path&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="no"&gt;FEATURE_REPO_PATH&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;get_latest_transaction_features&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;user_id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;dict&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="s2"&gt;"""
    Looks up the most recent materialized transaction features for a
    user_id from MongoDB (the online store) via Feast.
    """&lt;/span&gt;
    &lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;_store&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get_online_features&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="n"&gt;features&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;
            &lt;span class="s2"&gt;"transaction_features:amount"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="s2"&gt;"transaction_features:category"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="s2"&gt;"transaction_features:location"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="n"&gt;entity_rows&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"user_id"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;user_id&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;to_dict&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;values&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;values&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;items&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;transactions/views.py&lt;/code&gt; uses it to apply the z-score model trained in "Train a fraud model" section and flag potentially fraudulent transactions. It reads the model parameters from &lt;code&gt;training/model_params.json&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;json&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;math&lt;/span&gt;

&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;django&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;conf&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;settings&lt;/span&gt;
&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;django&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;http&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nc"&gt;JsonResponse&lt;/span&gt;

&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;transactions&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;feast_client&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;get_latest_transaction_features&lt;/span&gt;

&lt;span class="no"&gt;PARAMS_PATH&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;settings&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;BASE_DIR&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="s2"&gt;"training"&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="s2"&gt;"model_params.json"&lt;/span&gt;
&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_load_model_params&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;with&lt;/span&gt; &lt;span class="nb"&gt;open&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="no"&gt;PARAMS_PATH&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;json&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;load&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;score_transaction&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;user_id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;try&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;params&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;_load_model_params&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;except&lt;/span&gt; &lt;span class="nc"&gt;FileNotFoundError&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nc"&gt;JsonResponse&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"error"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"Model parameters not found. Run training/train_model.py first."&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;503&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="p"&gt;)&lt;/span&gt;


    &lt;span class="n"&gt;features&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;get_latest_transaction_features&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;user_id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;amount&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;features&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"amount"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;amount&lt;/span&gt; &lt;span class="k"&gt;is&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nc"&gt;JsonResponse&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"error"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"No features found for user_id {user_id}"&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;404&lt;/span&gt;
        &lt;span class="p"&gt;)&lt;/span&gt;


    &lt;span class="n"&gt;z_score&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;math&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;amount&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;params&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"mean_log_amount"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="n"&gt;params&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"std_log_amount"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
    &lt;span class="n"&gt;is_potentially_fraudulent&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;z_score&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;params&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"z_score_threshold"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nc"&gt;JsonResponse&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="s2"&gt;"user_id"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;user_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="s2"&gt;"amount"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;amount&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="s2"&gt;"category"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;features&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"category"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="s2"&gt;"location"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;features&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"location"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="s2"&gt;"z_score"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;round&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;z_score&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="s2"&gt;"is_potentially_fraudulent"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;is_potentially_fraudulent&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;From the project root, start the development server:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;python manage.py runserver
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In a second terminal, request a score for a given user:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;curl http://127.0.0.1:8000/score/2/
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You should get a JSON response like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nl"&gt;"user_id"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nl"&gt;"amount"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;28.079999923706055&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nl"&gt;"category"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"entertainment"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nl"&gt;"location"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"London"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nl"&gt;"z_score"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;-0.422&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nl"&gt;"is_potentially_fraudulent"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;false&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;User 2’s latest transaction is normal. The seeded data’s fraudulent transaction is user 6’s latest so we can request that by running:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;curl http://127.0.0.1:8000/score/6/
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Results:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nl"&gt;"user_id"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nl"&gt;"amount"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;143.04425048828125&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nl"&gt;"category"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"utilities"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nl"&gt;"location"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"London"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nl"&gt;"z_score"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;3.052&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nl"&gt;"is_potentially_fraudulent"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The online store holds only each user’s latest values, so an older fraudulent transaction would be overwritten by newer ones. The generator deliberately makes the fraud a user’s most recent transaction so you can see a positive result.&lt;/p&gt;

&lt;p&gt;NB: the z-score is a baseline; it uses one baseline for all users rather than each user’s spending pattern and it’s evaluated in the same data it was trained on with no test set.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion and next steps
&lt;/h2&gt;

&lt;p&gt;Great job on making it to this point 🎉. You've built an end-to-end pipeline that generates transaction data, stores it in MongoDB through Django, defines and registers features with Feast, trains a statistical model on historical features, materializes the latest feature values into MongoDB as an online store, and serves real-time fraud scores from a Django view.&lt;/p&gt;

&lt;p&gt;From here, you could explore:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Replace the z-score model with a trained scikit-learn classifier (&lt;code&gt;pip install scikit-learn&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;Add more features such as the average spend per user to &lt;code&gt;transaction_features&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Schedule &lt;code&gt;feast materialize-incremental&lt;/code&gt; to run on a cron job so the online store stays up to date as new transactions are loaded.&lt;/li&gt;
&lt;li&gt;Add authentication and input validation to the &lt;code&gt;score_transaction&lt;/code&gt; endpoint.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  References
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://docs.feast.dev/tutorials/agent_feature_store#quickstart" rel="noopener noreferrer"&gt;Feast-Powered AI Agent&lt;/a&gt; &lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.mongodb.com/products/updates/mongodb-support-in-feast-framework/?utm_campaign=devrel&amp;amp;utm_source=third-party-content&amp;amp;utm_medium=cta&amp;amp;utm_content=buildrel-feast-implementation-devto&amp;amp;utm_term=abigail.gbadago" rel="noopener noreferrer"&gt;MongoDB Support in Feast Framework&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.mongodb.com/docs/atlas/ai-integrations/feast/?utm_campaign=devrel&amp;amp;utm_source=third-party-content&amp;amp;utm_medium=cta&amp;amp;utm_content=buildrel-feast-implementation-devto&amp;amp;utm_term=abigail.gbadago" rel="noopener noreferrer"&gt;Integrate MongoDB with Feast&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.mongodb.com/docs/languages/python/django-mongodb/current/get-started/?utm_campaign=devrel&amp;amp;utm_source=third-party-content&amp;amp;utm_medium=cta&amp;amp;utm_content=buildrel-feast-implementation-devto&amp;amp;utm_term=abigail.gbadago" rel="noopener noreferrer"&gt;Get Started with Django MongoDB Backend&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>ai</category>
      <category>mongodb</category>
      <category>agents</category>
      <category>django</category>
    </item>
    <item>
      <title>Implementing SSO for MongoDB Atlas Using Entra ID</title>
      <dc:creator>MongoDB Guests</dc:creator>
      <pubDate>Wed, 11 Nov 2026 12:00:00 +0000</pubDate>
      <link>https://dev.to/mongodb/implementing-sso-for-mongodb-atlas-using-entra-id-4l2f</link>
      <guid>https://dev.to/mongodb/implementing-sso-for-mongodb-atlas-using-entra-id-4l2f</guid>
      <description>&lt;p&gt;&lt;em&gt;This tutorial was written by &lt;a href="https://www.linkedin.com/in/dbadarsh/" rel="noopener noreferrer"&gt;Darshan Jayarama&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;MongoDB offers enterprise authentication, which includes LDAP, Kerberos, and x.509 certificates. These are widely accepted but require extensive infrastructure setup, complex certificate management, and domain dependency. If your organization is moving towards a cloud-native and SaaS based environment, managing traditional authentication systems at scale can be difficult.&lt;/p&gt;

&lt;p&gt;This is the reason we lean towards implementing OIDC authentication. It is integrated with Active Directory, a token-based auth protocol, and a modern solution built on top of OAuth that provides SSO with a cloud identity provider such as Microsoft Entra ID. For modern solutions like Atlas, OIDC is a scalable, easy-to-set-up, and cloud-friendly approach that improves the security and user experience.&lt;/p&gt;

&lt;h2&gt;
  
  
  &amp;nbsp;Understanding the Architecture:
&lt;/h2&gt;

&lt;p&gt;Let’s understand how authentication flows between Entra ID and Atlas.&lt;/p&gt;

&lt;p&gt;In our current setup:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Microsoft Entra ID acts as the Identity Provider(IdP)&lt;/li&gt;
&lt;li&gt;MongoDB Atlas is a service provider&lt;/li&gt;
&lt;li&gt;OIDC tokens are used to establish trust and validate the identity&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;When a user attempts to access Atlas:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Atlas redirects the authentication to Microsoft Entra ID&lt;/li&gt;
&lt;li&gt;User completes the Authentication (via browser or token-based)&lt;/li&gt;
&lt;li&gt;Entra ID generates the OIDC token&lt;/li&gt;
&lt;li&gt;Atlas validates that token&lt;/li&gt;
&lt;li&gt;Atlas maps the authenticated user to MongoDB roles and privileges.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;User → Microsoft Entra ID → OIDC Token → MongoDB Atlas → Authorized Access &lt;/p&gt;

&lt;h2&gt;
  
  
  Implementation
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Prerequisites:
&lt;/h3&gt;

&lt;p&gt;In Microsoft Entra ID&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Make sure you have Microsoft Entra Admin Center access&lt;/li&gt;
&lt;li&gt;Permission to register enterprise applications&lt;/li&gt;
&lt;li&gt;Ability to create client secrets&lt;/li&gt;
&lt;li&gt;Permission to configure token claims and API permissions&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In MongoDB Atlas&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Organization Owner or Project Owner access&lt;/li&gt;
&lt;li&gt;Atlas cluster is currently running&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://www.mongodb.com/docs/atlas/workforce-oidc/?utm_campaign=devrel&amp;amp;utm_source=third-party-content&amp;amp;utm_medium=cta&amp;amp;utm_content=buildrel-sso-for-atlas-devto&amp;amp;utm_term=hugh.murray#std-label-configure-idp-oidc/" rel="noopener noreferrer"&gt;Federated Authentication feature enabled&lt;/a&gt; &lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Application Registration in Entra ID:
&lt;/h3&gt;

&lt;p&gt;The application has to be registered inside Microsoft Entra ID, which establishes trust between Entra ID and Atlas. You can follow the &lt;a href="https://learn.microsoft.com/en-us/entra/identity/saas-apps/mongodb-cloud-tutorial" rel="noopener noreferrer"&gt;official documentation&lt;/a&gt;, as this is specific to registering MongoDB Atlas, or talk with the Azure admin team to register the application and ask them to share it.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fbxqj73ewovrnfufxudsz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fbxqj73ewovrnfufxudsz.png" alt=" " width="800" height="383"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Once you have finished the above step, copy the Object ID, which will be required for the next steps.&lt;/p&gt;

&lt;h3&gt;
  
  
  Configure OIDC in MongoDB Atlas:
&lt;/h3&gt;

&lt;p&gt;In order to establish trust with Microsoft Entra ID as an Identity Provider (IdP), you must complete the identity configuration within MongoDB Atlas. This process links your Entra ID application registration with MongoDB Atlas Federated Authentication, enabling seamless Single Sign-On (SSO) and centralized access management.&lt;/p&gt;

&lt;h4&gt;
  
  
  Step 1: Configure OIDC IdP in Atlas:
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;Log in to MongoDB Atlas. You should have Organization Owner privilege.&lt;/li&gt;
&lt;li&gt;Click on the organization you desire &lt;a href="https://cloud.mongodb.com/v2#/preferences/organizations" rel="noopener noreferrer"&gt;https://cloud.mongodb.com/v2#/preferences/organizations&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Click on “Federation”, then “Open Federation Management App”.&lt;/li&gt;
&lt;li&gt;Now click “Identity Providers”, then “Configure Identity Provider”.&lt;/li&gt;
&lt;li&gt;Click on the “Allow software workloads …” button, then click Continue&lt;/li&gt;
&lt;li&gt;Fill out the details:

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Configuration Name:&lt;/strong&gt; Any descriptive name for identification.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Configuration Description:&lt;/strong&gt; Optional Description for this configuration&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Issuer URI:&lt;/strong&gt; Navigate to &lt;a href="https://portal.azure.com/#view/Microsoft_AAD_RegisteredApps/ApplicationsListBlade" rel="noopener noreferrer"&gt;App registrations&lt;/a&gt; in Azure, search for the application you have created, and copy the value of Directory (tenant) ID highlighted in Yellow below. Paste the tenant ID in the placeholder:
&lt;a href="https://login.microsoftonline.com/TENANT_ID/v2.0" rel="noopener noreferrer"&gt;https://login.microsoftonline.com/TENANT_ID/v2.0&lt;/a&gt; &lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fj5z3mu20hlg8ehw9of1g.png" alt=" " width="800" height="385"&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Client ID:&lt;/strong&gt; From the same screenshot, you can copy the Client ID (highlighted in green). Paste it as is.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Audience:&lt;/strong&gt; Same as above; paste the Client ID&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Requested Scopes:&lt;/strong&gt; Just place Client_ID value then .default ( CLIENT_ID/.default)&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Leave the remaining fields as is, then hit Save and Finish.&lt;/p&gt;

&lt;h4&gt;
  
  
  Step 2: Create Entra group:
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;Go to Enterprise Applications All applications &lt;a href="https://portal.azure.com/#view/Microsoft_AAD_IAM/StartboardApplicationsMenuBlade/~/AppAppsPreview" rel="noopener noreferrer"&gt;page&lt;/a&gt; &lt;/li&gt;
&lt;li&gt;Search for the application that you created earlier and click on it.&lt;/li&gt;
&lt;li&gt;Go to the “Users and Groups” tab in the left-hand panel:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fbxdizz0201vtcq8ir3sk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fbxdizz0201vtcq8ir3sk.png" alt=" " width="800" height="424"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Select Add user/group. &lt;/li&gt;
&lt;li&gt;Fill out the details and click the Save button. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For more details, please follow the official &lt;a href="https://learn.microsoft.com/en-us/entra/identity/enterprise-apps/assign-user-or-group-access-portal" rel="noopener noreferrer"&gt;Azure documentation&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Once the group is created, click on it to copy the Object ID of that group:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fwgi9nmteqtelce9m1xg2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fwgi9nmteqtelce9m1xg2.png" alt=" " width="800" height="470"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Step 3: Add Entra to Atlas Cluster:
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;Go to the Database &amp;amp; Network page in the cluster:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fk5brmhtmvk82rv0pjrd6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fk5brmhtmvk82rv0pjrd6.png" alt=" " width="703" height="783"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Fill in the details:

&lt;ul&gt;
&lt;li&gt;Identity provider is the application that we added at the organization level (from Step 1)&lt;/li&gt;
&lt;li&gt;Group Identifier is the value you copied once we created the group in Entra (from Step 2)&lt;/li&gt;
&lt;li&gt;Give a description as needed, and the rest of the fields are the same as a regular user&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fti5b2bo5udlpogigesle.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fti5b2bo5udlpogigesle.png" alt=" " width="800" height="1171"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Once done, click the Add Group button.&lt;/p&gt;

&lt;p&gt;Now we have added the group. In order to authenticate using this group. Go to the cluster page, click the Connect button to get the MongoDB URI:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fic1jtdwqr857zpgf7v4h.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fic1jtdwqr857zpgf7v4h.png" alt=" " width="634" height="688"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Select the “Federated Auth” option and copy the connection string that is available.&lt;/p&gt;

&lt;p&gt;In order to use this in Compass, you should be running MongoDB Compass version 1.49+. Once you use the Federated Auth URI, it will open a browser, and you should log in to your Microsoft Account.&lt;/p&gt;

&lt;p&gt;After a successful login, you are all set to use the MongoDB cluster with OIDC Authentication.&lt;/p&gt;

</description>
      <category>cloud</category>
      <category>database</category>
      <category>security</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Upgrade from MongoDB 8.0 to 9.0 Without Surprises: A Realistic Walkthrough with Docker</title>
      <dc:creator>Nic Raboy</dc:creator>
      <pubDate>Mon, 09 Nov 2026 17:53:59 +0000</pubDate>
      <link>https://dev.to/mongodb/upgrade-from-mongodb-80-to-90-without-surprises-a-realistic-walkthrough-with-docker-3mji</link>
      <guid>https://dev.to/mongodb/upgrade-from-mongodb-80-to-90-without-surprises-a-realistic-walkthrough-with-docker-3mji</guid>
      <description>&lt;p&gt;A new major version of your database is exciting right up until you have to run it in production. The release notes are long, the upgrade procedure has more than one step, and the question that actually matters is hard to answer from a document: what happens to my application when I do this?&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.mongodb.com/docs/manual/release-notes/9.0/?utm_campaign=devrel&amp;amp;utm_source=third-party-content&amp;amp;utm_medium=cta&amp;amp;utm_content=mongodb-9-upgrade&amp;amp;utm_term=nicolas.raboy" rel="noopener noreferrer"&gt;MongoDB 9.0&lt;/a&gt; is generally available, and it brings performance gains over 8.0, including up to 35% faster find-one queries and up to 30% faster update-one queries. Those figures are "up to" numbers that depend on hardware, workload, and data, so the best way to find out what 9.0 does for you is to try it on your own workload, and the first step to doing that is a safe upgrade path.&lt;/p&gt;

&lt;p&gt;In this tutorial, we'll walk through a realistic upgrade of a three-member replica set from MongoDB 8.0 to 9.0 using Docker. We'll check the health of the deployment, take a backup and verify it restores, make a go/no-go decision, perform a rolling upgrade one member at a time, and then raise the feature compatibility version. Along the way, we'll look at what changes for an application and how to measure your own workload with &lt;code&gt;$queryStats&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Prerequisites
&lt;/h2&gt;

&lt;p&gt;Prior to starting this tutorial, you'll need a few things in place:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Docker with Compose v2, and at least 2 GB of memory available to it
&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;curl&lt;/code&gt; for downloading the sample dataset&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The expectation is that you're comfortable running commands in a terminal. You don't need Node.js installed on your machine because the sample application runs inside a container.&lt;/p&gt;

&lt;p&gt;It's worth being clear about why Docker is in the picture. We're using it for the sake of this tutorial, because it lets us create a three-member replica set on a single machine, reset it, and run through the whole process as many times as we want. Docker is not a requirement for upgrading to MongoDB 9.0. The same procedure applies to a self-managed replica set running on virtual machines or bare metal, where you'd replace the MongoDB packages or binaries on each member instead of swapping a container image. If you run on MongoDB Atlas, the platform performs the rolling upgrade for you, and we'll touch on what that looks like later.&lt;/p&gt;

&lt;p&gt;We'll use the &lt;code&gt;sample_mflix&lt;/code&gt; dataset that you may already know from MongoDB Atlas, but since we're not using Atlas for the main walkthrough, we'll restore it to our own deployment. Start by creating a project directory with a place for each part of the project:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;mkdir &lt;/span&gt;mongodb-9-upgrade
&lt;span class="nb"&gt;cd &lt;/span&gt;mongodb-9-upgrade
&lt;span class="nb"&gt;mkdir &lt;/span&gt;data docker backup scripts
&lt;span class="nb"&gt;mkdir&lt;/span&gt; &lt;span class="nt"&gt;-p&lt;/span&gt; app/src
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above commands create the project and the directories we'll fill in as we go. We'll end up with the following shape:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;.
├── app/
│   ├── package.json
│   └── src/
│       ├── db.js
│       ├── baseline.js
│       └── utcDemo.js
├── backup/
│   ├── backup.sh
│   └── verify.sh
├── data/
│   └── sampledata.archive
├── docker/
│   ├── compose.yml
│   └── restore.sh
└── scripts/
    ├── run-app.sh
    └── queryStats.js
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The sample dataset is a single archive that contains several databases. Download it into the &lt;strong&gt;data&lt;/strong&gt; directory:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;curl &lt;span class="nt"&gt;-o&lt;/span&gt; data/sampledata.archive https://atlas-education.s3.amazonaws.com/sampledata.archive
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The archive is roughly 400 MB, so it may take a minute. We'll only restore the &lt;code&gt;sample_mflix&lt;/code&gt; database from it later.&lt;/p&gt;

&lt;h2&gt;
  
  
  What Changes in MongoDB 9.0
&lt;/h2&gt;

&lt;p&gt;Before touching any servers, it helps to know what you're signing up for. The &lt;a href="https://www.mongodb.com/docs/manual/release-notes/9.0-compatibility/?utm_campaign=devrel&amp;amp;utm_source=third-party-content&amp;amp;utm_medium=cta&amp;amp;utm_content=mongodb-9-upgrade&amp;amp;utm_term=nicolas.raboy" rel="noopener noreferrer"&gt;compatibility changes&lt;/a&gt; page is the authoritative list, and you should read it in full before upgrading a real deployment. The changes most likely to affect an application fall into three groups.&lt;/p&gt;

&lt;p&gt;Some changes happen silently, meaning nothing errors and you get a different answer:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Server-side JavaScript in &lt;code&gt;$function&lt;/code&gt;, &lt;code&gt;$accumulator&lt;/code&gt;, &lt;code&gt;$where&lt;/code&gt;, and &lt;code&gt;mapReduce&lt;/code&gt; now evaluates &lt;code&gt;Date&lt;/code&gt; operations in UTC rather than in the time zone of the &lt;code&gt;mongod&lt;/code&gt; host.
&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;$queryStats&lt;/code&gt; &lt;code&gt;key&lt;/code&gt; and &lt;code&gt;keyHash&lt;/code&gt; for &lt;code&gt;aggregate&lt;/code&gt; queries that set &lt;code&gt;allowPartialResults&lt;/code&gt; are serialized differently, so anything that matches on &lt;code&gt;keyHash&lt;/code&gt; for those queries may see new values. The &lt;code&gt;queryShapeHash&lt;/code&gt; doesn't change.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Some changes can cause new errors:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A single operation is limited to the greater of 1 GB or 20% of server memory. Queries that previously used unbounded memory can fail with &lt;code&gt;ExceededMemoryLimit&lt;/code&gt;, or with &lt;code&gt;QueryExceededMemoryLimitNoDiskUseAllowed&lt;/code&gt; if disk use isn't allowed.
&lt;/li&gt;
&lt;li&gt;All ingested BSON is validated by default, so invalid BSON that older versions accepted now returns an error.
&lt;/li&gt;
&lt;li&gt;An accumulator with an empty field name in &lt;code&gt;$group&lt;/code&gt; now returns an error.
&lt;/li&gt;
&lt;li&gt;A query can fail with &lt;code&gt;QueryKilledError&lt;/code&gt; if an indexed field becomes multikey while the query runs.
&lt;/li&gt;
&lt;li&gt;A change stream opened with a &lt;code&gt;readPreference&lt;/code&gt; of &lt;code&gt;primary&lt;/code&gt; or &lt;code&gt;secondary&lt;/code&gt; returns error code &lt;code&gt;11602&lt;/code&gt; from &lt;code&gt;getMore&lt;/code&gt; after an election. Compliant drivers resume on their own, but manual &lt;code&gt;getMore&lt;/code&gt; loops need to resume with &lt;code&gt;resumeAfter&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;And some changes are new tooling worth knowing about:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;$queryStats&lt;/code&gt; is on by default, samples 1% of operations, and now covers &lt;code&gt;update&lt;/code&gt;, &lt;code&gt;insert&lt;/code&gt;, and &lt;code&gt;delete&lt;/code&gt;.
&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;$function&lt;/code&gt;, &lt;code&gt;$accumulator&lt;/code&gt;, and &lt;code&gt;$where&lt;/code&gt; are no longer deprecated, and they run on a sandboxed WebAssembly-based engine.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We'll demonstrate the time zone change later because it's the one most likely to go unnoticed.&lt;/p&gt;

&lt;h2&gt;
  
  
  Create a Three-Member Replica Set on MongoDB 8.0
&lt;/h2&gt;

&lt;p&gt;A realistic upgrade starts from a realistic deployment. In production, you'd run a replica set with at least three members, and the upgrade procedure for a replica set is a rolling one that takes advantage of that. We'll recreate the same shape locally.&lt;/p&gt;

&lt;p&gt;Create a &lt;strong&gt;docker/compose.yml&lt;/strong&gt; file with the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;name: mongo9blog

x-mongo: &amp;amp;mongo
  command: ["--replSet", "rs0", "--bind_ip_all", "--wiredTigerCacheSizeGB", "0.25"]
  environment:
    TZ: America/New_York

services:
  mongo1:
    &amp;lt;&amp;lt;: *mongo
    image: ${MONGO1_IMAGE:-mongodb/mongodb-community-server:8.0.34-ubuntu2204}
    volumes:
      - mongo1-data:/data/db
  mongo2:
    &amp;lt;&amp;lt;: *mongo
    image: ${MONGO2_IMAGE:-mongodb/mongodb-community-server:8.0.34-ubuntu2204}
    volumes:
      - mongo2-data:/data/db
  mongo3:
    &amp;lt;&amp;lt;: *mongo
    image: ${MONGO3_IMAGE:-mongodb/mongodb-community-server:8.0.34-ubuntu2204}
    volumes:
      - mongo3-data:/data/db

volumes:
  mongo1-data:
  mongo2-data:
  mongo3-data:
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There are a few things happening in this file. The &lt;code&gt;x-mongo&lt;/code&gt; block at the top holds the settings that all three members share, and each service pulls them in with &lt;code&gt;&amp;lt;&amp;lt;: *mongo&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;x-mongo: &amp;amp;mongo
  command: ["--replSet", "rs0", "--bind_ip_all", "--wiredTigerCacheSizeGB", "0.25"]
  environment:
    TZ: America/New_York
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;--replSet rs0&lt;/code&gt; flag makes each &lt;code&gt;mongod&lt;/code&gt; a replica set member. The cache size is capped at a quarter of a gigabyte so that three members fit comfortably on a laptop alongside everything else you're running. The &lt;code&gt;TZ&lt;/code&gt; value runs the servers in the New York time zone, which will matter when we look at the server-side JavaScript change. Production servers are very often set to UTC, and if yours are, you won't see that particular difference, but the demo is still a good way to understand it.&lt;/p&gt;

&lt;p&gt;The more important part for the upgrade is how each member gets its image:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  mongo1:
    &amp;lt;&amp;lt;: *mongo
    image: ${MONGO1_IMAGE:-mongodb/mongodb-community-server:8.0.34-ubuntu2204}
    volumes:
      - mongo1-data:/data/db
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Each member has its own image variable, which defaults to MongoDB 8.0.34. That means we can start everything on 8.0 now, and later upgrade a single member by setting just that member's variable. Each member also has its own named volume, so the data survives when a container is replaced with a different image.&lt;/p&gt;

&lt;p&gt;Start the three members:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;docker compose &lt;span class="nt"&gt;-f&lt;/span&gt; docker/compose.yml up &lt;span class="nt"&gt;-d&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The first run pulls the image, which takes a moment. Even after the containers are running, each &lt;code&gt;mongod&lt;/code&gt; needs a few seconds to start accepting connections, so wait a few seconds before running the next command. If you see a connection refused error, wait a moment and run it again. The members also don't know about each other yet, so we need to initiate the replica set:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;docker compose &lt;span class="nt"&gt;-f&lt;/span&gt; docker/compose.yml &lt;span class="nb"&gt;exec &lt;/span&gt;mongo1 mongosh &lt;span class="nt"&gt;--quiet&lt;/span&gt; &lt;span class="nt"&gt;--eval&lt;/span&gt; &lt;span class="s1"&gt;'
  rs.initiate({
    _id: "rs0",
    members: [
      { _id: 0, host: "mongo1:27017", priority: 2 },
      { _id: 1, host: "mongo2:27017" },
      { _id: 2, host: "mongo3:27017" }
    ]
  })
'&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;priority: 2&lt;/code&gt; on the first member makes &lt;code&gt;mongo1&lt;/code&gt; the preferred primary, which keeps the walkthrough predictable. The hostnames only resolve inside the Docker network, which is why the sample application will run in a container later.&lt;/p&gt;

&lt;p&gt;Give the replica set a few seconds to elect a primary, then load the sample data. Create &lt;strong&gt;docker/restore.sh&lt;/strong&gt; with the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="c"&gt;#!/bin/sh&lt;/span&gt;
&lt;span class="nb"&gt;set&lt;/span&gt; &lt;span class="nt"&gt;-eu&lt;/span&gt;

&lt;span class="nb"&gt;cd&lt;/span&gt; &lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="si"&gt;$(&lt;/span&gt;&lt;span class="nb"&gt;dirname&lt;/span&gt; &lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="nv"&gt;$0&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="si"&gt;)&lt;/span&gt;&lt;span class="s2"&gt;/.."&lt;/span&gt;

docker run &lt;span class="nt"&gt;--rm&lt;/span&gt; &lt;span class="se"&gt;\&lt;/span&gt;
  &lt;span class="nt"&gt;--network&lt;/span&gt; mongo9blog_default &lt;span class="se"&gt;\&lt;/span&gt;
  &lt;span class="nt"&gt;-v&lt;/span&gt; &lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="nv"&gt;$PWD&lt;/span&gt;&lt;span class="s2"&gt;/data:/data-in:ro"&lt;/span&gt; &lt;span class="se"&gt;\&lt;/span&gt;
  mongo:8.0 &lt;span class="se"&gt;\&lt;/span&gt;
  mongorestore &lt;span class="se"&gt;\&lt;/span&gt;
    &lt;span class="nt"&gt;--uri&lt;/span&gt; &lt;span class="s2"&gt;"mongodb://mongo1:27017,mongo2:27017,mongo3:27017/?replicaSet=rs0"&lt;/span&gt; &lt;span class="se"&gt;\&lt;/span&gt;
    &lt;span class="nt"&gt;--archive&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;/data-in/sampledata.archive &lt;span class="se"&gt;\&lt;/span&gt;
    &lt;span class="nt"&gt;--nsInclude&lt;/span&gt; &lt;span class="s1"&gt;'sample_mflix.*'&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The script runs &lt;code&gt;mongorestore&lt;/code&gt; from a throwaway container on the same network, so you don't have to install the MongoDB Database Tools. The &lt;code&gt;--nsInclude&lt;/code&gt; flag restores only the &lt;code&gt;sample_mflix&lt;/code&gt; database from the archive. Run it with:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;sh docker/restore.sh
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When it finishes, the last line should tell you everything was restored:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;67661 document(s) restored successfully. 0 document(s) failed to restore.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That's 21,349 movies, 41,079 comments, and the rest of the &lt;code&gt;sample_mflix&lt;/code&gt; collections, and our starting point is ready.&lt;/p&gt;

&lt;h2&gt;
  
  
  Create an Application to Test the Upgrade
&lt;/h2&gt;

&lt;p&gt;An upgrade that only proves the server starts isn't much of a test, so we'll use a small application that talks to the replica set before, during, and after the upgrade. It's written in Node.js, but the specifics matter less than the habit of running something real against the deployment at each stage.&lt;/p&gt;

&lt;p&gt;Create &lt;strong&gt;app/package.json&lt;/strong&gt; with the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"name"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"mongodb-9-upgrade-demo"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"version"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"0.1.0"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"private"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"type"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"module"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"scripts"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"baseline"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"node src/baseline.js"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"utc-demo"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"node src/utcDemo.js"&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"dependencies"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"mongodb"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"^7.8.0"&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The two scripts correspond to the two files we're about to write. Next, create &lt;strong&gt;app/src/db.js&lt;/strong&gt;, which is a small helper that connects, runs a function, and always closes the client:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;MongoClient&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;mongodb&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;uri&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;process&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;env&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;MONGODB_URI&lt;/span&gt; &lt;span class="o"&gt;??&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;mongodb://mongo1:27017,mongo2:27017,mongo3:27017/?replicaSet=rs0&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;withDb&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;fn&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;client&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;MongoClient&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;uri&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;client&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;connect&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nf"&gt;fn&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;client&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;db&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;sample_mflix&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="nx"&gt;client&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;finally&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;client&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;close&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The connection string lists all three members and names the replica set. That's what lets the driver find whichever member is primary, and it's also what lets it keep working while members restart during a rolling upgrade.&lt;/p&gt;

&lt;p&gt;The first script, &lt;strong&gt;app/src/baseline.js&lt;/strong&gt;, reports what the application sees and does a read and a write:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;withDb&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;./db.js&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nf"&gt;withDb&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;async &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;db&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;admin&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;db&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;admin&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;version&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;admin&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;serverInfo&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;fcv&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;admin&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;command&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt; &lt;span class="na"&gt;getParameter&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;featureCompatibilityVersion&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="p"&gt;});&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;version:&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;version&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;fcv:&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;fcv&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;featureCompatibilityVersion&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;version&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;movies&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;db&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;collection&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;movies&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;movies:&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;movies&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;countDocuments&lt;/span&gt;&lt;span class="p"&gt;());&lt;/span&gt;

  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;one&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;movies&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;findOne&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt; &lt;span class="na"&gt;title&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;The Matrix&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt; &lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;projection&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;title&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;year&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="p"&gt;});&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;find-one:&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;one&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;update&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;movies&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;updateOne&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt; &lt;span class="na"&gt;title&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;The Matrix&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt; &lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;$inc&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;demoViews&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="p"&gt;});&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;update-one:&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;matched&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;update&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;matchedCount&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;modified&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;update&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;modifiedCount&lt;/span&gt; &lt;span class="p"&gt;});&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The script prints the server version and feature compatibility version, counts the movies, runs a &lt;code&gt;findOne&lt;/code&gt;, and runs an &lt;code&gt;updateOne&lt;/code&gt;. Because it does both a read and a write, it shows that the application keeps working through each stage. It is not a benchmark.&lt;/p&gt;

&lt;p&gt;To run it, we need a Node.js container on the same network as the replica set. Create &lt;strong&gt;scripts/run-app.sh&lt;/strong&gt; with the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="c"&gt;#!/bin/sh&lt;/span&gt;
&lt;span class="nb"&gt;set&lt;/span&gt; &lt;span class="nt"&gt;-eu&lt;/span&gt;

&lt;span class="nb"&gt;cd&lt;/span&gt; &lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="si"&gt;$(&lt;/span&gt;&lt;span class="nb"&gt;dirname&lt;/span&gt; &lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="nv"&gt;$0&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="si"&gt;)&lt;/span&gt;&lt;span class="s2"&gt;/.."&lt;/span&gt;

docker run &lt;span class="nt"&gt;--rm&lt;/span&gt; &lt;span class="se"&gt;\&lt;/span&gt;
  &lt;span class="nt"&gt;--network&lt;/span&gt; mongo9blog_default &lt;span class="se"&gt;\&lt;/span&gt;
  &lt;span class="nt"&gt;-v&lt;/span&gt; &lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="nv"&gt;$PWD&lt;/span&gt;&lt;span class="s2"&gt;/app:/app"&lt;/span&gt; &lt;span class="se"&gt;\&lt;/span&gt;
  &lt;span class="nt"&gt;-w&lt;/span&gt; /app &lt;span class="se"&gt;\&lt;/span&gt;
  &lt;span class="nt"&gt;-e&lt;/span&gt; &lt;span class="nv"&gt;MONGODB_URI&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"mongodb://mongo1:27017,mongo2:27017,mongo3:27017/?replicaSet=rs0"&lt;/span&gt; &lt;span class="se"&gt;\&lt;/span&gt;
  node:22 &lt;span class="se"&gt;\&lt;/span&gt;
  sh &lt;span class="nt"&gt;-c&lt;/span&gt; &lt;span class="s2"&gt;"npm install --silent --no-audit --no-fund &amp;amp;&amp;amp; npm run --silent &lt;/span&gt;&lt;span class="nv"&gt;$1&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The script mounts the &lt;strong&gt;app&lt;/strong&gt; directory into a &lt;code&gt;node:22&lt;/code&gt; container, installs the dependencies, and runs whichever npm script you pass in. Run the baseline:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;sh scripts/run-app.sh baseline
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You should see output similar to the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;version: 8.0.34
fcv: 8.0
movies: 21349
find-one: {
  _id: new ObjectId('573a139bf29313caabcf3d23'),
  year: 1999,
  title: 'The Matrix'
}
update-one: { matched: 1, modified: 1 }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is our "before" picture: MongoDB 8.0.34, feature compatibility version 8.0, and an application that reads and writes without any trouble.&lt;/p&gt;

&lt;h2&gt;
  
  
  Add a Check for a Behavior Change
&lt;/h2&gt;

&lt;p&gt;A clean upgrade tells you that the server runs, not that your application behaves the same. One change in 9.0 is easy to miss because nothing errors: server-side JavaScript now evaluates &lt;code&gt;Date&lt;/code&gt; operations in UTC instead of the time zone of the &lt;code&gt;mongod&lt;/code&gt; host. We'll capture a "before" result now so we can compare it after the upgrade.&lt;/p&gt;

&lt;p&gt;Create &lt;strong&gt;app/src/utcDemo.js&lt;/strong&gt; with the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;withDb&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;./db.js&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nf"&gt;withDb&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;async &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;db&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;comments&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;db&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;collection&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;comments&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;total&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;comments&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;countDocuments&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;matchesNewYorkHour&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;comments&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;countDocuments&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;
    &lt;span class="na"&gt;$expr&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="na"&gt;$eq&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
        &lt;span class="p"&gt;{&lt;/span&gt;
          &lt;span class="na"&gt;$function&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="na"&gt;body&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;function (d) { return d.getHours(); }&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="na"&gt;args&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;$date&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
            &lt;span class="na"&gt;lang&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;js&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
          &lt;span class="p"&gt;},&lt;/span&gt;
        &lt;span class="p"&gt;},&lt;/span&gt;
        &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;$hour&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;date&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;$date&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;timezone&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;America/New_York&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="p"&gt;},&lt;/span&gt;
      &lt;span class="p"&gt;],&lt;/span&gt;
    &lt;span class="p"&gt;},&lt;/span&gt;
  &lt;span class="p"&gt;});&lt;/span&gt;

  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;`getHours() equals the New York hour: &lt;/span&gt;&lt;span class="p"&gt;${&lt;/span&gt;&lt;span class="nx"&gt;matchesNewYorkHour&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="s2"&gt; of &lt;/span&gt;&lt;span class="p"&gt;${&lt;/span&gt;&lt;span class="nx"&gt;total&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;`&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The query counts the comments where the hour returned by JavaScript's &lt;code&gt;getHours()&lt;/code&gt; equals the hour calculated by &lt;code&gt;$hour&lt;/code&gt; with an explicit &lt;code&gt;America/New_York&lt;/code&gt; time zone. Our servers run in the New York time zone, so on 8.0 these should always agree. Run it against the 8.0 replica set:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;sh scripts/run-app.sh utc-demo
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Every comment agrees:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;getHours() equals the New York hour: 41079 of 41079
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Keep that number in mind. We'll run the same query again after the upgrade.&lt;/p&gt;

&lt;h2&gt;
  
  
  Check the Health of the Deployment Before You Upgrade
&lt;/h2&gt;

&lt;p&gt;Before changing anything, confirm that what you have is healthy. The upgrade documentation calls out that no member should be in the &lt;code&gt;ROLLBACK&lt;/code&gt; or &lt;code&gt;RECOVERING&lt;/code&gt; state, and you also want to know how far each secondary is behind the primary.&lt;/p&gt;

&lt;p&gt;Run the following to get a summary of the replica set:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;docker compose &lt;span class="nt"&gt;-f&lt;/span&gt; docker/compose.yml &lt;span class="nb"&gt;exec &lt;/span&gt;mongo1 mongosh &lt;span class="nt"&gt;--quiet&lt;/span&gt; &lt;span class="nt"&gt;--eval&lt;/span&gt; &lt;span class="s1"&gt;'
  const status = rs.status();
  const primary = status.members.find((m) =&amp;gt; m.stateStr === "PRIMARY");
  printjson({
    members: status.members.map((m) =&amp;gt; ({
      name: m.name,
      state: m.stateStr,
      health: m.health,
      lagSecs: (primary.optimeDate - m.optimeDate) / 1000
    })),
    version: db.version(),
    fcv: db.adminCommand({ getParameter: 1, featureCompatibilityVersion: 1 }).featureCompatibilityVersion.version
  })
'&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The command lists each member with its state, health, and replication lag in seconds, plus the server version and feature compatibility version. A healthy set looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  members: [
    { name: 'mongo1:27017', state: 'PRIMARY', health: 1, lagSecs: 0 },
    { name: 'mongo2:27017', state: 'SECONDARY', health: 1, lagSecs: 0 },
    { name: 'mongo3:27017', state: 'SECONDARY', health: 1, lagSecs: 0 }
  ],
  version: '8.0.34',
  fcv: '8.0'
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;All three members are healthy with no lag, and the feature compatibility version is 8.0. If you see a member in &lt;code&gt;RECOVERING&lt;/code&gt; or &lt;code&gt;ROLLBACK&lt;/code&gt;, or lag that isn't shrinking, stop here and fix that first.&lt;/p&gt;

&lt;p&gt;Two more checks belong in a real pre-flight and can't be shown with a sample dataset. First, you can only upgrade to 9.0 from 8.0 or 8.3, so if you're on 7.0 or earlier, upgrade to 8.0 first. If you're on 8.3, its feature compatibility version must be 8.3. Second, confirm that your drivers are compatible with 9.0. The upgrade documentation warns that incompatible drivers can produce unexpected or undefined behavior. These are the first driver versions that are fully compatible with MongoDB 9.0, according to the &lt;a href="https://www.mongodb.com/docs/drivers/compatibility/?utm_campaign=devrel&amp;amp;utm_source=third-party-content&amp;amp;utm_medium=cta&amp;amp;utm_content=mongodb-9-upgrade&amp;amp;utm_term=nicolas.raboy" rel="noopener noreferrer"&gt;client library compatibility tables&lt;/a&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Node.js: 7.6
&lt;/li&gt;
&lt;li&gt;PyMongo: 4.18
&lt;/li&gt;
&lt;li&gt;Java (sync and reactive streams), Kotlin, and Scala: 5.12
&lt;/li&gt;
&lt;li&gt;.NET/C#: 3.10
&lt;/li&gt;
&lt;li&gt;Go: 2.9
&lt;/li&gt;
&lt;li&gt;Rust: 3.9
&lt;/li&gt;
&lt;li&gt;Ruby: 2.26
&lt;/li&gt;
&lt;li&gt;PHP library: 2.5
&lt;/li&gt;
&lt;li&gt;C: 2.5
&lt;/li&gt;
&lt;li&gt;C++: 4.6&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Older versions listed as partially compatible will work with 9.0, but they don't support every new 9.0 feature, and the tables recommend moving to the versions above. The sample application in this tutorial uses version 7.8 of the Node.js driver, so it meets the requirement. Check the compatibility page for any driver or framework that isn't listed here.&lt;/p&gt;

&lt;h2&gt;
  
  
  Take a Backup and Prove That It Restores
&lt;/h2&gt;

&lt;p&gt;If something goes wrong during an upgrade, a backup is the one safety net that doesn't depend on the upgrade itself working. It's also the step people skip, so we'll make it a real step and verify it.&lt;/p&gt;

&lt;p&gt;For this tutorial, we'll use &lt;code&gt;mongodump&lt;/code&gt;, which is a logical backup that most readers can run. Create &lt;strong&gt;backup/backup.sh&lt;/strong&gt; with the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="c"&gt;#!/bin/sh&lt;/span&gt;
&lt;span class="nb"&gt;set&lt;/span&gt; &lt;span class="nt"&gt;-eu&lt;/span&gt;

&lt;span class="nb"&gt;cd&lt;/span&gt; &lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="si"&gt;$(&lt;/span&gt;&lt;span class="nb"&gt;dirname&lt;/span&gt; &lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="nv"&gt;$0&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="si"&gt;)&lt;/span&gt;&lt;span class="s2"&gt;/.."&lt;/span&gt;

&lt;span class="nv"&gt;FILE&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"backup-&lt;/span&gt;&lt;span class="si"&gt;$(&lt;/span&gt;&lt;span class="nb"&gt;date&lt;/span&gt; +%Y%m%d-%H%M%S&lt;span class="si"&gt;)&lt;/span&gt;&lt;span class="s2"&gt;.archive.gz"&lt;/span&gt;

docker run &lt;span class="nt"&gt;--rm&lt;/span&gt; &lt;span class="se"&gt;\&lt;/span&gt;
  &lt;span class="nt"&gt;--network&lt;/span&gt; mongo9blog_default &lt;span class="se"&gt;\&lt;/span&gt;
  &lt;span class="nt"&gt;-v&lt;/span&gt; &lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="nv"&gt;$PWD&lt;/span&gt;&lt;span class="s2"&gt;/backup:/backup"&lt;/span&gt; &lt;span class="se"&gt;\&lt;/span&gt;
  mongo:8.0 &lt;span class="se"&gt;\&lt;/span&gt;
  mongodump &lt;span class="se"&gt;\&lt;/span&gt;
    &lt;span class="nt"&gt;--uri&lt;/span&gt; &lt;span class="s2"&gt;"mongodb://mongo1:27017,mongo2:27017,mongo3:27017/?replicaSet=rs0"&lt;/span&gt; &lt;span class="se"&gt;\&lt;/span&gt;
    &lt;span class="nt"&gt;--oplog&lt;/span&gt; &lt;span class="se"&gt;\&lt;/span&gt;
    &lt;span class="nt"&gt;--gzip&lt;/span&gt; &lt;span class="se"&gt;\&lt;/span&gt;
    &lt;span class="nt"&gt;--archive&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"/backup/&lt;/span&gt;&lt;span class="nv"&gt;$FILE&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;

&lt;span class="nb"&gt;echo&lt;/span&gt; &lt;span class="s2"&gt;"Wrote backup/&lt;/span&gt;&lt;span class="nv"&gt;$FILE&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The script is run from your own machine, not from inside a container. The container names in the connection string, &lt;code&gt;mongo1&lt;/code&gt;, &lt;code&gt;mongo2&lt;/code&gt;, and &lt;code&gt;mongo3&lt;/code&gt;, only resolve inside the Docker network, so the script uses &lt;code&gt;docker run&lt;/code&gt; to start a short-lived &lt;code&gt;mongo:8.0&lt;/code&gt; container on that network (&lt;code&gt;mongo9blog_default&lt;/code&gt;) and runs &lt;code&gt;mongodump&lt;/code&gt; there. The &lt;code&gt;-v&lt;/code&gt; flag mounts your local &lt;strong&gt;backup&lt;/strong&gt; directory into that container, which is how the archive ends up on your machine. The &lt;code&gt;--rm&lt;/code&gt; flag removes the container when the dump finishes, so there's nothing to clean up.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;--oplog&lt;/code&gt; flag is the important one for a replica set. While the dump runs, writes keep arriving, and &lt;code&gt;--oplog&lt;/code&gt; captures those changes so the archive reflects a single point in time. The &lt;code&gt;--gzip&lt;/code&gt; flag compresses the archive, and the timestamp in the file name keeps backups from overwriting each other. From the root of the project, in a terminal on your host machine, run it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;sh backup/backup.sh
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;On a small dataset, this finishes quickly and ends with the name of the file it wrote:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Wrote backup/backup-20261103-075154.archive.gz
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Our archive is about 73 MB. Having a file isn't the same as having a backup, though, because you don't know a backup works until you've restored it. Create &lt;strong&gt;backup/verify.sh&lt;/strong&gt;, which restores an archive into a throwaway MongoDB container and compares document counts against the live replica set:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="c"&gt;#!/bin/sh&lt;/span&gt;
&lt;span class="nb"&gt;set&lt;/span&gt; &lt;span class="nt"&gt;-eu&lt;/span&gt;

&lt;span class="nb"&gt;cd&lt;/span&gt; &lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="si"&gt;$(&lt;/span&gt;&lt;span class="nb"&gt;dirname&lt;/span&gt; &lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="nv"&gt;$0&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="si"&gt;)&lt;/span&gt;&lt;span class="s2"&gt;/.."&lt;/span&gt;

&lt;span class="nv"&gt;ARCHIVE&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="si"&gt;$(&lt;/span&gt;&lt;span class="nb"&gt;basename&lt;/span&gt; &lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="nv"&gt;$1&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="si"&gt;)&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;
&lt;span class="nv"&gt;SOURCE&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"mongodb://mongo1:27017,mongo2:27017,mongo3:27017/?replicaSet=rs0"&lt;/span&gt;
&lt;span class="nv"&gt;COUNT&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s1"&gt;'JSON.stringify({movies: db.getSiblingDB("sample_mflix").movies.countDocuments(), comments: db.getSiblingDB("sample_mflix").comments.countDocuments()})'&lt;/span&gt;

docker &lt;span class="nb"&gt;rm&lt;/span&gt; &lt;span class="nt"&gt;-f&lt;/span&gt; mongo9blog-scratch &lt;span class="o"&gt;&amp;gt;&lt;/span&gt;/dev/null 2&amp;gt;&amp;amp;1 &lt;span class="o"&gt;||&lt;/span&gt; &lt;span class="nb"&gt;true
&lt;/span&gt;docker run &lt;span class="nt"&gt;-d&lt;/span&gt; &lt;span class="nt"&gt;--name&lt;/span&gt; mongo9blog-scratch &lt;span class="nt"&gt;--network&lt;/span&gt; mongo9blog_default mongo:8.0 &lt;span class="o"&gt;&amp;gt;&lt;/span&gt;/dev/null

&lt;span class="k"&gt;until &lt;/span&gt;docker &lt;span class="nb"&gt;exec &lt;/span&gt;mongo9blog-scratch mongosh &lt;span class="nt"&gt;--quiet&lt;/span&gt; &lt;span class="nt"&gt;--eval&lt;/span&gt; &lt;span class="s1"&gt;'db.runCommand({ping: 1}).ok'&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt;/dev/null 2&amp;gt;&amp;amp;1&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="k"&gt;do
  &lt;/span&gt;&lt;span class="nb"&gt;sleep &lt;/span&gt;1
&lt;span class="k"&gt;done

&lt;/span&gt;docker run &lt;span class="nt"&gt;--rm&lt;/span&gt; &lt;span class="se"&gt;\&lt;/span&gt;
  &lt;span class="nt"&gt;--network&lt;/span&gt; mongo9blog_default &lt;span class="se"&gt;\&lt;/span&gt;
  &lt;span class="nt"&gt;-v&lt;/span&gt; &lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="nv"&gt;$PWD&lt;/span&gt;&lt;span class="s2"&gt;/backup:/backup:ro"&lt;/span&gt; &lt;span class="se"&gt;\&lt;/span&gt;
  mongo:8.0 &lt;span class="se"&gt;\&lt;/span&gt;
  mongorestore &lt;span class="se"&gt;\&lt;/span&gt;
    &lt;span class="nt"&gt;--uri&lt;/span&gt; &lt;span class="s2"&gt;"mongodb://mongo9blog-scratch:27017"&lt;/span&gt; &lt;span class="se"&gt;\&lt;/span&gt;
    &lt;span class="nt"&gt;--oplogReplay&lt;/span&gt; &lt;span class="se"&gt;\&lt;/span&gt;
    &lt;span class="nt"&gt;--gzip&lt;/span&gt; &lt;span class="se"&gt;\&lt;/span&gt;
    &lt;span class="nt"&gt;--archive&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"/backup/&lt;/span&gt;&lt;span class="nv"&gt;$ARCHIVE&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt; &lt;span class="se"&gt;\&lt;/span&gt;
    &lt;span class="nt"&gt;--quiet&lt;/span&gt;

&lt;span class="nv"&gt;LIVE&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="si"&gt;$(&lt;/span&gt;docker run &lt;span class="nt"&gt;--rm&lt;/span&gt; &lt;span class="nt"&gt;--network&lt;/span&gt; mongo9blog_default mongo:8.0 mongosh &lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="nv"&gt;$SOURCE&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt; &lt;span class="nt"&gt;--quiet&lt;/span&gt; &lt;span class="nt"&gt;--eval&lt;/span&gt; &lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="nv"&gt;$COUNT&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="si"&gt;)&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;
&lt;span class="nv"&gt;RESTORED&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="si"&gt;$(&lt;/span&gt;docker &lt;span class="nb"&gt;exec &lt;/span&gt;mongo9blog-scratch mongosh &lt;span class="nt"&gt;--quiet&lt;/span&gt; &lt;span class="nt"&gt;--eval&lt;/span&gt; &lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="nv"&gt;$COUNT&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="si"&gt;)&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;
docker &lt;span class="nb"&gt;rm&lt;/span&gt; &lt;span class="nt"&gt;-f&lt;/span&gt; mongo9blog-scratch &lt;span class="o"&gt;&amp;gt;&lt;/span&gt;/dev/null

&lt;span class="nb"&gt;echo&lt;/span&gt; &lt;span class="s2"&gt;"live:     &lt;/span&gt;&lt;span class="nv"&gt;$LIVE&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;
&lt;span class="nb"&gt;echo&lt;/span&gt; &lt;span class="s2"&gt;"restored: &lt;/span&gt;&lt;span class="nv"&gt;$RESTORED&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;

&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="o"&gt;[&lt;/span&gt; &lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="nv"&gt;$LIVE&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="nv"&gt;$RESTORED&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt; &lt;span class="o"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="k"&gt;then
  &lt;/span&gt;&lt;span class="nb"&gt;echo&lt;/span&gt; &lt;span class="s2"&gt;"Backup verified."&lt;/span&gt;
&lt;span class="k"&gt;else
  &lt;/span&gt;&lt;span class="nb"&gt;echo&lt;/span&gt; &lt;span class="s2"&gt;"Counts do not match."&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&amp;amp;2
  &lt;span class="nb"&gt;exit &lt;/span&gt;1
&lt;span class="k"&gt;fi&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That's a longer script, so it helps to look at the parts. The first part starts a scratch &lt;code&gt;mongod&lt;/code&gt; and waits until it answers a ping:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;docker &lt;span class="nb"&gt;rm&lt;/span&gt; &lt;span class="nt"&gt;-f&lt;/span&gt; mongo9blog-scratch &lt;span class="o"&gt;&amp;gt;&lt;/span&gt;/dev/null 2&amp;gt;&amp;amp;1 &lt;span class="o"&gt;||&lt;/span&gt; &lt;span class="nb"&gt;true
&lt;/span&gt;docker run &lt;span class="nt"&gt;-d&lt;/span&gt; &lt;span class="nt"&gt;--name&lt;/span&gt; mongo9blog-scratch &lt;span class="nt"&gt;--network&lt;/span&gt; mongo9blog_default mongo:8.0 &lt;span class="o"&gt;&amp;gt;&lt;/span&gt;/dev/null

&lt;span class="k"&gt;until &lt;/span&gt;docker &lt;span class="nb"&gt;exec &lt;/span&gt;mongo9blog-scratch mongosh &lt;span class="nt"&gt;--quiet&lt;/span&gt; &lt;span class="nt"&gt;--eval&lt;/span&gt; &lt;span class="s1"&gt;'db.runCommand({ping: 1}).ok'&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt;/dev/null 2&amp;gt;&amp;amp;1&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="k"&gt;do
  &lt;/span&gt;&lt;span class="nb"&gt;sleep &lt;/span&gt;1
&lt;span class="k"&gt;done&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The scratch container is completely separate from the replica set, so restoring into it can't affect your data. The second part restores the archive into it with &lt;code&gt;--oplogReplay&lt;/code&gt;, which applies the oplog entries that &lt;code&gt;--oplog&lt;/code&gt; captured:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;docker run &lt;span class="nt"&gt;--rm&lt;/span&gt; &lt;span class="se"&gt;\&lt;/span&gt;
  &lt;span class="nt"&gt;--network&lt;/span&gt; mongo9blog_default &lt;span class="se"&gt;\&lt;/span&gt;
  &lt;span class="nt"&gt;-v&lt;/span&gt; &lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="nv"&gt;$PWD&lt;/span&gt;&lt;span class="s2"&gt;/backup:/backup:ro"&lt;/span&gt; &lt;span class="se"&gt;\&lt;/span&gt;
  mongo:8.0 &lt;span class="se"&gt;\&lt;/span&gt;
  mongorestore &lt;span class="se"&gt;\&lt;/span&gt;
    &lt;span class="nt"&gt;--uri&lt;/span&gt; &lt;span class="s2"&gt;"mongodb://mongo9blog-scratch:27017"&lt;/span&gt; &lt;span class="se"&gt;\&lt;/span&gt;
    &lt;span class="nt"&gt;--oplogReplay&lt;/span&gt; &lt;span class="se"&gt;\&lt;/span&gt;
    &lt;span class="nt"&gt;--gzip&lt;/span&gt; &lt;span class="se"&gt;\&lt;/span&gt;
    &lt;span class="nt"&gt;--archive&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"/backup/&lt;/span&gt;&lt;span class="nv"&gt;$ARCHIVE&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt; &lt;span class="se"&gt;\&lt;/span&gt;
    &lt;span class="nt"&gt;--quiet&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The final part compares counts between the live replica set and the restored copy, and exits with an error if they differ. Run it against the backup you just took, using your own file name:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;sh backup/verify.sh backup/backup-20261103-075154.archive.gz
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If the backup is good, the counts match and the script says so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;live:     {"movies":21349,"comments":41079}
restored: {"movies":21349,"comments":41079}
Backup verified.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Comparing two document counts is a deliberately small check. In a real environment, you'd also restore into something that resembles production and run a representative query or two against the restored copy.&lt;/p&gt;

&lt;p&gt;Atlas handles backups differently. On a paid cluster, snapshots run automatically once backups are enabled. Before you upgrade, confirm that backups are enabled and that your most recent snapshot is recent. Then take an on-demand snapshot so you have a restore point from just before the change, which matters here because Atlas can't downgrade a major version. And just like on Docker, a snapshot you haven't restored is a snapshot you haven't tested, so restore one to a separate cluster and check the result.&lt;/p&gt;

&lt;p&gt;If your cluster doesn't include cloud backups, take the backup the same way we did here, by connecting to the cluster with &lt;code&gt;mongodump&lt;/code&gt; and using the connection string from Atlas.&lt;/p&gt;

&lt;h2&gt;
  
  
  Decide Whether to Go Ahead
&lt;/h2&gt;

&lt;p&gt;At this point, you have everything you need to make a decision, and it's worth making that decision deliberately instead of just continuing because the next step is on the page. Before moving forward, make sure the following are true:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The replica set is healthy, with no member in &lt;code&gt;ROLLBACK&lt;/code&gt; or &lt;code&gt;RECOVERING&lt;/code&gt; and no growing lag.
&lt;/li&gt;
&lt;li&gt;You have a backup, and you've restored it and checked the result.
&lt;/li&gt;
&lt;li&gt;You've read the compatibility changes and none of them break your application, or you have a plan for the ones that do.
&lt;/li&gt;
&lt;li&gt;Your drivers support 9.0.
&lt;/li&gt;
&lt;li&gt;You're on 8.0 or 8.3, and you can afford to run for a while with mixed versions in the replica set.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If any of those aren't true, stop here. Nothing has changed yet, and nothing needs to be undone. The remaining steps are the ones that touch your servers.&lt;/p&gt;

&lt;h2&gt;
  
  
  Upgrade the Secondaries First
&lt;/h2&gt;

&lt;p&gt;A rolling upgrade replaces one member at a time so the replica set stays available throughout. You upgrade the secondaries first, then step down the primary and upgrade it last. The application keeps working while this happens because the replica set always has a majority of members online.&lt;/p&gt;

&lt;p&gt;We'll start with &lt;code&gt;mongo2&lt;/code&gt;. Setting the image variable for just that member and bringing it up again replaces its container with one running MongoDB 9.0.4, while keeping its data volume:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nv"&gt;MONGO2_IMAGE&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;mongodb/mongodb-community-server:9.0.4-ubuntu2204 &lt;span class="se"&gt;\&lt;/span&gt;
  docker compose &lt;span class="nt"&gt;-f&lt;/span&gt; docker/compose.yml up &lt;span class="nt"&gt;-d&lt;/span&gt; mongo2
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Compose recreates only &lt;code&gt;mongo2&lt;/code&gt;. The member shuts down, starts again with the 9.0 binaries against the same data files, and rejoins the replica set. It takes a few seconds to start, so if you see a connection error, wait a moment and try again. Start by asking &lt;code&gt;mongo2&lt;/code&gt; itself which version it's running:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;docker compose &lt;span class="nt"&gt;-f&lt;/span&gt; docker/compose.yml &lt;span class="nb"&gt;exec &lt;/span&gt;mongo2 mongosh &lt;span class="nt"&gt;--quiet&lt;/span&gt; &lt;span class="nt"&gt;--eval&lt;/span&gt; &lt;span class="s1"&gt;'db.version()'&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once it answers, you should see the new version:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;9.0.4
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Another member's view of the replica set can briefly show a stale state right after a restart, so don't rely on it alone. Once &lt;code&gt;mongo2&lt;/code&gt; answers, ask the primary for each member's state and how far behind it is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;docker compose &lt;span class="nt"&gt;-f&lt;/span&gt; docker/compose.yml &lt;span class="nb"&gt;exec &lt;/span&gt;mongo1 mongosh &lt;span class="nt"&gt;--quiet&lt;/span&gt; &lt;span class="nt"&gt;--eval&lt;/span&gt; &lt;span class="s1"&gt;'
  const status = rs.status();
  const primary = status.members.find((m) =&amp;gt; m.stateStr === "PRIMARY");
  status.members.map((m) =&amp;gt; m.name + " " + m.stateStr + " lag: " + (primary.optimeDate - m.optimeDate) / 1000 + "s").join("\n")
'&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Wait until &lt;code&gt;mongo2&lt;/code&gt; is a &lt;code&gt;SECONDARY&lt;/code&gt; with no lag:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mongo1:27017 PRIMARY lag: 0s
mongo2:27017 SECONDARY lag: 0s
mongo3:27017 SECONDARY lag: 0s
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The replica set is now running mixed versions. The primary and &lt;code&gt;mongo3&lt;/code&gt; are on 8.0.34, and &lt;code&gt;mongo2&lt;/code&gt; is on 9.0.4, which is normal and expected during a rolling upgrade. The feature compatibility version is still 8.0 on all members, so the data is still readable by 8.0.&lt;/p&gt;

&lt;p&gt;Upgrade &lt;code&gt;mongo3&lt;/code&gt; the same way. Each &lt;code&gt;docker compose&lt;/code&gt; command only knows the variables you pass it, so keep passing the one for &lt;code&gt;mongo2&lt;/code&gt;. We name only &lt;code&gt;mongo3&lt;/code&gt; here, so &lt;code&gt;mongo2&lt;/code&gt; isn't touched either way, but the habit protects you if you ever run &lt;code&gt;up -d&lt;/code&gt; without a service name, which would put &lt;code&gt;mongo2&lt;/code&gt; back on the 8.0 image:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nv"&gt;MONGO2_IMAGE&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;mongodb/mongodb-community-server:9.0.4-ubuntu2204 &lt;span class="se"&gt;\&lt;/span&gt;
&lt;span class="nv"&gt;MONGO3_IMAGE&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;mongodb/mongodb-community-server:9.0.4-ubuntu2204 &lt;span class="se"&gt;\&lt;/span&gt;
  docker compose &lt;span class="nt"&gt;-f&lt;/span&gt; docker/compose.yml up &lt;span class="nt"&gt;-d&lt;/span&gt; mongo3
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once &lt;code&gt;mongo3&lt;/code&gt; reports &lt;code&gt;SECONDARY&lt;/code&gt; again, run the application to confirm that it still works while the primary is the only member left on 8.0:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;sh scripts/run-app.sh baseline
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The output still shows &lt;code&gt;version: 8.0.34&lt;/code&gt; because the driver is talking to the primary, and the read and write both succeed:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;version: 8.0.34
fcv: 8.0
movies: 21349
find-one: {
  _id: new ObjectId('573a139bf29313caabcf3d23'),
  year: 1999,
  title: 'The Matrix'
}
update-one: { matched: 1, modified: 1 }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The application never noticed that two of the three members changed underneath it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step Down the Primary and Upgrade It
&lt;/h2&gt;

&lt;p&gt;The primary is the last member to upgrade. You can't just restart it without causing a brief interruption, so first ask it to step down, which triggers an election and lets one of the 9.0 secondaries take over. Run the following against &lt;code&gt;mongo1&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;docker compose &lt;span class="nt"&gt;-f&lt;/span&gt; docker/compose.yml &lt;span class="nb"&gt;exec &lt;/span&gt;mongo1 mongosh &lt;span class="nt"&gt;--quiet&lt;/span&gt; &lt;span class="nt"&gt;--eval&lt;/span&gt; &lt;span class="s1"&gt;'rs.stepDown(60)'&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;60&lt;/code&gt; tells the old primary not to seek re-election for 60 seconds. The connection from &lt;code&gt;mongosh&lt;/code&gt; may drop as the node changes roles, which is normal. Check who the primary is now:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;docker compose &lt;span class="nt"&gt;-f&lt;/span&gt; docker/compose.yml &lt;span class="nb"&gt;exec &lt;/span&gt;mongo2 mongosh &lt;span class="nt"&gt;--quiet&lt;/span&gt; &lt;span class="nt"&gt;--eval&lt;/span&gt; &lt;span class="s1"&gt;'
  rs.status().members.map((m) =&amp;gt; m.name + " " + m.stateStr).join(" | ")
'&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;One of the 9.0 members has taken over as primary:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mongo1:27017 SECONDARY | mongo2:27017 PRIMARY | mongo3:27017 SECONDARY
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now &lt;code&gt;mongo1&lt;/code&gt; is a secondary, and it's safe to upgrade it with the same approach as the others. This time all three variables are set:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nv"&gt;MONGO1_IMAGE&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;mongodb/mongodb-community-server:9.0.4-ubuntu2204 &lt;span class="se"&gt;\&lt;/span&gt;
&lt;span class="nv"&gt;MONGO2_IMAGE&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;mongodb/mongodb-community-server:9.0.4-ubuntu2204 &lt;span class="se"&gt;\&lt;/span&gt;
&lt;span class="nv"&gt;MONGO3_IMAGE&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;mongodb/mongodb-community-server:9.0.4-ubuntu2204 &lt;span class="se"&gt;\&lt;/span&gt;
  docker compose &lt;span class="nt"&gt;-f&lt;/span&gt; docker/compose.yml up &lt;span class="nt"&gt;-d&lt;/span&gt; mongo1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once &lt;code&gt;mongo1&lt;/code&gt; rejoins, confirm that every member is running 9.0.4:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="k"&gt;for &lt;/span&gt;m &lt;span class="k"&gt;in &lt;/span&gt;mongo1 mongo2 mongo3&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="k"&gt;do
  &lt;/span&gt;&lt;span class="nb"&gt;echo&lt;/span&gt; &lt;span class="nt"&gt;-n&lt;/span&gt; &lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="nv"&gt;$m&lt;/span&gt;&lt;span class="s2"&gt;: "&lt;/span&gt;
  docker compose &lt;span class="nt"&gt;-f&lt;/span&gt; docker/compose.yml &lt;span class="nb"&gt;exec&lt;/span&gt; &lt;span class="nv"&gt;$m&lt;/span&gt; mongosh &lt;span class="nt"&gt;--quiet&lt;/span&gt; &lt;span class="nt"&gt;--eval&lt;/span&gt; &lt;span class="s1"&gt;'db.version()'&lt;/span&gt;
&lt;span class="k"&gt;done&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The loop asks each member for its version:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mongo1: 9.0.4
mongo2: 9.0.4
mongo3: 9.0.4
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Every binary is now 9.0.4. Because &lt;code&gt;mongo1&lt;/code&gt; has the highest priority, it will likely have called an election and become primary again once it caught up. That detail matters in the next step.&lt;/p&gt;

&lt;h2&gt;
  
  
  Burn In Before You Raise the Feature Compatibility Version
&lt;/h2&gt;

&lt;p&gt;The replica set is on 9.0 binaries, but the feature compatibility version (FCV) is still 8.0. This is the window where you let the new version prove itself. In this state, the data files are still compatible with 8.0, so rolling back is as simple as reversing the steps you just took.&lt;/p&gt;

&lt;p&gt;Run the application again:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;sh scripts/run-app.sh baseline
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The output shows the new binary version with the old FCV:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;version: 9.0.4
fcv: 8.0
movies: 21349
find-one: {
  _id: new ObjectId('573a139bf29313caabcf3d23'),
  year: 1999,
  title: 'The Matrix'
}
update-one: { matched: 1, modified: 1 }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In a tutorial, this takes seconds. In production, the burn-in period is days or weeks, depending on how comfortable you are with your own monitoring and how much traffic you can observe. Use it to watch error rates, latency, and the application behaviors listed earlier, and don't skip it, because the next step is the one that makes rollback harder.&lt;/p&gt;

&lt;h2&gt;
  
  
  Raise the Feature Compatibility Version
&lt;/h2&gt;

&lt;p&gt;Raising the FCV to 9.0 enables 9.0 features and makes the replica set commit to the 9.0 data format. The documentation notes that it must run on the primary, and that it shouldn't run while an initial sync is in progress. The command is idempotent, so retrying it is safe if it doesn't complete.&lt;/p&gt;

&lt;p&gt;Because the primary can change, find it first instead of assuming:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="k"&gt;for &lt;/span&gt;m &lt;span class="k"&gt;in &lt;/span&gt;mongo1 mongo2 mongo3&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="k"&gt;do
  &lt;/span&gt;docker compose &lt;span class="nt"&gt;-f&lt;/span&gt; docker/compose.yml &lt;span class="nb"&gt;exec&lt;/span&gt; &lt;span class="nv"&gt;$m&lt;/span&gt; mongosh &lt;span class="nt"&gt;--quiet&lt;/span&gt; &lt;span class="nt"&gt;--eval&lt;/span&gt; &lt;span class="s1"&gt;'
    if (db.hello().isWritablePrimary) print("primary: '&lt;/span&gt;&lt;span class="nv"&gt;$m&lt;/span&gt;&lt;span class="s1"&gt;'")
  '&lt;/span&gt;
&lt;span class="k"&gt;done&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The loop prints a line for whichever member is primary:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;primary: mongo1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Right after the upgrade, &lt;code&gt;mongo1&lt;/code&gt; can take 10 to 20 seconds to win the election and become primary again, so if the loop printed a different member, wait a few seconds and run it again. Now run the command on whichever member is primary. The example below uses &lt;code&gt;mongo1&lt;/code&gt;, so substitute the name the loop printed if it's different. If you run it on a secondary, you'll get a &lt;code&gt;not primary&lt;/code&gt; error:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;docker compose &lt;span class="nt"&gt;-f&lt;/span&gt; docker/compose.yml &lt;span class="nb"&gt;exec &lt;/span&gt;mongo1 mongosh &lt;span class="nt"&gt;--quiet&lt;/span&gt; &lt;span class="nt"&gt;--eval&lt;/span&gt; &lt;span class="s1"&gt;'
  db.adminCommand({ setFeatureCompatibilityVersion: "9.0", confirm: true })
'&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The command waits until a majority of members have the new configuration, and then returns &lt;code&gt;ok: 1&lt;/code&gt;. Verify the result on every member:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="k"&gt;for &lt;/span&gt;m &lt;span class="k"&gt;in &lt;/span&gt;mongo1 mongo2 mongo3&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="k"&gt;do
  &lt;/span&gt;&lt;span class="nb"&gt;echo&lt;/span&gt; &lt;span class="nt"&gt;-n&lt;/span&gt; &lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="nv"&gt;$m&lt;/span&gt;&lt;span class="s2"&gt; fcv: "&lt;/span&gt;
  docker compose &lt;span class="nt"&gt;-f&lt;/span&gt; docker/compose.yml &lt;span class="nb"&gt;exec&lt;/span&gt; &lt;span class="nv"&gt;$m&lt;/span&gt; mongosh &lt;span class="nt"&gt;--quiet&lt;/span&gt; &lt;span class="nt"&gt;--eval&lt;/span&gt; &lt;span class="s1"&gt;'
    db.adminCommand({ getParameter: 1, featureCompatibilityVersion: 1 }).featureCompatibilityVersion.version
  '&lt;/span&gt;
&lt;span class="k"&gt;done&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Each member reports the new version:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mongo1 fcv: 9.0
mongo2 fcv: 9.0
mongo3 fcv: 9.0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The upgrade is complete. This is also the point where a downgrade is no longer a simple binary swap, which we'll cover shortly.&lt;/p&gt;

&lt;h2&gt;
  
  
  See the Behavior Change After the Upgrade
&lt;/h2&gt;

&lt;p&gt;Now that the replica set is on 9.0, we can run the time zone check from earlier a second time against the upgraded replica set:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;sh scripts/run-app.sh utc-demo
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;On MongoDB 9.0.4, the output is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;getHours() equals the New York hour: 0 of 41079
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Before the upgrade, the same query against the same data returned &lt;code&gt;41079 of 41079&lt;/code&gt;. Every row agreed, and now none of them do.&lt;/p&gt;

&lt;p&gt;Nothing failed, and nothing logged a warning. The query returned a different answer, which is exactly why this kind of change deserves a search through your code for &lt;code&gt;$function&lt;/code&gt;, &lt;code&gt;$accumulator&lt;/code&gt;, &lt;code&gt;$where&lt;/code&gt;, and &lt;code&gt;mapReduce&lt;/code&gt; before you upgrade.&lt;/p&gt;

&lt;p&gt;If you do find a case that depends on the host time zone, the fix is to be explicit about the time zone. An aggregation operator such as &lt;code&gt;$hour&lt;/code&gt; accepts a &lt;code&gt;timezone&lt;/code&gt; option and behaves the same on every version:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nl"&gt;$hour&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;date&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;$date&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;timezone&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;America/New_York&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That's the same &lt;code&gt;$hour&lt;/code&gt; expression we used as the comparison value, and it's the reliable half of the query.&lt;/p&gt;

&lt;h2&gt;
  
  
  Measure Your Own Workload with \$queryStats
&lt;/h2&gt;

&lt;p&gt;The numbers we've published for 9.0 are "up to" figures measured against 8.0, and the announcement ties part of the gains to Atlas Gen2 compute. Results like these depend on the hardware, the workload, and the shape of your data, so treat them as a reason to test, not as a prediction.&lt;/p&gt;

&lt;p&gt;Running a fair test on your own workload means using the same data and indexes on both versions, warming up first, running several times, and using realistic concurrency. It also means measuring reads and writes separately and recording the hardware you used. A laptop running a three-member replica set in Docker containers can't tell you anything about a production cluster, so we won't publish numbers from this one.&lt;/p&gt;

&lt;p&gt;What 9.0 does give you is better visibility out of the box. &lt;code&gt;$queryStats&lt;/code&gt; is on by default, samples 1% of operations, and now covers writes. For a short test, you can sample everything. Create &lt;strong&gt;scripts/queryStats.js&lt;/strong&gt; with the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;admin&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;db&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getSiblingDB&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;admin&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="nx"&gt;admin&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;runCommand&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;
  &lt;span class="na"&gt;setParameter&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="na"&gt;internalQueryStatsSampleRate&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="na"&gt;internalQueryStatsWriteCmdSampleRate&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;stats&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;admin&lt;/span&gt;
  &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;aggregate&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;$queryStats&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{}&lt;/span&gt; &lt;span class="p"&gt;},&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;$match&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;key.queryShape.cmdNs.db&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;sample_mflix&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="p"&gt;},&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
      &lt;span class="na"&gt;$project&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="na"&gt;_id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="na"&gt;command&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;$key.queryShape.command&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="na"&gt;collection&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;$key.queryShape.cmdNs.coll&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="na"&gt;execCount&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;$metrics.execCount&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="na"&gt;totalExecMicros&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;$metrics.totalExecMicros.sum&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
      &lt;span class="p"&gt;},&lt;/span&gt;
    &lt;span class="p"&gt;},&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;$sort&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;execCount&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="p"&gt;},&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;$limit&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt; &lt;span class="p"&gt;},&lt;/span&gt;
  &lt;span class="p"&gt;])&lt;/span&gt;
  &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;toArray&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

&lt;span class="nf"&gt;printjson&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;stats&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The script first turns sampling up to 100% for reads and for writes. It then reads &lt;code&gt;$queryStats&lt;/code&gt;, keeps only operations against &lt;code&gt;sample_mflix&lt;/code&gt;, and reports the command type, the collection, how many times it ran, and the total execution time in microseconds. Sampling is configured and reported per node, so run it against the primary. The commands below use &lt;code&gt;mongo1&lt;/code&gt;, which is the primary at this point in the tutorial, so substitute a different name if your primary changed. Run it once to turn sampling on, run the workload, and then run it again to read the stats:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;docker compose &lt;span class="nt"&gt;-f&lt;/span&gt; docker/compose.yml &lt;span class="nb"&gt;exec&lt;/span&gt; &lt;span class="nt"&gt;-T&lt;/span&gt; mongo1 mongosh &lt;span class="nt"&gt;--quiet&lt;/span&gt; &lt;span class="nt"&gt;--eval&lt;/span&gt; &lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="si"&gt;$(&lt;/span&gt;&lt;span class="nb"&gt;cat &lt;/span&gt;scripts/queryStats.js&lt;span class="si"&gt;)&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;
sh scripts/run-app.sh baseline
docker compose &lt;span class="nt"&gt;-f&lt;/span&gt; docker/compose.yml &lt;span class="nb"&gt;exec&lt;/span&gt; &lt;span class="nt"&gt;-T&lt;/span&gt; mongo1 mongosh &lt;span class="nt"&gt;--quiet&lt;/span&gt; &lt;span class="nt"&gt;--eval&lt;/span&gt; &lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="si"&gt;$(&lt;/span&gt;&lt;span class="nb"&gt;cat &lt;/span&gt;scripts/queryStats.js&lt;span class="si"&gt;)&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The first command turns sampling on, the second generates a workload, and the third prints what was recorded. The final result lists each kind of operation that ran:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[
  { command: 'update', collection: 'movies', execCount: Long('1'), totalExecMicros: Long('1666') },
  { command: 'aggregate', collection: 'movies', execCount: Long('1'), totalExecMicros: Long('4047') },
  { command: 'find', collection: 'movies', execCount: Long('1'), totalExecMicros: Long('1467') }
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;update&lt;/code&gt; entry is there because starting in 9.0, &lt;code&gt;$queryStats&lt;/code&gt; collects statistics for &lt;code&gt;update&lt;/code&gt;, &lt;code&gt;insert&lt;/code&gt;, and &lt;code&gt;delete&lt;/code&gt; commands.&lt;/p&gt;

&lt;p&gt;With realistic traffic, this gives you the number of times each query shape ran and how long it took in total, which is exactly the data you need to compare a workload before and after an upgrade.&lt;/p&gt;

&lt;h2&gt;
  
  
  If You Need to Roll Back
&lt;/h2&gt;

&lt;p&gt;How hard a rollback is depends on how far along you are, so it helps to think about it in terms of the steps we took.&lt;/p&gt;

&lt;p&gt;Before you raise the feature compatibility version, the data files are still compatible with 8.0. Rolling back means reversing the rolling upgrade, replacing one member at a time with the 8.0 image, stepping down the primary before you replace it. It's the same procedure you followed to upgrade, run in the other direction, with the 8.0 image in place of the 9.0 one. Check that each member is back to &lt;code&gt;SECONDARY&lt;/code&gt; and caught up before you move to the next, just like you did on the way up.&lt;/p&gt;

&lt;p&gt;After you raise the feature compatibility version, a downgrade is still supported to the immediately previous major version, but it takes more work. The documentation says you have to remove any persisted features that 9.0 introduced before you downgrade. One example is a view that uses &lt;code&gt;$convert&lt;/code&gt; to convert an object to &lt;code&gt;binData&lt;/code&gt;, which returns errors after a downgrade. The full procedure is on the &lt;a href="https://www.mongodb.com/docs/manual/release-notes/9.0-downgrade-to-8.0/?utm_campaign=devrel&amp;amp;utm_source=third-party-content&amp;amp;utm_medium=cta&amp;amp;utm_content=mongodb-9-upgrade&amp;amp;utm_term=nicolas.raboy" rel="noopener noreferrer"&gt;Downgrade 9.0 to 8.0&lt;/a&gt; page, which also says to downgrade to the latest patch release of 8.0. This tutorial doesn't walk through that procedure.&lt;/p&gt;

&lt;p&gt;That's the reason the backup came first and the burn-in period comes before the feature compatibility version. If you're unsure, wait. The backup is your real safety net, and a longer burn-in is cheap.&lt;/p&gt;

&lt;h2&gt;
  
  
  Upgrading on MongoDB Atlas
&lt;/h2&gt;

&lt;p&gt;If you run on MongoDB Atlas, most of what we did by hand is managed for you. MongoDB 9.0 is rolling out incrementally to clusters that use the "Latest Version With Auto Upgrades" option. Atlas performs the rolling upgrade for you, one member at a time, so there's no binary swap or feature compatibility version step for you to run. What it doesn't do is let you go back, because an Atlas cluster can't be downgraded from one major version to the previous one. That makes the backup and compatibility checks from this tutorial matter just as much on Atlas as they do anywhere else.&lt;/p&gt;

&lt;h2&gt;
  
  
  Before You Do This in Production
&lt;/h2&gt;

&lt;p&gt;What we built is good for rehearsing the process, but a production upgrade needs more care. Our deployment has no authentication or TLS, our dataset is tiny, and a three-member replica set of Docker containers on one machine behaves very differently from a loaded production cluster. A real dataset also takes much longer to back up and verify, so plan for that, and for the extra load that a dump puts on a member.&lt;/p&gt;

&lt;p&gt;Run the procedure on a staging environment that resembles production first, with your real application and a copy of real data, and write down what you observe. Plan the upgrade for a quiet window, and make sure your monitoring is in place before you start. And if you run sharded clusters, read the release notes carefully, because the known issues for sharded deployments are different from the ones that apply here.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;You just saw how to upgrade a replica set from MongoDB 8.0 to 9.0 in a way that resembles the real thing. We checked the health of the deployment, took a backup and proved that it restores, decided whether to go ahead, upgraded the secondaries and then the primary, burned in on the new binaries, and finally raised the feature compatibility version. We also looked at a behavior change that doesn't produce an error, and at &lt;code&gt;$queryStats&lt;/code&gt; as a way to measure your own workload.&lt;/p&gt;

&lt;p&gt;To take this further, try the other behavior changes, such as the per-operation memory limit or change streams after an election, against the same replica set. You could also load a larger dataset and use &lt;code&gt;$queryStats&lt;/code&gt; to compare a real workload between versions.  &lt;/p&gt;

</description>
      <category>docker</category>
      <category>mongodb</category>
      <category>javascript</category>
      <category>devops</category>
    </item>
    <item>
      <title>How to Deploy Your First Agent to MongoDB Atlas Agent Engine</title>
      <dc:creator>MongoDB Guests</dc:creator>
      <pubDate>Tue, 03 Nov 2026 12:00:00 +0000</pubDate>
      <link>https://dev.to/mongodb/how-to-deploy-your-first-agent-to-mongodb-atlas-agent-engine-1j0n</link>
      <guid>https://dev.to/mongodb/how-to-deploy-your-first-agent-to-mongodb-atlas-agent-engine-1j0n</guid>
      <description>&lt;p&gt;&lt;em&gt;This article was written by &lt;a href="https://www.linkedin.com/in/damilola-oladele-85310275/" rel="noopener noreferrer"&gt;Damilola Oladele&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Imagine you built an employee onboarding assistant agent for your company. The agent answers questions about company policies, guides new employees through onboarding, and provides role-specific training.&lt;/p&gt;

&lt;p&gt;As employees begin using the agent, you encounter a few challenges. The agent cannot remember previous conversations, so employees must repeat information they have already provided. It also struggles to retrieve accurate answers from company documents and sometimes recommends training that employees have already completed. You might also want to monitor its behavior and ensure it only accesses information that each employee is authorized to see.&lt;/p&gt;

&lt;p&gt;A common approach to addressing these challenges is to combine several systems. You might use a vector database to retrieve company documents and a separate database to store conversation history. An agent framework would coordinate workflows, while an observability platform would monitor agent execution. You would also need infrastructure to run the agent and enforce security policies. While this approach works, integrating and maintaining these systems introduces additional complexity.&lt;/p&gt;

&lt;p&gt;So instead of building and managing these systems separately, you can use &lt;strong&gt;MongoDB Atlas Agent Engine (Agent Engine)&lt;/strong&gt;. It provides a unified platform that runs AI agents, stores conversation history, manages long-term memory, retrieves relevant information, and monitors agent execution.&lt;/p&gt;

&lt;p&gt;This tutorial helps you get started with Agent Engine. You'll install the &lt;code&gt;agentengine&lt;/code&gt; CLI, scaffold a Hello World agent, test it locally, and deploy it to Agent Engine.&lt;/p&gt;

&lt;p&gt;The following flowchart outlines the local setup and deployment stages:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fqh9nuzmeri4is707lwjm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fqh9nuzmeri4is707lwjm.png" alt=" " width="800" height="523"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The tutorial uses OpenRouter's free tier and a free Atlas M0 cluster, so you don't need a credit card.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; Agent Engine is in public preview. MongoDB intends it for evaluation and prototyping, and doesn't recommend production deployments during preview. MongoDB expects breaking changes periodically. When your terminal output differs from this tutorial, trust your terminal.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  Prerequisites
&lt;/h2&gt;

&lt;p&gt;Before you start, make sure you have the following ready:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Operating system:&lt;/strong&gt; macOS or Linux.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Git:&lt;/strong&gt; Git installed on your machine&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Docker Desktop:&lt;/strong&gt; Docker Desktop installed and running on your machine.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Python:&lt;/strong&gt; Version 3.1 or later installed on your machine.&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Atlas cluster:&lt;/strong&gt; A MongoDB Atlas account with a free M0 cluster.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; Agent Engine doesn't support Atlas free clusters. This tutorial turns off the memory feature and stores only a few short sessions, so it can run on an M0 cluster. For an agent that uses the memory feature, use a Flex cluster or higher. To learn more, see &lt;a href="https://www.mongodb.com/docs/agentengine/deploy/atlas-setup/?utm_campaign=devrel&amp;amp;utm_source=third-party-content&amp;amp;utm_medium=cta&amp;amp;utm_content=buildrel-first-agent-mdb-agent-eng-devto&amp;amp;utm_term=hugh.murray" rel="noopener noreferrer"&gt;Set Up Atlas Resources&lt;/a&gt; and &lt;a href="https://www.mongodb.com/docs/atlas/reference/free-shared-limitations/?utm_campaign=devrel&amp;amp;utm_source=third-party-content&amp;amp;utm_medium=cta&amp;amp;utm_content=buildrel-first-agent-mdb-agent-eng-devto&amp;amp;utm_term=hugh.murray" rel="noopener noreferrer"&gt;Atlas Free Cluster Limits&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Connection string:&lt;/strong&gt; The connection string for your Atlas cluster. In Atlas, click &lt;strong&gt;Connect&lt;/strong&gt; on your cluster, then select &lt;strong&gt;Drivers&lt;/strong&gt;. Atlas prompts you to create a database user if you don't have one.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Voyage AI API key:&lt;/strong&gt; An API key created in the same Atlas project as your cluster. To create one, follow these steps:&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;1. Sign in to your Atlas account, the same one as your M0 cluster.
2. Go to **SERVICES &amp;gt; AI Model APIs**.
3. Select **Create model API key**.
4. Give it a name, then select **Create**.
5. Copy the key immediately and store it somewhere safe.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;OpenRouter account:&lt;/strong&gt; A free OpenRouter account with an API key.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Install the agentengine CLI
&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;agentengine&lt;/code&gt; CLI creates, runs, and deploys your agent, so it's the first tool to set up. Download it from the &lt;a href="https://agentengine.mongodb.com/download-cli" rel="noopener noreferrer"&gt;CLI download page&lt;/a&gt;, and follow the instructions for your operating system. The page requires an Atlas sign-in. You can also open it from the Atlas UI, under &lt;strong&gt;SERVICES &amp;gt; Agent Engine &amp;gt; Open Agent Engine&lt;/strong&gt;, then &lt;strong&gt;Authorize&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;When I first tried installing the CLI, the installation failed with a network error. If you encounter the same issue, try running the installer again or switching to the manual download tab on the same page.&lt;/p&gt;

&lt;p&gt;Confirm the installation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;agentengine &lt;span class="nt"&gt;--version&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If the installation succeeds, the command displays the installed version, such as &lt;code&gt;0.1.120&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Sign In to Atlas Agent Engine
&lt;/h2&gt;

&lt;p&gt;Now sign in with your Atlas login information to allow the CLI to access your Atlas account:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;agentengine auth login
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A sign-in URL opens in your browser. After you sign in, the terminal confirms it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Open the following URL to authenticate:
https://agentengine.mongodb.com/auth/start?...
Successfully logged in.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Set Up Docker for Local Development
&lt;/h2&gt;

&lt;p&gt;After signing in to Agent Engine, set up Docker to run the agent locally in containers. Before you begin local development, check that Docker meets these three requirements:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Docker Desktop is installed on your machine.&lt;/li&gt;
&lt;li&gt;The Docker daemon is running. Launching Docker Desktop starts it.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;docker&lt;/code&gt; command works in your terminal.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Launch Docker Desktop, then check all three conditions at once:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;docker info
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If the command displays both client and server details, then Docker is ready. If your shell can't find &lt;code&gt;docker&lt;/code&gt;, then the command isn't on your &lt;code&gt;PATH&lt;/code&gt;. So add the directory containing the Docker CLI to your &lt;code&gt;PATH&lt;/code&gt;, then try again. If the command runs but can't connect to the server, then make sure Docker Desktop has finished starting.&lt;/p&gt;

&lt;h2&gt;
  
  
  Get a Free OpenRouter API Key
&lt;/h2&gt;

&lt;p&gt;Your agent needs a language model to generate responses. The next step is to obtain an LLM API key. OpenRouter provides one API for many models, including free ones, and you don't need a credit card to use it.&lt;/p&gt;

&lt;p&gt;Go to &lt;a href="https://openrouter.ai" rel="noopener noreferrer"&gt;OpenRouter&lt;/a&gt;, create an account, and open your account settings. Create a new API key, copy it, and save it. You'll paste it when prompted in the next section.&lt;/p&gt;

&lt;p&gt;OpenRouter's free models have the following rate limits:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;20 requests per minute.&lt;/li&gt;
&lt;li&gt;50 requests per day for accounts that have never purchased credits, or 1,000 requests per day for accounts that have purchased at least $10 in credits.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;One message to your agent can trigger multiple model requests. This is because the agent calls the model, runs its tools, and calls the model again to generate a response. A 50-request daily allowance is enough for this tutorial.&lt;/p&gt;

&lt;p&gt;The Hello World agent calls tools to process your request, so its model must support tool calling. I chose &lt;code&gt;nvidia/nemotron-3.5-lightning:free&lt;/code&gt; because it supports tool calling and is available on OpenRouter's free tier. To list every free model that supports tool calling, query OpenRouter's public models endpoint by running the following in your terminal:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;curl &lt;span class="nt"&gt;-sS&lt;/span&gt; https://openrouter.ai/api/v1/models | python3 &lt;span class="nt"&gt;-c&lt;/span&gt; &lt;span class="s2"&gt;"
import json, sys
for m in json.load(sys.stdin)['data']:
    if m['id'].endswith(':free') and 'tools' in (m.get('supported_parameters') or []):
        print(m['id'])
"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Any model in that list can run this agent.&lt;/p&gt;

&lt;h2&gt;
  
  
  Scaffold a Hello World Agent
&lt;/h2&gt;

&lt;p&gt;With the tools ready, generate the agent and confirm it can reach its model before you start any containers.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;agentengine create&lt;/code&gt; command builds the project directory from MongoDB's Hello World template. Typing &lt;code&gt;back&lt;/code&gt; at any prompt returns you to the previous one:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;agentengine create
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Answer the prompts as follows:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Prompt&lt;/th&gt;
&lt;th&gt;Answer&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Starter template&lt;/td&gt;
&lt;td&gt;Hello World Agent&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Framework and language&lt;/td&gt;
&lt;td&gt;Google ADK + Python&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Application name&lt;/td&gt;
&lt;td&gt;&lt;code&gt;my-agent&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Local directory&lt;/td&gt;
&lt;td&gt;accept the default&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;LLM connection&lt;/td&gt;
&lt;td&gt;OpenRouter&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Model or deployment name&lt;/td&gt;
&lt;td&gt;&lt;code&gt;nvidia/nemotron-3.5-lightning:free&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;LLM API key&lt;/td&gt;
&lt;td&gt;your OpenRouter key&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Enable memory for local dev&lt;/td&gt;
&lt;td&gt;no&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;External host access&lt;/td&gt;
&lt;td&gt;accept the recommended egress option&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Smoke test&lt;/td&gt;
&lt;td&gt;yes&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;After the prompts, the CLI reports what it generated and runs the smoke test:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;✓ Created my-agent from the Hello World Agent (Google ADK) template
✓ Personalized app name, slug, module, and local defaults
✓ Applied the selected LLM connection to the agent source
✓ Wrote .env
✓ Declared network.egress for openrouter.ai:443 (Agent and Tool)
  This list covers the LLM only. Add other destinations in agent.yaml under network.egress, or later with `agentengine agent egress add &amp;lt;fqdn&amp;gt;:443`.
✓ Installed the Atlas Agent Engine skill for Codex, Copilot, and Claude Code
✓ Installed the Atlas Agent Engine docs skill. Ask your coding agent platform questions to retrieve current docs.
Smoke test now? (one 'Hello' request from this machine, 10s timeout) [Y/n] y
✓ openrouter/nvidia/nemotron-3.5-lightning:free responded in 4.4s

Next:
1. cd my-agent/agents/my-agent
2. agentengine dev up
3. When you're ready to deploy: agentengine deploy
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The final line, &lt;code&gt;✓ openrouter/nvidia/nemotron-3.5-lightning:free responded in 4.4s&lt;/code&gt;, confirms that the generated agent reached OpenRouter and received a response. That rules out key and network problems before Docker is involved.&lt;/p&gt;

&lt;p&gt;During my earlier setup attempt, the smoke test prompt returned an &lt;code&gt;HTTP 401 (Unauthorized)&lt;/code&gt; error, even though my OpenRouter API key was valid. If you encounter the same error, don't assume that project creation failed. Continue with the instructions in the Run the Agent Locally section.&lt;/p&gt;

&lt;h2&gt;
  
  
  Explore the Hello World Agent
&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;agentengine create&lt;/code&gt; command creates a &lt;code&gt;my-agent&lt;/code&gt; project directory containing an &lt;code&gt;agents/&lt;/code&gt; directory, with your agent in a subdirectory. Your project structure looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;my-agent/
├── project-config.yaml
└── agents/
    └── my-agent/
        ├── agent.yaml
        ├── pyproject.toml
        ├── .env
        └── src/
            └── agent_my_agent/
                ├── main.py
                ├── llm.py
                ├── system_message.py
                └── tools.py
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;agent.yaml&lt;/code&gt; file tells Agent Engine what your agent is called, which tools it has, and where it can connect:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;&lt;span class="c1"&gt;# Human-readable app slug used by Agent Engine tooling.&lt;/span&gt;
&lt;span class="c1"&gt;# `agentengine create` should rewrite this when generating a new app from the template.&lt;/span&gt;
&lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;my-agent&lt;/span&gt;
&lt;span class="c1"&gt;# Python import path to the SDK App instance.&lt;/span&gt;
&lt;span class="c1"&gt;# Format: &amp;lt;module path&amp;gt;:&amp;lt;variable name&amp;gt;. This template exposes `app` from&lt;/span&gt;
&lt;span class="c1"&gt;# src/agent_my_agent/main.py.&lt;/span&gt;
&lt;span class="na"&gt;entrypoint&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;agent_my_agent.main:app&lt;/span&gt;
&lt;span class="na"&gt;framework&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;adk&lt;/span&gt;
&lt;span class="c1"&gt;# Runtime feature flags controlled by agent.yaml, not .env. A key that is&lt;/span&gt;
&lt;span class="c1"&gt;# present here wins over any ENABLE_* environment variable, so declaring memory&lt;/span&gt;
&lt;span class="c1"&gt;# keeps ambient environment state from switching it on behind your back.&lt;/span&gt;
&lt;span class="c1"&gt;# Set memory to true to enable long-term profile memory; VOYAGE_API_KEY must be&lt;/span&gt;
&lt;span class="c1"&gt;# present in .env when memory is enabled.&lt;/span&gt;
&lt;span class="na"&gt;features&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
    &lt;span class="na"&gt;durable_workflow&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;
    &lt;span class="na"&gt;memory&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;false&lt;/span&gt;
&lt;span class="c1"&gt;# Tool placement and pass-through secrets. This template's tools are all&lt;/span&gt;
&lt;span class="c1"&gt;# remote-capable, so they run in the tool sandbox.&lt;/span&gt;
&lt;span class="na"&gt;sandboxes&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
    &lt;span class="na"&gt;agent&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
        &lt;span class="na"&gt;secrets&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="pi"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="s"&gt;*"&lt;/span&gt;&lt;span class="pi"&gt;]&lt;/span&gt;
        &lt;span class="na"&gt;tools&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="pi"&gt;[]&lt;/span&gt;
    &lt;span class="na"&gt;tool&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
        &lt;span class="na"&gt;secrets&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="pi"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="s"&gt;*"&lt;/span&gt;&lt;span class="pi"&gt;]&lt;/span&gt;
        &lt;span class="na"&gt;tools&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
            &lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="s"&gt;get_current_date&lt;/span&gt;
            &lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="s"&gt;save_user_info&lt;/span&gt;
            &lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="s"&gt;recall_user_info&lt;/span&gt;
&lt;span class="na"&gt;version&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;0.1.0&lt;/span&gt;
&lt;span class="na"&gt;network&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
    &lt;span class="na"&gt;egress&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt;
        &lt;span class="pi"&gt;-&lt;/span&gt; &lt;span class="na"&gt;fqdn&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="s"&gt;openrouter.ai&lt;/span&gt;
          &lt;span class="na"&gt;ports&lt;/span&gt;&lt;span class="pi"&gt;:&lt;/span&gt; &lt;span class="pi"&gt;[&lt;/span&gt;&lt;span class="nv"&gt;443&lt;/span&gt;&lt;span class="pi"&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;These settings do the following:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;name&lt;/code&gt;: The name Agent Engine uses for your agent. It appears in your invoke URL and in &lt;code&gt;agentengine workspace list&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;features.memory&lt;/code&gt;: Turns the optional memory feature on or off. It's &lt;code&gt;false&lt;/code&gt; because you answered no to the "Enable memory for local dev" prompt.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;sandboxes.tool.tools&lt;/code&gt;: The tools the agent can call.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;network.egress&lt;/code&gt;: The hosts the agent can contact. The CLI added &lt;code&gt;openrouter.ai&lt;/code&gt; on port 443 because your model is served there.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The &lt;code&gt;system_message.py&lt;/code&gt; file in &lt;code&gt;src/agent_my_agent&lt;/code&gt; holds the agent's instructions:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;SYSTEM_PROMPT&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="sh"&gt;"""&lt;/span&gt;&lt;span class="s"&gt;
You are a daily inspiration assistant. Your name is Daily.

If long-term memory is enabled, call `recall_user_info` at the start of a
conversation to check what you know about the user. Address them by name and
use any known details to personalize your responses.

When long-term memory is enabled and the user shares personal details
(name, location, interests, occupation, etc.), save each piece with
`save_user_info` so you remember them in future conversations.

When the user greets you or asks for inspiration, use the get_current_date tool
to find out today&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;s date, then craft a short, uplifting message of the day.
Tailor the message to the season or any notable aspect of the date (e.g. start
of a new month, a Friday, mid-year, etc.). Keep it warm, positive, and concise.
&lt;/span&gt;&lt;span class="sh"&gt;"""&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The instructions are plain text that the model reads with every request. They give the agent its name, &lt;code&gt;Daily&lt;/code&gt;, and say when to call a tool. This is why a prompt that asks for inspiration makes the agent call its &lt;code&gt;get_current_date&lt;/code&gt; tool.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;main.py&lt;/code&gt; file combines the instructions, the model, and the tools into one agent:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="nd"&gt;@app.entrypoint&lt;/span&gt;
&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;build_agent&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;LlmAgent&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="c1"&gt;# ...
&lt;/span&gt;    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nc"&gt;LlmAgent&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;daily&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="n"&gt;instruction&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;SYSTEM_PROMPT&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;strip&lt;/span&gt;&lt;span class="p"&gt;(),&lt;/span&gt;
        &lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;llm&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;build_llm&lt;/span&gt;&lt;span class="p"&gt;()),&lt;/span&gt;
        &lt;span class="n"&gt;tools&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;tools&lt;/span&gt;&lt;span class="p"&gt;(),&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;build_llm()&lt;/code&gt; function in &lt;code&gt;llm.py&lt;/code&gt; sets the model you chose during &lt;code&gt;agentengine create&lt;/code&gt; and reads your OpenRouter key from &lt;code&gt;LLM_API_KEY&lt;/code&gt;. The &lt;code&gt;daily&lt;/code&gt; here is the agent's name inside the code, which is separate from the &lt;code&gt;name&lt;/code&gt; in &lt;code&gt;agent.yaml&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Finally, the &lt;code&gt;tools.py&lt;/code&gt; file defines the tools. Each tool is a Python function with the &lt;code&gt;@app.tool()&lt;/code&gt; decorator, which registers it so the model can call it. For example, the following is the &lt;code&gt;get_current_date&lt;/code&gt; tool from the &lt;code&gt;tools.py&lt;/code&gt; file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;register&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;app&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;App&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="bp"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="nd"&gt;@app.tool&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;get_current_date&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;timezone_name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;str&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;UTC&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="sh"&gt;"""&lt;/span&gt;&lt;span class="s"&gt;Return today&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;s date in ISO 8601 format for an IANA timezone.&lt;/span&gt;&lt;span class="sh"&gt;"""&lt;/span&gt;
        &lt;span class="k"&gt;try&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;timezone&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;ZoneInfo&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;timezone_name&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;except&lt;/span&gt; &lt;span class="n"&gt;ZoneInfoNotFoundError&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;json&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;dumps&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
                &lt;span class="p"&gt;{&lt;/span&gt;
                    &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;error&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Unknown timezone: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;timezone_name&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                    &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;hint&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Use an IANA timezone like America/Los_Angeles.&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="p"&gt;}&lt;/span&gt;
            &lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;datetime&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;now&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;timezone&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;date&lt;/span&gt;&lt;span class="p"&gt;().&lt;/span&gt;&lt;span class="nf"&gt;isoformat&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The model reads the function's docstring to determine when to call it. The template defines three tools:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;get_current_date&lt;/code&gt;: Returns today's date for a timezone, UTC by default.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;recall_user_info&lt;/code&gt;: Looks up what the agent has stored about you.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;save_user_info&lt;/code&gt;: Stores a detail about you, such as your name.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Run the Agent Locally
&lt;/h2&gt;

&lt;p&gt;Before you deploy your agent, run it on your machine.&lt;/p&gt;

&lt;p&gt;First, move into the agent directory:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;cd &lt;/span&gt;my-agent/agents/my-agent
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then run every remaining &lt;code&gt;agentengine&lt;/code&gt; command from the &lt;code&gt;my-agent/agents/my-agent&lt;/code&gt; directory, because the CLI looks for &lt;code&gt;agent.yaml&lt;/code&gt; in the current directory.&lt;/p&gt;

&lt;h3&gt;
  
  
  Start the local stack
&lt;/h3&gt;

&lt;p&gt;To start the local stack, run:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;agentengine dev up
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; Docker must be running before you run the preceding command.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The stack is ready when the output returns &lt;code&gt;✓ Stack running&lt;/code&gt;, followed by its services and an example request:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;✓ Stack running (hot-reload)

  oe       http://localhost:55542
  mongo    mongodb://localhost:55544
  ui       http://localhost:3000

  Invoke:
    curl -X POST 'http://localhost:3000/api/v1/projects/&amp;lt;project-id&amp;gt;/workspaces/my-agent/invoke' \
      -H 'Content-Type: application/json' \
      -d '{"message": "Hello"}'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;My first &lt;code&gt;agentengine dev up&lt;/code&gt; run took several minutes because Docker had to download images and install Python dependencies. If yours takes a while, don't assume something has gone wrong. Subsequent runs reuse those dependencies and start much faster.&lt;/p&gt;

&lt;p&gt;The first run can also stop with the following error while the app is still installing its dependencies:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Error: local app failed before becoming ready: Up About a minute (unhealthy)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you get the error, then leave the stack running and check its progress with the following command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;agentengine dev status
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Until the install finishes, the status reports fewer than &lt;code&gt;4/4 running&lt;/code&gt; and ends with &lt;code&gt;error="status unhealthy"&lt;/code&gt;. Don't stop or restart the stack while you wait. Run &lt;code&gt;agentengine dev status&lt;/code&gt; again every few minutes until the output looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Stack: hot-reload

  app       Up ... (healthy)
  oe        Up ... (healthy)
  mongodb   Up ... (healthy)
  ui        Up ...

4/4 running
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once all services report a healthy status, run &lt;code&gt;agentengine dev up&lt;/code&gt; to get your invoke URL:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;...
✓ Stack running (hot-reload)

  oe       http://localhost:55542
  mongo    mongodb://localhost:55542
  ui       http://localhost:3000
  egress   agent sandbox allow_list (openrouter.ai:443); tool sandbox allow_list (openrouter.ai:443)
           HTTP(S)_PROXY agent sandbox: http://host.docker.internal:62445; tool sandbox: http://host.docker.internal:62446
           only clients that honor HTTP_PROXY are blocked; native sockets are not

  Invoke:
    my-agent    'http://localhost:3000/api/v1/projects/eff47008585047156a391d7d/workspaces/my-agent/invoke'

    curl -X POST 'http://localhost:3000/api/v1/projects/eff470.../workspaces/my-agent/invoke' \
      -H 'Content-Type: application/json' \
      -d '{"message": "Hello"}'

  Next:    Open VS Code and run "Dev Containers: Reopen in Container"
           for editing and debugging inside the running app container
  Restart: from this workspace dir, run
           agentengine dev restart
  Logs:    agentengine dev logs
  Stop:    agentengine dev stop
  Clean:   agentengine dev clean

  ##############################
  #                            #
  # ui   http://localhost:3000 #
  #                            #
  ##############################
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Four containers now run in Docker Desktop, under &lt;strong&gt;Containers&lt;/strong&gt;, grouped as &lt;code&gt;my-agent&lt;/code&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;my-agent-ui&lt;/code&gt;: Serves the agent playground.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;my-agent-oe-1&lt;/code&gt;: Runs the Orchestration Engine, which coordinates each request.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;my-agent-app-1&lt;/code&gt;: Runs your agent code.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;my-agent-mongodb-1&lt;/code&gt;: Stores data locally, so local development doesn't touch your Atlas cluster.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Talk to your agent in the playground
&lt;/h3&gt;

&lt;p&gt;Open &lt;code&gt;http://localhost:3000&lt;/code&gt; in your browser, and send your agent this message:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;I am starting a new job tomorrow. Can I get some inspiration for my first day?
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The free model writes out its reasoning first, so expect a few paragraphs of planning before the reply.&lt;/p&gt;

&lt;h3&gt;
  
  
  Invoke the agent from the command line
&lt;/h3&gt;

&lt;p&gt;You can also invoke the agent without using the browser. To do that, send the agent a request with &lt;code&gt;curl&lt;/code&gt;. The request needs two values:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Invoke URL:&lt;/strong&gt; Copy it from the &lt;code&gt;Invoke:&lt;/code&gt; line of your &lt;code&gt;agentengine dev up&lt;/code&gt; output. The URL contains your local project ID and your workspace name.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; A workspace is the unit Agent Engine runs, and locally it takes your application's name, &lt;code&gt;my-agent&lt;/code&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;User ID:&lt;/strong&gt; Any name you choose to identify yourself to the agent, such as &lt;code&gt;Oladele&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I found that the example &lt;code&gt;curl&lt;/code&gt; command generated by &lt;code&gt;agentengine dev up&lt;/code&gt; omits &lt;code&gt;user_id&lt;/code&gt;, which the Google ADK template requires. To avoid the resulting error, use the following command instead, with your own invoke URL:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;curl &lt;span class="nt"&gt;-X&lt;/span&gt; POST &lt;span class="s1"&gt;'http://localhost:3000/api/v1/projects/&amp;lt;project-id&amp;gt;/workspaces/my-agent/invoke'&lt;/span&gt; &lt;span class="se"&gt;\&lt;/span&gt;
  &lt;span class="nt"&gt;-H&lt;/span&gt; &lt;span class="s1"&gt;'Content-Type: application/json'&lt;/span&gt; &lt;span class="se"&gt;\&lt;/span&gt;
  &lt;span class="nt"&gt;-d&lt;/span&gt; &lt;span class="s1"&gt;'{"message": "I am starting a new job tomorrow. Can I get some inspiration for my first day?", "user_id": "Oladele"}'&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The response contains the agent's reply in its &lt;code&gt;result&lt;/code&gt; field and reports &lt;code&gt;"status": "completed"&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Stop the local stack
&lt;/h3&gt;

&lt;p&gt;To stop the containers, run the following command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;agentengine dev stop
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Register the Project on Atlas Agent Engine
&lt;/h2&gt;

&lt;p&gt;Now that you've tested your agent locally, let's prepare it for deployment to Agent Engine.&lt;/p&gt;

&lt;p&gt;Locally, Docker supplied everything the agent needed. On Agent Engine, three things change. The agent needs a workspace to run in, its own copy of your secrets, and network access to your Atlas cluster. This section and the next two set these up in order.&lt;/p&gt;

&lt;p&gt;To register your agent, run:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;agentengine init
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Choose your Atlas organization, then the Atlas project that holds your M0 cluster. The CLI registers your agent as a workspace on Agent Engine. &lt;/p&gt;

&lt;h2&gt;
  
  
  Upload Your Secrets to Atlas Agent Engine
&lt;/h2&gt;

&lt;p&gt;The deployed agent can't access your local &lt;code&gt;.env&lt;/code&gt; file, so you must upload the following values as Agent Engine secrets:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;MONGODB_URI&lt;/code&gt;:&lt;/strong&gt; Your Atlas connection string.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;LLM_API_KEY&lt;/code&gt;:&lt;/strong&gt; Your OpenRouter API key.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;VOYAGE_API_KEY&lt;/code&gt;:&lt;/strong&gt; Your Voyage AI API key.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Upload each one as a secret with the &lt;code&gt;secret set&lt;/code&gt; command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;agentengine secret &lt;span class="nb"&gt;set &lt;/span&gt;MONGODB_URI
agentengine secret &lt;span class="nb"&gt;set &lt;/span&gt;LLM_API_KEY
agentengine secret &lt;span class="nb"&gt;set &lt;/span&gt;VOYAGE_API_KEY
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Each command prompts for a value. A connection string looks like the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mongodb+srv://&amp;lt;db_username&amp;gt;:&amp;lt;db_password&amp;gt;@&amp;lt;cluster-host&amp;gt;/?appName=devrel-tutorial-agentengine-deploy
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Replace the placeholders with your database user, its password, and your cluster host. Agent Engine stores these values as project secrets, so every workspace in your Atlas project can read them.&lt;/p&gt;

&lt;p&gt;Each &lt;code&gt;secret set&lt;/code&gt; command confirms the upload. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;✓ Project secret VOYAGE_API_KEY set
  version: 3
  updated_at: 2026-10-14T12:11:30Z
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Connect Atlas Agent Engine to Your Atlas Cluster
&lt;/h2&gt;

&lt;p&gt;Before you deploy your agent, you need to configure network access between Agent Engine and your MongoDB Atlas cluster. Without the required IP access entries, Agent Engine cannot connect to your cluster, and deployment may time out after waiting up to 30 minutes.&lt;/p&gt;

&lt;p&gt;You can configure your network access using the &lt;code&gt;agentengine atlas setup&lt;/code&gt; command. The command's cluster list hides free M0 clusters, so you can't select yours there. It instead asks whether to keep the &lt;code&gt;MONGODB_URI&lt;/code&gt; secret you uploaded in the previous section.&lt;/p&gt;

&lt;p&gt;The command also adds Agent Engine's IP ranges to the access list of your Atlas project.&lt;/p&gt;

&lt;p&gt;Run the command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;agentengine atlas setup
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When prompted, enter &lt;code&gt;y&lt;/code&gt; to keep the existing &lt;code&gt;MONGODB_URI&lt;/code&gt;. The CLI then displays the IP address ranges that Agent Engine needs to access your cluster. Enter &lt;code&gt;y&lt;/code&gt; again to add these ranges to your cluster's IP access list:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Keep the existing MONGODB_URI for this Agent Engine project? [Y/n] y

These CIDR ranges will be added so the platform can reach this cluster:
  - 44.214.209.237/32
  - 52.44.27.64/32

Add these CIDR ranges to Atlas IP access? [Y/n] y
...
Atlas integration is ready.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;Atlas integration is ready&lt;/code&gt; output confirms that the network configuration is complete.&lt;/p&gt;

&lt;h2&gt;
  
  
  Build and Deploy the Agent
&lt;/h2&gt;

&lt;p&gt;Your agent now has a workspace, its secrets, and a path to your cluster. Build and deploy it in one step:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;agentengine deploy &lt;span class="nt"&gt;--auto&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Without the &lt;code&gt;--auto&lt;/code&gt; flag, you first run &lt;code&gt;agentengine build&lt;/code&gt; to create the agent image, then &lt;code&gt;agentengine deploy&lt;/code&gt; to deploy it. The &lt;code&gt;--auto&lt;/code&gt; flag combines both steps into a single command and monitors the deployment until completion.&lt;/p&gt;

&lt;p&gt;Deployment takes several minutes. When it finishes, each component reports its status:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;✓ Build succeeded
...
✓ Deployment succeeded
  version: v0.1.0
  components:
    Orchestration Engine      ready (2 replicas)
    Agent Sandbox             ready (4 replicas)
    Tool Sandbox              ready (4 replicas)
  url: https://agentengine.mongodb.com/project/&amp;lt;project-id&amp;gt;/deployments/&amp;lt;deployment-id&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;All three components reporting &lt;code&gt;ready&lt;/code&gt; means that Agent Engine built your agent and started it. Agent Engine now runs the agent and its supporting services instead of your local Docker environment.&lt;/p&gt;

&lt;h2&gt;
  
  
  Invoke the Deployed Agent
&lt;/h2&gt;

&lt;p&gt;Once your deployment succeeds, send your deployed agent a message:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;agentengine invoke &lt;span class="s2"&gt;"I have a big presentation today. Can you give me some motivation?"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As in the playground, the free model writes out its reasoning before the reply.&lt;/p&gt;

&lt;p&gt;Now test whether the deployed agent remembers. Each invocation starts a new session unless you pass &lt;code&gt;--session&lt;/code&gt;. A session holds the history of one conversation, while the optional memory feature stores facts about a user across conversations.&lt;/p&gt;

&lt;p&gt;Run these two commands in order, with the same session name:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;agentengine invoke &lt;span class="nt"&gt;--session&lt;/span&gt; tutorial-session &lt;span class="s2"&gt;"My name is Oladele."&lt;/span&gt;
agentengine invoke &lt;span class="nt"&gt;--session&lt;/span&gt; tutorial-session &lt;span class="s2"&gt;"What is my name?"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The output for the second command ends with the answer:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Your name is Oladele.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The second request doesn't contain your name, so the answer came from the session's history. Agent Engine stored that history in your Atlas cluster, and the deployed agent read it back.&lt;/p&gt;

&lt;h2&gt;
  
  
  Clean Up Your Resources
&lt;/h2&gt;

&lt;p&gt;You've now deployed your agent, sent it a message, and tested its session history. If you no longer need the agent, follow these steps to remove the resources you created locally, on Agent Engine, and in Atlas.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; Other workspaces or applications in your Atlas project may use the project secrets, IP access entries, database user, or Voyage AI API key. Delete them only when nothing else uses them.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;First, stop and remove the local stack:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;agentengine dev stop
agentengine dev clean
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, find your workspace ID:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;agentengine workspace list
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The list shows your workspace's ID next to its name:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;WORKSPACE ID                 NAME      FRAMEWORK
ws-xxxxxxxxxxxxxxxxxxxxxxxx  my-agent  adk
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then delete the workspace:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;agentengine workspace delete &amp;lt;workspace-id&amp;gt; &lt;span class="nt"&gt;--yes&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You stored &lt;code&gt;MONGODB_URI&lt;/code&gt;, &lt;code&gt;LLM_API_KEY&lt;/code&gt;, and &lt;code&gt;VOYAGE_API_KEY&lt;/code&gt; as Agent Engine secrets. To remove them, follow the instructions in &lt;a href="https://www.mongodb.com/docs/agentengine/deploy/provision-secrets/?utm_campaign=devrel&amp;amp;utm_source=third-party-content&amp;amp;utm_medium=cta&amp;amp;utm_content=buildrel-first-agent-mdb-agent-eng-devto&amp;amp;utm_term=hugh.murray#std-label-agentic-platform-secret-delete" rel="noopener noreferrer"&gt;Delete a Secret&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Three resources remain in the Atlas UI:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;The IP access entries:&lt;/strong&gt; Go to &lt;strong&gt;SECURITY &amp;gt; Database &amp;amp; Network Access &amp;gt; IP Access List&lt;/strong&gt; and delete your IP access entries.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The database user:&lt;/strong&gt; Go to &lt;strong&gt;SECURITY &amp;gt; Database &amp;amp; Network Access &amp;gt; Database Users&lt;/strong&gt; and delete the user you created for your connection string if you no longer need it.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The Voyage AI API key:&lt;/strong&gt; Go to &lt;strong&gt;SERVICES &amp;gt; AI Model APIs &amp;gt; Model API Keys&lt;/strong&gt; and delete the key if you no longer need it.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Key Takeaways
&lt;/h2&gt;

&lt;p&gt;Here's what to take away from this tutorial:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Agent Engine is in public preview and only intended for evaluation and prototyping, with breaking changes expected.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;agentengine create&lt;/code&gt; generates a project directory on your machine, and &lt;code&gt;agentengine init&lt;/code&gt; registers it with Agent Engine.&lt;/li&gt;
&lt;li&gt;A &lt;code&gt;.env&lt;/code&gt; file serves local development only. Upload every value the deployed agent needs with &lt;code&gt;agentengine secret set&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;A deployed agent reaches your cluster from Agent Engine's network, so the cluster's IP access list must include Agent Engine's address ranges.&lt;/li&gt;
&lt;li&gt;Agent Engine keeps each session's history in your Atlas cluster, so requests that share a &lt;code&gt;--session&lt;/code&gt; value continue one conversation.
## Further Reading&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;For more information on Agent Engine, see the following resources:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://www.mongodb.com/docs/agentengine/get-started/?utm_campaign=devrel&amp;amp;utm_source=third-party-content&amp;amp;utm_medium=cta&amp;amp;utm_content=buildrel-first-agent-mdb-agent-eng-devto&amp;amp;utm_term=hugh.murray" rel="noopener noreferrer"&gt;Get Started with the Atlas Agent Engine&lt;/a&gt;: MongoDB's reference guide for this workflow.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://www.mongodb.com/docs/agentengine/build/install-authenticate/?utm_campaign=devrel&amp;amp;utm_source=third-party-content&amp;amp;utm_medium=cta&amp;amp;utm_content=buildrel-first-agent-mdb-agent-eng-devto&amp;amp;utm_term=hugh.murray" rel="noopener noreferrer"&gt;Install and Authenticate&lt;/a&gt;: Setup instructions for Windows and Linux.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://github.com/mongodb/agent-engine-examples" rel="noopener noreferrer"&gt;Atlas Agent Engine examples&lt;/a&gt;: The repository holding this tutorial's template and the other starter templates.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://www.mongodb.com/docs/agentengine/deploy/invoke-agent/?utm_campaign=devrel&amp;amp;utm_source=third-party-content&amp;amp;utm_medium=cta&amp;amp;utm_content=buildrel-first-agent-mdb-agent-eng-devto&amp;amp;utm_term=hugh.murray" rel="noopener noreferrer"&gt;Invoke an Agent&lt;/a&gt;: How to call your deployed agent from your own code.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://www.mongodb.com/docs/agentengine/manage/monitor/?utm_campaign=devrel&amp;amp;utm_source=third-party-content&amp;amp;utm_medium=cta&amp;amp;utm_content=buildrel-first-agent-mdb-agent-eng-devto&amp;amp;utm_term=hugh.murray" rel="noopener noreferrer"&gt;Monitor&lt;/a&gt;: How to watch your deployed agent run.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>ai</category>
      <category>mongodb</category>
      <category>database</category>
      <category>agents</category>
    </item>
    <item>
      <title>Building a context-aware support agent on MongoDB Atlas</title>
      <dc:creator>MongoDB Guests</dc:creator>
      <pubDate>Wed, 21 Oct 2026 09:00:00 +0000</pubDate>
      <link>https://dev.to/mongodb/building-a-context-aware-support-agent-on-mongodb-atlas-168e</link>
      <guid>https://dev.to/mongodb/building-a-context-aware-support-agent-on-mongodb-atlas-168e</guid>
      <description>&lt;p&gt;&lt;em&gt;This tutorial is written by &lt;a href="https://www.linkedin.com/in/samuelmolling/?isSelfProfile=false" rel="noopener noreferrer"&gt;Samuel Molling&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;A customer support agent looks simple from the outside: a chat box where someone asks a question and gets an answer. However, behind that interface, the job is less simple. The answer might be in product documentation, in a support ticket another agent resolved months ago, in the customer's own account data, or nowhere the agent is allowed to act on its own.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;At the center of this lab is a retrieval-augmented generation (RAG) pipeline built on MongoDB Atlas. A question is embedded and searched against document chunks with Atlas Vector Search, while Atlas Search retrieves lexical matches from whole articles. The ranked lists are combined with Reciprocal Rank Fusion, the strongest candidates are reranked with a cross-encoder, and the best passages are passed to an LLM as context for the answer.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;That pipeline works well when the input is a self-contained search query. Customer support is different.&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;A customer rarely asks one perfectly self-contained question. They ask something, clarify it, refer back to a previous answer, ask about their own account, and sometimes request something the agent should not handle at all.&lt;/p&gt;

&lt;p&gt;Consider this conversation:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;em&gt;Does your product support SAML SSO?&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;&lt;em&gt;Is it available on the Pro plan?&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;&lt;em&gt;And how much is that?&lt;/em&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The last question is almost useless as a retrieval query. There is no product, feature, or plan name in it. Its meaning exists because of the conversation before it.&lt;/p&gt;

&lt;p&gt;And retrieval is only one part of the problem. Across a support session, one answer might come from documentation, another from a previously resolved ticket, another from operational customer data, and sometimes the correct next step is not an answer at all. It is a human.&lt;/p&gt;

&lt;p&gt;This article builds the layers a support agent needs around that retrieval pipeline: query rewriting, conversation memory, multiple corpora, customer entitlements, operational tools, confidence, and escalation.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F2xtgm06n4644e78endqh.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F2xtgm06n4644e78endqh.jpg" alt="Example of the console answering as the Enterprise customer. The inspection panel shows the condensed question, the classification, the confidence band, and the five passages that survived fusion and reranking." width="799" height="461"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;Example of the console answering as the Enterprise customer. The inspection panel shows the condensed question, the classification, the confidence band, and the five passages that survived fusion and reranking.&lt;/em&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  What changes when the query becomes a conversation
&lt;/h2&gt;

&lt;p&gt;The unit of work moves from answering one query with one passage to resolving a whole conversation. That sounds like a UX change, but it is a data modeling change, a security change, and a control flow change.&lt;/p&gt;

&lt;p&gt;Consider a real fourth turn: “&lt;em&gt;and how much is that?&lt;/em&gt;” Five words. No product, no plan, no verb worth embedding. Send it to a vector index as written, and it retrieves noise, because the vector is computed from a sentence that means nothing on its own. The failure surfaces as bad retrieval, and the engineer goes and tunes numCandidates.&lt;/p&gt;

&lt;p&gt;Now consider what the customer actually needs across a session. The answer to turn one lives in documentation. The answer to turn two lives in a resolved ticket from eight months ago, because a human already solved this exact thing and wrote it down. The answer to turn three is the shipping status of order ORD-1042, which lives in an operational collection and is not a retrieval problem at all. The answer to turn four is that this customer wants to cancel, and no passage in any corpus authorizes the agent to handle that.&lt;/p&gt;

&lt;p&gt;Four turns, four different data sources, one of which is a person. The retrieval pipeline handles one of them.&lt;/p&gt;

&lt;p&gt;The full per-turn flow in this implementation:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fv1u08ln6m3ncyp2tpg74.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fv1u08ln6m3ncyp2tpg74.png" alt="One turn of the agent, end to end. Condensation runs first and can skip retrieval entirely. Escalation is evaluated before generation, not after it." width="800" height="431"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;One turn of the agent, end-to-end. Condensation runs first and can skip retrieval entirely. Escalation is evaluated before generation, not after it.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Stages 2 and 3 run against the same Atlas cluster that holds the transcript. That matters more than it may sound, and I will come back to it.&lt;/p&gt;
&lt;h2&gt;
  
  
  Condensation: rewrite, and do not answer
&lt;/h2&gt;

&lt;p&gt;Before a turn can be retrieved against, it has to be made self-contained. One LLM call in JSON mode rewrites the turn and classifies it at the same time, because both need identical context and a second round trip would double per-turn latency for no new information.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;standaloneQuestion:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"How much does SAML SSO cost?"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;intent:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"billing_question"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;needsRetrieval:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;needsTools:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;[],&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;sentiment:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"neutral"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;mentionedOrderId:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The interesting part of the prompt is not the instruction. It is the prohibition.&lt;/p&gt;

&lt;p&gt;An unconstrained rewriter is an efficient machine for inventing facts. Given "and how much is that?" after a thread about SSO, it happily produces:&lt;/p&gt;

&lt;p&gt;&lt;em&gt;How much does SAML SSO cost on the Pro plan for a 50-seat team billed annually?&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Three constraints the customer never said. Plan, seat count, billing period. Each one prunes the candidate set inside the index. The passage that would have answered the question is now unreachable, and nothing in the logs says the query was fabricated. What you see is a reasonable-looking question that returned bad results.&lt;/p&gt;

&lt;p&gt;Over-condensation fails silently and reads as a retrieval bug. That is why the system prompt spends more words on what not to do than on the task:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;- Do NOT answer the question. You are not the support agent.
- Do NOT add any constraint, number, product name, plan name, version,
  quantity, or qualifier that the customer did not actually say.
- Do NOT resolve ambiguity by guessing. If "it" is genuinely unclear, keep
  it vague rather than picking a referent.
- DO resolve pronouns and elisions that the earlier turns make unambiguous.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;needsRetrieval&lt;/em&gt; is the other half of the call, and it covers the entire stage. When a customer types "thanks, that worked", the classifier returns &lt;code&gt;false&lt;/code&gt; and the turn skips embedding, two vector searches, a rerank, and five passages in the prompt. Running the full pipeline on every turn is most of the per-turn cost of a naive agent, and a meaningful share of turns in a real support thread are acknowledgments.&lt;/p&gt;

&lt;p&gt;JSON mode guarantees syntactically valid JSON. It does not guarantee a valid shape. Every field gets clamped to a closed set before anything downstream reads it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="err"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;intent&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;INTENTS.includes(obj.intent)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;?&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;obj.intent&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"other"&lt;/span&gt;&lt;span class="err"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;An unrecognized intent that slips through would bypass the escalation policy without ever being tested against it. Clamping is not a defensive style. It is the thing that keeps a classifier hallucination from becoming a policy bypass.&lt;/p&gt;

&lt;h2&gt;
  
  
  Memory in three layers
&lt;/h2&gt;

&lt;p&gt;Conversation state is the part of this system where the obvious data model is wrong in three directions at once.&lt;/p&gt;

&lt;p&gt;The obvious model puts messages in an array on the conversation document. It preserves locality, one &lt;code&gt;findOne&lt;/code&gt; returns everything, and the shape mirrors the application. It degrades as follows.&lt;/p&gt;

&lt;p&gt;Every append rewrites the entire document. Turn 40 rewrites 39 turns of text to add one line, so write amplification grows linearly with conversation length. The working set is sized by the longest conversation instead of the median one, because any read of that conversation pulls every turn into cache, and one customer who never closes the widget inflates the memory profile of the whole collection. And there is a hard wall at 16MB. It is far away. A persistent enough user will find it, and when they do, the failure is an unhandled write error on an ordinary message.&lt;/p&gt;

&lt;p&gt;Messages live in their own collection:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="err"&gt;messages:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;conversationId&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;seq&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;role&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;content&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;meta:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{},&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;createdAt&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With &lt;em&gt;{ conversationId: 1, seq: -1 }&lt;/em&gt;, the "last K turns" read is an index scan and appends stay constant-time regardless of length.&lt;/p&gt;

&lt;p&gt;On top of the transcript sit two more layers, both on the conversation document:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="err"&gt;conversations:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;customerId&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;status&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;summary&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;        &lt;/span&gt;&lt;span class="err"&gt;//&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;rolling&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;prose&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;digest&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;facts&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;          &lt;/span&gt;&lt;span class="err"&gt;//&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;extracted&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;identifiers&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;turnCount&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;failedTurns&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;lastIntent&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;createdAt&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;updatedAt&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;expiresAt?&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The context window sent to the model is summary + last K verbatim turns + facts. That budget is fixed. Replaying the whole transcript instead means cost and latency grow with conversation length, which is exactly backward, because the longest conversations are the ones already going badly.&lt;/p&gt;

&lt;p&gt;The summary regenerates every 6 turns, not every turn. Summarizing on every turn doubles the LLM calls to restate information that changes slowly, since the digest of turns 1 through 20 is nearly identical to that of turns 1 through 21. The verbatim window covers whatever the summary has not absorbed yet.&lt;/p&gt;

&lt;p&gt;The facts array exists because the summarizer is a paraphraser by construction. Ask a model to compress a conversation, and it will smooth "ORD-1042" into "the customer's recent order" somewhere around turn fifteen. The summarizer prompt demands verbatim preservation of every identifier, error code, product name, and stated constraint, and I still would not bet a customer interaction on it. The structured layer is where the order ID survives, because nothing there is trying to make the text read better.&lt;/p&gt;

&lt;h3&gt;
  
  
  TTL that expires sessions but not customers
&lt;/h3&gt;

&lt;p&gt;One index deserves its own explanation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nl"&gt;key&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;expiresAt&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="nx"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;conversations_ttl_anonymous&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;expireAfterSeconds&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A TTL index only expires documents that have the indexed field. Documents without expiresAt are ignored forever. And expiresAt is written in exactly one place, when an anonymous visitor starts a session.&lt;/p&gt;

&lt;p&gt;So the rule this expresses is that an anonymous session is a cache and a signed-in customer's conversation is not.&lt;/p&gt;

&lt;p&gt;A uniform TTL across all conversations is the version that looks tidier and is data loss in slow motion. A customer's support history is operational data with a retention policy, a compliance story, and a "what did you tell me in March" question attached to it. Deleting it on a rolling 30-day window destroys that record silently, one document at a time, with no error and no backup. You find out when someone asks for the March conversation.&lt;/p&gt;

&lt;h2&gt;
  
  
  Two corpora: documentation and resolved tickets
&lt;/h2&gt;

&lt;p&gt;Documentation describes the product as designed. Tickets describe it as experienced. Those are different corpora, and the second one is not optional, because the phrasing gap between them is where support actually happens.&lt;/p&gt;

&lt;p&gt;An error is documented like this:&lt;br&gt;
&lt;em&gt;AUTH_302 is returned when the SAML assertion presented by the identity provider carries an Audience URI that does not match the Entity ID configured for the workspace.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;A customer reports it like this:&lt;br&gt;
_I get bounced back to the login page after signing in with Okta&lt;br&gt;
_&lt;br&gt;
Those two texts share almost no vocabulary. A resolved ticket written by the agent who fixed it sits in the middle, phrased in symptoms and closed with the resolution, and it is what actually matches the customer's words.&lt;/p&gt;

&lt;p&gt;So the pipeline runs three rankers over two corpora and fuses them:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="w"&gt;  &lt;/span&gt;&lt;span class="err"&gt;weights:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="err"&gt;kbChunks:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mf"&gt;1.0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="err"&gt;kbArticles:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mf"&gt;0.7&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="err"&gt;tickets:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mf"&gt;0.5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Fusion is Reciprocal Rank Fusion with per-ranker weights. RRF fuses by rank and never by raw score, because BM25 is unbounded and cosine similarity lives in [0,1], and normalizing them against each other means inventing a conversion nobody can defend.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;score(doc) = Σ over rankers   weight_r × 1 / (k + rank_r(doc))     // k = 60
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;MongoDB 8.1 ships $rankFusion as a native stage. The lab implements RRF by hand so the arithmetic is visible; production on 8.1+ should prefer the stage.&lt;/p&gt;

&lt;p&gt;The ticket ranker carries two adjustments that documentation does not.&lt;/p&gt;

&lt;p&gt;Recency decay. A resolution from eighteen months ago may describe a console screen that no longer exists. The ticket's contribution halves every 180 days:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="err"&gt;export&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;function&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;recencyDecay(resolvedAt,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;now&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;Date())&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;(!resolvedAt)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mf"&gt;0.5&lt;/span&gt;&lt;span class="err"&gt;;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;//&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;unknown&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;age:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;assume&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;one&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;half-life&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;ageDays&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;(now.getTime()&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;-&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;new&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;Date(resolvedAt).getTime())&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;/&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;86&lt;/span&gt;&lt;span class="err"&gt;_&lt;/span&gt;&lt;span class="mi"&gt;400&lt;/span&gt;&lt;span class="err"&gt;_&lt;/span&gt;&lt;span class="mi"&gt;000&lt;/span&gt;&lt;span class="err"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;(!Number.isFinite(ageDays)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;||&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;ageDays&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;&amp;lt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="err"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="err"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;Math.pow(&lt;/span&gt;&lt;span class="mf"&gt;0.5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;ageDays&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;/&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;tuning.ticketHalfLifeDays);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;An old ticket can still win when nothing else matches. A fresh document outranks it whenever one exists.&lt;/p&gt;

&lt;p&gt;A quality bar, enforced in the index. Only status: "resolved" tickets with quality &amp;gt;= 0.7 are eligible:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="err"&gt;filter:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;status:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;$eq:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"resolved"&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;quality:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;$gte:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;tuning.ticketMinQuality&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;...(customer.locale&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;?&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;locale:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;$eq:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;customer.locale&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{}&lt;/span&gt;&lt;span class="err"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A ticket corpus that includes unresolved threads or wrong answers is a machine for reproducing past mistakes at scale, and it does it in the confident register of a closed case. Both conditions are filter fields on the vector index rather than a downstream $match, for the reason in the next section.&lt;/p&gt;

&lt;h3&gt;
  
  
  Embed the rewrite, rerank the original
&lt;/h3&gt;

&lt;p&gt;One subtlety that took me a while to see clearly.&lt;/p&gt;

&lt;p&gt;The condensed question is what gets embedded. That is the whole point of condensation, since the vector has to come from a self-contained sentence.&lt;/p&gt;

&lt;p&gt;The reranker gets the original turn.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="err"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;rerankQuery&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;originalMessage?.trim()&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;||&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;condensedQuestion;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="err"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;ranked&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;await&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;rerank(rerankQuery,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;docs,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;tuning.topPassages)&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The rewrite is a lossy transformation optimized for embedding similarity. It drops tone, urgency, and the customer's own phrasing to produce a clean retrievable sentence. That is the right input for an approximate nearest-neighbor index and the wrong input for judging relevance. The reranker is a cross-encoder that reads query and passage together, so it should see what the customer actually wrote, including the words the rewrite threw away.&lt;/p&gt;

&lt;p&gt;Feeding the rewrite to both stages is the default that nobody questions, and it quietly costs precision on exactly the turns where the customer was most specific.&lt;/p&gt;

&lt;h2&gt;
  
  
  Entitlement belongs in retrieval
&lt;/h2&gt;

&lt;p&gt;This is an authorization boundary, not a prompt instruction.&lt;/p&gt;

&lt;p&gt;A Free-plan customer must never be answered out of an Enterprise-only runbook. That is an authorization requirement, and it has a correct implementation and two popular incorrect ones.&lt;/p&gt;

&lt;p&gt;The correct implementation is a filter field evaluated inside the vector index:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="err"&gt;export&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;function&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;entitlementFilter(customer&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{}&lt;/span&gt;&lt;span class="err"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;filter&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="err"&gt;audience:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;$in:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;audienceFor(customer.plan)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="err"&gt;status:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;$eq:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"published"&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="err"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;(customer.locale)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;filter.locale&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;$eq:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;customer.locale&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="err"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;filter;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Passed to &lt;code&gt;$vectorSearch&lt;/code&gt; as a filter, this means the Enterprise passage is never scored. Not scored and then hidden. Never scored, so it never enters the candidate set, never reaches the reranker, and cannot appear in the prompt.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F8fzzojzm57zwd2faquve.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F8fzzojzm57zwd2faquve.jpg" alt="The same question asked as the Free customer. Seventeen chunks were scored instead of twenty-two, the audit-log article is absent, and the best remaining passage is a tangential ticket at 0.563 -- weak, not strong.&lt;br&gt;
" width="799" height="461"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;The same question asked as the Free customer. Seventeen chunks were scored instead of twenty-two, the audit-log article is absent, and the best remaining passage is a tangential ticket at 0.563 -- weak, not strong.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The first incorrect implementation is a prompt instruction. "Only use passages the customer is entitled to see." That is not a control. It is a request, addressed to a component whose entire job is to be agreeable, evaluated after the restricted text is already in the context window. Once it is in the prompt, it is one clever question away from being in the answer.&lt;/p&gt;

&lt;p&gt;The second incorrect implementation is a $match after $vectorSearch, which is better and still wrong. limit is applied by the index. Filtering afterward silently shrinks the result set instead of changing it. Ten Enterprise hits and the Free customer gets an empty page, which is correct on paper and broken in the product.&lt;/p&gt;

&lt;p&gt;The BM25 ranker needs the same guarantee, and $search has no filter field. The restriction goes into the compound query itself, still evaluated by the index:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="err"&gt;compound:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;should:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;/*&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;title&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;content&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;tags&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;*/&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;filter:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;in:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;path:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"audience"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;value:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;audienceFor(customer.plan)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;equals:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;path:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"status"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;value:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"published"&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;minimumShouldMatch:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That in operator carries a trap worth naming, because it cost me a working ranker and said nothing about it.&lt;/p&gt;

&lt;p&gt;in and equals do not match a field indexed as an analyzed string. They return 0 hits, with no error. Map the filtered fields as token instead:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="err"&gt;tags:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;type:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"string"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;analyzer:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"lucene.keyword"&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="err"&gt;,&lt;/span&gt;&lt;span class="w"&gt;   &lt;/span&gt;&lt;span class="err"&gt;//&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;scored,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;stays&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;a&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;string&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="err"&gt;audience:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;type:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"token"&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="err"&gt;,&lt;/span&gt;&lt;span class="w"&gt;                            &lt;/span&gt;&lt;span class="err"&gt;//&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;filtered,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;never&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;scored&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="err"&gt;locale:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;type:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"token"&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="err"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="err"&gt;status:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;type:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"token"&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="err"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With audience mapped as a keyword-analyzed string, the compound filter silently discarded every document, and the BM25 ranker returned nothing on every query. Vector search still worked, results still looked reasonable, and the entitlement guarantee this section is about was simply not being enforced on that ranker. The offline test suite cannot catch this: it needs a real index. It took running the thing against a cluster and noticing that one ranker reported zero hits on every single query.&lt;/p&gt;

&lt;p&gt;One more detail. The ladder fails closed:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="err"&gt;export&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;function&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;audienceFor(plan)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;tuning.audienceLadder&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="err"&gt;plan&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;||&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;tuning.audienceLadder.free;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;An unknown plan string, a typo, a new tier someone added to the billing system and forgot to add here - all of them degrade to the most restrictive rung. An authorization default that fails open is a bug that ships quietly and is found by an auditor.&lt;/p&gt;

&lt;p&gt;This is also the concrete payoff of keeping everything in one cluster. The chunk carries audience, locale, category, tags, and status denormalized from its parent article, because a $lookup cannot participate in a $vectorSearch pre-filter. The filter is evaluated by the index on the chunk document, so the fields have to be there. In a split architecture, that same denormalization is a synchronization problem between a vector store and a database, and the failure mode is an entitlement field that is correct in one system and stale in the other.&lt;/p&gt;

&lt;h2&gt;
  
  
  Tools: the model picks which, the server picks whose
&lt;/h2&gt;

&lt;p&gt;Some answers are not in any corpus. "Where is my order" is a query against operational data, and in this architecture it is a query against the same cluster.&lt;br&gt;
T&lt;br&gt;
hree tools: lookupOrder, listRecentOrders, lookupSubscription. The rule that governs all of them:&lt;/p&gt;
&lt;h3&gt;
  
  
  The model chooses which tool runs. The server decides what it can see.
&lt;/h3&gt;

&lt;p&gt;customerId comes from the authenticated session and from nowhere else. The model's arguments answer the question ("which order reference?") and never the subject ("whose orders?").&lt;/p&gt;

&lt;p&gt;Look at what is absent from the schema the model sees:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;name:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"lookupOrder"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;description:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;""&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="s2"&gt;"Look up one order belonging to the current customer by its order reference (e.g. ORD-1042)."&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;parameters:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="err"&gt;type:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"object"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="err"&gt;properties:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
      &lt;/span&gt;&lt;span class="err"&gt;orderRef:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;type:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"string"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;description:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"&lt;/span&gt;&lt;span class="se"&gt;\"&lt;/span&gt;&lt;span class="s2"&gt;The order reference to look up.&lt;/span&gt;&lt;span class="se"&gt;\"&lt;/span&gt;&lt;span class="s2"&gt; },"&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="err"&gt;required:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"orderRef"&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;No customerId. The model cannot pass it because it is not part of the contract it is shown.&lt;/p&gt;

&lt;p&gt;Accepting customerId from model arguments turns the agent into an IDOR with a natural-language interface. The attack is not sophisticated. It is typing "show me the orders for customer 507f1f77bcf86cd799439011" and having a helpful model pass it through. No amount of prompt hardening fixes this, because the vulnerability is in the plumbing. Once the parameter is attacker-controlled, the model is just the transport.&lt;/p&gt;

&lt;p&gt;The session ID goes into the query filter, not into a check afterward:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="err"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;order&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;await&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;db&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;.collection(Collections.orders)&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;.findOne(&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;customerId:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;cid&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;orderRef&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="err"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;projection:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;customerId:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="err"&gt;);&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Fetching by orderRef and then comparing owners leaks existence through timing, and through any code path that forgets the comparison.&lt;/p&gt;

&lt;p&gt;One more thing worth saying explicitly, because it is where well-meaning implementations go wrong. An empty result is a legitimate answer. "I don't see that order on your account" is correct output, not an error to be routed around. Widening the query until something comes back is how a scoped lookup quietly becomes a global one.&lt;/p&gt;

&lt;h2&gt;
  
  
  Escalation: four signals, and a packet instead of a flag
&lt;/h2&gt;

&lt;p&gt;The third broken assumption. Sometimes the correct output is a human, and answering confidently is the failure.&lt;/p&gt;

&lt;p&gt;Four independent signals, any one sufficient:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="err"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;turnFailed&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;confidence&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;!==&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"strong"&lt;/span&gt;&lt;span class="err"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="err"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;nextFailedTurns&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;turnFailed&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;?&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;failedTurns&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;+&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="err"&gt;;&lt;/span&gt;&lt;span class="w"&gt;

&lt;/span&gt;&lt;span class="err"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;(tuning.alwaysEscalateIntents.includes(intent))&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;escalate:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;reason:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;`policy:$&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="err"&gt;intent&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="err"&gt;`&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;failedTurns:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;nextFailedTurns&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="err"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="err"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;(explicitRequest&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;||&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;intent&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;===&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"human_handoff"&lt;/span&gt;&lt;span class="err"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;escalate:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;reason:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"explicit_request"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;failedTurns:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;nextFailedTurns&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="err"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="err"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;((sentiment&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;===&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"frustrated"&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;||&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;sentiment&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;===&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"angry"&lt;/span&gt;&lt;span class="err"&gt;)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;&amp;amp;&amp;amp;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;turnFailed)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;escalate:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;reason:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"frustration_with_failed_turn"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;failedTurns:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;nextFailedTurns&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="err"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="err"&gt;if&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;(nextFailedTurns&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;&amp;gt;&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;tuning.maxFailedTurns)&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;escalate:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;reason:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"repeated_low_confidence"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;failedTurns:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;nextFailedTurns&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="err"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="err"&gt;return&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;escalate:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kc"&gt;false&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;reason:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;failedTurns:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;nextFailedTurns&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="err"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;They stay independent on purpose. A single blended escalation score is untunable, because when it misfires you cannot tell which input moved it, and every threshold change silently reweights all four.&lt;/p&gt;

&lt;p&gt;The first signal is the one people leave out. cancellation, refund_request, billing_dispute, data_deletion, legal escalate on arrival, whatever retrieval found. Confidence is irrelevant, because finding a perfect passage about the refund policy does not give the agent authority to issue a refund. These are authority boundaries, not knowledge gaps, and a confident answer there is worse than no answer.&lt;/p&gt;

&lt;p&gt;The third signal is deliberately a conjunction. Frustration alone does not escalate, since an annoyed customer who is being answered well is being helped. Frustration on a turn that also failed means the agent is making things worse, and one more attempt is one more reason to cancel the subscription.&lt;/p&gt;

&lt;p&gt;The fourth counts consecutive failures, and one strong answer resets it. A customer who got a good answer and then asks about something new is not two-thirds of the way to a handoff.&lt;/p&gt;

&lt;p&gt;Confidence comes from the reranker rather than from vector distance or BM25 in isolation. In the seeded corpus, a top rerank score at or above 0.6 is strong, 0.45 to 0.6 is weak, and below that is none. A passage that answers the question lands around 0.79 to 0.88, a tangential one around 0.56, a wrong retrieval on an un-condensed turn around 0.44, and an out-of-corpus question around 0.33. These are calibration values for this corpus, not universal thresholds.&lt;/p&gt;

&lt;h3&gt;
  
  
  The handoff is more than a status
&lt;/h3&gt;

&lt;p&gt;status: "escalated" tells the human nothing. They open the conversation, read fourteen turns, and repeat every question the bot already asked. That is precisely the experience behind "I had to explain everything twice."&lt;/p&gt;

&lt;p&gt;The packet is what the agent knows, serialized:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;reason:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"repeated_low_confidence"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;intent:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"troubleshooting"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;askedFor:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"Why does SAML sign-in fail with Okta?"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;sentiment:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"frustrated"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;customer:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;email&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;plan&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;seats&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;subscriptionStatus&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;renewsAt&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;conversation:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;turnCount&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;failedTurns&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;summary&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;facts&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;attempted:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="err"&gt;confidence:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"none"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="err"&gt;topRerankScore:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mf"&gt;0.21&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="err"&gt;passages:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;[{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;kind&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;title&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;breadcrumb&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;rerankScore&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;}],&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="err"&gt;tools:&lt;/span&gt;&lt;span class="w"&gt;    &lt;/span&gt;&lt;span class="p"&gt;[{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;tool&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;ok&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;found&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;}],&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F5v30opnuywub5p8864pd.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F5v30opnuywub5p8864pd.jpg" alt="A cancellation escalates on arrival. Retrieval is skipped, confidence is none, and the panel carries the handoff packet rather than a flag." width="799" height="461"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;A cancellation escalates on arrival. Retrieval is skipped, confidence is none, and the panel carries the handoff packet rather than a flag.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;attempted is the part that earns its place. With rerank scores attached, the human can tell a knowledge gap (nothing relevant existed) from a retrieval miss (something relevant existed and ranked badly). Those need completely different fixes, and the distinction is invisible without the numbers.&lt;/p&gt;
&lt;h2&gt;
  
  
  Deflection is not resolution
&lt;/h2&gt;

&lt;p&gt;Deflection rate is the number that looks good on a slide. Conversations that ended without a human, divided by total conversations.&lt;/p&gt;

&lt;p&gt;A customer who gives up in frustration and closes the tab counts as a deflection. So does one who was told something wrong and believed it. Optimizing for deflection rewards an agent that is hard to escalate out of, which is the opposite of the goal.&lt;/p&gt;

&lt;p&gt;Resolution rate is the honest number, and it cannot be inferred from the transcript, because "ok thanks" is what people type both when it worked and when they have given up. It has to be collected, which is why there is a feedback endpoint and why the admin endpoint reports both numbers side by side. The gap between them is the interesting part.&lt;/p&gt;

&lt;p&gt;The other thing the per-message metadata buys is the docs backlog. Every turn stores its confidence band and condensed question:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="err"&gt;meta:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;intent:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;condensed.intent&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;confidence:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;retrieval.confidence&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;condensedQuestion:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;condensed.standaloneQuestion&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;topRerankScore:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;retrieval.topScore&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;escalated:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;decision.escalate&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;passageCount:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;retrieval.passages.length&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;model&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;One aggregation over the weak and none turns, grouped by intent, is a ranked list of what the documentation does not cover, in the customer's own phrasing:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="err"&gt;$match:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
      &lt;/span&gt;&lt;span class="err"&gt;role:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"assistant"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
      &lt;/span&gt;&lt;span class="nl"&gt;"meta.confidence"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;$in:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"weak"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"none"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="err"&gt;$group:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
      &lt;/span&gt;&lt;span class="err"&gt;_id:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"$meta.intent"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
      &lt;/span&gt;&lt;span class="err"&gt;count:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;$sum:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
      &lt;/span&gt;&lt;span class="err"&gt;avgTopScore:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;$avg:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"$meta.topRerankScore"&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
      &lt;/span&gt;&lt;span class="err"&gt;escalated:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;$sum:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;$cond:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"$meta.escalated"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
      &lt;/span&gt;&lt;span class="err"&gt;examples:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;$addToSet:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"$meta.condensedQuestion"&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="err"&gt;$project:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
      &lt;/span&gt;&lt;span class="err"&gt;_id:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
      &lt;/span&gt;&lt;span class="err"&gt;intent:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"$_id"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
      &lt;/span&gt;&lt;span class="err"&gt;count:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
      &lt;/span&gt;&lt;span class="err"&gt;escalated:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
      &lt;/span&gt;&lt;span class="err"&gt;avgTopScore:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;$round:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"$avgTopScore"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
      &lt;/span&gt;&lt;span class="err"&gt;examples:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;$slice:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"$examples"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;$sort:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;count:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;-1&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;},]&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Backed by { "meta.confidence": 1, "meta.intent": 1 }. This is the editorial backlog derived instead of guessed, and it is a better source of article titles than any planning meeting, because the phrasing comes from the people who could not find the answer.&lt;/p&gt;

&lt;p&gt;That aggregation is also the second payoff of one cluster. The agent's confidence signal and the analytics query are the same documents in the same database. No export job, no warehouse sync, no window where the two disagree.&lt;/p&gt;

&lt;h2&gt;
  
  
  What this lab does not solve
&lt;/h2&gt;

&lt;p&gt;The lab is deliberately not production-ready, and the gaps worth naming:&lt;/p&gt;

&lt;p&gt;customerId arrives in the request body. The tool boundary treats it as the authoritative session identity, which is the right shape, but in production that value comes from a verified session. Retrieved passages and ticket text go into the prompt as-is, so prompt injection through a hostile document is unaddressed and needs its own treatment. Transcripts are stored in the clear, and real support data needs field-level encryption, redaction, and a retention policy per jurisdiction. There is no evaluation harness, which is what you would actually need before touching any threshold in the tuning object.&lt;/p&gt;

&lt;p&gt;That last one is the honest limitation. The confidence bands are measured against the seeded corpus; every other number here is a defensible starting point rather than a measured optimum. The weights, the half-life, the tolerance of two failed turns. They are all in one file for exactly that reason:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="err"&gt;export&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;const&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;tuning&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="err"&gt;=&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;rrfK:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;60&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;weights:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="err"&gt;kbChunks:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mf"&gt;1.0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="err"&gt;kbArticles:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mf"&gt;0.7&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="err"&gt;tickets:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mf"&gt;0.5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;vectorNumCandidates:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;200&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;vectorLimit:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;40&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;keywordLimit:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;30&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;ticketLimit:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;rerankShortlist:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;topPassages:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;ticketHalfLifeDays:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;180&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;ticketMinQuality:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mf"&gt;0.7&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;confidence:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="err"&gt;strong:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mf"&gt;0.6&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="err"&gt;weak:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mf"&gt;0.45&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;maxFailedTurns:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;alwaysEscalateIntents:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="s2"&gt;"billing_dispute"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="s2"&gt;"cancellation"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="s2"&gt;"refund_request"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="s2"&gt;"data_deletion"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="s2"&gt;"legal"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="s2"&gt;"human_handoff"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;verbatimTurns:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;summarizeEveryTurns:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;anonymousSessionTtlDays:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;30&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;maxChunkSize:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1500&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="err"&gt;audienceLadder:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="err"&gt;free:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"all"&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="err"&gt;pro:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"all"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"pro"&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="err"&gt;enterprise:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"all"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"pro"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"enterprise"&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="err"&gt;;&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When these live scattered across five modules, nobody can answer "why did the agent escalate that conversation?" without reading all five.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;The retrieval pipeline is only the center of the system. Atlas Search, Atlas Vector Search, fusion, and reranking can retrieve relevant context, but a support conversation adds a different set of problems around that pipeline.&lt;/p&gt;

&lt;p&gt;What a conversation adds is a set of problems that live entirely outside retrieval. A turn that has to be rewritten before it can be embedded, and a rewriter that will invent constraints if you let it. State that has to be budgeted rather than accumulated. A second corpus that is more useful and less trustworthy than the first. An authorization boundary that only holds if it is enforced by the index. And a class of request where the correct behavior is to stop.&lt;/p&gt;

&lt;p&gt;Every one of those is a data modeling decision before it is a prompt engineering decision. The transcript layout determines whether memory scales. The filter field determines whether entitlement is a guarantee or a suggestion. The per-message metadata determines whether the docs backlog is a query or a meeting. In Atlas, all of it is the same cluster, the same aggregation language, and the same access control as the operational data the agent is reasoning about.&lt;/p&gt;

&lt;p&gt;A support agent is not a chatbot with retrieval attached. It is a system that has to know what it does not know, and know when the answer is a person.&lt;/p&gt;




&lt;p&gt;&lt;em&gt;The full lab is on GitHub at SamuelMolling/mongodb-labs/tree/main/support-chatbot, with a make smoke suite that runs offline without an Atlas cluster or API keys. The chunker, entitlement ladder, and escalation policy are pure functions, so those parts of the application can be tested independently of the external services around them.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>mongodb</category>
      <category>ai</category>
      <category>database</category>
      <category>agents</category>
    </item>
    <item>
      <title>How to Create a Vector Search Index in MongoDB</title>
      <dc:creator>MongoDB Guests</dc:creator>
      <pubDate>Mon, 19 Oct 2026 09:00:00 +0000</pubDate>
      <link>https://dev.to/mongodb/how-to-create-a-vector-search-index-in-mongodb-285f</link>
      <guid>https://dev.to/mongodb/how-to-create-a-vector-search-index-in-mongodb-285f</guid>
      <description>&lt;p&gt;&lt;em&gt;This tutorial was written by &lt;a href="https://www.linkedin.com/in/damilola-oladele-85310275/?isSelfProfile=false" rel="noopener noreferrer"&gt;Damilola Oladele&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;This tutorial shows you how to define, create, and verify a MongoDB Atlas Vector Search index, field by field, in Python. To give the index something real to search, you'll also build a small tool that uses AI to answer questions about your own text documents.&lt;/p&gt;

&lt;p&gt;In this tutorial, you'll learn:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;How to generate and store vector embeddings with Voyage AI's free tier.&lt;/li&gt;
&lt;li&gt;How a MongoDB Atlas Vector Search index works, field by field: dimensions, similarity, quantization, and indexing method.&lt;/li&gt;
&lt;li&gt;How to create a Vector Search index with PyMongo, and why your code should check &lt;code&gt;queryable&lt;/code&gt; instead of the status.&lt;/li&gt;
&lt;li&gt;How to verify the index with a &lt;code&gt;$vectorSearch&lt;/code&gt; query.&lt;/li&gt;
&lt;li&gt;How to use the index to generate AI-powered answers from your own documents.&lt;/li&gt;
&lt;li&gt;How to edit, monitor, and delete a Vector Search index.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You can find all the code samples for this tutorial in the &lt;a href="https://github.com/activus-d/vector-search-index-tutorial" rel="noopener noreferrer"&gt;GitHub repository&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Prerequisites
&lt;/h2&gt;

&lt;p&gt;Before you start, make sure you have the following ready:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Python 3.10 or later.&lt;/li&gt;
&lt;li&gt;A &lt;a href="https://mongodb.com/cloud/atlas/register/?utm_campaign=devrel&amp;amp;utm_source=third-party-content&amp;amp;utm_medium=cta&amp;amp;utm_content=buildrel-vsi-in-mdb-devto&amp;amp;utm_term=hugh.murray" rel="noopener noreferrer"&gt;MongoDB Atlas&lt;/a&gt; account with a free M0 cluster.&lt;/li&gt;
&lt;li&gt;Your Atlas connection string, from &lt;em&gt;Database&lt;/em&gt; &amp;gt; &lt;em&gt;Connect&lt;/em&gt; &amp;gt; &lt;em&gt;Drivers&lt;/em&gt;.&lt;/li&gt;
&lt;li&gt;Your current IP address added to the Atlas access list, from &lt;em&gt;Security&lt;/em&gt; &amp;gt; &lt;em&gt;Network Access&lt;/em&gt;.&lt;/li&gt;
&lt;li&gt;A Voyage AI model API key, created from &lt;em&gt;AI Model APIs&lt;/em&gt; in the same Atlas project as your cluster. To get the API key, follow these steps:&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;1. Sign in to your Atlas account, the same one as your M0 cluster.
2. In your Atlas project, select *AI Model APIs* from the left navigation.
3. Select *Create model API key*.
4. Give it a name, then select *Create*.
5. Copy the key immediately and store it somewhere safe. You'll add it to `.env` when you set up the project.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://ollama.com/download" rel="noopener noreferrer"&gt;Ollama&lt;/a&gt; installed on your machine.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;A small folder of your own &lt;code&gt;.txt&lt;/code&gt; files to analyze. This tutorial's GitHub repository also includes a sample set, if you would rather use those.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  What Is a MongoDB Vector Search Index and Why Do You Need One?
&lt;/h2&gt;

&lt;p&gt;Before diving into the setup, it helps to know what a vector index is.&lt;/p&gt;

&lt;p&gt;A regular MongoDB index can't answer "find documents similar in meaning to this one." It can only match exact or ranged values, not semantic closeness.&lt;/p&gt;

&lt;p&gt;A vector index solves this differently. It operates on embeddings, which are lists of numbers produced by an embedding model that capture the meaning of a piece of text. Two passages with similar meaning produce embeddings that sit close together in that number space, even if they don't share a single word.&lt;/p&gt;

&lt;p&gt;At a high level, MongoDB Vector Search performs an approximate nearest neighbor search over these embeddings.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;mongot&lt;/code&gt; is the separate process that Atlas uses to build and serve Search and Vector Search indexes. It's distinct from &lt;code&gt;mongod&lt;/code&gt;, the process that stores your documents. &lt;code&gt;mongot&lt;/code&gt; builds and serves the index in the background. That's why "created" and "queryable" are two different moments for a Vector Search index. This tutorial covers that in depth later, when you create one.&lt;/p&gt;

&lt;p&gt;The rest of this tutorial follows one path. Embed and store your documents first, then build the index on top of those stored embeddings.&lt;/p&gt;

&lt;h2&gt;
  
  
  Set Up the Project and Connect to Atlas
&lt;/h2&gt;

&lt;p&gt;This section prepares the local language model, your Python environment, and the files that connect your code to Atlas.&lt;/p&gt;

&lt;p&gt;Create a project folder and move into it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;mkdir &lt;/span&gt;vector-search-index-tutorial
&lt;span class="nb"&gt;cd &lt;/span&gt;vector-search-index-tutorial
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Pull the language model
&lt;/h3&gt;

&lt;p&gt;Ollama runs the language model on your own machine, so no request leaves your computer.&lt;/p&gt;

&lt;p&gt;Confirm Ollama is installed:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;ollama &lt;span class="nt"&gt;--version&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you use the Ollama desktop application, open it before continuing. If you use Ollama from the command line instead, start the server in its own terminal:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;ollama serve
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Leave that terminal running. Open a second terminal, then pull the model:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;cd &lt;/span&gt;vector-search-index-tutorial
ollama pull llama3.2:3b
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Confirm the pull succeeded:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;ollama list
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;llama3.2:3b&lt;/code&gt; should appear in the list.&lt;/p&gt;

&lt;h3&gt;
  
  
  Create a virtual environment
&lt;/h3&gt;

&lt;p&gt;Create a virtual environment, then activate it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;python3 &lt;span class="nt"&gt;-m&lt;/span&gt; venv venv
&lt;span class="nb"&gt;source &lt;/span&gt;venv/bin/activate
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;On Windows, create it with &lt;code&gt;python -m venv venv&lt;/code&gt; and activate it with &lt;code&gt;venv\Scripts\activate&lt;/code&gt; instead.&lt;/p&gt;

&lt;h3&gt;
  
  
  Install the packages
&lt;/h3&gt;

&lt;p&gt;Install the tutorial's dependencies:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;pip &lt;span class="nb"&gt;install &lt;/span&gt;pymongo voyageai ollama python-dotenv
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;ollama&lt;/code&gt; package you installed with the preceding command is the Python client library that calls the Ollama application you already set up. It's a separate install from the application itself, the same way &lt;code&gt;pymongo&lt;/code&gt; is the Python client for MongoDB rather than MongoDB itself.&lt;/p&gt;

&lt;h3&gt;
  
  
  Add your connection details to an environment file
&lt;/h3&gt;

&lt;p&gt;Create a file named &lt;code&gt;.env&lt;/code&gt; in your project folder, and add the following to it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;MONGODB_URI="&amp;lt;your-connection-string&amp;gt;"
VOYAGE_API_KEY="&amp;lt;your-voyage-api-key&amp;gt;"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Replace the placeholders with their actual values. &lt;code&gt;python-dotenv&lt;/code&gt; loads both into your environment at runtime.&lt;/p&gt;

&lt;h3&gt;
  
  
  Create the configuration file
&lt;/h3&gt;

&lt;p&gt;Create a &lt;code&gt;config.py&lt;/code&gt; file and add the following code, which holds your project's constants and loads &lt;code&gt;.env&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;os&lt;/span&gt;

&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;dotenv&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;load_dotenv&lt;/span&gt;

&lt;span class="nf"&gt;load_dotenv&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;

&lt;span class="n"&gt;APP_NAME&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;devrel-tutorial-python-vectorsearch-content&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;
&lt;span class="n"&gt;MONGODB_URI&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;os&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;environ&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;MONGODB_URI&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="n"&gt;VOYAGE_API_KEY&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;os&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;environ&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;VOYAGE_API_KEY&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

&lt;span class="n"&gt;DATABASE_NAME&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;document_insights&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;
&lt;span class="n"&gt;COLLECTION_NAME&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;chunks&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;
&lt;span class="n"&gt;EMBEDDING_MODEL&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;voyage-4&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;
&lt;span class="n"&gt;EMBEDDING_DIMENSIONS&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;1024&lt;/span&gt;
&lt;span class="n"&gt;VECTOR_INDEX_NAME&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;vector_index&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Create the database access file
&lt;/h3&gt;

&lt;p&gt;Create a &lt;code&gt;db.py&lt;/code&gt; file and add the following code, which defines &lt;code&gt;get_client()&lt;/code&gt; and &lt;code&gt;get_collection()&lt;/code&gt;, which are helpers every other file reuses:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;functools&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;cache&lt;/span&gt;

&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;pymongo&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;MongoClient&lt;/span&gt;

&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;config&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;APP_NAME&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;COLLECTION_NAME&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;DATABASE_NAME&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;MONGODB_URI&lt;/span&gt;


&lt;span class="nd"&gt;@cache&lt;/span&gt;
&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;get_client&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nc"&gt;MongoClient&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;MONGODB_URI&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;appname&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;APP_NAME&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;get_collection&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt;
    &lt;span class="n"&gt;client&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;get_client&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;client&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;DATABASE_NAME&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="n"&gt;COLLECTION_NAME&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A &lt;code&gt;MongoClient&lt;/code&gt; manages its own pool of connections, so a program needs only one. The &lt;code&gt;@cache&lt;/code&gt; decorator makes &lt;code&gt;get_client()&lt;/code&gt; create the client on its first call and return the same client on every later call.&lt;/p&gt;

&lt;h2&gt;
  
  
  Generate Embeddings with Voyage AI
&lt;/h2&gt;

&lt;p&gt;An embed call takes text in and returns a fixed-length vector out. This tutorial splits each document into smaller passages, called chunks, and embeds each chunk. The next section covers the splitting.&lt;/p&gt;

&lt;p&gt;This tutorial uses &lt;code&gt;voyage-4&lt;/code&gt;, which defaults to 1,024 dimensions. Voyage models also support flexible output sizes. This is useful if you later want to trade size for speed. This tutorial sticks with the default.&lt;/p&gt;

&lt;p&gt;Each embed call also sets an &lt;code&gt;input_type&lt;/code&gt;. Voyage applies a different task-specific prompt depending on whether text is being stored (&lt;code&gt;input_type="document"&lt;/code&gt;) or used as a search query (&lt;code&gt;input_type="query"&lt;/code&gt;). Document and query embeddings still land in the same embedding space, so they stay comparable for retrieval either way. The different prompts exist only to improve retrieval quality.&lt;/p&gt;

&lt;p&gt;Accounts without a payment method on file get reduced rate limits: 3 requests per minute and 10,000 tokens per minute. A single document's full chunk list can easily exceed that in a single call, so &lt;code&gt;embed_documents()&lt;/code&gt; needs to batch requests and pace itself.&lt;/p&gt;

&lt;p&gt;Create an &lt;code&gt;embeddings.py&lt;/code&gt; file and add the following code to it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;time&lt;/span&gt;

&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;voyageai&lt;/span&gt;

&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;config&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;EMBEDDING_MODEL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;VOYAGE_API_KEY&lt;/span&gt;

&lt;span class="n"&gt;vo&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;voyageai&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Client&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;api_key&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;VOYAGE_API_KEY&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="n"&gt;BATCH_SIZE&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;30&lt;/span&gt;
&lt;span class="n"&gt;SECONDS_BETWEEN_CALLS&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;21&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;embed_documents&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;texts&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;embeddings&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;start&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nf"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nf"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;texts&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt; &lt;span class="n"&gt;BATCH_SIZE&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="n"&gt;batch&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;texts&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;start&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;start&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;BATCH_SIZE&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
        &lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;vo&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;embed&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;batch&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;EMBEDDING_MODEL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;input_type&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;document&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;embeddings&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;extend&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;embeddings&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;time&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;sleep&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;SECONDS_BETWEEN_CALLS&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;embeddings&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;embed_query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;vo&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;embed&lt;/span&gt;&lt;span class="p"&gt;([&lt;/span&gt;&lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;EMBEDDING_MODEL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;input_type&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;query&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;embeddings&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;embed_documents()&lt;/code&gt; splits a chunk list into batches of 30. That stays well under the 10,000-token limit, even at the free tier. It also pauses 21 seconds after every call. This keeps the entire ingest run under 3 requests per minute, across every file, not just one.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;embed_query()&lt;/code&gt; embeds a single question at search time. One small request never comes close to either limit.&lt;/p&gt;

&lt;h2&gt;
  
  
  Split and Store Documents With Their Embeddings
&lt;/h2&gt;

&lt;p&gt;Chunks retrieve better than whole documents. A model matches a question to a focused passage more precisely than against an entire file. A chunk also lets a citation point to a specific passage rather than a whole document. This tutorial keeps chunking simple. For a deeper look at chunking, see &lt;a href="https://dev.to/mongodb/how-to-build-an-ai-pdf-analyzer-with-mongodb-rag-and-ollama-47j6"&gt;How to Build an AI PDF Analyzer with MongoDB, RAG, and Ollama&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Each stored chunk ends up shaped like this, once its embedding is attached:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"source_file"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"notes.txt"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"chunk_index"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"text"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"..."&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"embedding"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mf"&gt;0.0128&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mf"&gt;-0.0341&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"..."&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Add the following &lt;code&gt;save_chunks()&lt;/code&gt; helper to &lt;code&gt;db.py&lt;/code&gt;, after the two functions already there:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;save_chunks&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;filename&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;chunks&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;embeddings&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;collection&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;get_collection&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;index&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;chunk&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;embedding&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nf"&gt;enumerate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;zip&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;chunks&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;embeddings&lt;/span&gt;&lt;span class="p"&gt;)):&lt;/span&gt;
        &lt;span class="n"&gt;collection&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;update_one&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;source_file&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;filename&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;chunk_index&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;index&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
            &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;$set&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                    &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;source_file&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;filename&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                    &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;chunk_index&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;index&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                    &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;text&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;chunk&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                    &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;embedding&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;embedding&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="p"&gt;}&lt;/span&gt;
            &lt;span class="p"&gt;},&lt;/span&gt;
            &lt;span class="n"&gt;upsert&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="bp"&gt;True&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;collection&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;delete_many&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;source_file&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;filename&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;chunk_index&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;$gte&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nf"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;chunks&lt;/span&gt;&lt;span class="p"&gt;)}})&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The filter matches on &lt;code&gt;source_file&lt;/code&gt; and &lt;code&gt;chunk_index&lt;/code&gt; to identify each chunk. Because &lt;code&gt;upsert=True&lt;/code&gt;, rerunning the ingest script updates the matching chunk rather than inserting a duplicate. The final &lt;code&gt;delete_many()&lt;/code&gt; removes chunks left over from an earlier run, for a file that now produces fewer chunks than before.&lt;/p&gt;

&lt;p&gt;Create an &lt;code&gt;ingest.py&lt;/code&gt; file and add the following code to it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;os&lt;/span&gt;

&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;db&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;save_chunks&lt;/span&gt;
&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;embeddings&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;embed_documents&lt;/span&gt;

&lt;span class="n"&gt;SAMPLE_DOCS_DIR&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;sample_documents&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;
&lt;span class="n"&gt;CHUNK_SIZE&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;900&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;chunk_text&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;paragraphs&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;paragraph&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;strip&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;paragraph&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;split&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="se"&gt;\n\n&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;paragraph&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;strip&lt;/span&gt;&lt;span class="p"&gt;()]&lt;/span&gt;
    &lt;span class="n"&gt;chunks&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;
    &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="sh"&gt;""&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;paragraph&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;paragraphs&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="nf"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="nf"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;paragraph&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;CHUNK_SIZE&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;chunks&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;paragraph&lt;/span&gt;
        &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="se"&gt;\n\n&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;paragraph&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt; &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="n"&gt;paragraph&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;chunks&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;chunks&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;ingest_documents&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;filename&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nf"&gt;sorted&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;os&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;listdir&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;SAMPLE_DOCS_DIR&lt;/span&gt;&lt;span class="p"&gt;)):&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="n"&gt;filename&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;endswith&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;.txt&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
            &lt;span class="k"&gt;continue&lt;/span&gt;

        &lt;span class="n"&gt;path&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;os&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;path&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;join&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;SAMPLE_DOCS_DIR&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;filename&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;with&lt;/span&gt; &lt;span class="nf"&gt;open&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;path&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;encoding&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;utf-8&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="nb"&gt;file&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;text&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;file&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;read&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;

        &lt;span class="n"&gt;chunks&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;chunk_text&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;embeddings&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;embed_documents&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;chunks&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="nf"&gt;save_chunks&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;filename&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;chunks&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;embeddings&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="nf"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Ingested &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="nf"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;chunks&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s"&gt; chunks from &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;filename&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s"&gt;.&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;


&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;__name__&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;__main__&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="nf"&gt;ingest_documents&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;chunk_text()&lt;/code&gt; splits a file on blank lines into paragraphs, then groups whole paragraphs into chunks of up to &lt;code&gt;CHUNK_SIZE&lt;/code&gt; characters. A chunk never splits a word or sentence, and no text appears in two chunks. A single paragraph longer than &lt;code&gt;CHUNK_SIZE&lt;/code&gt; becomes a chunk on its own.&lt;/p&gt;

&lt;p&gt;Put a few &lt;code&gt;.txt&lt;/code&gt; files in a &lt;code&gt;sample_documents&lt;/code&gt; folder, then run the script. Keep each file to a few thousand words on the free trial tier, so a single file's chunks fit in one paced batch. You can find sample documents in the &lt;a href="https://github.com/activus-d/vector-search-index-tutorial" rel="noopener noreferrer"&gt;GitHub repository&lt;/a&gt; which hosts this tutorial's code samples.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;python ingest.py
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You should get a response similar to the following in your terminal:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;Ingested 25 chunks from a_modest_proposal.txt.
Ingested 13 chunks from declaration_of_independence.txt.
Ingested 17 chunks from the_cask_of_amontillado.txt.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can also confirm that the chunks landed in Atlas using the Atlas UI or with a quick count query in &lt;code&gt;mongosh&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Create the Vector Search Index
&lt;/h2&gt;

&lt;p&gt;A MongoDB Vector Search index tells &lt;code&gt;mongot&lt;/code&gt; how to organize your stored embeddings for fast similarity search. Instead of scanning every document, &lt;code&gt;mongot&lt;/code&gt; builds a searchable structure over the embedding field. The index definition controls how &lt;code&gt;mongot&lt;/code&gt; builds and searches that structure.&lt;/p&gt;

&lt;p&gt;The definition's &lt;code&gt;fields&lt;/code&gt; array holds one entry for each indexed field. This tutorial indexes two fields:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;embedding&lt;/code&gt;: a &lt;code&gt;vector&lt;/code&gt; field that holds each chunk's embedding.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;source_file&lt;/code&gt;: a &lt;code&gt;filter&lt;/code&gt; field that lets a query narrow results to one document.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The vector field needs the most configuration. Its &lt;code&gt;type&lt;/code&gt; is &lt;code&gt;vector&lt;/code&gt;, and its &lt;code&gt;path&lt;/code&gt; names the document field that contains the embedding:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"type"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"vector"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"path"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"embedding"&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Four more settings on the vector field control how &lt;code&gt;mongot&lt;/code&gt; stores and compares your embeddings:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;numDimensions&lt;/code&gt;: the size of each embedding.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;similarity&lt;/code&gt;: how the index measures closeness between two vectors.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;quantization&lt;/code&gt;: how much precision each stored vector keeps.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;indexingMethod&lt;/code&gt;: the structure the index searches through.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The first setting, &lt;code&gt;numDimensions&lt;/code&gt;, must exactly match the number of dimensions in your embedding model's output. This tutorial uses &lt;code&gt;voyage-4&lt;/code&gt;, which produces 1,024-dimensional embeddings. If the value doesn't match, Atlas rejects the index definition or the query fails.&lt;/p&gt;

&lt;p&gt;With the vector size set, &lt;code&gt;similarity&lt;/code&gt; decides how the index compares two vectors. It accepts one of three values:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;euclidean&lt;/code&gt;: measures the distance between vectors.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;cosine&lt;/code&gt;: measures the angle between vectors.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;dotProduct&lt;/code&gt;: suits normalized vectors, and is what MongoDB's own reference examples pair with Voyage embeddings.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This tutorial follows that pairing and uses &lt;code&gt;dotProduct&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Where &lt;code&gt;similarity&lt;/code&gt; shapes how vectors are compared, &lt;code&gt;quantization&lt;/code&gt; shapes how precisely they're stored. &lt;code&gt;quantization&lt;/code&gt; accepts one of three values:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;none&lt;/code&gt;: full precision, the default.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;scalar&lt;/code&gt;: trades some precision for lower memory use and faster search.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;binary&lt;/code&gt;: compresses much further, at a greater cost to precision.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This tutorial uses &lt;code&gt;scalar&lt;/code&gt;, since it cuts resource usage without binary's much more aggressive compression. &lt;code&gt;scalar&lt;/code&gt; isn't always the right default. The best setting depends on your own retrieval-quality needs.&lt;/p&gt;

&lt;p&gt;The last setting, &lt;code&gt;indexingMethod&lt;/code&gt;, decides how the index finds the closest vectors. It accepts &lt;code&gt;hnsw&lt;/code&gt;, the default graph-based method, or &lt;code&gt;flat&lt;/code&gt;. HNSW builds a multi-layered graph that connects each embedding to its nearest neighbors. A query then skips most of the collection and jumps straight toward the closest matches.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;flat&lt;/code&gt; skips that graph and compares a query directly against every vector, which stays fast with only a few vectors to check. &lt;code&gt;flat&lt;/code&gt; is a Public Preview option built for multitenant workloads, where many tenants each have few vectors.&lt;/p&gt;

&lt;p&gt;This tutorial's collection uses the default &lt;code&gt;hnsw&lt;/code&gt;, with its default &lt;code&gt;hnswOptions&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The second entry in &lt;code&gt;fields&lt;/code&gt; indexes &lt;code&gt;source_file&lt;/code&gt; as a &lt;code&gt;filter&lt;/code&gt; field:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"type"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"filter"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"path"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"source_file"&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A field indexed as &lt;code&gt;filter&lt;/code&gt; only becomes available to filter on. It doesn't filter anything by itself. A query does the actual filtering, with a &lt;code&gt;filter&lt;/code&gt; clause in its &lt;code&gt;$vectorSearch&lt;/code&gt; stage, such as &lt;code&gt;"filter": {"source_file": {"$eq": "declaration_of_independence.txt"}}&lt;/code&gt;. That restricts a search to one document.&lt;/p&gt;

&lt;p&gt;Now create a &lt;code&gt;create_index.py&lt;/code&gt; file and add the following code, which combines both entries and their settings into one index definition:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;time&lt;/span&gt;

&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;pymongo.operations&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;SearchIndexModel&lt;/span&gt;

&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;config&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;EMBEDDING_DIMENSIONS&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;VECTOR_INDEX_NAME&lt;/span&gt;
&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;db&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;get_collection&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;create_vector_index&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt;
    &lt;span class="n"&gt;collection&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;get_collection&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;

    &lt;span class="n"&gt;search_index_model&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;SearchIndexModel&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="n"&gt;definition&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;fields&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
                &lt;span class="p"&gt;{&lt;/span&gt;
                    &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;type&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;vector&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                    &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;path&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;embedding&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                    &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;numDimensions&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;EMBEDDING_DIMENSIONS&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                    &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;similarity&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;dotProduct&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                    &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;quantization&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;scalar&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="p"&gt;},&lt;/span&gt;
                &lt;span class="p"&gt;{&lt;/span&gt;
                    &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;type&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;filter&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                    &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;path&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;source_file&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="p"&gt;},&lt;/span&gt;
            &lt;span class="p"&gt;]&lt;/span&gt;
        &lt;span class="p"&gt;},&lt;/span&gt;
        &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;VECTOR_INDEX_NAME&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="nb"&gt;type&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;vectorSearch&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;collection&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;create_search_index&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;search_index_model&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="nf"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Creating index &lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;. Waiting for it to become queryable...&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="bp"&gt;True&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;indexes&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;list&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;collection&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;list_search_indexes&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;indexes&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="n"&gt;indexes&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;queryable&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
            &lt;span class="k"&gt;break&lt;/span&gt;
        &lt;span class="n"&gt;time&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;sleep&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="nf"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Index &lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt; is ready to query.&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;


&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;__name__&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;__main__&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="nf"&gt;create_vector_index&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run the script:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;python create_index.py
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The script returns almost immediately, but the index isn't searchable until Atlas finishes building it in the background. Build time depends on your collection, deployment, and current cluster conditions, so this script polls for &lt;code&gt;queryable&lt;/code&gt; instead of assuming a fixed wait.&lt;/p&gt;

&lt;p&gt;While it builds, &lt;code&gt;list_search_indexes()&lt;/code&gt; reports one of these status values:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Status&lt;/th&gt;
&lt;th&gt;Meaning&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;PENDING&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Not yet started. Always non-queryable.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;BUILDING&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Building or rebuilding. May or may not be queryable.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;READY&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Ready to query. Always queryable.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;STALE&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Queryable, but has stopped replicating and may serve outdated data.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;FAILED&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;The build failed. May or may not be queryable.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;DELETING&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Being deleted. Always non-queryable.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;DOES_NOT_EXIST&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;The index doesn't exist. Always non-queryable.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;&lt;code&gt;queryable&lt;/code&gt; is the field your application code should check. &lt;code&gt;BUILDING&lt;/code&gt; and &lt;code&gt;FAILED&lt;/code&gt; don't tell you whether the index is currently queryable.&lt;/p&gt;

&lt;p&gt;M0 clusters allow a maximum of three Search and Vector Search indexes combined. This tutorial creates only one index, so it stays within that limit.&lt;/p&gt;

&lt;h2&gt;
  
  
  Verify the Index With a Vector Search Query
&lt;/h2&gt;

&lt;p&gt;It's important to check your index to be sure it works before you build anything on top of it.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;limit&lt;/code&gt; can't exceed &lt;code&gt;numCandidates&lt;/code&gt; in a &lt;code&gt;$vectorSearch&lt;/code&gt; query, and MongoDB recommends setting &lt;code&gt;numCandidates&lt;/code&gt; to at least 20 times &lt;code&gt;limit&lt;/code&gt; for good recall. Use that ratio here instead of an arbitrary pair of numbers.&lt;/p&gt;

&lt;p&gt;Create a &lt;code&gt;search.py&lt;/code&gt; file and add the following code to it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;config&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;VECTOR_INDEX_NAME&lt;/span&gt;
&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;db&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;get_collection&lt;/span&gt;
&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;embeddings&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;embed_query&lt;/span&gt;

&lt;span class="n"&gt;NUM_CANDIDATES_MULTIPLIER&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;20&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;search&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;question&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;limit&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;collection&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;get_collection&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="n"&gt;query_vector&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;embed_query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;question&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="n"&gt;pipeline&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
        &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;$vectorSearch&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;index&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;VECTOR_INDEX_NAME&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;path&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;embedding&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;queryVector&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;query_vector&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;numCandidates&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;limit&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;NUM_CANDIDATES_MULTIPLIER&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;limit&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;limit&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="p"&gt;},&lt;/span&gt;
        &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;$project&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;_id&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;text&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;source_file&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;chunk_index&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;score&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;$meta&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;vectorSearchScore&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="p"&gt;},&lt;/span&gt;
    &lt;span class="p"&gt;]&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nf"&gt;list&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;collection&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;aggregate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;pipeline&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;


&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;__name__&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;__main__&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nf"&gt;search&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;What unalienable rights does the Declaration list?&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="nf"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;source_file&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s"&gt; (chunk &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;chunk_index&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s"&gt;, score &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;score&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="si"&gt;:&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s"&gt;)&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="nf"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;text&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;][:&lt;/span&gt;&lt;span class="mi"&gt;200&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt;
        &lt;span class="nf"&gt;print&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run the script:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;python search.py
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The script searches with a sample question about the Declaration of Independence. The top matching chunks print with their source file, chunk number, and score. This confirms the index returns results. To test a question about your own documents, edit the string passed to &lt;code&gt;search()&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Answer Questions About Your Documents With AI
&lt;/h2&gt;

&lt;p&gt;The index now powers a small interactive tool.&lt;/p&gt;

&lt;p&gt;The tool embeds your question and uses &lt;code&gt;$vectorSearch&lt;/code&gt; to retrieve the top matching chunks. It passes those chunks to a local Ollama model, which generates an answer using only the retrieved text. Ollama returns the answer text, while the application builds the citation list from each retrieved chunk's &lt;code&gt;source_file&lt;/code&gt; and &lt;code&gt;chunk_index&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Create an &lt;code&gt;ask.py&lt;/code&gt; file and add the following code to it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;ollama&lt;/span&gt;

&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;config&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;VECTOR_INDEX_NAME&lt;/span&gt;
&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;db&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;get_collection&lt;/span&gt;
&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;embeddings&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;embed_query&lt;/span&gt;

&lt;span class="n"&gt;OLLAMA_MODEL&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;llama3.2:3b&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;
&lt;span class="n"&gt;NUM_CANDIDATES_MULTIPLIER&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;20&lt;/span&gt;
&lt;span class="n"&gt;RESULT_LIMIT&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;retrieve&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;question&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;collection&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;get_collection&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="n"&gt;query_vector&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;embed_query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;question&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="n"&gt;pipeline&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
        &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;$vectorSearch&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;index&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;VECTOR_INDEX_NAME&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;path&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;embedding&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;queryVector&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;query_vector&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;numCandidates&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;RESULT_LIMIT&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;NUM_CANDIDATES_MULTIPLIER&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;limit&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;RESULT_LIMIT&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="p"&gt;},&lt;/span&gt;
        &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;$project&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;_id&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;text&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;source_file&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;chunk_index&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;}},&lt;/span&gt;
    &lt;span class="p"&gt;]&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nf"&gt;list&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;collection&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;aggregate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;pipeline&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;build_prompt&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;question&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;chunks&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;ordered&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;sorted&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;chunks&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="k"&gt;lambda&lt;/span&gt; &lt;span class="n"&gt;chunk&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;chunk&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;source_file&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt; &lt;span class="n"&gt;chunk&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;chunk_index&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;]))&lt;/span&gt;
    &lt;span class="n"&gt;context&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="se"&gt;\n\n&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;join&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;[&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;chunk&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;source_file&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s"&gt;, chunk &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;chunk&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;chunk_index&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s"&gt;]&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;chunk&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;text&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;chunk&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;ordered&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="nf"&gt;return &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Answer the question using only the context below. &lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;
        &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;If the context doesn&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;t contain the answer, say so.&lt;/span&gt;&lt;span class="se"&gt;\n\n&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;
        &lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Context:&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;context&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="se"&gt;\n\n&lt;/span&gt;&lt;span class="s"&gt;Question: &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;question&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;ask&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;question&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;chunks&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;retrieve&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;question&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;prompt&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;build_prompt&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;question&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;chunks&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="n"&gt;response&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;ollama&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;chat&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;OLLAMA_MODEL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="n"&gt;messages&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;[{&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;role&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;user&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;content&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;prompt&lt;/span&gt;&lt;span class="p"&gt;}],&lt;/span&gt;
        &lt;span class="n"&gt;options&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;temperature&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;answer&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;message&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;][&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;content&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

    &lt;span class="n"&gt;citations&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;chunk&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;source_file&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s"&gt; (chunk &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;chunk&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;chunk_index&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s"&gt;)&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;chunk&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;chunks&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;answer&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;citations&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt;
    &lt;span class="nf"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Ask a question about your documents. Type &lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;quit&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt; to exit.&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="bp"&gt;True&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;question&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;input&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;&amp;gt; &lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;strip&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;question&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;lower&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;quit&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;""&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
            &lt;span class="k"&gt;break&lt;/span&gt;

        &lt;span class="n"&gt;answer&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;citations&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;ask&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;question&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="nf"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;answer&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="nf"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Sources:&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;citation&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;citations&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="nf"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;  - &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;citation&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="nf"&gt;print&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;


&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;__name__&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;__main__&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;$vectorSearch&lt;/code&gt; returns chunks ordered by similarity score, so &lt;code&gt;build_prompt()&lt;/code&gt; sorts them back into document order. The model then reads each passage in the sequence it appears in the source. The &lt;code&gt;temperature&lt;/code&gt; option set to &lt;code&gt;0&lt;/code&gt; makes the model return the same wording for the same question on every run.&lt;/p&gt;

&lt;p&gt;Make sure Ollama is running, then run the script:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;python ask.py
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Type a question at the prompt, then press Enter. Try "What unalienable rights does the Declaration list?" Then try "What wine does the narrator say he bought, and why does he want Fortunato's opinion?" You should get an answer, along with a &lt;code&gt;Sources&lt;/code&gt; list naming the file and chunk behind it.&lt;/p&gt;

&lt;p&gt;The quality of the answer depends first on which chunks the index retrieves. The Vector Search index controls how MongoDB searches the embeddings. Its dimensions, similarity function, and filtering configuration determine how those vectors are indexed and compared.&lt;/p&gt;

&lt;p&gt;Other parts of the pipeline also affect the result:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Chunking determines what information each embedding represents.&lt;/li&gt;
&lt;li&gt;Query formulation determines what the application searches for.&lt;/li&gt;
&lt;li&gt;Prompt construction determines how the retrieved text is presented to the model.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The questions you ask matter too. If a question requires more of a document than &lt;code&gt;RESULT_LIMIT&lt;/code&gt; chunks cover, the retrieved context may not contain enough information to support a complete answer. The prompt tells the model to use only the given context, but a small local model doesn't always follow that instruction reliably. It can fill a gap with a plausible-sounding guess instead of admitting the context doesn't cover it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Edit, Monitor, and Delete the Index
&lt;/h2&gt;

&lt;p&gt;An index needs care beyond the moment you create it. Create a &lt;code&gt;manage_index.py&lt;/code&gt; file and add the following code to it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;config&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;EMBEDDING_DIMENSIONS&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;VECTOR_INDEX_NAME&lt;/span&gt;
&lt;span class="kn"&gt;from&lt;/span&gt; &lt;span class="n"&gt;db&lt;/span&gt; &lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="n"&gt;get_collection&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;update_quantization&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;quantization&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;none&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;collection&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;get_collection&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="n"&gt;definition&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;fields&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
            &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;type&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;vector&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;path&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;embedding&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;numDimensions&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;EMBEDDING_DIMENSIONS&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;similarity&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;dotProduct&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;quantization&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;quantization&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="p"&gt;},&lt;/span&gt;
            &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;type&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;filter&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;path&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;source_file&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;
        &lt;span class="p"&gt;]&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="n"&gt;collection&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;update_search_index&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;VECTOR_INDEX_NAME&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;definition&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="nf"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Updated &lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;VECTOR_INDEX_NAME&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt; to use quantization=&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;quantization&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;.&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;show_index_status&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt;
    &lt;span class="n"&gt;collection&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;get_collection&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;index&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;collection&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;list_search_indexes&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt;
        &lt;span class="nf"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;index&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;name&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s"&gt;: status=&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;index&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;status&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s"&gt;, queryable=&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;index&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;queryable&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;delete_index&lt;/span&gt;&lt;span class="p"&gt;():&lt;/span&gt;
    &lt;span class="n"&gt;collection&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;get_collection&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="n"&gt;collection&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;drop_search_index&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;VECTOR_INDEX_NAME&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="nf"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;Deleted &lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;VECTOR_INDEX_NAME&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="sh"&gt;'&lt;/span&gt;&lt;span class="s"&gt;.&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;


&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;__name__&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;__main__&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="nf"&gt;show_index_status&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;update_search_index()&lt;/code&gt; changes settings like &lt;code&gt;quantization&lt;/code&gt; after the fact. &lt;code&gt;list_search_indexes()&lt;/code&gt; checks status or definition at any time. The status table shown earlier explains what each value means. &lt;code&gt;drop_search_index()&lt;/code&gt; deletes the index outright.&lt;/p&gt;

&lt;p&gt;Run the script to print the index's current status:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;python manage_index.py
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You will get a response similar to the following in your terminal:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;vector_index: &lt;span class="nv"&gt;status&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;READY, &lt;span class="nv"&gt;queryable&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;True
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To edit or delete the index instead, replace &lt;code&gt;show_index_status()&lt;/code&gt; in the &lt;code&gt;__main__&lt;/code&gt; block with &lt;code&gt;update_quantization()&lt;/code&gt; or &lt;code&gt;delete_index()&lt;/code&gt;, then run the script again.&lt;/p&gt;

&lt;p&gt;An edited index triggers a rebuild in the background. The old index keeps serving queries until the rebuild finishes, so an edit isn't a service interruption.&lt;/p&gt;

&lt;p&gt;A deleted index is no longer available, so &lt;code&gt;search.py&lt;/code&gt; and &lt;code&gt;ask.py&lt;/code&gt; stop working until you run &lt;code&gt;create_index.py&lt;/code&gt; again.&lt;/p&gt;

&lt;h2&gt;
  
  
  Key Takeaways
&lt;/h2&gt;

&lt;p&gt;Here's what to take away from this tutorial:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A vector index needs at least one &lt;code&gt;vector&lt;/code&gt;-type field, with &lt;code&gt;numDimensions&lt;/code&gt; matching your embedding model and a &lt;code&gt;similarity&lt;/code&gt; function suited to it. Everything else (&lt;code&gt;quantization&lt;/code&gt;, &lt;code&gt;indexingMethod&lt;/code&gt;, &lt;code&gt;filter&lt;/code&gt; fields) is tunable on top of that baseline.&lt;/li&gt;
&lt;li&gt;Index creation and index queryability are two different moments. Always check &lt;code&gt;queryable&lt;/code&gt; before querying a brand-new index.&lt;/li&gt;
&lt;li&gt;Free M0 clusters fully support MongoDB Vector Search, capped at three Search and Vector Search indexes combined.&lt;/li&gt;
&lt;li&gt;Voyage AI's free tier (200 million tokens, no credit card) and a local Ollama model keep this tutorial's entire pipeline free.&lt;/li&gt;
&lt;li&gt;The quality of any AI-generated answer is bounded by what the vector index retrieves. That's why the index's own configuration is worth understanding in depth.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You can find all the code samples for this tutorial in the &lt;a href="https://github.com/activus-d/vector-search-index-tutorial" rel="noopener noreferrer"&gt;GitHub repository&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Further Reading
&lt;/h2&gt;

&lt;p&gt;For more on the concepts this tutorial covers:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://www.mongodb.com/docs/vector-search/indexes/vector-search-type/?utm_campaign=devrel&amp;amp;utm_source=third-party-content&amp;amp;utm_medium=cta&amp;amp;utm_content=buildrel-vsi-in-mdb-devto&amp;amp;utm_term=hugh.murray" rel="noopener noreferrer"&gt;How to Index Fields for Vector Search&lt;/a&gt;: the full field reference this tutorial draws from.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://www.mongodb.com/docs/voyageai/models/?utm_campaign=devrel&amp;amp;utm_source=third-party-content&amp;amp;utm_medium=cta&amp;amp;utm_content=buildrel-vsi-in-mdb-devto&amp;amp;utm_term=hugh.murray" rel="noopener noreferrer"&gt;Voyage AI Embedding and Reranking Models Overview&lt;/a&gt;: for choosing a different embedding model or dimension size.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://dev.to/mongodb/how-to-build-an-ai-pdf-analyzer-with-mongodb-rag-and-ollama-47j6"&gt;How to Build an AI PDF Analyzer with MongoDB, RAG, and Ollama&lt;/a&gt;: a full retrieval-augmented Q&amp;amp;A pipeline built on the same core ideas.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>ai</category>
      <category>mongodb</category>
      <category>python</category>
      <category>database</category>
    </item>
    <item>
      <title>Leveraging Skills in a MongoDB MCP Agent</title>
      <dc:creator>MongoDB Guests</dc:creator>
      <pubDate>Fri, 16 Oct 2026 09:00:00 +0000</pubDate>
      <link>https://dev.to/mongodb/leveraging-skills-in-a-mongodb-mcp-agent-4dc0</link>
      <guid>https://dev.to/mongodb/leveraging-skills-in-a-mongodb-mcp-agent-4dc0</guid>
      <description>&lt;p&gt;&lt;em&gt;This article was written by &lt;a href="https://www.linkedin.com/in/jackwoehr/" rel="noopener noreferrer"&gt;Jack Woehr&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;a href="http://www.softwoehr.com/" rel="noopener noreferrer"&gt;SoftWoehr LLC&lt;/a&gt; - &lt;a href="https://www.seidengroup.com/" rel="noopener noreferrer"&gt;Seiden Group&lt;/a&gt; - &lt;a href="https://procern.com/" rel="noopener noreferrer"&gt;ProCern Technology Solutions&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;




&lt;h1&gt;
  
  
  Skills in a ReAct (Reason - Act) Agent for MongoDB
&lt;/h1&gt;

&lt;p&gt;In this article, we describe our open-source &lt;a href="https://github.com/jwoehr/mymongodbmcpagent" rel="noopener noreferrer"&gt;mymongodbmcpagent&lt;/a&gt; implementing a ReAct (Reason - Act) agent leveraging the &lt;a href="https://github.com/mongodb-js/mongodb-mcp-server" rel="noopener noreferrer"&gt;MongoDB MCP&lt;/a&gt; Server and the &lt;a href="https://github.com/mongodb/agent-skills" rel="noopener noreferrer"&gt;MongoDB agent-skills package&lt;/a&gt;. Our code also provides a chat interface so that you can talk to your MongoDB instance and offer queries whose answers require strategies derived from the skills package, leading to multiple exchanges between the agent and the LLM.&lt;/p&gt;

&lt;h1&gt;
  
  
  Evolving from a one-pass MongoDB Server Agent
&lt;/h1&gt;

&lt;p&gt;If you read my previous article, &lt;a href="https://dev.to/mongodb/a-simple-mongodb-mcp-server-agent-na7"&gt;A Simple MongoDB Server Agent&lt;/a&gt;, you saw an agent/chat pair using an LLM provider to answer one-pass queries to MongoDB via the &lt;a href="https://github.com/mongodb-js/mongodb-mcp-server" rel="noopener noreferrer"&gt;MongoDB MCP Server&lt;/a&gt;. I used that architecture to add MongoDB capabilities to a multi-agent dashboard that connects to many different projects I work on.&lt;/p&gt;

&lt;h2&gt;
  
  
  Reuse the scripting from the earlier article
&lt;/h2&gt;

&lt;p&gt;Keep a link to that earlier article because its associated code on GitHub includes a nice script and &lt;code&gt;.env.example&lt;/code&gt; to start the MongoDB MCP server, which can be used with the code we're presenting in this article.&lt;/p&gt;

&lt;h2&gt;
  
  
  Prerequisite
&lt;/h2&gt;

&lt;p&gt;As in the earlier article, we assume you have a &lt;a href="https://www.mongodb.com/products/platform/atlas-database/?utm_campaign=devrel&amp;amp;utm_source=third-party-content&amp;amp;utm_medium=cta&amp;amp;utm_content=buildrel-leveraging-mdb-mcp-devto&amp;amp;utm_term=hugh.murray" rel="noopener noreferrer"&gt;MongoDB Atlas&lt;/a&gt; Cluster with some sample data to query.&lt;/p&gt;

&lt;h2&gt;
  
  
  Getting Started
&lt;/h2&gt;

&lt;p&gt;A full &lt;a href="https://github.com/jwoehr/mymongodbmcpagent/blob/main/GettingStarted.md" rel="noopener noreferrer"&gt;Getting Started document&lt;/a&gt; is available in the repository to help you set up.&lt;/p&gt;

&lt;h2&gt;
  
  
  Add Skills to MCP
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;MCP tools are&lt;/strong&gt; … tools! An LLM has no arms and legs. All it can do is talk, but once informed that there are tools (provided by the MCP server) and the skills to use them, it can call for the tools to be used based on its decisions.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Skills&lt;/strong&gt; are instructions for using tools to accomplish tasks that require more than one tool call. They're in text, in Markdown format, and are prompts, plain English instructions for the language model to follow. Take a look at the skills directory of the repo just mentioned.&lt;/li&gt;
&lt;li&gt;The &lt;strong&gt;Agent&lt;/strong&gt; mediates between

&lt;ul&gt;
&lt;li&gt;the User&lt;/li&gt;
&lt;li&gt;the Inference Engine (the LLM)&lt;/li&gt;
&lt;li&gt;the tools and skills

&lt;ul&gt;
&lt;li&gt;loading the tools list for the LLM&lt;/li&gt;
&lt;li&gt;loading the skills list for the LLM&lt;/li&gt;
&lt;li&gt;calling the tools on behalf of the LLM&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Skills add complexity to the Agent
&lt;/h2&gt;

&lt;p&gt;Using skills requires the agent to execute a ReAct (Reasoning + Acting) loop that supports multiple LLM tool calls until it arrives at a response.&lt;/p&gt;

&lt;h3&gt;
  
  
  The enhanced ReAct loop agent
&lt;/h3&gt;

&lt;p&gt;The code for the enhanced agent and its associated chat REPL is found at &lt;a href="https://github.com/jwoehr/mymongodbmcpagent" rel="noopener noreferrer"&gt;mymongodbmcpagent&lt;/a&gt;. Pay close attention to the &lt;code&gt;.env.example&lt;/code&gt; file and create a .env file so that the agent and chat will both load and function as expected.&lt;/p&gt;

&lt;p&gt;The diagram below shows the flow of the agent.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fms3jssp9hj58ch6afap9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fms3jssp9hj58ch6afap9.png" alt=" " width="799" height="436"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  The payoff: more sophisticated queries
&lt;/h1&gt;

&lt;p&gt;In the screenshot below, with the agent (and, of course, the MongoDB MCP server) running, I have asked "find me pottery mugs".&lt;/p&gt;

&lt;p&gt;Answering this query requires that the LLM use its skills to exercise the ReAct loop to:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;list the databases in the Atlas installation we've pointed it to&lt;/li&gt;
&lt;li&gt;list collections in those databases looking for something useful ("Ha! There's a collection called pottery in the herwheel3_test database!")&lt;/li&gt;
&lt;li&gt;work out how to find "mugs" in that collection ("Hmm, there are arrays of categories and tags in these documents …")&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;As the Agent itself prints some of its processing to standard out, we can see that it took 6 iterations:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[req=72b91571-d634-4597-a54a-6b992939335a] [ReAct] Iteration 1...
[req=72b91571-d634-4597-a54a-6b992939335a] [ReAct] Tool selected: list-databases
[req=72b91571-d634-4597-a54a-6b992939335a] Session may have expired, attempting to reconnect...
[req=72b91571-d634-4597-a54a-6b992939335a] ✓ Successfully initialized session with MongoDB MCP server
[req=72b91571-d634-4597-a54a-6b992939335a] Reconnected, retrying tool call...
[req=72b91571-d634-4597-a54a-6b992939335a] [ReAct] Iteration 2...
[req=72b91571-d634-4597-a54a-6b992939335a] [ReAct] Tool selected: list-collections
[req=72b91571-d634-4597-a54a-6b992939335a] [ReAct] Iteration 3...
[req=72b91571-d634-4597-a54a-6b992939335a] [ReAct] Tool selected: find
[req=72b91571-d634-4597-a54a-6b992939335a] [ReAct] Iteration 4...
[req=72b91571-d634-4597-a54a-6b992939335a] [ReAct] Tool selected: collection-schema
[req=72b91571-d634-4597-a54a-6b992939335a] [ReAct] Iteration 5...
[req=72b91571-d634-4597-a54a-6b992939335a] [ReAct] Tool selected: find
[req=72b91571-d634-4597-a54a-6b992939335a] [ReAct] Iteration 6...
[req=72b91571-d634-4597-a54a-6b992939335a] [ReAct] Final answer reached.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  The secret sauce in the &lt;code&gt;agent-server.js&lt;/code&gt; code
&lt;/h2&gt;

&lt;p&gt;The prompt reveals how the LLM interacts with the agent to make multiple tool calls and then signal when it has arrived at a final response:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  let currentPrompt = `You are an expert MongoDB autonomous agent.
Your goal is to answer the user's question by taking actions and analyzing their results.


Here is a list of available tools:
${formattedTools}


${loadedSkills ? `You have the following skills available to guide your actions:\n${loadedSkills}\n` : ''}
User's request: "${question}"


Decide what to do next based on the request.
- If you need to use a tool to gather more information or execute a step, return a JSON object with "action": "tool", "toolName": "&amp;lt;name&amp;gt;", and "toolArguments": {&amp;lt;args&amp;gt;}.
- If you have gathered enough information and can answer the user's request (or if no tools are needed), return a JSON object with "action": "answer", and "finalAnswer": "&amp;lt;your natural language answer&amp;gt;".


Your response MUST be exactly ONE valid JSON object and nothing else. Do not use markdown blocks like \`\`\`json.`;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;br&gt;
json&lt;br&gt;
You'll see in the source code that &lt;a href="http://agent-server.js" rel="noopener noreferrer"&gt;agent-server.js&lt;/a&gt; checks the incoming JSON on each pass through the LLM's responses, where it executes tool calls and watches for that &lt;code&gt;finalAnswer&lt;/code&gt; indicator. Naturally, there is a configurable '.env ' limit to the number of iterations so you don't spend your rent money on a wedged inference.&lt;/p&gt;

&lt;h2&gt;
  
  
  Agentic code assistance
&lt;/h2&gt;

&lt;p&gt;This project is extracted from a component of a larger project (my Dashboard, not yet released) and was coded over several months in spare time using the following agentic code assistants (listed in alphabetical order):&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://cline.bot/" rel="noopener noreferrer"&gt;Cline&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://github.com/google-gemini/gemini-cli" rel="noopener noreferrer"&gt;Gemini CLI&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://bob.ibm.com/" rel="noopener noreferrer"&gt;IBM Bob&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://kilo.ai/" rel="noopener noreferrer"&gt;Kilo&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://opencode.ai/" rel="noopener noreferrer"&gt;OpenCode&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://github.com/Zoo-Code-Org/Zoo-Code" rel="noopener noreferrer"&gt;Zoo (formerly Roo)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Variety may well be the spice of life, but it's also an essential oil for lubricating one's experience with agentic code assistance as this field rapidly evolves.&lt;/p&gt;

&lt;h1&gt;
  
  
  Summary
&lt;/h1&gt;

&lt;ul&gt;
&lt;li&gt;MongoDB MCP server is not just a plugin to code assist; it's an application building block.&lt;/li&gt;
&lt;li&gt;MongoDB MCP server is best leveraged using skills.&lt;/li&gt;
&lt;li&gt;Skills require the agent to present a ReAct (Reasoning + Acting) architecture.&lt;/li&gt;
&lt;li&gt;This article is accompanied by &lt;a href="https://github.com/jwoehr/mymongodbmcpagent" rel="noopener noreferrer"&gt;code&lt;/a&gt;.

&lt;ul&gt;
&lt;li&gt;The code supports several popular LLM providers.&lt;/li&gt;
&lt;li&gt;The code is capable of servicing multiple concurrent requests.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>ai</category>
      <category>mongodb</category>
      <category>agents</category>
      <category>database</category>
    </item>
    <item>
      <title>What agent memory actually asks of a database</title>
      <dc:creator>Pash10g</dc:creator>
      <pubDate>Mon, 12 Oct 2026 13:08:39 +0000</pubDate>
      <link>https://dev.to/mongodb/what-agent-memory-actually-asks-of-a-database-544a</link>
      <guid>https://dev.to/mongodb/what-agent-memory-actually-asks-of-a-database-544a</guid>
      <description>&lt;p&gt;Most agent-memory posts are about the memory algorithm. This one is about the storage layer underneath it, because that's where I've watched these systems actually fall over.&lt;/p&gt;

&lt;p&gt;The pattern is familiar by now. An agent accumulates conversation history, you can't replay all of it into every call, so you compress it into some smaller representation and retrieve the relevant parts on demand. Plenty of libraries do the compression well. What they mostly hand-wave is what happens next: the compressed state has to live somewhere, and that somewhere has to survive a crash, resist tampering, serve hybrid queries fast, and delete on request in a way you can prove to an auditor.&lt;/p&gt;

&lt;p&gt;Those four requirements turn out to be a fairly demanding database spec. I spent a couple of days testing them against &lt;a href="https://mongodb.com/try/?utm_campaign=devrel&amp;amp;utm_source=content&amp;amp;utm_medium=cta&amp;amp;utm_term=pavel.duchovny" rel="noopener noreferrer"&gt;MongoDB&lt;/a&gt; using &lt;a href="https://semvec.io/" rel="noopener noreferrer"&gt;Semvec&lt;/a&gt;, a memory engine that keeps a fixed-size state vector plus bounded memory tiers, with an Atlas persistence layer on top. Everything below is measured on a laptop against &lt;code&gt;mongodb/mongodb-atlas-local 8.3.8&lt;/code&gt;, and you can reproduce it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Requirement 1: The write has to be atomic across three shapes of data
&lt;/h2&gt;

&lt;p&gt;Every turn produces three writes that have to agree with each other:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;What&lt;/th&gt;
&lt;th&gt;Collection&lt;/th&gt;
&lt;th&gt;Role&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;The turn itself, sequence-numbered&lt;/td&gt;
&lt;td&gt;&lt;code&gt;compliance_events&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;source of truth&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;A serialized engine state blob&lt;/td&gt;
&lt;td&gt;&lt;code&gt;state_snapshots&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;recovery fast path&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Extracted facts plus their embeddings&lt;/td&gt;
&lt;td&gt;&lt;code&gt;memory_items&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;what queries hit&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;If those three drift apart, the memory is corrupt in ways that are hard to detect. An event logged without its items means a fact silently vanishes from retrieval. A snapshot written from a state that doesn't match the log means recovery restores the wrong thing.&lt;/p&gt;

&lt;p&gt;This requirement quietly rules out most of the standard stack. If your log is in Postgres and your vectors are in a dedicated vector store, there is no transaction boundary around those three writes, so you reach for an outbox table or a saga and accept a window of inconsistency. In MongoDB, there are three collections in one database, and the commit is one multi-document transaction:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;committer&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;TurnCommitter&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;client&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;db&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;scope&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;embedder&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;embedder&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;snapshot_every&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;committer&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;run_turn&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;state&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;session&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;s1&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;turn&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="s"&gt;customer prefers index funds&lt;/span&gt;&lt;span class="sh"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight markdown"&gt;&lt;code&gt;turn 04 committed | event_seq=4 | items +1 | dedup.is_update=False | snapshot ✓
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Measured (on a laptop) cost of that atomicity: p50 21.7 ms, p95 47.2 ms. For context, generating the embedding for the same turn took p50 81.8 ms on CPU. The transaction is not what you'll be optimizing.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;event_seq&lt;/code&gt; is monotonic per tenant and agent, so gaps are detectable rather than silent. That matters for the next requirement.&lt;/p&gt;

&lt;h2&gt;
  
  
  Requirement 2: You have to be able to rebuild state and prove it's the same state
&lt;/h2&gt;

&lt;p&gt;"Durable" usually means "we back it up." For agent memory that's too weak. If you restore a snapshot and the state is subtly different from what the agent had before, the agent's behavior changes, and nothing tells you.&lt;/p&gt;

&lt;p&gt;Because every turn is in an append-only log, recovery can replay the log from scratch and compare:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;recovered: replayed_events=10  (= the 10 memory turns of the event log;mode=full replay, log is the source of truth)
engine checksum (recovered): a8d9d3b4ffa8adf3… == live ✓

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Byte-identical, not approximately equal. That's what lets you treat the snapshots collection as a disposable cache: if a snapshot is missing or suspect, throw it away and replay. The same property held across the LOCOMO benchmark, where checksums matched on 10 of 10 conversations and the run is set to abort on the first mismatch.&lt;/p&gt;

&lt;p&gt;Two MongoDB details make this practical rather than theoretical. Snapshots are compare-and-swap versioned, so two processes racing to checkpoint the same session can't silently overwrite each other. And integrity is checked twice on read, once against a SHA-256 of the blob and once against the engine's own embedded checksum, which distinguishes storage corruption from a version mismatch.&lt;/p&gt;

&lt;h2&gt;
  
  
  Requirement 3: Retrieval has to be hybrid, and it should happen server-side
&lt;/h2&gt;

&lt;p&gt;Semantic search alone doesn't work for this workload. Ask an agent, "What's my policy number?" and vector similarity gives you insurance-adjacent chunks. You need the lexical match too, plus a recency bias, because in a conversation, the newer statement usually supersedes the older one.&lt;/p&gt;

&lt;p&gt;MongoDB 8.1 added &lt;a href="https://www.mongodb.com/docs/vector-search/hybrid-search/vector-search-with-full-text-search/?utm_campaign=devrel&amp;amp;utm_source=content&amp;amp;utm_medium=cta&amp;amp;utm_term=pavel.duchovny" rel="noopener noreferrer"&gt;&lt;code&gt;$rankFusion&lt;/code&gt;&lt;/a&gt;, which does that fusion inside a single aggregation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;retrieval path: $rankFusion (server-side, MongoDB 8.3)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;One round trip, p50 15.2 ms, with per-tenant weights over the semantic, lexical, and recency rankings. The alternative is three queries and a reciprocal-rank-fusion loop in your application, which is more code, more latency, and a reranking implementation you now own.&lt;/p&gt;

&lt;p&gt;Worth checking your server version before you count on it. My cloud test cluster was on 8.0.30, which predates &lt;code&gt;$rankFusion&lt;/code&gt;; the library detects this and falls back to client-side fusion, so it keeps working. Nothing raises: the fallback is logged at &lt;code&gt;INFO&lt;/code&gt; level, &lt;code&gt;RetrievalEngine.uses_rank_fusion&lt;/code&gt; turns false, and &lt;code&gt;python -m semvec_atlas.deployment &amp;lt;uri&amp;gt;&lt;/code&gt; reports &lt;code&gt;$rankFusion: no&lt;/code&gt;. Check one of those rather than assuming you are on the server-side path.&lt;/p&gt;

&lt;p&gt;In the benchmark, hybrid retrieval through Atlas scored 0.5773 on LLM-judge accuracy, compared to 0.5322 for the same engine retrieving in-process with no database. LLM-judge accuracy here means an LLM grades each answer against ground truth and you take the pass rate using the mem0 evaluation prompts verbatim. Persisting to a database and querying it did not cost accuracy; it gained about 4.5 points, because fused ranking beats the in-process scorer. Retrieval latency went from 165 ms to 187 ms at p50 to get that.&lt;/p&gt;

&lt;p&gt;Reader context also stayed flat while this happened, which I'll come back to at the end. Fair warning on the benchmark: those accuracy figures aren't comparable to published mem0 or Zep numbers, because this run doesn't replicate their prompt routing or entity extraction. The comparison that's valid is Atlas-backed against in-process under identical conditions.&lt;/p&gt;

&lt;h2&gt;
  
  
  Requirement 4: Deletion has to be provable, and it reaches further than you think
&lt;/h2&gt;

&lt;p&gt;This is the requirement I'd underestimated, and it's the one I'd now lead with when talking to anyone in a regulated industry.&lt;/p&gt;

&lt;p&gt;A GDPR Article 17 request means a user's data must be gone, and "gone" has to be demonstrable. In this implementation, the erasure produces a signed certificate:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;certificate: user=&amp;lt;tenant&amp;gt;/&amp;lt;agent&amp;gt; events_wiped=16
signature (RS256): jRKdVEuIbnDfuT5KZwMSE6Hy07RzASc0…
signature verifies: ✓
memory_items left: 0 | snapshots left: 0
quarantine vault left: 0 | learned anchors left: 0
retrieval after forget: 0 hits (expected 0)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note the two lines before the retrieval check, because they're the interesting failure mode. This system has an ingest filter that blocks suspicious text before it reaches memory, and blocked text is held in a quarantine collection for human review. It also derives embeddings from blocked text to recognize future variants.&lt;/p&gt;

&lt;p&gt;Both of those contain user data. The quarantine vault holds the full original text. The learned anchors are vectors derived from it. An implementation that deletes &lt;code&gt;memory_items&lt;/code&gt; and calls the job done has left personal data sitting in its own safety subsystem, which, under Article 17, is not a technicality. Getting this right requires knowing every derived copy, and it's much easier to enumerate those when they're collections in one database rather than artifacts spread across four services.&lt;/p&gt;

&lt;p&gt;A word on what the signature does and doesn't prove. The RS256 key is yours: the operator supplies the private key, and the certificate is signed after every wipe step has completed and been counted. So the signature proves the deletion ran to completion under your key and hasn't been altered since. It is not third-party attestation; if you need an external party to vouch for it, you hand them the certificate and your public key. That's the same trust model as any self-signed audit record, and it's worth being upfront about before an auditor asks.&lt;/p&gt;

&lt;p&gt;Same argument in general form: the moment your source of truth and your vector index live in separate systems, "delete this user" becomes a distributed systems problem with no transaction boundary and no single place to verify the result.&lt;/p&gt;

&lt;h2&gt;
  
  
  The security layer, briefly
&lt;/h2&gt;

&lt;p&gt;The ingest filter deserves a note because it's the part I expected to be hand-wavy, but it wasn't.&lt;/p&gt;

&lt;p&gt;The threat is specific to persistent memory. A one-shot prompt injection is a bad answer, and then it's over. An injection that gets written into memory is retrieved and re-injected on every future turn, and it will be retrieved precisely because it's semantically relevant to whatever the attacker aimed it at.&lt;/p&gt;

&lt;p&gt;The filter is cosine similarity against a handful of anchor sentences describing what must never enter memory, with a 0.45 threshold. A direct injection attempt scored 0.696 and was blocked. A leetspeak version of the same attack (&lt;code&gt;1gn0r3 4ll pr3v10u5 1n57ruc710n5&lt;/code&gt;) scored 0.298 and passed, because the embedder sees gibberish tokens. So there's a de-obfuscation pass that normalizes character substitutions and homoglyphs and re-checks: 0.633, blocked. I appreciated that the demo shows its first line of defense failing rather than only the version that works.&lt;/p&gt;

&lt;p&gt;The part with operational teeth: blocked text is quarantined, not dropped, and the review queue shows only a hash, a 16-character preview, and the score, so an operator can triage without reading customer data. Releases require a reason. Legitimate text that trips the filter (one test case scored 0.632, phrased like an injection but entirely benign) can be released and recommitted. Cosine similarity can't read intent, so false positives are a certainty, and the workflow assumes them.&lt;/p&gt;

&lt;p&gt;Every block also teaches. The embedding of a blocked attempt is stored as a learned anchor, and those anchors live in a collection shared across the whole tenant rather than per agent. In the demo, the attack is blocked at &lt;code&gt;advisor-01&lt;/code&gt;. A reworded variant is then sent to &lt;code&gt;advisor-02&lt;/code&gt;, an agent with no seed catalog of its own and no history with this attacker, and it's blocked at 0.938 against the anchor &lt;code&gt;advisor-01&lt;/code&gt; learned. One agent gets hit, the fleet is immune. Releasing a false positive un-learns its anchor, so the operator workflow above doesn't poison the shared list. I haven't seen another memory layer demonstrate this, and it's only trivial because the anchors are documents in the same database every agent already reads: no sync job, no cache invalidation, no second system.&lt;/p&gt;

&lt;p&gt;To be clear about scope: this catches the obvious class of attack, the kind that reads like an instruction to the model. It is not a defense against an adversarially optimized payload. An injection phrased to sound like a benign customer statement won't resemble any anchor and will pass, for the same reason the leetspeak variant passed before de-obfuscation. It raises the cost of the lazy attack and leaves an audit trail, and that's what it claims to do.&lt;/p&gt;

&lt;p&gt;Blocked attempts leave the engine state bit-identical to a run where the attack never happened, while still writing content-free audit markers recording that something was blocked. Audit trail without storing the payload.&lt;/p&gt;

&lt;h2&gt;
  
  
  Reproducing it
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;git clone &lt;span class="o"&gt;[&lt;/span&gt;https://github.com/VersinoPsiOmega/semvec-mongodb-atlas.git]&lt;span class="o"&gt;(&lt;/span&gt;https://github.com/VersinoPsiOmega/semvec-mongodb-atlas.git&lt;span class="o"&gt;)&lt;/span&gt;
&lt;span class="nb"&gt;cd &lt;/span&gt;semvec-mongodb-atlas
docker run &lt;span class="nt"&gt;-d&lt;/span&gt; &lt;span class="nt"&gt;--name&lt;/span&gt; semvec-atlas-mongo &lt;span class="nt"&gt;-p&lt;/span&gt; 27017:27017 &lt;span class="se"&gt;\&lt;/span&gt;
    &lt;span class="nt"&gt;--ulimit&lt;/span&gt; &lt;span class="nv"&gt;nofile&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;64000:64000 mongodb/mongodb-atlas-local:8.3.8

python3 &lt;span class="nt"&gt;-m&lt;/span&gt; venv ~/.venvs/semvec-atlas
~/.venvs/semvec-atlas/bin/pip &lt;span class="nb"&gt;install&lt;/span&gt; &lt;span class="nt"&gt;-e&lt;/span&gt; &lt;span class="s2"&gt;".[langgraph,compliance,mcp,dev]"&lt;/span&gt; &lt;span class="se"&gt;\&lt;/span&gt;
    sentence-transformers openai tiktoken

demo/run.sh &lt;span class="nt"&gt;--no-llm&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;--ulimit&lt;/code&gt; flag is not decoration. Each test provisions its own database, and a few hundred of those exhausted the default file-descriptor limit, at which point WiredTiger takes a fatal assertion and &lt;code&gt;mongod&lt;/code&gt; dies mid-run. What you see is a wall of &lt;code&gt;OSError: connection closed&lt;/code&gt; failures that look like application bugs. With the limit raised, the suite goes from a 25-minute partial collapse to 41 seconds.&lt;/p&gt;

&lt;p&gt;Everything except the answer text is deterministic: checksums, sequence numbers and counts reproduce exactly; the latencies depend on your hardware.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why you'd want this
&lt;/h2&gt;

&lt;p&gt;If you're building agents, you've already hit the wall, or you're about to: conversation history grows, context costs grow with it, and every turn gets more expensive than the last. The usual fix is to compress. The part nobody tells you is that compression only pays off if the compressed state is somewhere you can trust.&lt;/p&gt;

&lt;p&gt;Here's what that looked like in practice. Across 5,882 turns of real conversation, the context sent to the model per call stayed at 987 tokens. That held on the 689-turn conversation just like the 369-turn one. Replaying the full history would have cost 27,353. So: 96% less context, and it doesn't drift upward as the conversation gets longer. Turn 700 costs what turn 7 did.&lt;/p&gt;

&lt;p&gt;And it didn't cost quality. LLM-judge accuracy was 0.5773 going through Atlas against 0.5322 for the same engine holding everything in memory with no database at all. Persisting to a database didn't tax accuracy, it improved it, because fused ranking beats an in-process scorer.&lt;/p&gt;

&lt;p&gt;Fixed cost per turn, and accuracy that holds. That's what makes an agent affordable to run at turn 1,000 rather than just impressive in a demo.&lt;/p&gt;

&lt;h2&gt;
  
  
  What MongoDB is doing for this
&lt;/h2&gt;

&lt;p&gt;Fixed-size memory isn't a new idea. What's different here is not having to assemble the storage underneath it from four separate services.&lt;/p&gt;

&lt;p&gt;Everything in this post ran on one &lt;a href="https://mongodb.com/try/?utm_campaign=devrel&amp;amp;utm_source=content&amp;amp;utm_medium=cta&amp;amp;utm_term=pavel.duchovny" rel="noopener noreferrer"&gt;database&lt;/a&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The turn log, the state snapshot, and the vectors commit together in one transaction, 21.7 ms at p50. No outbox, no saga, no window where a fact exists in your log but not your index.&lt;/li&gt;
&lt;li&gt;Hybrid ranking over semantic, lexical, and recency signals happens server-side in one aggregation via &lt;a href="https://www.mongodb.com/docs/vector-search/hybrid-search/vector-search-with-full-text-search/?utm_campaign=devrel&amp;amp;utm_source=content&amp;amp;utm_medium=cta&amp;amp;utm_term=pavel.duchovny" rel="noopener noreferrer"&gt;&lt;code&gt;$rankFusion&lt;/code&gt;&lt;/a&gt;, 15.2 ms at p50. Not three queries and a fusion loop you have to write and own.&lt;/li&gt;
&lt;li&gt;"Delete this user" is one operation you can verify, with a signed certificate, because there is one place the data lives.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Try that on Postgres plus a dedicated vector store, and every one of those becomes distributed-systems work: consistency code you maintain, reranking you implement, and a GDPR request that turns into an archaeology project across four services. The alternative to one database isn't four databases, it's four databases plus the glue between them and the compliance gaps in the seams.&lt;/p&gt;

&lt;p&gt;The whole thing runs on your laptop today: &lt;code&gt;mongodb/mongodb-atlas-local&lt;/code&gt;, one docker run, same code path as Atlas in production.&lt;/p&gt;

&lt;p&gt;One last data point for anyone about to optimize the wrong layer. The embedder was 4x the cost of the database write and 5x the cost of retrieval. The database was never the bottleneck.&lt;/p&gt;

</description>
      <category>ai</category>
      <category>vectordatabase</category>
      <category>mongodb</category>
      <category>semvec</category>
    </item>
  </channel>
</rss>
