diff --git "a/mongodb_docs_chunked.json" "b/mongodb_docs_chunked.json" --- "a/mongodb_docs_chunked.json" +++ "b/mongodb_docs_chunked.json" @@ -1,795 +1,3 @@ -{"chunk_id": "6abbddbbc55cf82488ba663e-0", "page_id": "6abbddbbc55cf82488ba663e", "source_name": "agentengine", "product_name": null, "url": "https://mongodb.com/docs/agentengine/sdk/javascript/packages/agent-engine-memory", "title": "@mongodb-js/agent-engine-sdk-memory", "text": "# @mongodb-js/agent-engine-sdk-memory\n\nMongoDB Atlas Agent Engine is in Public Preview and intended for evaluation and prototyping purposes only. We do not recommend production deployments during preview and expect to communicate breaking changes with you periodically. To learn more about preview feature considerations, see Preview Features.Unified **Memory** facade for Atlas Agent Engine (TypeScript). The counterpart of the Python `agent-engine-sdk-memory` package: TypeScript agents read from and write to the Memory Server through the same routes, with memory that persists across turns and sessions.\n\n## Install\n\n```bash\nnpm install @mongodb-js/agent-engine-sdk-memory\n```\n\n## The `Memory` facade\n\n`Memory` exposes every memory type behind one transport-agnostic surface:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nType\n\n\nWrite\n\n\nRead\n\n
\nConversation turns (STM)\n\n\n`recordTurn`\n\n\n(feeds `buildContext`)\n\n
\nSemantic (facts)\n\n\n`saveSemantic`\n\n\n`searchSemantic`, `getSemantic`\n\n
\nEpisodic (conversations)\n\n\n`saveEpisode`\n\n\n`searchEpisodes`, `listEpisodes`\n\n
\nTaxonomic (knowledge base)\n\n\n`saveTaxonomic`\n\n\n`searchTaxonomic`, `getTaxonomicTerm`, `listDomains`\n\n
\nProcedural (how-tos)\n\n\n`saveProcedure`\n\n\n`discoverProcedures`, `getProcedure`\n\n
\nCustom types (declared per project)\n\n\n`save`\n\n\n`retrieve`\n\n
\nUnified\n\n\n\u2014\n\n\n`buildContext`, `search`\n\n
All methods are async. Identity (`userId` / `sessionId`) is resolved per call \u2014 from the argument, then a bound context, then the runtime\u2019s ambient context. The custom-type operations are the exception: they carry no identity fields \u2014 the platform stamps org, project, and user from the request \u2014 so they do not resolve client-side identity, and they require a backend that can stamp it (project-scoped Gateway routes, or an execution-scoped runtime).\n\n## Two modes\n\nThe facade is the same in both; only how the URL, auth, and identity are supplied differs.\n\n### HTTP-direct (standalone / off-platform)\n\nA self-contained client for scripts, tests, and code running outside the platform. Configure via constructor args or `AGENTIC_MEMORY_*` env vars.\n\n```ts\nimport { Memory } from \"@mongodb-js/agent-engine-sdk-memory\";\n\nconst memory = new Memory({\n serviceAccountToken: process.env.AGENTIC_MEMORY_SERVICE_ACCOUNT_TOKEN, // service-account access token\n projectId: \"my-project\", // set => project-scoped Gateway routes\n}); // unset => flat OE routes\n\nawait memory.saveSemantic({\n text: \"favorite color is teal\",\n label: \"favorite_color\",\n userId: \"u1\",\n metadata: { channel: \"web\", priority: \"high\" }, // optional caller-supplied metadata\n});\nconst hits = await memory.searchSemantic({ query: \"color\", userId: \"u1\" });\nawait memory.close();\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nEnv var\n\n\nPurpose\n\n
\n`AGENTIC_MEMORY_SERVICE_ACCOUNT_TOKEN`\n\n\nService-account access token (falls back to the hosted Gateway URL when set). `AGENTIC_MEMORY_API_KEY` is a deprecated alias: it still works, prints a `DeprecationWarning`, and conflicts with the new variable (setting both throws). Mint a token with `agentengine service-account create` plus the OAuth token exchange shown in the Python SDK README.\n\n
\n`AGENTIC_MEMORY_BASE_URL`\n\n\nBackend address.\n\n
\n`AGENTIC_MEMORY_PROJECT_ID`\n\n\nSet => project-scoped Gateway routes; empty => flat OE routes.\n\n
\n\n### App-bound (inside a deployed agent)\n\nAgent code uses `app.memory` (from `@mongodb-js/agent-engine-sdk-langgraph`). Identity comes from the ambient request context and calls route through the Orchestration Engine\u2019s memory proxy \u2014 no tokens to manage, no `userId` threading:\n\n```ts\n// inside a tool or entrypoint\nawait app.memory.saveSemantic({ text: \"prefers email over SMS\", label: \"contact_pref\" });\nconst context = await app.memory.buildContext({ query: \"how does the user like to be contacted?\" });\n```\n\nApp-bound memory is reachable only while handling a platform request (it needs the execution context\u2019s `OE_URL`).\n\n### Context token budget\n\n`buildContext({ maxTokens })` sets an optional gross context-construction budget (not a fetch cost). After retrieval and ranking, the server subtracts a 500-token formatting reserve, then greedily selects whole memory chunks that fit in the remainder. Positive values at or below 500 leave no budget for memories. Values above 500 can still yield empty context when no chunk fits. `metadata.token_count` reports formatted output only and excludes the reserve. Omit `maxTokens` to keep the server default.\n\n## Errors\n\nTyped errors let callers branch on failure mode: `MemoryAuthError` (401/403), `MemoryRouteNotFoundError` (404 with a route-shape hint), `MemoryBadRequestError`, `MemoryServerError` (5xx / bad body), `MemoryConnectionError`, `MemoryNotSupportedError` (capability gap), and `MemoryIdentityError` (a required identity field could not be resolved). `MemoryNotSupportedError` covers both client-side gaps and, on the custom-type routes, capability gaps only the platform can report: a bare 404/405 (platform too old to serve the route) or the gateway\u2019s structured 400 reporting custom memory types disabled on the deployment. A structured unknown-type 404 raises `MemoryBadRequestError`. Transport retries 502/503/504 up to three times.\n\n## Development\n\n```bash\nnpm install\nnpm test # vitest\nnpm run build # tsc\n```"} -{"chunk_id": "6abbddbac55cf82488ba65b9-0", "page_id": "6abbddbac55cf82488ba65b9", "source_name": "agentengine", "product_name": null, "url": "https://mongodb.com/docs/agentengine/cli/agentengine_atlas_database-user_save", "title": "agentengine atlas database-user save", "text": "# agentengine atlas database-user save\n\nMongoDB Atlas Agent Engine is in Public Preview and intended for evaluation and prototyping purposes only. We do not recommend production deployments during preview and expect to communicate breaking changes with you periodically. To learn more about preview feature considerations, see Preview Features.Save or create the Atlas database user for this workspace.\n\n```bash\nagentengine atlas database-user save [flags]\n```\n\n## Options\n\n```bash\n --base-url string Platform base URL\n --context string Named context to target (see 'agentengine context list')\n --env string Atlas environment name, such as cloud-dev\n-h, --help help for save\n --input string Database user selection JSON. Prefer --input - for stdin (required on macOS and Windows). On Linux, path files must be temporary, owner-only, untracked, deleted after use, and rotated if exposed\n --json Output saved Atlas database user as JSON\n --org-id string Organization ID\n --profile string Atlas service account profile to use\n --project-id string Project ID\n --workspace string Monorepo: use Atlas setup for a specific workspace by name\n --workspace-id string Workspace ID\n```\n\n## Options inherited from parent commands\n\n```bash\n --log-file string override log file path\n --log-level string file log verbosity (error|warn|info|debug) (default \"info\")\n --no-log disable file logging\n-q, --quiet silence stderr below error\n-v, --verbose count raise stderr verbosity (-v info, -vv debug)\n```\n\n## SEE ALSO\n\n- agentengine atlas database-user - Manage the Atlas database user selected for this workspace."} -{"chunk_id": "6abbddbac55cf82488ba65b4-0", "page_id": "6abbddbac55cf82488ba65b4", "source_name": "agentengine", "product_name": null, "url": "https://mongodb.com/docs/agentengine/add-features/memory-only", "title": "Use the Standalone Memory Service", "text": "# Use the Standalone Memory Service\n\nMongoDB Atlas Agent Engine is in Public Preview and intended for evaluation and prototyping purposes only. We do not recommend production deployments during preview and expect to communicate breaking changes with you periodically. To learn more about preview feature considerations, see Preview Features.## Overview\n\nThe MongoDB Atlas Agent Engine memory service can run as a standalone service, separate from a full agent deployment. Use this guide to provision the memory server for a memory project and use the `agent-engine-sdk-memory` Python Software Development Kit (SDK) to record and retrieve conversation context from an external application.\n\nYou can run the memory service in one of the following modes:\n\n- **Hosted**: The memory server runs on the Atlas Agent Engine, and your application connects to it by using a service account access token. Use this mode for a deployed application.\n\n- **Local**: The memory server runs in local Docker containers managed by the `agentengine` CLI, and your application connects to it directly. Use this mode to develop and test locally.\n\n### Hosted Memory Service\n\nIn hosted mode, the `agent-engine-sdk-memory` SDK connects to the hosted memory gateway by using a service account access token. The gateway reads the organization and project from the service account. For each conversation, you pass `user_id` and `session_id` values to the SDK to scope the conversation's memory to that user and session.\n\nTo learn more about memory, see the Agent Memory guide.\n\nThe following features are available in hosted mode:\n\n- `record_turn()`, `build_context()`, and `search()` SDK methods for recording and retrieving conversation context\n\n- Semantic, episodic, procedural, and taxonomic search\n\n- Direct create and read operations, in the form of `save_*`, `get_*` or `list_*`\n\n- Custom memory types, by using the generic `save()` and `retrieve()` methods\n\n### Local Memory Service\n\nIn local mode, the `agent-engine-sdk-memory` SDK connects directly to a local Orchestration Engine (`oe`) proxy that the `agentengine dev up` command starts on your machine. You must set the `base_url` value to the local `oe` URL. Do not set `project_id` or an access token for the connection.\n\nThe following features are available in local mode:\n\n- `record_turn()`, `build_context()`, and `search()` SDK methods for recording and retrieving conversation context\n\n- Semantic, episodic, procedural, and taxonomic search\n\n- Direct create and read operations, in the form of `save_*`, `get_*` or `list_*`\n\nYou cannot use custom memory types in local mode.\n\nTo learn more about the different memory types, see the Agent Memory guide.\n\n## Configure the Hosted Memory Service\n\nThis section shows how to create a memory-only project hosted on the Atlas Agent Engine by performing the following tasks:\n\n- Save the target project as a CLI context\n\n- Upload the required project secrets\n\n- Start the hosted memory runtime\n\n- Use the Python SDK to call the memory runtime from your application\n\nTo create a memory-only project, you don't deploy an agent or create a workspace.\n\n### Prerequisites\n\nBefore you begin this tutorial, ensure that you have the following resources:\n\n- The `agentengine` CLI installed and authenticated. Use version `0.1.120` or later. To learn more, see Install and Authenticate.\n\n- Access to the Atlas Agent Engine by running `agentengine auth login`.\n\n- A Voyage AI API key for generating memory embeddings.\n\n- An API key for the LLM provider that you use for background extraction.\n\n- `pip` or `uv` installed, which is required to install the Python SDK.\n\n- Python 3.11 or later installed.\n\n- `curl` and `jq` installed.\n\n- A provisioned Atlas cluster that meets the following requirements:\n\n - Your cluster is tier `M10` or larger. Free and shared tiers are not supported, since they cannot hold the Atlas Search and Vector Search indexes that memory creates.\n\n - Your connection string is percent-encoded and includes the database user's username and password. To learn how to retrieve your connection string, see the Connect to a Cluster guide.\n\n - Your Atlas user account has the Project Owner role on the Atlas project. Save the project ID and organization ID.\n\n - Your database user has the `readWriteAnyDatabase` role. Memory creates its own databases, so a user scoped to one database cannot authenticate to all required databases.\n\nIf the linked Atlas cluster can't create the Search and Vector Search indexes that memory requires, the Atlas Agent Engine stops deployment at the `Memory: waiting` stage and might time out with an `Error: context deadline exceeded` error message.\n\n### Update Your IP Access List\n\nMemory connects to your cluster from the Atlas Agent Engine network, not from your local machine. Before you provision memory, complete the following steps to add the Atlas Agent Engine Atlas addresses to your Atlas project's IP access list:\n\n#### Open the Atlas project that contains your cluster.\n\n#### Navigate to the IP Access List page.\n\nIn the left navigation, select Database & Network Access in the Security section. Then, select IP Access List from the sidebar.\n\n#### Add the required IP addresses.\n\nClick the Add IP Address button on the top-right corner of the page. Add the following entries in the Access List Entry field, click Confirm, and wait until Atlas shows both as active in the Status column.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nCIDR\n\n\nDescription\n\n
\n`44.214.209.237/32`\n\n\nAtlas Agent Engine Atlas access\n\n
\n`52.44.27.64/32`\n\n\nAtlas Agent Engine Atlas access\n\n
\n\nIf you skip these steps, memory never reaches a ready state and does not progress past the `orchestration_engine` status.\n\nThese addresses are the production addresses that the Atlas Agent Engine uses for Atlas traffic. They differ from the egress addresses described in Manage Network Egress Policies, which cover traffic to external services other than Atlas. Do not add `0.0.0.0/0` to the IP access list.\n\nThe `agentengine atlas setup` command adds these IP address entries for you. However, this command requires a workspace, which memory-only projects don't have."} -{"chunk_id": "6abbddbac55cf82488ba65b4-1", "page_id": "6abbddbac55cf82488ba65b4", "source_name": "agentengine", "product_name": null, "url": "https://mongodb.com/docs/agentengine/add-features/memory-only", "title": "Use the Standalone Memory Service", "text": "### Steps\n\n#### Sign in and create a context.\n\nTo sign into the Atlas Agent Engine and create a context, complete the following steps:\n\n- Set the following values in your shell. Replace `` and `` with the IDs of the Atlas organization and project that contain your cluster:\n\n ```bash\n export PLATFORM_URL='https://agentengine.mongodb.com'\n export ORG_ID=''\n export PROJECT_ID=''\n export MEMORY_CONTEXT='my-project'\n ```\n\n- Run the following commands to sign in and confirm that the project is visible:\n\n ```bash\n agentengine version\n agentengine auth login --base-url \"$PLATFORM_URL\"\n agentengine project list --org-id \"$ORG_ID\" --base-url \"$PLATFORM_URL\"\n ```\n\n- Run the following command to save the target project as a named context:\n\n ```bash\n agentengine context create \"$MEMORY_CONTEXT\" \\\n --org-id \"$ORG_ID\" \\\n --project-id \"$PROJECT_ID\" \\\n --base-url \"$PLATFORM_URL\"\n ```\n\n A context names the platform, organization, and project. It doesn't require a workspace. Future steps pass `--context \"$MEMORY_CONTEXT\"` to target this project.\n\n#### Generate the memory configuration.\n\nScaffold a memory-only project, and choose the LLM that memory uses for background extraction.\n\nTo use a provider's public API, such as Anthropic with its default model, run the following command:\n\n```bash\nagentengine create --memory-only --name \"My Project\" --llm anthropic --yes\n```\n\nTo choose a different provider, you can pass `--llm openai` or `--llm gemini`. To choose a different model, you can pass `--llm-model `.\n\nTo use an OpenAI-compatible gateway, such as Azure AI Foundry, run the following command:\n\n```bash\nagentengine create --memory-only --name \"My Project\" \\\n --llm openai-compatible \\\n --llm-base-url '' \\\n --llm-model '' \\\n --llm-auth-header 'api-key' | 'authorization' \\\n --yes\n```\n\nFor the `--llm-auth-header` flag, choose one of the following values based on the header your gateway expects:\n\n- `api-key`: Sends the key in an `api-key` header\n\n- `authorization`: Sends `Authorization: Bearer `\n\n#### Verify your `project-config.yaml` file structure.\n\nEither command from the preceding step creates a `my-project` directory that contains only a `project-config.yaml` file, with no `agent.yaml` file or workspace.\n\nNavigate to the `my-project` directory and open the `project-config.yaml` file. Confirm that its `memory:` block resembles the following example:\n\n```yaml\nmemory_only: true\n\nmemory:\n voyage:\n model: \"voyage-4-large\"\n dimension: 1024\n\n extraction_llm:\n provider: openai\n model: \n base_url: \n api_key_secret: LLM_API_KEY\n auth_header: api-key\n\n background_extraction:\n snapshot:\n max_messages: 20\n stale_minutes: 1\n\n extraction:\n enabled:\n - semantic\n - episodic\n - taxonomic\n - procedural\n```\n\nIf you chose the public API option, the `extraction_llm` block omits the `base_url` and `auth_header` fields. When you pass `--llm openai-compatible`, the CLI stores it in the `provider` field as `provider: openai`.\n\nThe `extraction_llm` block's `api_key_secret` field names the project secret that holds your LLM provider key. Both options set this field to `LLM_API_KEY`, so upload your key under that name in the next step, not as `ANTHROPIC_API_KEY` or `OPENAI_API_KEY`. This secret supplies only the key, and the `extraction_llm` block supplies the endpoint and model.\n\n#### Upload project secrets.\n\nRun the following commands to upload your project secrets and enter the corresponding values when prompted:\n\n```bash\nagentengine secret set MONGODB_URI --context \"$MEMORY_CONTEXT\" --project-scope\nagentengine secret set VOYAGE_API_KEY --context \"$MEMORY_CONTEXT\" --project-scope\nagentengine secret set LLM_API_KEY --context \"$MEMORY_CONTEXT\" --project-scope\n```\n\nThen, confirm that you successfully uploaded the secrets by running the following command:\n\n```bash\nagentengine secret list --context \"$MEMORY_CONTEXT\" --project-scope\n```\n\nThe `--project-scope` flag is required when you pass the `--context` flag.\n\nDon't pass secret values by using the `--value` flag or as a positional argument. Both are deprecated, because they can expose secrets to other processes on your machine. If you set the secret from a script, pipe the value to the command by using the `--stdin` flag.\n\n#### Start memory.\n\nFrom the `my-project` directory, run the following commands:\n\n```bash\nagentengine memory configure ./project-config.yaml --context \"$MEMORY_CONTEXT\"\nagentengine memory apply --wait --context \"$MEMORY_CONTEXT\"\n```\n\nThese commands perform the following actions:\n\n- `agentengine memory configure` stores the configuration.\n\n- `agentengine memory apply` provisions the memory runtime the first time, delivers the configuration, restarts memory, and waits until the runtime reports ready.\n\n#### Monitor the memory status.\n\nThe memory runtime's own internal logs aren't visible. Instead, monitor the memory status in the following ways:\n\n- Run the `agentengine memory status --context \"$MEMORY_CONTEXT\"` command.\n\n- In the UI, open the project's Memory page from the Manage section. For a memory-only project, memory appears there, not on the Workspaces page.\n\nOn a new project, the first `agentengine memory apply` command can fail with a `memory-server deployment not found` error. The runtime keeps provisioning in the background. Instead of re-running `agentengine memory apply`, continue to run the `agentengine memory status` command every minute and wait until the `state` value reads `ready`.\n\nIf the `blocked_on` field remains in your `memory status` output and your `state` value does not progress to `ready`, contact MongoDB Support and provide your output.\n\n#### Create a service account and retrieve an access token.\n\nYour application authenticates by using a service account access token, not your CLI login. To retrieve this access token, perform the following steps:\n\n- Run the following command to create a service account for the project:\n\n ```bash\n agentengine service-account create memory-client \\\n --context \"$MEMORY_CONTEXT\" \\\n --role PROJECT_OWNER \\\n --enable-atlas-pairing\n ```\n\n Save the client ID and client secret from the command output. The Atlas Agent Engine shows the client secret only once.\n\n The `PROJECT_OWNER` role requires a paired Atlas service account. The `--enable-atlas-pairing` flag enables Atlas service-account pairing for the project, which allows the `agentengine service-account create` command to create this service account. Without the flag, non-interactive commands fail with a `\"Atlas service account pairing is disabled for this project\"` message.\n\n- Export your client ID, and then run the following command to exchange the client ID and client secret for an access token. `curl` prompts for the client secret without echoing it:\n\n ```bash\n export MEMORY_CLIENT_ID=''\n\n export ACCESS_TOKEN=$(curl --fail-with-body --silent --show-error \\\n --user \"$MEMORY_CLIENT_ID\" \\\n --data grant_type=client_credentials \\\n \"$PLATFORM_URL/api/v1/oauth/token\" | jq -er .access_token)\n ```\n\n In a script or CI pipeline, read the client secret from your secret manager in code instead of relying on the interactive prompt. Don't pass the client secret as a command-line argument.\n\n The access token is valid for one hour. Request a new token before the current one expires, and don't print it.\n\n#### Install the Python SDK.\n\nRun the following commands to install the `agent-engine-sdk-memory` package from PyPI, and pin the version:\n\n```bash\npython3 -m venv .venv\nsource .venv/bin/activate\npython -m pip install 'agent-engine-sdk-memory==0.11.8'\n```\n\nDon't install the package from the Atlas Agent Engine package registry, because it currently serves an older SDK version."} -{"chunk_id": "6abbddbac55cf82488ba65b4-2", "page_id": "6abbddbac55cf82488ba65b4", "source_name": "agentengine", "product_name": null, "url": "https://mongodb.com/docs/agentengine/add-features/memory-only", "title": "Use the Standalone Memory Service", "text": "#### Record and retrieve conversation context.\n\nIn your application, add the following code to create a client, bind a user identity, record turns, and retrieve relevant context for the same session:\n\n```python\nimport json\nimport os\nimport uuid\n\nfrom agent_engine_sdk_memory import Memory, MemoryRequestContext\n\nrun_id = uuid.uuid4().hex\nsession_id = f\"memory-setup-{run_id}\"\n\nwith Memory(\n base_url=os.environ[\"PLATFORM_URL\"],\n project_id=os.environ[\"PROJECT_ID\"],\n service_account_token=os.environ[\"ACCESS_TOKEN\"],\n) as memory:\n chat = memory.bind(\n MemoryRequestContext(\n user_id=f\"memory-setup-user-{run_id}\",\n session_id=session_id,\n )\n )\n\n # Record turns.\n chat.record_turn(role=\"user\", content=\"My home airport is Boston Logan.\")\n chat.record_turn(role=\"assistant\", content=\"Understood, I noted your home airport as Boston Logan.\")\n\n # Retrieve context from the same session.\n context = chat.build_context(\n query=\"What is my home airport?\",\n enabled_sources={\"stm\"},\n max_tokens=2048,\n )\n assert \"Boston Logan\" in json.dumps(context.formatted_context), (\n \"The recorded turn was not returned\"\n )\n print(\"PASS: turn recording and same-session context\")\n```\n\nTo learn more about the SDK, including how identity and context retrieval work, see the agent-engine-sdk-memory reference.\n\nThis script retrieves only short-term memory, which is available immediately. Long-term memory, such as the semantic and episodic sources, is extracted asynchronously and can take a minute or two to appear. To learn how extraction works, see Memory Extraction.\n\n### Update Memory Configuration or Rotate a Key\n\nTo change the memory configuration, edit the `memory:` block in your `project-config.yaml` file, and then run the following commands:\n\n```bash\nagentengine memory configure ./project-config.yaml --context \"$MEMORY_CONTEXT\"\nagentengine memory apply --wait --context \"$MEMORY_CONTEXT\"\n```\n\nThe `agentengine memory apply` command does not reload secrets. It restarts memory by using the values memory already has stored. To rotate an existing secret, such as your LLM provider key, pass the `--sync` flag instead:\n\n```bash\nagentengine secret set LLM_API_KEY --context \"$MEMORY_CONTEXT\" --project-scope --sync\n```\n\nIf you previously ran `agentengine secret set` without `--sync`, run the following command to apply the new value:\n\n```bash\nagentengine secret sync --context \"$MEMORY_CONTEXT\" --project-scope\n```\n\nFor a memory-only project, this command prints a message that there are no active deployments to sync, but it still refreshes the secrets that memory uses. Wait a few minutes, and then run `agentengine memory status` to confirm that the `state` field in your output still reads `ready` after the rotation.\n\nTo learn how to configure memory on the platform, see Configure Memory.\n\n## Configure the Local Memory Service\n\nThis section shows how to scaffold, start, and connect to a local memory stack.\n\n### Prerequisites\n\nBefore you begin this tutorial, ensure that you have the following resources:\n\n- The `agentengine` CLI installed. To learn more, see Install and Authenticate.\n\n- A Voyage AI API key for generating memory embeddings.\n\n- An API key for a large language model (LLM) provider, such as `ANTHROPIC_API_KEY`, if you enable background extraction.\n\n- `pip` or `uv` installed to install the Python SDK.\n\n### Steps\n\n#### Scaffold a local memory project.\n\nRun the following command to scaffold a memory-only project for local development. Replace `\"My Project\"` with your project name:\n\n```bash\nagentengine create --memory-only --name \"My Project\"\n```\n\nThe command writes a `project-config.yaml` file that sets `memory_only` to `true` and specifies the memory configuration schema.\n\nThis command does not generate an `agent.yaml` file, an `agents/` directory, or agent runtime code. You cannot combine the `--memory-only` flag with the `--template`, `--memory`, or `--open-egress` flags. To choose the extraction provider at scaffold time, you can combine the `--memory-only` flag with `--llm`.\n\n#### Configure environment variables.\n\nCreate an `.env` file in your project directory, and then set the following variables in the file:\n\n- `VOYAGE_API_KEY`: Required for Voyage AI embeddings\n\n- LLM provider key, such as `ANTHROPIC_API_KEY`: Required if background extraction is enabled in `project-config.yaml`\n\nYou don't need to set the `MONGODB_URI` variable. The `agentengine dev up` command provisions and connects to the bundled local MongoDB container automatically. If you want to use an external MongoDB instance instead, set this variable.\n\n#### Start the local stack.\n\nFrom the project directory, run the following command to start the local memory stack:\n\n```bash\nagentengine dev up\n```\n\nFor a memory-only project, this command starts only the following containers:\n\n- `mongodb`: A local Atlas-compatible MongoDB instance\n\n- `memory-server`: The memory runtime service\n\n- `oe`: The local Orchestration Engine proxy that the SDK connects through\n\nThe command output includes the URLs for the local `oe` and `memory-server` services. Copy the `oe` URL to use in a future step.\n\nUse the following commands to manage the local stack:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nCommand\n\n\nDescription\n\n
\n`agentengine dev status`\n\n\nShows the status of the local stack.\n\n
\n`agentengine dev logs`\n\n\nStreams logs for all services. Pass `memory-server` as an argument to stream logs for that service only.\n\n
\n`agentengine dev stop`\n\n\nStops the local stack without removing containers.\n\n
\n`agentengine dev clean`\n\n\nStops the local stack and removes containers and volumes.\n\n
\n\n#### Install the `agent-engine-sdk-memory` package.\n\nRun the following command to install the `agent-engine-sdk-memory` package:\n\n```bash\npip install agent-engine-sdk-memory\n```\n\n#### Connect the SDK to the local stack.\n\nNavigate to your Python application directory. This directory can be separate from the project directory that you created in the first step.\n\nThen, connect to the local stack by adding the following code to your application. Replace `http://localhost:` with the URL that you copied from the `agentengine dev up` command output.\n\n```python\nfrom agent_engine_sdk_memory import Memory, MemoryRequestContext\n\n# Set the base_url to the local oe URL printed by \"agentengine dev up\".\nmemory = Memory(base_url=\"http://localhost:\")\n\n# Bind conversation identity.\nsession = memory.bind(\n MemoryRequestContext(\n user_id=\"user_123\",\n session_id=\"session_456\",\n )\n)\n\n# Record a turn.\nsession.record_turn(role=\"user\", content=\"I prefer window seats on flights.\")\n\n# Build context.\ncontext = session.build_context(\n query=\"What seat preferences are known?\",\n enabled_sources={\"stm\", \"semantic\", \"episodic\"},\n)\nprint(context.formatted_context)\n```"} -{"chunk_id": "6abbddbac55cf82488ba65b4-3", "page_id": "6abbddbac55cf82488ba65b4", "source_name": "agentengine", "product_name": null, "url": "https://mongodb.com/docs/agentengine/add-features/memory-only", "title": "Use the Standalone Memory Service", "text": "### Troubleshoot Local Connection Errors\n\nWhen running a local memory stack, you might see a `MemoryRouteNotFoundError` (404) error. To address this error, ensure that you do not set the `project_id` value.\n\nThe SDK uses your `project_id` value to identify the URL path that receives requests. When `project_id` is not set, as is the case for local connections, the SDK sends requests to a path that the local `oe` proxy serves. When `project_id` is set, the SDK sends requests to a project-scoped path that only the hosted Atlas Agent Engine serves. A local stack does not serve the project-scoped path, so a request sent to this path generates an error.\n\nIf a stale `AGENTIC_MEMORY_PROJECT_ID` environment variable is set in your shell from the hosted workflow, the SDK requests a project-scoped route, which returns a `MemoryRouteNotFoundError` against a local stack. Before connecting to a local stack, unset this variable by running the following command:\n\n```bash\nunset AGENTIC_MEMORY_PROJECT_ID\n```\n\n## Next Steps\n\nTo enable memory for an agent that runs on the Atlas Agent Engine, see the Add Memory to Your Agent guide."} -{"chunk_id": "6abbddbcc55cf82488ba665f-0", "page_id": "6abbddbcc55cf82488ba665f", "source_name": "agentengine", "product_name": null, "url": "https://mongodb.com/docs/agentengine/sdk/python/packages/agent-engine-sdk-langgraph/docs/durable-deep-agent", "title": "Durable Deep Agent delegation", "text": "# Durable Deep Agent delegation\n\nMongoDB Atlas Agent Engine is in Public Preview and intended for evaluation and prototyping purposes only. We do not recommend production deployments during preview and expect to communicate breaking changes with you periodically. To learn more about preview feature considerations, see Preview Features.Atlas Agent Engine supports statically configured Deep Agent subagents through Deep Agent\u2019s public ``task` tool `__ and middleware hooks. The adapter gives each delegated subagent occurrence a deterministic durable operation path before that subagent reaches a secure LLM or Tool.\n\nDeep Agent builds its agent loop with LangChain\u2019s agent factory. That factory uses LangGraph ``Send` `__ packets internally to route pending ToolCalls to ToolNode workers. `Send` is a framework routing instruction, not an external effect and not an OE activity.\n\n## End-to-end flow\n\n```mermaid\nsequenceDiagram\n participant Model as Secure LLM / model node\n participant Middleware as DurableDeepAgentMiddleware\n participant Pending as Attempt-scoped pending batch\n participant Checkpointer as PlatformCheckpointer\n participant LangGraph as LangGraph routing / ToolNode\n participant Allocator as Child-path allocator\n participant Subagent as Deep Agent subagent\n participant OE as Orchestration Engine\n\n Note over Model,Checkpointer: Root step N: produce the task batch\n Model->>OE: Record or replay the LLM activity\n OE-->>Model: Ordered task ToolCalls A, B\n Model->>Middleware: after_model(state)\n Middleware->>Pending: Phase 1: store boundaries [A, B]\n Model->>LangGraph: Return AIMessage with task ToolCalls\n LangGraph->>Checkpointer: Persist internal Send packets\n Checkpointer->>OE: FinalizeStep(N)\n Checkpointer->>Checkpointer: Advance current root step to N+1\n\n Note over LangGraph,Subagent: Root step N+1: run ToolNode workers\n par Worker B may start first\n LangGraph->>Middleware: wrap_tool_call(task B)\n Middleware->>Allocator: Phase 2: preallocate A=1, B=2\n Middleware->>Subagent: Run B under research/2\n and Worker A\n LangGraph->>Middleware: wrap_tool_call(task A)\n Middleware->>Allocator: Reuse A=1\n Middleware->>Subagent: Run A under research/1\n end\n Subagent->>OE: Record or replay secure LLM and Tool activities\n```\n\n## The durable boundary\n\nFor this model response:\n\n```text\n1. task(call-A, subagent_type=\"research\")\n2. task(call-B, subagent_type=\"research\")\n```\n\nthe middleware creates these framework-neutral boundaries:\n\n```text\nChildOperationBoundary(name=\"research\", occurrence_key=\"call-A\")\nChildOperationBoundary(name=\"research\", occurrence_key=\"call-B\")\n```\n\nThe subagent type supplies the structural name. The `task` ToolCall ID supplies an opaque occurrence key. Runner-shared assigns durable child ordinals from the ordered batch:\n\n```text\ncall-A -> agent/1 / research/1\ncall-B -> agent/1 / research/2\n```\n\nThe raw ToolCall ID is an allocator key; it is not written into the final operation path.\n\n## Phase 1: preserve model order\n\n``DurableDeepAgentMiddleware.after_model` <../src/agent_engine_sdk_langgraph/durable_deep_agent.py>`__ runs after the model returns and before LangGraph starts ToolNode workers. It extracts every `task` ToolCall from the last AI message, validates its subagent type and ToolCall ID, and stores the complete ordered boundary batch with ``set_pending_child_operation_batch` <../../agent-engine-runner-shared/src/agent_engine_runner_shared/workflow/context.py>`__.\n\nThe pending batch belongs to the current durable attempt. It is held inside the mutable attempt state so the Pregel worker contexts copied by LangGraph see the same value without a process-global map.\n\nPhase 1 deliberately does not allocate child ordinals. At this point the model node still belongs to root step N.\n\n## How `Send` crosses the step boundary\n\nDeep Agent delegates graph assembly to LangChain\u2019s agent factory. For each pending ToolCall, that factory emits an internal packet equivalent to:\n\n```python\nSend(\"tools\", [tool_call])\n```\n\nLangGraph owns the packet lifecycle:\n\n1. The model-to-tools edge emits the ordered packets.\n\n2. LangGraph writes them through the configured checkpointer.\n\n3. The checkpoint transition makes them pending PUSH tasks.\n\n4. LangGraph creates one ToolNode worker per packet.\n\n5. Worker scheduling may differ from the original ToolCall order.\n\nGraphs created by `app.deep_agent()` receive the private checkpointer policy in ``deep_agent_checkpointer.py` <../src/agent_engine_sdk_langgraph/deep_agent_checkpointer.py>`__. It permits this framework-owned routing and then uses the normal inherited `put_writes` / `aput_writes`, scratch persistence, and checkpoint finalization behavior. There is no Atlas Agent Engine-specific `Send` activity, identity resolver, or replay protocol.\n\nThe ordinary ``PlatformCheckpointer` <../src/agent_engine_sdk_langgraph/platform_checkpointer.py>`__ continues to reject `Send` in application-authored durable graphs. The policy boundary is the opaque graph constructed by `app.deep_agent()`, not inspection of LangChain\u2019s private packet shape.\n\n## Phase 2: allocate in the Tool step\n\nThe root checkpoint commit calls OE `FinalizeStep` and advances the current durable step to N+1. LangGraph then invokes ``wrap_tool_call` or `awrap_tool_call` <../src/agent_engine_sdk_langgraph/durable_deep_agent.py>`__ for each ToolNode worker.\n\nBefore a `task` handler runs, the middleware:\n\n1. Reconstructs the current child boundary from the ToolCall.\n\n2. Reads the ordered task batch from `request.state`, falling back to the Phase 1 attempt-scoped batch when the worker state does not carry it.\n\n3. Calls ``preallocate_child_operation_ordinals` <../../agent-engine-runner-shared/src/agent_engine_runner_shared/workflow/context.py>`__ for the whole batch under root step N+1.\n\n4. Clears the pending batch so a later model step cannot consume stale data.\n\n5. Runs the handler inside ``child_operation_boundary_scope` <../../agent-engine-runner-shared/src/agent_engine_runner_shared/workflow/context.py>`__.\n\nPreallocating the whole batch before any handler starts makes worker scheduling irrelevant. If worker B starts before worker A, B still receives `research/2` because the model placed A first.\n\nAllocating during Phase 1 would be incorrect. The child-path allocator includes the current root step in its key, so Phase 1 would register the boundaries under model step N while the subagent effects are admitted during Tool step N+1.\n\n## Secure effects and replay\n\nThe boundary scope stays active for the complete delegated handler. Secure LLM and Tool calls inside that subagent therefore build OE activities under the same child path. Arbitrary framework work and `Send` routing do not become OE activities."} -{"chunk_id": "6abbddbcc55cf82488ba665f-1", "page_id": "6abbddbcc55cf82488ba665f", "source_name": "agentengine", "product_name": null, "url": "https://mongodb.com/docs/agentengine/sdk/python/packages/agent-engine-sdk-langgraph/docs/durable-deep-agent", "title": "Durable Deep Agent delegation", "text": "### Message identity follows graph state\n\nDeep Agent creates the delegated input `HumanMessage`, intermediate `ToolMessage` results, and the parent `task` result message. LangChain otherwise assigns fresh UUIDs to those messages on replacement. The UUIDs are part of the LLM semantic input and LangGraph checkpoint state, so changing them would make the same logical replay look like different work even when its operation path is unchanged.\n\nWhile the `task` handler is running, ``DurableDeepAgentMiddleware` <../src/agent_engine_sdk_langgraph/durable_deep_agent.py>`__ keeps the task ToolCall ID in the delegated context. Before each model call, ``SecureWrappedLLM` <../src/agent_engine_sdk_langgraph/secure_llm.py>`__ uses that stable ID to stamp the delegated input and Tool result messages. When the handler returns, the middleware stamps the parent task result message from the same ID. These are the real message objects used by the graph; LangGraph then carries their IDs through checkpointing and replay without a separate identity store. Provider-authored AI message IDs remain unchanged because the recorded secure LLM response already supplies them deterministically.\n\nFor task ToolCall `call-A`, the relevant identities are therefore stable on replacement:\n\n```text\ndelegated input durable-deep-agent-input:call-A:0\nsubagent tool result durable-deep-agent-tool-result:call-A:\nparent task result durable-deep-agent-task-result:call-A\n```\n\nOn replacement:\n\n1. The secure LLM reaches the same OE activity position and receives its recorded ordered ToolCalls.\n\n2. LangGraph emits and schedules its internal `Send` packets again.\n\n3. The middleware recreates the boundary batch and assigns the same child ordinals.\n\n4. Secure effects inside each subagent reach the same OE activity positions and receive recorded outcomes instead of executing again.\n\nThe pending batch is attempt-scoped and is discarded with cancelled or completed attempt state. Durable identity comes from the reconstructed ordered ToolCalls and the child-path allocator, not from persisting the batch as its own durable record.\n\n## Supported boundary\n\nA durable graph must use either compiled-subgraph nesting or Deep Agent task delegation. A graph that nests a Deep Agent as a compiled child is rejected during compiled-topology validation because the Deep Agent owns its own checkpointer. LangGraph\u2019s compiled-subgraph contract requires a child to inherit the root checkpointer instead.\n\nApplication-authored LangGraph `Send` fan-out remains unsupported for durable workflows. Supporting arbitrary `Send` would require a public occurrence contract across producer order, checkpoint transition, PUSH-worker identity, and secure-effect admission. The private Deep Agent exception does not expose that framework mechanism as an application API.\n\n## Call-site map\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nResponsibility\n\n\nCall site\n\n
\nExpose `app.deep_agent()`\n\n\n``runtime.py` <../src/agent_engine_sdk_langgraph/runtime.py>`__\n\n
\nBuild the Deep Agent and install durable middleware/checkpointer policy\n\n\n``deep_agent.py` <../src/agent_engine_sdk_langgraph/deep_agent.py>`__\n\n
\nPermit Deep Agent\u2019s internal `Send` routing\n\n\n``deep_agent_checkpointer.py` <../src/agent_engine_sdk_langgraph/deep_agent_checkpointer.py>`__\n\n
\nCapture Phase 1 and scope Phase 2\n\n\n``durable_deep_agent.py` <../src/agent_engine_sdk_langgraph/durable_deep_agent.py>`__\n\n
\nParse the public Deep Agent `task` call\n\n\n``deep_agent_task.py` <../src/agent_engine_sdk_langgraph/deep_agent_task.py>`__\n\n
\nPersist checkpoint writes and advance the root step\n\n\n``platform_checkpointer.py` <../src/agent_engine_sdk_langgraph/platform_checkpointer.py>`__\n\n
\nStore the pending batch and allocate child ordinals\n\n\n``context.py` <../../agent-engine-runner-shared/src/agent_engine_runner_shared/workflow/context.py>`__\n\n
\nStamp delegated messages before the secure model boundary\n\n\n``secure_llm.py` <../src/agent_engine_sdk_langgraph/secure_llm.py>`__\n\n
\nAdmit secure LLM effects\n\n\n``secure_llm_proxy.py` <../../agent-engine-runner-shared/src/agent_engine_runner_shared/secure_llm_proxy.py>`__\n\n
\nAdmit secure Tool effects\n\n\n``secure_wrapper.py` <../../agent-engine-runner-shared/src/agent_engine_runner_shared/secure_wrapper.py>`__\n\n
\nBuild the OE activity position\n\n\n``activity.py` <../../agent-engine-runner-shared/src/agent_engine_runner_shared/workflow/activity.py>`__\n\n
\n\n## Verification and maintenance\n\nWhen upgrading Deep Agent, LangChain, or LangGraph:\n\n1. Revalidate the public Deep Agent `task`, middleware, and LangGraph `Send` contracts linked above.\n\n2. Run sibling ordering, native pass-through, invalid identity, and batch lifecycle scenarios in ``test_durable_deep_agent.py` <../tests/test_durable_deep_agent.py>`__.\n\n3. Run the checkpointer policy scenarios in ``test_deep_agent_checkpointer.py` <../tests/test_deep_agent_checkpointer.py>`__.\n\n4. Run the registered sequential-subagent, same-step-subagent, and Deep Agent product-baseline durable qualifications."} -{"chunk_id": "6abbddbbc55cf82488ba65ec-0", "page_id": "6abbddbbc55cf82488ba65ec", "source_name": "agentengine", "product_name": null, "url": "https://mongodb.com/docs/agentengine/cli/agentengine_deploy_get", "title": "agentengine deploy get", "text": "# agentengine deploy get\n\nMongoDB Atlas Agent Engine is in Public Preview and intended for evaluation and prototyping purposes only. We do not recommend production deployments during preview and expect to communicate breaking changes with you periodically. To learn more about preview feature considerations, see Preview Features.Get details of a deployment.\n\n## Synopsis\n\nShow the full status of a deployment: conditions, components, and health.\n\nWith no deployment ID this shows the current (most recent) deployment for the workspace. Run from an initialized agent directory, or pass --workspace-id.\n\n```bash\nagentengine deploy get [deployment-id] [flags]\n```\n\n## Options\n\n```bash\n --base-url string Platform base URL\n --context string Named context to target (see 'agentengine context list')\n-f, --follow Stream live events until the deployment completes\n-h, --help help for get\n --json Output JSON\n --org-id string Organization ID\n --project-id string Project ID\n --workspace string Monorepo: select a specific workspace by name\n --workspace-id string Workspace ID\n```\n\n## Options inherited from parent commands\n\n```bash\n --log-file string override log file path\n --log-level string file log verbosity (error|warn|info|debug) (default \"info\")\n --no-log disable file logging\n-q, --quiet silence stderr below error\n-v, --verbose count raise stderr verbosity (-v info, -vv debug)\n```\n\n## SEE ALSO\n\n- agentengine deploy - Deploy the last successful build to the platform."} -{"chunk_id": "6abbddbac55cf82488ba65db-0", "page_id": "6abbddbac55cf82488ba65db", "source_name": "agentengine", "product_name": null, "url": "https://mongodb.com/docs/agentengine/cli/agentengine_create", "title": "agentengine create", "text": "# agentengine create\n\nMongoDB Atlas Agent Engine is in Public Preview and intended for evaluation and prototyping purposes only. We do not recommend production deployments during preview and expect to communicate breaking changes with you periodically. To learn more about preview feature considerations, see Preview Features.Scaffold a new agent from a starter template.\n\n## Synopsis\n\nCreate a local-first starter agent from a supported template, rewrite identity fields such as name and package metadata, write a personalized environment file, and print template-specific next steps.\n\nInteractive creation offers an optional LLM smoke test after the files are written: one Hello request with a 10-second timeout. --smoke-test opts in without a prompt. A failed check leaves the project fully created and explains how to fix its configuration before running agentengine dev up; do not rerun create. Manual LLM setup, client apps, and memory-only projects skip the check.\n\n```bash\nagentengine create [flags]\n```\n\n## Examples\n\n```bash\nagentengine create\nagentengine create --name \"Acme Assistant\" --llm anthropic --memory\n```\n\n## Options\n\n```bash\n --dir string Target directory (default: ./)\n-h, --help help for create\n --json Output the scaffold result as JSON\n --llm string LLM connection: openai, anthropic, gemini, openrouter, openai-compatible, anthropic-compatible, or custom (configure in code)\n --llm-auth-header string Header field the compatible endpoint expects the API key in (default: inferred; authorization uses Bearer)\n --llm-base-url string Compatible endpoint base URL; its host is added to network.egress\n --llm-model string Model or deployment name (required for OpenRouter and compatible endpoints)\n --memory Enable memory for supported agent templates and prompt for Voyage API key\n --memory-only Scaffold a memory-only project (project-config.yaml only, no agent template)\n --name string Application display name\n --open-egress Allow open outbound access for Agent and Tool (writes network.egress_mode: allow_all)\n --smoke-test Send one Hello request to the selected LLM after creation (10s timeout)\n --template string Starter template to use (default: insurance-agent)\n --yes Accept defaults for optional prompts\n```\n\n## Options inherited from parent commands\n\n```bash\n --log-file string override log file path\n --log-level string file log verbosity (error|warn|info|debug) (default \"info\")\n --no-log disable file logging\n-q, --quiet silence stderr below error\n-v, --verbose count raise stderr verbosity (-v info, -vv debug)\n```\n\n## SEE ALSO\n\n- agentengine - Agent Engine local development CLI."} -{"chunk_id": "6abbddbac55cf82488ba65d6-0", "page_id": "6abbddbac55cf82488ba65d6", "source_name": "agentengine", "product_name": null, "url": "https://mongodb.com/docs/agentengine/cli/agentengine_context_create", "title": "agentengine context create", "text": "# agentengine context create\n\nMongoDB Atlas Agent Engine is in Public Preview and intended for evaluation and prototyping purposes only. We do not recommend production deployments during preview and expect to communicate breaking changes with you periodically. To learn more about preview feature considerations, see Preview Features.Create a named platform target.\n\n## Synopsis\n\nCreate a context named NAME binding a platform base URL, organization, and project. Without --org-id or --project-id this prompts with the organizations and projects visible to your current login. --base-url defaults to the only platform you are logged into, and is required when you are logged into more than one.\n\nCreating a name that already exists fails; a context cannot be rebound yet.\n\n```bash\nagentengine context create NAME [flags]\n```\n\n## Examples\n\n```bash\nagentengine context create prod\nagentengine context create local --base-url http://localhost:30050\n```\n\n## Options\n\n```bash\n --base-url string Platform API base URL (default: your current login, if you are logged into only one platform; required otherwise)\n-h, --help help for create\n --json Output JSON\n --org-id string Organization ID (default: prompts)\n --project-id string Project ID (default: prompts)\n```\n\n## Options inherited from parent commands\n\n```bash\n --log-file string override log file path\n --log-level string file log verbosity (error|warn|info|debug) (default \"info\")\n --no-log disable file logging\n-q, --quiet silence stderr below error\n-v, --verbose count raise stderr verbosity (-v info, -vv debug)\n```\n\n## SEE ALSO\n\n- agentengine context - Manage named platform targets."} -{"chunk_id": "6abbddbac55cf82488ba65c0-0", "page_id": "6abbddbac55cf82488ba65c0", "source_name": "agentengine", "product_name": null, "url": "https://mongodb.com/docs/agentengine/cli/agentengine_atlas_setup-ip-access", "title": "agentengine atlas setup-ip-access", "text": "# agentengine atlas setup-ip-access\n\nMongoDB Atlas Agent Engine is in Public Preview and intended for evaluation and prototyping purposes only. We do not recommend production deployments during preview and expect to communicate breaking changes with you periodically. To learn more about preview feature considerations, see Preview Features.Set up IP access list for platform connections.\n\n## Synopsis\n\nSet up IP access list for platform connections.\n\n```bash\nagentengine atlas setup-ip-access [flags]\n```\n\n## Options\n\n```bash\n --base-url string Platform base URL\n --context string Named context to target (see 'agentengine context list')\n --env string Atlas environment name, such as cloud-dev\n-h, --help help for setup-ip-access\n --json Output the setup result as JSON\n --org-id string Organization ID\n --profile string Atlas service account profile to use\n --project-id string Project ID\n --workspace string Monorepo: set up IP access for a specific workspace by name\n --workspace-id string Workspace ID\n```\n\n## Options inherited from parent commands\n\n```bash\n --log-file string override log file path\n --log-level string file log verbosity (error|warn|info|debug) (default \"info\")\n --no-log disable file logging\n-q, --quiet silence stderr below error\n-v, --verbose count raise stderr verbosity (-v info, -vv debug)\n```\n\n## SEE ALSO\n\n- agentengine atlas - Atlas workspace setup commands."} -{"chunk_id": "6abbddbcc55cf82488ba665e-0", "page_id": "6abbddbcc55cf82488ba665e", "source_name": "agentengine", "product_name": null, "url": "https://mongodb.com/docs/agentengine/sdk/python/packages/agent-engine-sdk-langgraph/docs/durable-activity-identity", "title": "Durable activity identity", "text": "# Durable activity identity\n\nMongoDB Atlas Agent Engine is in Public Preview and intended for evaluation and prototyping purposes only. We do not recommend production deployments during preview and expect to communicate breaking changes with you periodically. To learn more about preview feature considerations, see Preview Features.LangGraph-specific identity rules for Durable Workflow. Platform concepts (session, execution, attempt, event, step, branch, enablement, restrictions): Durable Workflow.\n\nDurable replay covers LLM and Tool effects that follow Atlas Agent Engine\u2019s complete secure-wrapper path:\n\n```text\nLangGraph node\n -> app.llm(...) or app.deep_agent(...)\n -> secure LLM wrapper\n -> ordered AIMessage.tool_calls\n -> LangGraph ToolNode\n -> tool returned by app.get_tools()\n -> secure Tool wrapper\n -> Orchestration Engine record or replay\n```\n\nThe secure LLM wrapper records the model effect and reserves the returned Tool calls in list order. The secure Tool wrapper records or replays each Tool effect. Arbitrary Python work and external effects outside these wrappers are outside the durable replay contract.\n\n## What identifies one effect\n\nAn OE activity position contains:\n\n```text\noperation path + workflow step ordinal + activity ordinal\n```\n\nThe operation path identifies the logical graph or subagent occurrence. The step ordinal identifies the durable graph step. Within that path and step, a ToolCall ID is the stable allocator key used to choose the Tool activity ordinal.\n\nFor example, a secure LLM returns:\n\n```text\n1. call-policy -> lookup_policy\n2. call-customer -> lookup_customer\n```\n\nThe LLM proxy reserves `call-policy` as Tool ordinal 1 and `call-customer` as Tool ordinal 2 before ToolNode starts either worker. Even if the customer worker starts first, the resulting positions remain:\n\n```text\nagent/1, step 2, Tool ordinal 1 -> lookup_policy\nagent/1, step 2, Tool ordinal 2 -> lookup_customer\n```\n\nOn replacement, the same ordered LLM result reserves the same ordinals. Each secure Tool reaches the same OE position and receives the recorded result instead of executing again.\n\n## Nested execution models\n\nThe adapter supports two distinct ways to identify a nested occurrence:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nModel\n\n\nPublic framework signal\n\n\nDetailed flow\n\n
\nCompiled subgraph\n\n\nLangGraph\u2019s active `checkpoint_ns`\n\n\nDurable compiled subgraphs\n\n
\nDeep Agent delegation\n\n\nDeep Agent\u2019s `task` ToolCall and middleware hooks\n\n\nDurable Deep Agent delegation\n\n
A compiled-subgraph graph is materialized up front. At each secure effect, its resolver reads the current namespace and converts statically known compiled children into durable operation boundaries.\n\nA Deep Agent uses its public `task` ToolCall as the delegated subagent boundary. The middleware preserves the secure LLM\u2019s ordered task batch across LangChain\u2019s internal `Send` routing, then scopes each ToolNode worker before the delegated subagent reaches a secure effect.\n\nOne durable graph chooses one nesting model. A mixed graph is rejected because the public LangGraph and Deep Agent contracts do not define how their separate occurrence identities compose.\n\nApplication-authored LangGraph ``Send` `__ fan-out is not a supported durable-workflow API. Graphs created by `app.deep_agent()` permit LangChain\u2019s internal `Send` routing as an opaque implementation detail; the detailed Deep Agent document explains that private compatibility boundary.\n\n## Root effect call sites\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nResponsibility\n\n\nCall site\n\n
\nCreate the secure model and ToolNode tools\n\n\n``runtime.py` <../src/agent_engine_sdk_langgraph/runtime.py>`__\n\n
\nAdapt LangChain model calls\n\n\n``secure_llm.py` <../src/agent_engine_sdk_langgraph/secure_llm.py>`__\n\n
\nRecord or replay the LLM and reserve ordered Tool calls\n\n\n``secure_llm_proxy.py` <../../agent-engine-runner-shared/src/agent_engine_runner_shared/secure_llm_proxy.py>`__\n\n
\nRecord or replay the Tool\n\n\n``secure_wrapper.py` <../../agent-engine-runner-shared/src/agent_engine_runner_shared/secure_wrapper.py>`__\n\n
\nResolve the current operation path\n\n\n``context.py` <../../agent-engine-runner-shared/src/agent_engine_runner_shared/workflow/context.py>`__\n\n
\nBuild and start the OE activity\n\n\n``activity.py` <../../agent-engine-runner-shared/src/agent_engine_runner_shared/workflow/activity.py>`__\n\n
The two detailed lifecycle documents extend this root path only by supplying the nested operation boundary used at secure-effect admission.\n\n## Maintenance\n\nWhen upgrading LangGraph, LangChain, or Deep Agent, revalidate the public contracts linked from the detailed documents and run the focused tests and registered qualifications listed there. Framework-specific discovery remains inside this adapter; agent-engine-runner-shared consumes only framework-neutral child boundaries."} -{"chunk_id": "6abbddbac55cf82488ba65b7-0", "page_id": "6abbddbac55cf82488ba65b7", "source_name": "agentengine", "product_name": null, "url": "https://mongodb.com/docs/agentengine/cli/agentengine_atlas_database-user", "title": "agentengine atlas database-user", "text": "# agentengine atlas database-user\n\nMongoDB Atlas Agent Engine is in Public Preview and intended for evaluation and prototyping purposes only. We do not recommend production deployments during preview and expect to communicate breaking changes with you periodically. To learn more about preview feature considerations, see Preview Features.Manage the Atlas database user selected for this workspace.\n\n## Options\n\n```bash\n-h, --help help for database-user\n```\n\n## Options inherited from parent commands\n\n```bash\n --log-file string override log file path\n --log-level string file log verbosity (error|warn|info|debug) (default \"info\")\n --no-log disable file logging\n-q, --quiet silence stderr below error\n-v, --verbose count raise stderr verbosity (-v info, -vv debug)\n```\n\n## SEE ALSO\n\n- agentengine atlas - Atlas workspace setup commands.\n\n- agentengine atlas database-user list - List Atlas database users for the saved Atlas project.\n\n- agentengine atlas database-user save - Save or create the Atlas database user for this workspace."} -{"chunk_id": "68d6348e7a7e4b3c5a4fa038-0", "page_id": "68d6348e7a7e4b3c5a4fa038", "source_name": "atlas-architecture", "product_name": "Atlas Architecture Center", "url": "https://mongodb.com/docs/atlas/architecture/current/deployment-paradigms/hybrid", "title": "Hybrid Deployment Paradigm", "text": "# Hybrid Deployment Paradigm\n\nHybrid deployments refer to architectures where applications and databases span multiple environments. In the context of Atlas, hybrid deployments involve two distinct architectural patterns:\n\n- **Hybrid Connectivity**: Applications run in one environment, for example on-premises or in a customer-managed VPC, while the database runs in Atlas. This is the default enterprise reality and the most common hybrid deployment pattern.\n\n- **Hybrid Data Topology**: MongoDB data exists in multiple environments, such as both Atlas and on-premises. This is a less common and more complex pattern that is typically used during migrations or for specialized use cases.\n\n## Hybrid Connectivity\n\nHybrid connectivity deployments run applications in one environment while the database runs in Atlas. Data lives entirely in Atlas. Hybrid refers to where the application runs, not where the database lives.\n\n### Use Cases\n\nHybrid connectivity is the default reality for most enterprise deployments. Common examples include a combination of the following:\n\n- Application servers on-premises that connect to Atlas in AWS, Azure, or GCP.\n\n- Applications or Kubernetes workloads in a customer VPC that connect to Atlas through Private Endpoints.\n\n- Legacy applications in a data center that connect to Atlas over VPN or Direct Connect.\n\n### Key Requirements\n\nWhen you implement hybrid connectivity, consider the following requirements:\n\n- **Unified Networking**: Establish secure network connectivity using VPN, AWS Direct Connect, Azure ExpressRoute, or similar technologies from other cloud service providers. Secure network connectivity helps to ensure no public Internet exposure.\n\n- **Private Connectivity**: Use private IPs and private DNS to connect to Atlas. Configure Private Endpoints for secure connections that do not traverse the public Internet.\n\n- **Shared Identity and Access**: Implement SSO and IAM integration to maintain consistent authentication and authorization across environments.\n\n- **Consistent Security and Governance**: Apply unified security policies, including IP allowlists, X.509 certificates, and network access controls.\n\n- **Latency Predictability**: Design network paths to minimize and stabilize latency between application servers and Atlas clusters.\n\n- **Operational Ownership Boundaries**: Clearly define which teams manage which components of the infrastructure.\n\nThe following diagram illustrates a typical hybrid connectivity architecture:\n\nHybrid connectivity architecture showing on-premises applications, customer VPC, and Atlas cluster connected through secure network paths and Private Endpoints.\n\n### Configuration\n\nTo configure hybrid connectivity:\n\n1. Set up network connectivity between your on-premises or customer-managed environment and the cloud provider hosting your Atlas cluster. Use VPN, Direct Connect, ExpressRoute, or similar technologies.\n\n2. Configure Private Endpoints in Atlas to enable private connectivity from your environment.\n\n3. Configure authentication and access controls. See Guidance for Atlas Authentication and Guidance for Atlas Authorization.\n\n4. Test connectivity and latency from your application environment to Atlas.\n\n## Hybrid Data Topology\n\nHybrid data topology deployments involve MongoDB data that exists in multiple environments, such as both Atlas and on-premises. Hybrid data topologies are advanced patterns with significant operational complexity.\n\nAtlas does not support splitting a single cluster to span multiple deployment types. Each cluster must exist entirely within Atlas or entirely on-premises.\n\n### Use Cases\n\nHybrid data topologies are less common than hybrid connectivity deployments. Organizations typically use them for:\n\n- **Migration**: Transitional hybrid states during cloud adoption where data is gradually moved from on-premises to Atlas.\n\n- **Specialized Requirements**: Advanced use cases that require you to maintain separate MongoDB deployments in multiple environments.\n\nExamples include:\n\n- An Atlas cluster and a separate on-premises MongoDB cluster, with applications that connect to one or both depending on requirements.\n\n- Using MongoDB tools to migrate data from on-premises to Atlas.\n\n### Important Considerations\n\nHybrid data topologies come with significant tradeoffs:\n\n- **Operational Burden**: Separate MongoDB deployments that you manage increase operational complexity and require additional expertise.\n\n- **Data Consistency**: Consistency across separate deployments is challenging to maintain and may require custom solutions.\n\n- **Temporary Nature**: These patterns are often temporary during migration rather than long-term architectures.\n\nContact the MongoDB's Professional Services team for guidance on implementing hybrid data topology patterns.\n\n### Configuration\n\nTo configure a hybrid data topology:\n\n1. Configure your cloud deployments.\n\n2. Do one of the following steps to configure your self-managed deployments:\n\n - Install MongoDB for self-managed deployments.\n\n - Create a local Atlas deployment with the Atlas CLI for development and testing.\n\n3. If you migrate data, see Migrate or Import Data for guidance on how to use MongoDB tools.\n\n## Cloud Deployment Options\n\nAtlas supports the following cloud deployment types:\n\n- Single-region is typically used when cost is a factor and the low risk of regional failure is acceptable.\n\n- Multi-region is typically used to enhance protection in the case of a regional outage and to improve the performance and availability for applications by locating data closer to users.\n\n- Multi-cloud is typically used to avoid vendor lock-in and enhance availability across multiple cloud providers.\n\n### Configure Cloud Deployments\n\nTo learn how to configure cloud deployments and learn about the different types of nodes you can add, see Create a Cluster in the Atlas documentation.\n\n## Self-Managed Deployment Options\n\nYou can create self-managed deployments using:\n\n- MongoDB Enterprise is typically used for production, testing, and development environments that have additional requirements for advanced security, operations, and integrations.\n\n- MongoDB Community is typically used for development and testing environments that require additional or bespoke configuration.\n\n- MongoDB Atlas Local Deployment is driven using the Atlas CLI, deployed using Docker, and typically used for simple, complete local deployments for development scenarios.\n\n### Install MongoDB for Self-Managed Deployments\n\nTo learn how to configure an on-premises self-managed deployment, see Install MongoDB for self-managed deployments in MongoDB Enterprise or MongoDB Community.\n\n### Create a Local Deployment\n\nTo learn how to configure a local deployment with the Atlas CLI for development and testing, see Create a Local Atlas Deployment."} -{"chunk_id": "6a514da1d727379c91b9eea1-0", "page_id": "6a514da1d727379c91b9eea1", "source_name": "atlas-architecture", "product_name": "Atlas Architecture Center", "url": "https://mongodb.com/docs/atlas/architecture/current/solutions-library/predictive-maintenance", "title": "Predictive Maintenance Excellence with MongoDB Atlas", "text": "# Predictive Maintenance Excellence with MongoDB Atlas\n\nTransform equipment maintenance with AI-powered analytics that help predict failures, generate repair plans, and reduce downtime.\n\n**Use cases:** App-Driven Analytics, Gen AI, IoT, Single View\n\n**Industries:** Manufacturing & Mobility, Aerospace & Defense, Energy & Environmental\n\n**Products:** MongoDB Atlas, MongoDB Atlas Charts, MongoDB Atlas Stream Processing, MongoDB Atlas Vector Search\n\n**Partners:** Cohere, LangChain\n\n## Solution Overview\n\nPredictive maintenance solutions can allow organizations to achieve significant operational achievements, such as reducing downtime by 15-20%, increasing labor productivity by 5-20%, and cutting maintenance costs by 30-60%, according to Deloitte.\n\nThis solution uses MongoDB Atlas to build an end-to-end predictive maintenance system that helps manufacturers prevent equipment failures and optimize maintenance operations. The solution has four stages:\n\n1. **Machine prioritization and criticality analysis:** Uses ML (Machine Learning and RAG (Retrieval-Augmented Generation)-based analysis to determine equipment to prioritize for predictive maintenance.\n\n2. **Failure prediction:** Uses Atlas Stream Processing to process real-time sensor data and detect potential failures before they occur.\n\n3. **Maintenance plan generation:** Uses LLMs (Large Language Models) trained on maintenance manuals, inventory data, and resource information to automatically generate detailed work orders for failure situations.\n\n4. **Maintenance guidance generation:** Generates enhanced maintenance guidance and uses Change Streams to deliver instructions directly to technicians' mobile devices.\n\nFigure 1. Four stages of predictive maintenance workflow\n\n## Reference Architectures\n\nThis section guides you through the architecture of each stage in this solution.\n\n### Machine Prioritization and Criticality Analysis\n\nFigure 2. AI system diagram for machine prioritization recommendations\n\nThis stage uses RAG to determine which machines require predictive maintenance. The system processes two types of input data:\n\n- **Structured data**, such as production parameters and machine breakdown frequency.\n\n- **Unstructured data**, such as institutional knowledge stored in PDF documents.\n\nThe workflow aggregates and operationalizes both data types as vector embeddings in MongoDB Atlas, then uses Vector Search to semantically search the database. The results of the search provide relevant context to an LLM, via Amazon Bedrock or Cohere, which generates responses to prioritization queries. This helps maintenance teams make data-driven decisions about which machines need attention first.\n\n### Failure Prediction\n\nFigure 3. Real-time sensor monitoring with MongoDB Atlas\n\nThis stage processes real-time machine sensor data for failure prediction through six key stages:\n\n1. **Data collection:** A prioritized machine captures metrics such as product type, temperature, speed, and tool wear.\n\n2. **Stream processing:** The system transforms the raw sensor data.\n\n3. **Data storage:** The data is stored in MongoDB Atlas.\n\n4. **Change detection:** Change streams monitor the data for significant changes.\n\n5. **ML inference:** A trained model predicts potential failures.\n\n6. **Dual output:** Atlas Charts visualizes the data, and Change Streams enable mobile notifications.\n\n### Maintenance Plan Generation\n\nFigure 4. AI-powered work order generation system diagram\n\nThis stage automates maintenance work order creation through the following architecture:\n\n1. **Document processing:** The solution splits machine manuals and old work orders into chunks and converts them to vectors using Cohere embedding models.\n\n2. **Vector storage:** The solution stores embeddings in MongoDB Atlas.\n\n3. **Work order generation:** A specialized app uses LLMs to generate work order templates, pulls inventory and resource information through an aggregation pipeline, and creates detailed repair plans.\n\n### Maintenance Guidance Generation\n\nFigure 5. RAG workflow enhances technician repair instructions\n\nThis stage uses RAG to enhance operator instructions with the following architecture:\n\n1. **Service note processing:** Converts multilingual PDF service notes to text.\n\n2. **Translation:** Processes non-English content through translation models.\n\n3. **Instruction generation:** Uses LLMs to combine translated service notes with original repair plans.\n\n4. **Delivery:** Provides updated maintenance instructions to technicians through a mobile app.\n\n## Build the Solution\n\nFor complete implementation details, including code samples, configuration files, and tutorial videos, visit this solution's GitHub repository.\n\nThis repository provides a production-ready template for implementing predictive maintenance. Follow the instructions in the repository's `README`, which guides you through the following steps.\n\n### Set up your MongoDB Atlas environment\n\n- Configure your cluster, database, and collections for the stages in this solution's architecture.\n\n- Set up MongoDB Atlas Search and Vector Search indexes for the `repair_manuals` and `maintenance_history` collections. Use the following document when setting up your search index.\n\n ```javascript\n {\n \"fields\": [\n {\n \"numDimensions\": 1024,\n \"path\": \"embeddings\",\n \"similarity\": \"euclidean\",\n \"type\": \"vector\"\n }\n ]\n }\n ```\n\n- Configure Atlas Stream Processing.\n\n- Create Atlas Charts dashboards for monitoring and visualization.\n\n### Configure your AI services integration\n\nSelect one of the following services for your LLM implementation:\n\n- **Amazon Bedrock:** Configure access to Cohere models, such as `cohere.embed-english-v3` or `cohere.command-r-10`, for embeddings and completions.\n\n- **Direct API access:** Integrate a third-party provider of your choice for embeddings and completions.\n\nAdditionally, set up Google Cloud Translation API for multilingual support.\n\n### Set up your application\n\n- Configure your environment variables such as your MongoDB connection strings, database settings, and required API credentials.\n\n- Deploy the inference script for continuous system monitoring.\n\n- Install and configure the alerts application.\n\n- Launch the main demo application.\n\n- Perform system testing and validation to ensure proper data flow and functionality.\n\n## Key Learnings\n\n- **MongoDB's flexibility enables predictive maintenance:** MongoDB Atlas combines structured sensor data and unstructured maintenance documents, providing both real-time monitoring and AI-powered analysis in one architecture.\n\n- **MongoDB's features power end-to-end predictive systems:** The solution integrates multiple MongoDB features, such as Atlas Stream Processing for real-time data, Vector Search for semantic analysis, and Change Streams for mobile alerts.\n\n- **AI enables automation:** This solution combines multiple AI technologies with MongoDB's developer data platform capabilities to create an automated maintenance workflow, from machine prioritization to mobile repair guidance delivery.\n\n## Authors\n\n- Dr. Humza Akhtar, MongoDB\n\n- Rami Pinto, MongoDB\n\n- Sebastian Rojas Arbulu, MongoDB\n\n## Learn More\n\n- Multi-Agent AI Predictive Maintenance with MongoDB\n\n- Transform the Driver Experience with MongoDB & Google Cloud\n\n- White Paper: Generative AI Predictive Maintenance Applications"} -{"chunk_id": "68a95c565e79d242619e3c2b-0", "page_id": "68a95c565e79d242619e3c2b", "source_name": "atlas-architecture", "product_name": "Atlas Architecture Center", "url": "https://mongodb.com/docs/atlas/architecture/current/backups", "title": "Guidance for Atlas Backups", "text": "# Guidance for Atlas Backups\n\nMongoDB Atlas provides fully managed and customizable backups to ensure data retention and recovery:\n\n- Cloud Backups: Supports full-copy snapshots and localized snapshot storage using your cloud provider's native snapshot capabilities. These snapshots are always incremental in nature for low cost and fast restores. You choose a backup policy that specifies the frequency and retention period of hourly, daily, weekly, monthly and yearly snapshots.\n\n- Continuous Cloud Backups: Enhances standard cloud backups by offering Point In Time (PIT) recovery. This additive feature stores snapshots along with the cluster's oplog to capture data changes between snapshots, enabling you to recover your data to the exact moment (a point in time) right before any failure or event. This supports Recovery Point Objectives (RPOs) as low as 1 minute.\n\nWe don't recommend enabling backup for development and test environments. For staging and production environments, we recommend developing automated deployment templates that include the backup policy recommendations described in this page.\n\nThe MongoDB Atlas Shared Responsibility Model defines the complementary duties of MongoDB and its customers in maintaining a secure and resilient data environment. Under this framework, MongoDB manages the security and operational integrity of the underlying platform, while customers are responsible for the configuration, management, and data policies of their specific deployments. For a detailed breakdown of ownership across security and operational excellence, see Shared Responsibility Model.\n\n## Features for Atlas Backups\n\nAtlas provides fully-managed backups of your data, including point-in-time data recovery and consistent, cluster-wide snapshots of all clusters, including sharded clusters. In Atlas, you can choose from five snapshot frequencies, each with its own retention period: hourly, daily, weekly, monthly, and yearly.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nCloud Backups\n\n\nThis feature provides localized backup storage using the native snapshot functionality of your cluster's cloud service provider. Benefits include a strong default backup retention schedule of 12 months, full flexibility to customize snapshot and retention schedules, and the ability to set different snapshot frequencies (such as hourly for recovery, weekly or monthly for long-term retention) to meet industry regulations. You can access your backup data instantly, which is useful for auditing, compliance, or data recovery purposes.\n\n
\nContinuous Cloud Backups\n\n\nThis feature can be enabled on top of Cloud Backups to provide Point In Time (PIT) recovery. Continuous Cloud Backups work by storing snapshots along with the cluster's oplog up to a customizable Point In Time Restore (PITr) window, enabling you to restore to the last snapshot and then replay all operations since the snapshot was taken. This allows you to recover your data to the exact moment (a point in time) right before any failure or data loss event, like a cyber attack.\n\n
\nMulti-region Snapshot Distribution\n\n\nThis feature allows you to increase resilience by distributing copies of backup snapshots and oplogs across geographic regions in addition to the default primary region. This configuration meets compliance requirements of storing backups in different geographical locations to ensure disaster recovery in case of regional outages.\n\nTo learn more, see Snapshot Distribution.\n\n
\nBackup Compliance Policy\n\n\nThis feature further secures business critical data by preventing all snapshots and oplogs stored in Atlas from being modified or deleted, guaranteeing that your backups are fully WORM (Write Once Read Many) compliant. Only a designated, authorized user can turn off this protection after completing a verification process with MongoDB support. There is a mandatory cooldown period to disable this feature so that an attacker cannot change the backup policy and export the data.\n\nTo learn more, see Configure a Backup Compliance Policy.\n\n
\n\n## Recommendations for Atlas Backups"} -{"chunk_id": "68a95c565e79d242619e3c2b-1", "page_id": "68a95c565e79d242619e3c2b", "source_name": "atlas-architecture", "product_name": "Atlas Architecture Center", "url": "https://mongodb.com/docs/atlas/architecture/current/backups", "title": "Guidance for Atlas Backups", "text": "### Recommendations for Backup Strategy\n\nYou must align your backup strategy with specific Recovery Point Objectives (RPO) and Recovery Time Objectives (RTO) to meet business continuity requirements, particularly for critical applications where near-zero RPO (Recovery Point Objective) and rapid recovery times are crucial. RPO (Recovery Point Objective) defines the maximum amount of data loss acceptable during a failure or disruption, while RTO (Recovery Time Objective) defines the maximum amount of time it takes for your cluster or service to recover. You must calculate your standards for RPO (Recovery Point Objective) and RTO (Recovery Time Objective) based on the criticality of your application. For example, mission-critical data typically requires a lower RPO (Recovery Point Objective) than clickstream analytics.\n\nThe nature of your disaster scenario and your method of recovery affects your achievable RPO (Recovery Point Objective) and RTO (Recovery Time Objective). The default high availability architecture in MongoDB supports automatic failover to recover from temporary cloud provider outages with a near-zero RTO (Recovery Time Objective) and RPO (Recovery Point Objective), depending on the scope of the outage and your chosen deployment paradigm. To learn more about deployment configurations that support automatic failover, see Guidance for Atlas High Availability.\n\nFor disaster scenarios that require you to restore from backup, such as a code error that corrupts your entire database or an accidental cluster deletion, your deployment's RTO (Recovery Time Objective) and RPO (Recovery Point Objective) depend on the following:\n\n- RPO (Recovery Point Objective) depends on the snapshot interval defined in your backup policy. When Continuous Cloud Backups is disabled, your RPO (Recovery Point Objective) directly corresponds to the amount of time between snapshots. If you take backup snapshots every four hours, for example, then you can lose up to four hours of data during a failure event. If you enable Continuous Cloud Backups, then you can perform PIT (Point in Time) restores that guarantee an RPO (Recovery Point Objective) as low as one minute within your customizable PITr (Point in Time Restore) window.\n\n- RTO (Recovery Time Objective) depends on the size of your backup and the efficiency of your restore operation. Large replica sets (and shards) take longer to restore. To speed up restores, Atlas automatically performs optimized direct attach restores for clusters that are based in the same project and regions where you store snapshot copies.\n\n If there is no local snapshot available, or if the cluster uses NVMe storage instead of standard General or Low CPU storage, then Atlas defaults to slower streaming restores.\n\n Additionally, if you enable Continuous Cloud Backups, then Atlas must replay operations after restoring to the last snapshot in order to complete a PIT (Point in Time) restore. The less time between snapshots, the fewer operations must be replayed. Therefore, you can lower your RTO (Recovery Time Objective) by prioritizing optimized restores and requiring more frequent snapshots in your backup policy.\n\nTo ensure a comprehensive backup strategy, we recommend using the following default backup policy as a starting point. Adjust this policy according to your business's data retention and disaster recovery needs.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nPolicy Type\n\n\nTier\n\n\nContinuous Cloud Backup\n\n\nSnapshot Taken\n\n\nSnapshot Retained\n\n
\nHourly\n\n\nNVMe (non-volatile memory express)\n\n\nEnabled\n\n\nEvery 12 hours\n\n\n7 days\n\n
\nHourly\n\n\nnon-NVMe (non-volatile memory express)\n\n\nEnabled\n\n\nEvery 6 hours\n\n\n7 days\n\n
\nDaily\n\n\nAll\n\n\nEither\n\n\nEvery day\n\n\n7 days\n\n
\nWeekly\n\n\nAll\n\n\nEither\n\n\nEvery Saturday\n\n\n4 weeks\n\n
\nMonthly\n\n\nAll\n\n\nEither\n\n\nLast day of the month\n\n\n12 months\n\n
\nYearly\n\n\nAll\n\n\nEither\n\n\nEvery 1st of December\n\n\n1 year\n\n
Choosing the Right Atlas Backup Policy\n\n### Recommendations for Backup Distribution\n\nTo further enhance resilience in a single-region deployment, we recommend that you configure Atlas to copy snapshots from the primary region to a secondary backup region to ensure that you can still restore to previous versions if the primary region goes down. To learn more, see Snapshot Distribution.\n\n### Recommendations for Backup Compliance Policy\n\nWe recommend enforcing Atlas's Backup Compliance Policy to prevent unauthorized modifications or deletions of backups, thereby ensuring data protection and robust disaster recovery.\n\n### Recommendations for PIT Recovery\n\nContinuous Cloud Backups enable precise Point In Time (PIT) recovery, which minimizes data loss during failures. Atlas can quickly recover to the exact timestamp before a failure event, guaranteeing at least a one minute RPO (Recovery Point Objective). This is because Atlas restores the most recent snapshot from before the desired point in time and then replays the oplog changes to restore to that particular point. Recovery times can vary due to cloud provider disk warming and how much of the oplog must replay during recovery. Your cluster performance might be slow until the cloud provider disk warming completes after a restore. If you can be flexible in your requirements for recovery, we recommend designing templates that identify the best compromise between reasonable recovery options and cost.\n\n### Recommendations for Backup Costs\n\nTo optimize Atlas backup costs, you can adjust backup frequency and retention policies to align with data criticality and reduce unnecessary storage expenses. For example, we recommend that you disable backups in lower environments, such as development or test clusters where data recovery is not critical. For upper environments, we recommend balancing cross-region data transfer costs against high availability requirements when distributing backup snapshots across regions."} -{"chunk_id": "68a95c565e79d242619e3c2b-2", "page_id": "68a95c565e79d242619e3c2b", "source_name": "atlas-architecture", "product_name": "Atlas Architecture Center", "url": "https://mongodb.com/docs/atlas/architecture/current/backups", "title": "Guidance for Atlas Backups", "text": "## Automation Examples: Atlas Backups\n\nThe following examples enable backup and restore operations using Atlas\ntools for automation.\n\nThese examples apply only for staging and production environments where backup is enabled for the cluster.\n\nFor a plug-and-play module that automates cluster backups, including snapshot export to a cloud provider storage bucket and Backup Compliance Policy configuration in Terraform, see the cluster module backup guide. When you use the module with NVMe (non-volatile memory express) storage, you must set the hourly snapshot `frequency_interval` to `12` explicitly, because the module does not derive the hourly interval from the instance tier.\n\n\n\n\n\nRun the following command to take a backup snapshot for the cluster named myDemo and retain the snapshot for 7 days:\n\n```shell\natlas backups snapshots create myDemo --desc \"my backup snapshot\" --retention 7\n```\n\nEnable backup compliance policy for your project with a designated, authorized user (`governance@example.org`) who alone can turn off this protection after completing a verification process with MongoDB support.\n\n```shell\natlas backups compliancePolicy enable \\\n --projectId 67212db237c5766221eb6ad9 \\\n --authorizedEmail governance@example.org \\\n --authorizedUserFirstName john \\\n --authorizedUserLastName doe\n```\n\nRun the following command to create a compliance policy for scheduled backup snapshots that enforces the number of times snapshots must be taken, which is set to every `6` hours, and the duration for retaining the snapshots, which is set to `1` month.\n\n```shell\natlas backups compliancePolicy policies scheduled create \\\n --projectId 67212db237c5766221eb6ad9 \\\n --frequencyInterval 6 \\\n --frequencyType hourly \\\n --retentionValue 1 \\\n --retentionUnit months\n```\n\n\n\n\n\nThe following examples demonstrate how to configure backups during deployment. Before you can create resources with Terraform, you must:\n\n- Create your paying organization and create an API key for the paying organization. Store your API key as environment variables by running the following command in the terminal:\n\n ```\n export MONGODB_ATLAS_PUBLIC_KEY=\"\"\n export MONGODB_ATLAS_PRIVATE_KEY=\"\"\n ```\n\n- Install Terraform.\n\nThe following examples use MongoDB Atlas Terraform Provider version 2.x (`~> 2.2`). If you're upgrading from provider version 1.x, see the 2.0.0 Upgrade Guide for breaking changes and migration steps. The examples use the `mongodbatlas_advanced_cluster` resource with v2.x syntax.\n\n### Common Files\n\nYou must create the following files for each example. Place the files for each example in their own directory. Change the IDs and names to use your values. Then run the commands to initialize Terraform, view the Terraform plan, and apply the changes.\n\n#### variables.tf\n\n```yaml\nvariable \"org_id\" {\n description = \"Atlas organization ID\"\n type = string\n}\n\nvariable \"project_name\" {\n description = \"Atlas project name\"\n type = string\n}\n\nvariable \"cluster_name\" {\n description = \"Atlas Cluster Name\"\n type = string\n}\n\nvariable \"point_in_time_utc_seconds\" {\n description = \"PIT in UTC\"\n default = 0\n type = number\n}\n```\n\n### Configure Backup Schedule for the Cluster\n\nUse the following to configure a backup schedule for the cluster with the following snapshot frequency and retention:\n\n- Hourly: Every 12 hours, retain for 7 days\n\n- Daily: Once a day, retain for 7 days\n\n- Weekly: Saturday, retain for 4 weeks\n\n- Monthly: Last day of month, retain for 12 months\n\n- Yearly: December 1, retain for 1 year\n\n#### main.tf\n\n```\nlocals {\n atlas_clusters = {\n \"cluster_1\" = { name = \"m10-aws-1e\", region = \"US_EAST_1\" },\n \"cluster_2\" = { name = \"m10-aws-2e\", region = \"US_EAST_2\" },\n }\n}\n\nresource \"mongodbatlas_project\" \"atlas-project\" {\n org_id = var.org_id\n name = var.project_name\n}\n\nresource \"mongodbatlas_advanced_cluster\" \"automated_backup_test_cluster\" {\n for_each = local.atlas_clusters\n project_id = mongodbatlas_project.atlas-project.id\n name = each.value.name\n cluster_type = \"REPLICASET\"\n\n replication_specs = [\n {\n region_configs = [\n {\n electable_specs = {\n instance_size = \"M10\"\n node_count = 3\n }\n analytics_specs = {\n instance_size = \"M10\"\n node_count = 1\n }\n\n provider_name = \"AWS\"\n region_name = each.value.region\n priority = 7\n }\n ]\n }\n ]\n\n backup_enabled = true # enable cloud backup snapshots\n pit_enabled = true\n}\n\nresource \"mongodbatlas_cloud_backup_schedule\" \"test\" {\n for_each = local.atlas_clusters\n project_id = mongodbatlas_project.atlas-project.id\n cluster_name = mongodbatlas_advanced_cluster.automated_backup_test_cluster[each.key].name\n reference_hour_of_day = 3 # backup start hour in UTC\n reference_minute_of_hour = 45 # backup start minute in UTC\n restore_window_days = 7 # Restore window for near-zero RPO\n\n copy_settings {\n cloud_provider = \"AWS\"\n frequencies = [\"HOURLY\",\n \"DAILY\",\n \"WEEKLY\",\n \"MONTHLY\",\n \"YEARLY\",\n \"ON_DEMAND\"]\n region_name = \"US_WEST_1\"\n zone_id = mongodbatlas_advanced_cluster.automated_backup_test_cluster[each.key].replication_specs.*.zone_id[0]\n should_copy_oplogs = true\n }\n\n policy_item_hourly {\n frequency_interval = 12 # backup every 12 hours, accepted values = 1, 2, 4, 6, 8, 12 -> every n hours\n retention_unit = \"days\"\n retention_value = 7 # retain for 7 days\n }\n policy_item_daily {\n frequency_interval = 1 # backup every day, accepted values = 1 -> every 1 day\n retention_unit = \"days\"\n retention_value = 7 # retain for 7 days\n }\n policy_item_weekly {\n frequency_interval = 6 # every Saturday, accepted values = 1 to 7 -> every 1=Monday,2=Tuesday,3=Wednesday,4=Thursday,5=Friday,6=Saturday,7=Sunday day of the week\n retention_unit = \"weeks\"\n retention_value = 4 # retain for 4 weeks\n }\n policy_item_monthly {\n frequency_interval = 40 # last day of the month, accepted values = 1 to 28 -> nth day of the month, or 40 -> last day of the month\n retention_unit = \"months\"\n retention_value = 12 # retain for 12 months\n }\n policy_item_yearly {\n frequency_interval = 12 # every December, accepted values = 1 to 12 -> nth month of the year\n retention_unit = \"years\"\n retention_value = 1 # retain for 1 year\n }\n\n depends_on = [\n mongodbatlas_advanced_cluster.automated_backup_test_cluster\n ]\n}\n```"} -{"chunk_id": "68a95c565e79d242619e3c2b-3", "page_id": "68a95c565e79d242619e3c2b", "source_name": "atlas-architecture", "product_name": "Atlas Architecture Center", "url": "https://mongodb.com/docs/atlas/architecture/current/backups", "title": "Guidance for Atlas Backups", "text": "### Configure Backup and PIT Restore for the Cluster\n\nUse the following to configure cloud backup snapshot and PIT restore job.\n\n#### main.tf\n\n```shell\n# Create a project\nresource \"mongodbatlas_project\" \"project_test\" {\n name = var.project_name\n org_id = var.org_id\n}\n\n# Create a cluster with 3 nodes\nresource \"mongodbatlas_advanced_cluster\" \"cluster_test\" {\n project_id = mongodbatlas_project.project_test.id\n name = var.cluster_name\n cluster_type = \"REPLICASET\"\n\n backup_enabled = true # enable cloud provider snapshots\n pit_enabled = true\n retain_backups_enabled = true # keep the backup snapshopts once the cluster is deleted\n\n replication_specs = [\n {\n region_configs = [\n {\n priority = 7\n provider_name = \"AWS\"\n region_name = \"US_EAST_1\"\n electable_specs = {\n instance_size = \"M10\"\n node_count = 3\n }\n }\n ]\n }\n ]\n}\n\n# Specify number of days to retain backup snapshots\nresource \"mongodbatlas_cloud_backup_snapshot\" \"test\" {\n project_id = mongodbatlas_advanced_cluster.cluster_test.project_id\n cluster_name = mongodbatlas_advanced_cluster.cluster_test.name\n description = \"My description\"\n retention_in_days = \"1\"\n}\n\n# Specify the snapshot ID to use to restore\nresource \"mongodbatlas_cloud_backup_snapshot_restore_job\" \"test\" {\n count = (var.point_in_time_utc_seconds == 0 ? 0 : 1)\n project_id = mongodbatlas_cloud_backup_snapshot.test.project_id\n cluster_name = mongodbatlas_cloud_backup_snapshot.test.cluster_name\n snapshot_id = mongodbatlas_cloud_backup_snapshot.test.id\n\n delivery_type_config {\n point_in_time = true\n target_cluster_name = mongodbatlas_advanced_cluster.cluster_test.name\n target_project_id = mongodbatlas_advanced_cluster.cluster_test.project_id\n point_in_time_utc_seconds = var.point_in_time_utc_seconds\n }\n}\n```\n\n\n\n"} -{"chunk_id": "68a95c565e79d242619e3c40-0", "page_id": "68a95c565e79d242619e3c40", "source_name": "atlas-architecture", "product_name": "Atlas Architecture Center", "url": "https://mongodb.com/docs/atlas/architecture/current/automation", "title": "Guidance for Atlas Automated Infrastructure Provisioning", "text": "# Guidance for Atlas Automated Infrastructure Provisioning\n\nMongoDB Atlas provides tools that enable programmatic management of the deployment, scaling, and maintenance of your Atlas clusters.\n\nAtlas provides the flexibility to implement Infrastructure as Code (IaC) using either imperative or declarative programming. For example, developers can write imperative scripts that call functions from our Atlas Go SDK (Software Development Kit) client, or manage Atlas resources using declarative IaC (Infrastructure as Code) tools like the Atlas Kubernetes Operator, Terraform, AWS (Amazon Web Services) CloudFormation, or the AWS (Amazon Web Services) CDK (Cloud Development Kit).\n\nAtlas's IaC (Infrastructure as Code) tools are especially useful at the enterprise scale. We recommend that our enterprise customers use IaC (Infrastructure as Code) tools for the following benefits:\n\n- **Consistency**: IaC (Infrastructure as Code) tools enable repeatability across environments, so that deployments generate consistent results.\n\n- **Scalability**: IaC (Infrastructure as Code) tools enable auto-scaling to automatically adjust the tier or storage capacity of clusters in response to real-time use.\n\n- **Reduced Human Error**: IaC (Infrastructure as Code) tools automate operational overhead, reducing manual interventions that produce common human errors.\n\n- **Faster Development**: IaC (Infrastructure as Code) tools streamline operations to promote more efficient development.\n\n- **Improved Change Management**: IaC (Infrastructure as Code) tools support reviews and standardization of infrastructure, allowing for better change management practices and compliance.\n\n## Features for Atlas Automation\n\nYou can automate the configuration, provisioning, and management of Atlas building blocks like database users and roles, and Atlas clusters, projects, and organizations. You can also automate various configuration and management tasks for cluster resources, including enabling auto-scaling compute and storage, creating and updating multi-cloud clusters, monitoring cluster performance and health, automating backups and restores, defining backup policies, and more.\n\nYou can align your choice of tools with your preferred workflow to ensure seamless integration of MongoDB Atlas into your existing processes. The following MongoDB Atlas tools allow you to easily deploy and manage Atlas at scale with repeatable, accurate, and scalable processes.\n\n### Atlas Administration API\n\nThe Atlas Administration API provides a REST (Representational State Transfer)ful interface that allows you to leverage your preferred client such as cURL or Postman to directly interact with API (Application Programming Interface) endpoints that correspond to Atlas resources. They can also be directly called in your favorite programming language or bash script.\n\nTo learn more, see Get Started with the Atlas Administration API.\n\n### Atlas CLI\n\nEnables you to manually or programmatically create, manage, and automate tasks related to Atlas resources from a unified command line tool.\n\nTo learn more, see the following resources:\n\n- Atlas CLI\n\n- Quick Start\n\nYou can also use the Atlas CLI examples in the Atlas Architecture Center such as the Org, Project, and Cluster examples to get started.\n\n### HashiCorp Terraform MongoDB Atlas Provider\n\nProvisions Atlas resources across cloud providers (AWS (Amazon Web Services), Azure (Microsoft Azure), GCP (Google Cloud Platform)) in the workflow of your choice. It allows you to integrate Atlas into your continuous delivery workflows with the official plugin.\n\nAlternatively, you can use the CDKTF (Cloud Development Kit for Terraform) to deploy Atlas in preferred languages such as JavaScript, TypeScript, Python, Java, C#, and Go.\n\nTo learn more, see Get Started with Terraform and the MongoDB Atlas Provider and the MongoDB Atlas Provider Terraform docs. You can also use the Terraform examples in the Atlas Architecture Center such as the Org, Project, and Cluster examples to get started.\n\nFor Terraform examples that enforce our recommendations across all pillars, see one of the following examples in GitHub:\n\n- Staging/Prod\n\n- Dev/Test\n\n### Atlas Go SDK (Software Development Kit) Client\n\nThe Atlas Go SDK (Software Development Kit) client simplifies interaction with the Atlas Administration API by providing pre-built functions and full API (Application Programming Interface) endpoint coverage. The SDK provides platform-specific and GoLang language-specific tools, libraries, and documentation to help build applications quickly and easily.\n\nTo learn more, see Atlas Go SDK.\n\nSee all of the Atlas Architecture Center Go SDK examples in a single project in the Atlas Architecture Go SDK GitHub repo.\n\n### CloudFormation Resources\n\nResources to manage Atlas include:\n\n- JSON and YAML templates allow you to leverage multiple different types of Atlas resources in the AWS (Amazon Web Services) CloudFormation Public Registry.\n\n- AWS Cloud Development Kit (CDK) defines infrastructure using familiar programming languages such as JavaScript, TypeScript, Python, Java, C#, and Go.\n\n### Atlas Kubernetes Operator\n\nAllows you to deploy and manage Atlas resources using you existing Kubernetes tools. The Operator enables management of Atlas through custom resources applied into Kubernetes, which the Operator uses to configure Atlas.\n\nTo learn more, see Quick Start.\n\n## Recommendations for Atlas Automation\n\nThe following recommendations apply to all deployment paradigms.\n\nIf you already have an existing tool integrated into your deployment workflow that you use today, we recommend that you use that tool for automation. For example, if your developers and operations team are already deploying to Kubernetes, apply Atlas configurations through the same tooling and pipelines and use the Atlas Kubernetes Operator to automate updating Atlas.\n\nIf you don't already have an existing tool integrated into your development workflow, we recommend an IaC tool because they provide more robust options for infrastructure provisioning and state management.\n\nYou can also use a combination of multiple tools. For example, use IaC (Infrastructure as Code) tools for provisioning and state management, and leverage the Atlas Administration API, Atlas Go SDK (Software Development Kit), and Atlas CLI for quick administrative tasks that are ephemeral in nature. The Atlas CLI is great for local development as well as integration into a suite of tests as part of your CI/CD pipeline for application development because it improves response times and reduces costs."} -{"chunk_id": "68d6348e7a7e4b3c5a4fa039-0", "page_id": "68d6348e7a7e4b3c5a4fa039", "source_name": "atlas-architecture", "product_name": "Atlas Architecture Center", "url": "https://mongodb.com/docs/atlas/architecture/current/deployment-paradigms/multi-cloud", "title": "Multi-Cloud Deployment Paradigm", "text": "# Multi-Cloud Deployment Paradigm\n\nMulti-cloud Atlas deployments are a special case of multi-region deployment in which you set up cluster nodes across multiple geographic regions *and* multiple cloud providers. Multi-cloud deployments enhance protection in the case of concurrent regional outage and cloud provider outage. By automatically rerouting traffic to a different cloud provider's node in another region, you get continuous availability and a smooth user experience. Multi-cloud deployments can also protect against vendor lock-in and enhance performance.\n\nAtlas supports multi-cloud deployment across any combination of AWS (Amazon Web Services), Azure (Microsoft Azure), and GCP (Google Cloud Platform).\n\nTo learn how to configure multi-cloud deployments and learn about the different types of nodes you can add, see Configure High Availability and Workload Isolation in the Atlas documentation.\n\n## Use Cases for Multi-Cloud Deployments\n\nThe following image shows a multi-region, multi-cloud Atlas deployment for regions that support availability zones. Note that this differs from a multi-region deployment only in that multiple cloud providers are used.\n\nA multi-region, multi-cloud deployment may be best for you if you want to:\n\n- Provide an application development team with the option to use any one of the cloud providers for deploying their application stack (including the Atlas cluster).\n\n- Migrate an application to a new cloud provider. You can add a node to a new cloud provider region, and Atlas will replicate the data to that new node.\n\n- Ensure faster data recovery if there is a cloud provider failure. If the backup is replicated to a separate cloud, automation will bring up a full app stack on a separate cloud and remount the backup to start serving traffic.\n\n- Run analytics on a separate cloud. For example, your the data science team wants to use BigQuery for business intelligence but your app stack is in AWS (Amazon Web Services).\n\n- Deploy your application stack on both AWS (Amazon Web Services) and Azure (Microsoft Azure) and serve read and write traffic from both clouds, whether sharded or not.\n\n## Considerations and Recommendations\n\nMulti-cloud deployments have the same considerations and recommendations as other multi-region deployments.\n\nTo automate multi-cloud deployment using Terraform, see the MongoDB Atlas Cluster Module.\n\nIn addition, the following are specific considerations for multi-cloud deployments:\n\n- Cost. Since you are getting charged higher rates for ingress/egress traffic on both cloud providers during replication.\n\n- Complexity of the deployment. There are many integrations you may want when deploying an Atlas database, and many of them are pinned to a single cloud provider. For example,\n\n - Encryption key management for KMS integration / encryption at rest.\n\n - Secrets management for database access.\n\n - Integration with a SSO federated identity provider.\n\n - Private networking, because each cloud provider only peers (uses private endpoints) with other regions within that provider.\n\n - Gather observability data like logs, metrics, and alerts in a centralized place.\n\nTherefore, multi-cloud deployments often require 3rd party integrations to meet these needs."} -{"chunk_id": "6a7579c9aa1b99d8ff1a25a4-0", "page_id": "6a7579c9aa1b99d8ff1a25a4", "source_name": "atlas-architecture", "product_name": "Atlas Architecture Center", "url": "https://mongodb.com/docs/atlas/architecture/current/solutions-library/agentic-network-automation", "title": "Intent-Based Networking: Agentic Network Automation", "text": "# Intent-Based Networking: Agentic Network Automation\n\nMongoDB Atlas serves as the unified operational data layer for agentic Intent-Based Networking, enabling AI agents to autonomously configure, monitor, and repair complex networks in real time.\n\n**Use cases:** Gen AI\n\n**Industries:** Telecommunications\n\n**Products:** MongoDB Atlas, MongoDB Search, MongoDB Atlas Vector Search, Voyage AI\n\n## Solution Overview\n\nTelecommunications and media are among the industries that lead AI adoption, alongside software and fintech. Yet the gap between leaders and everyone else keeps widening: companies at the frontier of AI capability generate roughly double the revenue growth of their peers, while nearly three-quarters of all companies have yet to show any tangible value from their AI investments. Telecom races ahead on one front in particular \u2014 it has the highest rate of agentic AI adoption of any industry. The gap isn't the model. It's everything underneath that agents need to act on live network data:\n\n- Data pipelines\n\n- Vector search\n\n- Embeddings\n\n- Short-term and long-term memory\n\n- Real-time processing\n\nAgentic network automation closes that gap. Instead of engineers translating requests into device configurations by hand, autonomous agents interpret goals, plan changes, act on the network, and verify the result. IBN (Intent-Based Networking) is the clearest expression of this pattern. You state a network outcome in plain business terms, and the system delivers and defends it without further intervention.\n\nWith IBN, an operator's customer describes what they need, not how to build it. For example: Open a new flagship store. Give POS (Point of Sale) traffic priority, keep guest WiFi strictly separated, add a camera uplink, and hold POS latency under 40 ms.\n\nA central agent translates that intent into network policies, provisions the services, and monitors them continuously. When the network drifts from the promise, the agent diagnoses the cause and applies a fix on its own.\n\nMongoDB Atlas serves as the operational data layer driving this workflow. It consolidates every resource the agent needs in one database, delivering real-time queries across the current network state, customer agreements, event histories, and operator insights. The AI layer connects directly to the data, eliminating message bus, cache, or ETL pipelines. The Reference Architectures section shows how this framework works in detail.\n\n## Reference Architectures\n\nThe solution runs on a single agent backed by MongoDB Atlas. Figure 1 shows the main components:\n\n- A ReAct-based orchestrator\n\n- A two-stage semantic router\n\n- A set of specialized MCP (Model Context Protocol) microservices\n\n- Atlas collections storing the network's data and the agent's memory\n\nEvery service reads from and writes to Atlas, eliminating the need to maintain message bus, cache, or ETL pipelines. This foundation is extensible: the same orchestrator, router, and memory layer take on new domains by adding MCP services and collections. This framework sets the stage for future use cases such as a Digital Network Twin for what-if capacity planning.\n\nFigure 1. The orchestrator routes each query through MongoDB Atlas, which stores the service catalog, the IBN collections, and the agent\u2019s memory.\n\n### Routing Queries to the Right Service\n\nAs the number of services grows, the agent needs a reliable way to pick the right one. Routing runs in two stages, both backed by MongoDB.\n\nFirst, a small LLM classifies the query against a short taxonomy of domains, using a few lines per domain rather than per service. This framework keeps routing accurate as services multiply. Second, an Atlas `$vectorSearch`, filtered to the selected domain, retrieves the best-matching service. The service catalog lives in Atlas, and queries are routed through it.\n\n### The Intent Lifecycle\n\nA network outcome intent passes through the following services from an initial request to a final resolution:\n\n- **Intent service:** Parses the natural-language request into structured fields with an LLM. It tracks the intent's state as it moves through submitted, feasible, planned, active, violated, and closed stages.\n\n- **Inventory service:** Holds the physical network, mapping sites with geospatial coordinates and the resources available at each location. When a site needs a spare device, it finds the nearest available one with a geospatial query.\n\n- **Feasibility service:** Matches the intent against the current inventory, builds a concrete service plan, and writes an immutable snapshot of that plan. Every change creates a new snapshot, so the full planning history stays auditable.\n\n- **Assurance service:** Monitors live telemetry against the agreed targets. When a metric breaches its threshold, it records a compliance event and pushes it to the dashboard in real time.\n\n- **Telemetry simulator:** Injects events on demand, so you can test the full violation, diagnosis, and remediation cycle in a controlled setting.\n\n### Diagnosis in a Single Query\n\nLive violations create the most demanding moment. Suppose POS latency at the new store breaches its 40 ms target. Instead of opening a ticket, the assurance agent runs a single Atlas aggregation pipeline that applies specific filters against the knowledge base, creating a single diagnosis query against four dimensions:\n\n- **Semantic similarity:** `$vectorSearch` finds past incidents whose description is closest to the current violation, such as queue scheduling collision, strict guest segmentation active, link utilization low.\n\n- **Structured filter:** limits results to past incidents, so runbooks and policy templates do not dilute the match.\n\n- **Time window:** excludes incidents older than 180 days, so conclusions from earlier network states do not mislead the results.\n\n- **Geospatial bounds:** keep the search local, so an incident in one city does not skew a diagnosis in another.\n\nThese operations run as pre-filters inside the Atlas Vector Search index, narrowing the candidate set before the similarity calculation runs. Responses return the closest past incident, its root cause, and its proven runbook together. The agent applies the runbook, records a recovery event, and the dashboard turns green. One pipeline in Atlas replaces multiple coordinated query passes across separate systems."} -{"chunk_id": "6a7579c9aa1b99d8ff1a25a4-1", "page_id": "6a7579c9aa1b99d8ff1a25a4", "source_name": "atlas-architecture", "product_name": "Atlas Architecture Center", "url": "https://mongodb.com/docs/atlas/architecture/current/solutions-library/agentic-network-automation", "title": "Intent-Based Networking: Agentic Network Automation", "text": "## Data Model Approach\n\nIBN works with different data shapes, and MongoDB Atlas holds them all in one place. Each of the following collections maps to a part of the workflow:\n\n- `ibn_intents`: Stores the parsed intent and its lifecycle state. It contains every field specified in the request, such as the latency ceiling or the segmentation policy.\n\n- `ibn_sites`: Contains the network sites with 2dsphere-indexed coordinates for geospatial lookups.\n\n- `ibn_resources`: Contains the network resources available at each site.\n\n- `ibn_policy_snapshots`: Stores immutable plan snapshots that preserve the full planning history.\n\n- `ibn_telemetry`. Stores metric samples in a time series collection.\n\n- `ibn_compliance_events`: Stores the record of every violation and recovery.\n\n- `ibn_knowledge_chunks`: Stores past incidents, runbooks, and templates, auto-embedded with Voyage AI for vector search.\n\nThe agent's memory also lives in MongoDB, stored in dedicated collections alongside the network data:\n\n- `agent_workstreams`: Stores short-term context for the current work thread.\n\n- `agent_memories`: Extracts long-term facts when a workstream closes, vector-indexed for recall across sessions.\n\n- `user_preferences`: Stores instructions the engineer teaches the agent.\n\nA single Atlas Vector Search index makes the four-dimensional diagnosis query possible. With Atlas auto-embedding, you point the index at a text field and Atlas generates and stores the embeddings for you. You don\u2019t need a separate embedding pipeline or service to run. That same index pairs the auto-embedded text field with structured, time, and geospatial filters. As a result, a `$vectorSearch` stage does the work of several query engines:\n\n```javascript\n{\n \"fields\": [\n {\n \"type\": \"autoEmbed\",\n \"modality\": \"text\",\n \"path\": \"text\",\n \"quantization\": \"float\",\n \"model\": \"voyage-4\"\n },\n {\n \"type\": \"filter\",\n \"path\": \"kind\"\n },\n {\n \"type\": \"filter\",\n \"path\": \"segment\"\n },\n {\n \"type\": \"filter\",\n \"path\": \"market\"\n },\n {\n \"type\": \"filter\",\n \"path\": \"plan_id\"\n },\n {\n \"type\": \"filter\",\n \"path\": \"ts\"\n },\n {\n \"type\": \"filter\",\n \"path\": \"lng\"\n },\n {\n \"type\": \"filter\",\n \"path\": \"lat\"\n }\n ]\n}\n```\n\n## Build the Solution\n\nThe full demo is available on this GitHub repository. Clone the repository, then follow these steps.\n\n### Set your API keys\n\nSet the environment variables for the external services the demo calls:\n\n- OpenAI for the language model\n\n- MongoDB Atlas for the data layer\n\n- Voyage AI for embeddings\n\n```sh\nexport OPENAI_API_KEY=\"\"\nexport MONGODB_URI=\"\"\nexport VOYAGE_API_KEY=\"\"\n```\n\n### Set up your Python environment\n\nInstall Python 3.13 and add it to your path. Then, create and activate a virtual environment. Finally, install the dependencies.\n\n```sh\nbrew install python@3.13\nexport PATH=\"$(brew --prefix)/opt/python@3.13/libexec/bin:$PATH\"\npython -m venv \nsource /bin/activate\ncd agentic-mcp-demo\npip install -r requirements.txt\n```\n\n### Run the agent and watch it live\n\nStart the web servers and point your browser to http://localhost:8070/ for the interactive shell.\n\n```sh\n./bin/start.sh\n```\n\nButtons at the top navigation allow you to:\n\n- Feed seed data into the MongoDB collections.\n\n- Reset the data for re-doing the demo.\n\n- Open another browser window to display the IBN dashboard.\n\n- See the live state of the monitored sites in real time.\n\n### Try a full intent lifecycle\n\nFrom the chat in the browser, walk the agent through a complete intent, from request to recovery. The diagnose violation prompt fires the four-dimensional diagnosis query.\n\n```text\n-I'm opening a new Alpenmarkt store at Marienplatz Munich. POS priority, guest WiFi strictly separated, camera uplink, online by 18:00, max 40ms POS latency, 99.95% availability\n-feasibility check\n-propose and activate\n-inject morning rush\n-diagnose violation\n-apply runbook\n```\n\n## Key Learnings\n\n- **Unify your data in one store:** Keep intent records, geospatial sites, time series telemetry, and vector-indexed knowledge in a single MongoDB Atlas database, queryable with one driver and one pipeline.\n\n- **Retrieve across dimensions in one query:** Combine vector similarity, structured filters, a time window, and geospatial bounds in a single Atlas Vector Search stage, with no application-side orchestration.\n\n- **Stream real-time changes:** Use MongoDB Change Streams to push intent activations, violations, and recoveries to dashboards without polling.\n\n- **Give your agent a memory:** Store short-term context, long-term facts, and user preferences as collections, so the agent improves with use rather than retraining.\n\n- **Automate the full intent lifecycle:** Let one agent parse, plan, activate, assure, and remediate network intents end to end, grounded in live data.\n\n## Authors\n\n- Benjamin Lorenz, MongoDB\n\n- Aditya Vikram Roy, MongoDB\n\n- Diego Canales, MongoDB\n\n## Learn More\n\n- AI-Driven Media Personalization\n\n- AI-Powered Chatbot for Network Management\n\n- Gen AI-Powered Video Summarization"} -{"chunk_id": "68a95c565e79d242619e3c74-0", "page_id": "68a95c565e79d242619e3c74", "source_name": "atlas-architecture", "product_name": "Atlas Architecture Center", "url": "https://mongodb.com/docs/atlas/architecture/current/solutions-library/ai-driven-interactive-banking", "title": "AI-Driven Interactive Banking", "text": "# AI-Driven Interactive Banking\n\nImprove the interactivity of banking applications by using MongoDB Atlas Vector Search and large language models.\n\n- **Use cases**: Gen AI, Personalization\n\n- **Industries**: Financial Services\n\n- **Products**: MongoDB Atlas Vector Search\n\n- **Partners**: Amazon Bedrock\n\n## Solution Overview\n\nWith interactive banking, financial services customers engage with digital platforms that anticipate and meet their needs in real time.\n\nThis approach uses Generative Artificial Intelligence (Gen AI) technologies like chatbots and virtual assistants to enhance basic banking operations. Banks can improve the customer experience by leveraging Gen AI to provide tailored, context-aware interactions via self-service digital channels. From AI-powered chatbots that resolve queries instantly to predictive analytics that offer tailored financial advice, interactive banking creates a more engaging and intuitive banking experience for users.\n\nBy integrating AI-driven advisors into the digital banking experience, banks can deliver instant and relevant answers. This results in smoother, more user-friendly interactions in which customers feel supported.\n\n## Reference Architectures\n\nIn this solution, MongoDB and Amazon Bedrock store bank documentation, such as terms and conditions, as vectorized embeddings within MongoDB documents. The following figure shows this solution's architecture:\n\nFigure 1. AI-driven interactive banking architecture\n\nMongoDB acts as a data store layer between the AI technology layer and the application layer. This streamlines data management by storing unstructured and structured data together and allowing organizations to operate with a more unified dataset. By breaking down data silos, businesses can deliver more consistent customer experiences across their digital platforms.\n\n## Data Model Approach\n\nThis solution uses MongoDB's flexibility to store both text chunks from PDFs and their embeddings within the same document. This simplifies queries and ensures high performance without needing additional technologies or features. This allows companies to build AI-enriched applications on MongoDB's modern, multi-cloud database platform, unifying real-time, unstructured, and AI-enhanced data.\n\nThe image below shows an example of the data used in this solution:\n\nFigure 2. Single document with text chunks and their embeddings\n\n## Build the Solution\n\nThis solution has the following GitHub repositories:\n\n- Leafy Personal Assistant Backend\n\n- Leafy Bank UI\n\nTo run the solutions, see the `README` files in the repositories.\n\nThe architecture has the following workflow:\n\n**1. Document Preprocessing**\n\nFirst, the text-based unstructured data, such as Terms & Conditions PDFs, is processed and transformed into chunks using the sliding window technique. This ensures that transitional data between chunks is preserved to maintain continuity and context.\n\nOnce the unstructured data has been transformed into vectorized chunks, it is passed through an embedding model to generate vector embeddings. You can select the embedding model based on your requirements. This demo uses Cohere's `cohere.embed-english-v3` model on AWS Bedrock.\n\nBoth the chunks and their corresponding vectors are stored in MongoDB Atlas. This demo uses the SuperDuper Python framework to integrate AI models and workflows with MongoDB.\n\n**2. Vector Search and Querying**\n\nAfter the chunks and embeddings are stored in MongoDB, you can use MongoDB Atlas Vector Search for semantic querying.\n\n**3. Using the Chatbot**\n\nThe chatbot in this solution is powered by MongoDB Atlas Vector Search and a pre-trained LLM (Large Language Model). When a user inputs a question, the question is vectorized, and MongoDB Atlas Vector Search is used to find documents with similar embeddings.\n\nAfter the relevant documents are retrieved, this data is sent to an LLM. This demo uses Claude from Anthropic, contained in Amazon Bedrock. The LLM uses the retrieved documents as context to generate a more comprehensive and accurate response. This process is known as retrieval-augmented generation (RAG (Retrieval-Augmented Generation)). RAG enhances the chatbot's ability to provide accurate answers by combining semantic search with language model generation.\n\nFigure 3. Leafy Bank chatbot in action\n\n## Key Learnings\n\n- **Chatbots enhance user experience:** AI-driven technologies like chatbots simplify customer interactions by providing instant, context-aware responses, allowing users to navigate banking operations independently without navigating through complex terms and conditions.\n\n- **Atlas Vector Search enables PDF search:** By using data chunking and Atlas Vector Search, MongoDB enables efficient querying of dense legal documentation, ensuring customers receive accurate, context-rich answers.\n\n- **MongoDB enables technology integration:** MongoDB's integration with Vector Search, LLMs, and dedicated search infrastructure allows financial institutions to scale AI solutions, improving performance and responsiveness as customer demands grow.\n\n## Authors\n\n- Luis Pazmino Diaz, FSI Principal EMEA, MongoDB\n\n- Ainhoa M\u00fagica, Senior Specialist, Industry Solutions, MongoDB\n\n- Pedro Bereilh, Specialist, Industry Solutions, MongoDB\n\n- Andrea Alaman Calderon, Senior Specialist, Industry Solutions, MongoDB\n\n## Learn More\n\n- Credit Card Application with Generative AI\n\n- Assess Business Loan Risks with Generative AI\n\n- Agentic AI-Powered Investment Portfolio Management"} -{"chunk_id": "68a95c565e79d242619e3cf9-0", "page_id": "68a95c565e79d242619e3cf9", "source_name": "atlas-architecture", "product_name": "Atlas Architecture Center", "url": "https://mongodb.com/docs/atlas/architecture/current/solutions-library/streamline-gaming-management", "title": "Streamline Global Gaming Management", "text": "# Streamline Global Gaming Management\n\nStreamline game data management with MongoDB Atlas.\n\n**Use cases:** Analytics\n\n**Industries:** Media\n\n**Products:** MongoDB Atlas, MongoDB Atlas Global Clusters, MongoDB Atlas Search, MongoDB Atlas Charts, MongoDB Aggregation, MongoDB Atlas Data Federation\n\n**Partners:** Unity Game Engine, Amazon EC2\n\n## Solution Overview\n\nIn the gaming industry, managing data such as player profiles, inventory, and game states is a challenge. This solution, named Leafsteroids, uses MongoDB Atlas to streamline and improve game data storage. Atlas Clusters hold player profiles, Atlas Charts enable real-time player dashboards, and Atlas Search enables user-friendly search interactions. This solution allows for global scalability, efficient data management, and user-focused design.\n\n## Reference Architectures\n\nThe following diagram displays what a game data management system looks like without MongoDB:\n\nFigure 1. Reference architecture without Atlas\n\nThis approach involves building a global query router, replication services between multiple nodes across the globe, and integrating different storage options. The architecture also requires a separate search engine and visualization tool, with a serverless query service to federate the data into the visualization tool.\n\nIn contrast, the following diagram displays game data management architecture with MongoDB:\n\nFigure 2. Reference architecture with Atlas\n\nWith MongoDB Atlas, you can host your data, generate visualizations, and perform search on a single platform by using MongoDB Atlas Global Clusters, Online Archive, Atlas Search, Atlas Charts, and Atlas Data Federation.\n\n## Data Model Approach\n\nThe following diagram displays the data models used by this solution:\n\nFigure 3. Data model approach illustration\n\nA Recording represents a player's gameplay from an event, including scores, moves, and statistics. Each Recording stores a subset of the Player and Event data types by using the extended reference pattern. This design enhances query performance by allowing selective field embedding. Additionally, it offers flexibility to add and change data in the future.\n\nIn massive online games with billions of players like PUBG, data locality is critical for optimal experience and to satisfy legal requirements. To support these needs, the Players and Recordings collections are sharded based on location ISO codes. Atlas Global Clusters associates ISO Country and Subdivision codes to zones of shards in a specific cloud region. This is used to route query and write requests, ensuring the best performance.\n\n## Build the Solution\n\nFor detailed instructions on how to build this solution, see the GitHub repository.\n\n### Features and Integration\n\nThis solution provides the following architecture features:\n\n- Atlas Global Clusters ensure an uninterrupted gaming journey regardless of a player's geographical location. For data precision, player information is stored based on ISO country codes.\n\n- Atlas Online Archive automatically offloads game data that is older than 90 days to optimize storage. This is especially useful for games with millions of players and game runs, as these generate large amounts of data that can increase costs and impact performance. Additionally, this solution uses Atlas Data Federation so you can access both recent and historic data.\n\n### User Experience Highlights\n\nThe solution offers the following user highlights:\n\n- A player dashboard, supported by Atlas Charts, ensures real-time updates on in-game achievements and progress. By using Atlas Charts' filtering and embedding features, you can repurpose dashboards for players and events.\n\n- Atlas Search provides features such as autocomplete and fuzzy matching, allowing players to search for their nicknames in the Web UI.\n\n### Architecture\n\nThis solution's architecture includes the following components:\n\n- **Game Client**: Developed using Unity3D, .NET, and C#\n\n- **Game Server**: Built on ASP.NET Web API, .NET, C#, and the MongoDB .NET/C# Driver\n\n- **Website**: Crafted as a Blazor Server Application using .NET and C#\n\n### Steps\n\nThe `README` in the GitHub repository contains a more detailed version of the following procedure.\n\n#### Set up your prerequisites\n\nInstall the .NET SDK 7 and set up your MongoDB Atlas database.\n\n#### Run the backend\n\nNavigate to the `rest_service` folder in the repository. Modify the `.env` file and start the backend using the following command:\n\n```sh\ndotnet run --urls \"http://0.0.0.0:8000\"\n```\n\n#### Launch the website\n\nNavigate to the `website` folder. Modify the `.env` file and start the website by running the following command:\n\n```sh\ndotnet run --urls \"http://0.0.0.0:8001\"\n```\n\n#### Start the game\n\nNavigate to the `game_client` folder. Modify the `.env` file in the `Assets` folder. Then, run the game.\n\n## Key Learnings\n\n- **Global clusters promote scaling**: Use global clusters, read from secondary, and write to primary to scale horizontally and cater to a global audience without side effects and latency.\n\n- **MongoDB's document model promotes flexibility and performance:** Leverage the document model to store all data for a single game run in a single document, but serialize a subset during run time to boost performance.\n\n- **Shard data based on player location:** By storing data based on ISO codes, Atlas Global Clusters enable increased performance and easier scalability, allowing shard and zone additions without service disruptions.\n\n## Author\n\n- Sigfrido Narvaez, MongoDB\n\n- Dominic Frei, MongoDB\n\n- Hubert Nguyen, MongoDB\n\n## Learn More\n\n- AI-Driven Media Personalization\n\n- Editorial Workflows with Gen AI\n\n- Gen AI-Powered Video Summarization"} -{"chunk_id": "68d6348e7a7e4b3c5a4fa036-0", "page_id": "68d6348e7a7e4b3c5a4fa036", "source_name": "atlas-architecture", "product_name": "Atlas Architecture Center", "url": "https://mongodb.com/docs/atlas/architecture/current/auth/authorization", "title": "Guidance for Atlas Authorization", "text": "# Guidance for Atlas Authorization\n\nMongoDB Atlas supports a variety of authorization methods to ensure robust access to resources. Atlas requires all users to authenticate. Once the user is authenticated, authorization determines the user's access to resources.\n\nWhen implementing Atlas authorization, you must use Role-Based Access Control (RBAC). Using an Federated Identity Provider's user groups with RBAC simplifies management.\n\nThe following recommendations apply to both workforce (human) and workload (application) users in all deployment paradigms.\n\nThe MongoDB Atlas Shared Responsibility Model defines the complementary duties of MongoDB and its customers in maintaining a secure and resilient data environment. Under this framework, MongoDB manages the security and operational integrity of the underlying platform, while customers are responsible for the configuration, management, and data policies of their specific deployments. For a detailed breakdown of ownership across security and operational excellence, see Shared Responsibility Model.\n\n## RBAC and Predefined Roles\n\nAtlas uses Role-Based Access Control (RBAC) to simplify management of user authorization. Atlas includes predefined user roles that provide specific levels of access commonly needed for managing the Atlas with the UI and APIs. To simplify management, you can then map the roles to to IdP (Identity Provider) groups.\n\nFor connecting to Atlas clusters, use fine-grained custom database roles to provide granular scoping based on the access required for the role to perform its function. This approach enables you to follow the principle of least privilege.\n\nYou should always restrict access by assigning the lowest-needed RBAC roles. You should also use domain restrictions.\n\nThere are two levels of roles that you can assign: organization-level and project-level.\n\n### Organization-Level Roles\n\nOrganization-level roles are used by service accounts to automate tasks such as creating new projects, managing IAM, and billing. They may also be used for platform team members.\n\n- The `Organization Owner` role should be heavily restricted and not assigned to a human, as it has the ability to change organization-wide settings and delete configurations. This role should be assigned to a service account which you use only to initially set up and configure the organization. Minimize configuration changes after the initial creation. To avoid account lockouts, you can create the following items:\n\n - SAML Organization Owner group with Just-in-Time Access.\n\n - Service account with the Organization Owner role. Keep it in a secure place with strong access management for break-glass emergency scenarios.\n\n- The `Organization Member` role should be for admins on the operations and platform team that can view settings and configuration for the organization.\n\n- The `Organization Project Creator` role should be a programmatic service account used to create projects on behalf of new applications for development and product teams.\n\n- The `Organization Billing Admin` role should be a programmatic service account used to pull invoices programmatically from the Billing API and feed them into your FinOps tool. This same service account should have access to all linked organizations for which it is responsible for reporting usage.\n\n### Project-Level Roles\n\nProject-level roles are for the development, test, and product teams that are responsible for application development and maintenance. As with organization-level roles, you should always follow the principle of least privilege. For example, the `Project Owner` role should only be used for governance enforced by the operations and provisioning team. Because a Project Owner can create and delete clusters, you should assign this role to a programmatic service account unless you are working in a sandbox environment.\n\nTo learn more about project-level roles, see:\n\n- Atlas User Roles\n\n## Federated Identity Providers\n\nBy integrating Atlas with a federated identity provider, you can use just-in-time provisioning by mapping identity provider groups to Atlas roles. This streamlines access management and ensures secure and organized role assignments throughout the platform. You can grant access programmatically based on the provisioning process of your orchestration layer.\n\nYou should use a modern Federated Identity Provider (FIP) that provides SSO, such as Azure Entra ID, Okta, or Ping Identity. This makes the authorization process more secure and supports the flexibility needed to programmatically assign IdP (Identity Provider) groups to Atlas roles. You should restrict access to your company's domain, which prevents users from logging into Atlas when they are not authorized for access.\n\nTo learn more about mapping roles to Federated Identity provider groups, see Role Mapping Process.\n\n## Just-in-Time Access\n\nAtlas also supports creating temporary database users that automatically expire after the predefined times. A user can be created for 6 hours, 1 day, or 1 week.\n\nTo learn more, see Configure Database Users.\n\n## Examples\n\nFor examples of configuring Authorization, see Authorization and Authentication Examples."} -{"chunk_id": "68a95c565e79d242619e3c71-0", "page_id": "68a95c565e79d242619e3c71", "source_name": "atlas-architecture", "product_name": "Atlas Architecture Center", "url": "https://mongodb.com/docs/atlas/architecture/current/security", "title": "Security in the Atlas Well-Architected Framework", "text": "# Security in the Atlas Well-Architected Framework\n\nThe Security pillar of the Atlas Well-Architected Framework includes features that ensure data integrity and privacy through comprehensive safeguarding measures, such as encryption at rest and in transit, fine-grained access controls, and adherence to regulatory standards.\n\nThe MongoDB Atlas Shared Responsibility Model defines the complementary duties of MongoDB and its customers in maintaining a secure and resilient data environment. Under this framework, MongoDB manages the security and operational integrity of the underlying platform, while customers are responsible for the configuration, management, and data policies of their specific deployments. For a detailed breakdown of ownership across security and operational excellence, see Shared Responsibility Model.\n\nUse the following Atlas Architecture Center resources to learn about security in Atlas:\n\nMongoDB Atlas enforces mandatory TLS (Transport Layer Security) encryption for database connections. Restrict database access to specific IP addresses and CIDR (Classless Inter-Domain Routing) ranges and use private endpoints and VPC peering.\n\nUse Role-Based Access Control (RBAC) with built-in and custom roles to control operations on resources. Get recommendations on the best authentication method for production environments.\n\nUse encryption features in Atlas to protect data while in transit, at rest, and in use to safeguard data through its full lifecycle.\n\nAtlas meets a list of compliance standards to ensure that you can protect and monitor data while complying with external requirements.\n\nUse auditing and logs to monitor and log Atlas platform activities. Get recommendations on the events you should audit."} -{"chunk_id": "68a95bd75e79d242619d384c-0", "page_id": "68a95bd75e79d242619d384c", "source_name": "atlas-cli", "product_name": "Atlas CLI", "url": "https://mongodb.com/docs/atlas/cli/current/command/atlas-dbusers-certs", "title": "atlas dbusers certs", "text": "# atlas dbusers certs\n\nManage Atlas x509 certificates for your database users.\n\n## Options\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\n-h, --help\n\n\n\n\nfalse\n\n\nhelp for certs\n\n
\n\n## Inherited Options\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\n-P, --profile\n\n\nstring\n\n\nfalse\n\n\nName of the profile to use from your configuration file. To learn about profiles for the Atlas CLI, see https://dochub.mongodb.org/core/atlas-cli-save-connection-settings.\n\n
\n\n## Related Commands\n\n- atlas dbusers certs create - Create a new Atlas-managed X.509 certificate for the specified database user.\n\n- atlas dbusers certs list - Return all Atlas-managed, unexpired X.509 certificates for the specified database user."} -{"chunk_id": "68a95bd75e79d242619d37c5-0", "page_id": "68a95bd75e79d242619d37c5", "source_name": "atlas-cli", "product_name": "Atlas CLI", "url": "https://mongodb.com/docs/atlas/cli/current/command/atlas-clusters-onlineArchives-delete", "title": "atlas clusters onlineArchives delete", "text": "# atlas clusters onlineArchives delete\n\nRemove the specified online archive from your cluster.\n\nTo use this command, you must authenticate with a user account, a service account, or an API key with the Project Data Access Admin role.\n\n## Syntax\n\n```\natlas clusters onlineArchives delete [options]\n```\n\n## Arguments\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\narchiveId\n\n\nstring\n\n\ntrue\n\n\nUnique identifier of the online archive to delete.\n\n
\n\n## Options\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\n--clusterName\n\n\nstring\n\n\ntrue\n\n\nName of the cluster. To learn more, see https://dochub.mongodb.org/core/create-cluster-api.\n\n
\n--force\n\n\n\n\nfalse\n\n\nFlag that indicates whether to skip the confirmation prompt before proceeding with the requested action.\n\n
\n-h, --help\n\n\n\n\nfalse\n\n\nhelp for delete\n\n
\n--projectId\n\n\nstring\n\n\nfalse\n\n\nHexadecimal string that identifies the project to use. This option overrides the settings in the configuration file or environment variable.\n\n
\n\n## Inherited Options\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\n-P, --profile\n\n\nstring\n\n\nfalse\n\n\nName of the profile to use from your configuration file. To learn about profiles for the Atlas CLI, see https://dochub.mongodb.org/core/atlas-cli-save-connection-settings.\n\n
\n\n## Output\n\nIf the command succeeds, the CLI returns output similar to the following sample. Values in brackets represent your values.\n\n```\nArchive '' deleted\n```\n\n## Examples\n\n```\n# Remove an online archive with the ID 5f189832e26ec075e10c32d3 for the cluster named myCluster:\natlas clusters onlineArchives delete 5f189832e26ec075e10c32d3 --clusterName myCluster\n```"} -{"chunk_id": "68a95bd75e79d242619d3843-0", "page_id": "68a95bd75e79d242619d3843", "source_name": "atlas-cli", "product_name": "Atlas CLI", "url": "https://mongodb.com/docs/atlas/cli/current/command/atlas-dataFederation-describe", "title": "atlas dataFederation describe", "text": "# atlas dataFederation describe\n\nReturn the details for the specified data federation database for your project.\n\nTo use this command, you must authenticate with a user account, a service account, or an API key with the Project Owner role.\n\n## Syntax\n\n```\natlas dataFederation describe [options]\n```\n\n## Arguments\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\nname\n\n\nstring\n\n\ntrue\n\n\nName of the data federation database.\n\n
\n\n## Options\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\n-h, --help\n\n\n\n\nfalse\n\n\nhelp for describe\n\n
\n-o, --output\n\n\nstring\n\n\nfalse\n\n\nOutput format. Valid values are json, json-path, go-template, or go-template-file. To see the full output, use the -o json option.\n\n
\n--projectId\n\n\nstring\n\n\nfalse\n\n\nHexadecimal string that identifies the project to use. This option overrides the settings in the configuration file or environment variable.\n\n
\n\n## Inherited Options\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\n-P, --profile\n\n\nstring\n\n\nfalse\n\n\nName of the profile to use from your configuration file. To learn about profiles for the Atlas CLI, see https://dochub.mongodb.org/core/atlas-cli-save-connection-settings.\n\n
\n\n## Examples\n\n```\n# retrieves data federation 'DataFederation1':\natlas dataFederation describe DataFederation1\n```"} -{"chunk_id": "68fb19f83b754f1e0c7e81d6-0", "page_id": "68fb19f83b754f1e0c7e81d6", "source_name": "atlas-cli", "product_name": "Atlas CLI", "url": "https://mongodb.com/docs/atlas/cli/current/command/atlas-api-streams-updateStreamProcessor", "title": "atlas api streams updateStreamProcessor", "text": "# atlas api streams updateStreamProcessor\n\nModify one existing Stream Processor within the specified stream workspace.\n\nThe atlas api sub-command is automatically generated from the MongoDB Atlas Admin API and offers full coverage of the Admin API. Admin API capabilities have their own release lifecycle, which you can check via the provided API endpoint documentation link.\n\nThis command is autogenerated and corresponds 1:1 with the Atlas API endpoint https://www.mongodb.com/docs/api/doc/atlas-admin-api-v2/operation/operation-updategroupstreamprocessor.\n\nFor more information and examples, see the referenced API documentation linked above.\n\n## Syntax\n\n```\natlas api streams updateStreamProcessor [options]\n```\n\n## Options\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\n--envelope\n\n\nenvelope\n\n\nfalse\n\n\nFlag that indicates whether Application wraps the response in an envelope JSON object. Some API clients cannot access the HTTP response headers or status code. To remediate this, set envelope=true in the query. Endpoints that return a list of results use the results object as an envelope. Application adds the status parameter to the response body.\n\n
\n--file\n\n\nstring\n\n\nfalse\n\n\npath to your API request file. Leave empty to use standard input instead - you must provide one or the other, but not both.\n\n
\n--groupId\n\n\nstring\n\n\ntrue\n\n\nUnique 24-hexadecimal digit string that identifies your project. Use the [/groups](#tag/Projects/operation/listProjects) endpoint to retrieve all projects to which the authenticated user has access.\n\n**NOTE**: Groups and projects are synonymous terms. Your group id is the same as your project id. For existing groups, your group/project id remains the same. The resource and corresponding endpoints use the term groups.\n\n
\n-h, --help\n\n\n\n\nfalse\n\n\nhelp for updateStreamProcessor\n\n
\n-o, --output\n\n\nstring\n\n\nfalse\n\n\npreferred api format, can be [\"json\", go-template] This value defaults to \"json\".\n\n
\n--outputFile\n\n\nstring\n\n\nfalse\n\n\nfile to write the api output to. This flag is required when the output of an endpoint is binary (ex: gzip) and the command is not piped (ex: atlas command > out.zip)\n\n
\n--pretty\n\n\n\n\nfalse\n\n\nFlag that indicates whether the response body should be in the prettyprint format.\n\n
\n--processorName\n\n\nstring\n\n\ntrue\n\n\nLabel that identifies the stream processor.\n\n
\n--tenantName\n\n\nstring\n\n\ntrue\n\n\nLabel that identifies the stream workspace.\n\n
\n--version\n\n\nstring\n\n\nfalse\n\n\nAPI version to use when calling the Atlas API endpoints [options: \"2024-05-30\"]. If not set by the user, defaults to the latest version or the profile's api_version config value if set. This value defaults to \"2024-05-30\".\n\n
\n\n## Inherited Options\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\n-P, --profile\n\n\nstring\n\n\nfalse\n\n\nName of the profile to use from your configuration file. To learn about profiles for the Atlas CLI, see https://dochub.mongodb.org/core/atlas-cli-save-connection-settings.\n\n
"} -{"chunk_id": "68fb19f83b754f1e0c7e80b1-0", "page_id": "68fb19f83b754f1e0c7e80b1", "source_name": "atlas-cli", "product_name": "Atlas CLI", "url": "https://mongodb.com/docs/atlas/cli/current/command/atlas-api-projects-createGroup", "title": "atlas api projects createGroup", "text": "# atlas api projects createGroup\n\nCreates one project.\n\nThe atlas api sub-command is automatically generated from the MongoDB Atlas Admin API and offers full coverage of the Admin API. Admin API capabilities have their own release lifecycle, which you can check via the provided API endpoint documentation link.\n\nProjects group clusters into logical collections that support an application environment, workload, or both. Each project can have its own users, teams, security, tags, and alert settings.\n\nThis command is autogenerated and corresponds 1:1 with the Atlas API endpoint https://www.mongodb.com/docs/api/doc/atlas-admin-api-v2/operation/operation-creategroup.\n\nFor more information and examples, see the referenced API documentation linked above.\n\n## Syntax\n\n```\natlas api projects createGroup [options]\n```\n\n## Options\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\n--envelope\n\n\nenvelope\n\n\nfalse\n\n\nFlag that indicates whether Application wraps the response in an envelope JSON object. Some API clients cannot access the HTTP response headers or status code. To remediate this, set envelope=true in the query. Endpoints that return a list of results use the results object as an envelope. Application adds the status parameter to the response body.\n\n
\n--file\n\n\nstring\n\n\nfalse\n\n\npath to your API request file. Leave empty to use standard input instead - you must provide one or the other, but not both.\n\n
\n-h, --help\n\n\n\n\nfalse\n\n\nhelp for createGroup\n\n
\n-o, --output\n\n\nstring\n\n\nfalse\n\n\npreferred api format, can be [\"json\", go-template] This value defaults to \"json\".\n\n
\n--outputFile\n\n\nstring\n\n\nfalse\n\n\nfile to write the api output to. This flag is required when the output of an endpoint is binary (ex: gzip) and the command is not piped (ex: atlas command > out.zip)\n\n
\n--pretty\n\n\n\n\nfalse\n\n\nFlag that indicates whether the response body should be in the prettyprint format.\n\n
\n--projectOwnerId\n\n\nstring\n\n\nfalse\n\n\nUnique 24-hexadecimal digit string that identifies the MongoDB Cloud user to whom to grant the Project Owner role on the specified project. If you set this parameter, it overrides the default value of the oldest Organization Owner.\n\n
\n--version\n\n\nstring\n\n\nfalse\n\n\nAPI version to use when calling the Atlas API endpoints [options: \"2023-01-01\"]. If not set by the user, defaults to the latest version or the profile's api_version config value if set. This value defaults to \"2023-01-01\".\n\n
\n\n## Inherited Options\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\n-P, --profile\n\n\nstring\n\n\nfalse\n\n\nName of the profile to use from your configuration file. To learn about profiles for the Atlas CLI, see https://dochub.mongodb.org/core/atlas-cli-save-connection-settings.\n\n
\n\n## Examples\n\nCreates a new project named \"MongoTube\" with an environment tag set to \"e2e\"\n\nCreate the file below and save it as `payload.json`\n\n```shell\n{\n \"name\": \"MongoTube\",\n \"orgId\": \"67b715468c10250b968dcb84\",\n \"tags\": [\n {\n \"key\": \"environment\",\n \"value\": \"e2e\"\n }\n ]\n}\n```\n\nAfter creating `payload.json`, run the command below in the same directory.\n\n```shell\natlas api projects createGroup --version 2023-01-01\n\n```"} -{"chunk_id": "68a95bd75e79d242619d343f-0", "page_id": "68a95bd75e79d242619d343f", "source_name": "atlas-cli", "product_name": "Atlas CLI", "url": "https://mongodb.com/docs/atlas/cli/current/command/atlas-api-encryptionAtRestUsingCustomerKeyManagement", "title": "atlas api encryptionAtRestUsingCustomerKeyManagement", "text": "# atlas api encryptionAtRestUsingCustomerKeyManagement\n\nReturns and edits the Encryption at Rest using Customer Key Management configuration.\n\nThe atlas api sub-command is automatically generated from the MongoDB Atlas Admin API and offers full coverage of the Admin API. Admin API capabilities have their own release lifecycle, which you can check via the provided API endpoint documentation link.\n\nMongoDB Cloud encrypts all storage whether or not you use your own key management.\n\n## Options\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\n-h, --help\n\n\n\n\nfalse\n\n\nhelp for encryptionAtRestUsingCustomerKeyManagement\n\n
\n\n## Inherited Options\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\n-P, --profile\n\n\nstring\n\n\nfalse\n\n\nName of the profile to use from your configuration file. To learn about profiles for the Atlas CLI, see https://dochub.mongodb.org/core/atlas-cli-save-connection-settings.\n\n
\n\n## Related Commands\n\n- atlas api encryptionAtRestUsingCustomerKeyManagement createRestPrivateEndpoint - Creates a private endpoint in the specified region for encryption at rest using customer key management.\n\n- atlas api encryptionAtRestUsingCustomerKeyManagement getEncryptionAtRest - Returns the configuration for encryption at rest using the keys you manage through your cloud provider.\n\n- atlas api encryptionAtRestUsingCustomerKeyManagement getRestPrivateEndpoint - Returns one private endpoint, identified by its ID, for encryption at rest using Customer Key Management.\n\n- atlas api encryptionAtRestUsingCustomerKeyManagement listRestPrivateEndpoints - Returns the private endpoints of the specified cloud provider for encryption at rest using customer key management.\n\n- atlas api encryptionAtRestUsingCustomerKeyManagement requestPrivateEndpointDeletion - Deletes one private endpoint, identified by its ID, for encryption at rest using Customer Key Management.\n\n- atlas api encryptionAtRestUsingCustomerKeyManagement updateEncryptionAtRest - Updates the configuration for encryption at rest using the keys you manage through your cloud provider."} -{"chunk_id": "68fb19f83b754f1e0c7e811f-0", "page_id": "68fb19f83b754f1e0c7e811f", "source_name": "atlas-cli", "product_name": "Atlas CLI", "url": "https://mongodb.com/docs/atlas/cli/current/command/atlas-api-queryShapeInsights-listQueryShapeSummaries", "title": "atlas api queryShapeInsights listQueryShapeSummaries", "text": "# atlas api queryShapeInsights listQueryShapeSummaries\n\nReturns a list of query shape statistics summaries for a given cluster.\n\nThe atlas api sub-command is automatically generated from the MongoDB Atlas Admin API and offers full coverage of the Admin API. Admin API capabilities have their own release lifecycle, which you can check via the provided API endpoint documentation link.\n\nQuery shape statistics provide performance insights about MongoDB queries, helping users identify problematic query patterns and potential optimizations.\n\nThis command is autogenerated and corresponds 1:1 with the Atlas API endpoint https://www.mongodb.com/docs/api/doc/atlas-admin-api-v2/operation/operation-listgroupclusterqueryshapeinsightsummaries.\n\nFor more information and examples, see the referenced API documentation linked above.\n\n## Syntax\n\n```\natlas api queryShapeInsights listQueryShapeSummaries [options]\n```\n\n## Options\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\n--clusterName\n\n\nstring\n\n\ntrue\n\n\nHuman-readable label that identifies the cluster.\n\n
\n--commands\n\n\n&\n\n\nfalse\n\n\nRetrieve query shape statistics matching specified MongoDB commands. To include multiple commands, pass the parameter multiple times delimited with an ampersand (&) between each command. The currently supported parameters are: find, distinct, aggregate, count, insert, update, and delete. The insert, update, and delete commands return results only for clusters running MongoDB 9.0 or later with write query shape statistics enabled for the project. Omit this parameter to return results for all supported commands.\n\n
\n--envelope\n\n\nenvelope\n\n\nfalse\n\n\nFlag that indicates whether Application wraps the response in an envelope JSON object. Some API clients cannot access the HTTP response headers or status code. To remediate this, set envelope=true in the query. Endpoints that return a list of results use the results object as an envelope. Application adds the status parameter to the response body.\n\n
\n--groupId\n\n\nstring\n\n\ntrue\n\n\nUnique 24-hexadecimal digit string that identifies your project. Use the [/groups](#tag/Projects/operation/listProjects) endpoint to retrieve all projects to which the authenticated user has access.\n\n**NOTE**: Groups and projects are synonymous terms. Your group id is the same as your project id. For existing groups, your group/project id remains the same. The resource and corresponding endpoints use the term groups.\n\n
\n-h, --help\n\n\n\n\nfalse\n\n\nhelp for listQueryShapeSummaries\n\n
\n--nSummaries\n\n\nint\n\n\nfalse\n\n\nMaximum number of query statistic summaries to return.\n\n
\n--namespaces\n\n\n.\n\n\nfalse\n\n\nNamespaces from which to retrieve query shape statistics. A namespace consists of one database and one collection resource written as .: `.`. To include multiple namespaces, pass the parameter multiple times delimited with an ampersand (`&`) between each namespace. Omit this parameter to return results for all namespaces.\n\n
\n-o, --output\n\n\nstring\n\n\nfalse\n\n\npreferred api format, can be [\"json\", go-template] This value defaults to \"json\".\n\n
\n--outputFile\n\n\nstring\n\n\nfalse\n\n\nfile to write the api output to. This flag is required when the output of an endpoint is binary (ex: gzip) and the command is not piped (ex: atlas command > out.zip)\n\n
\n--pretty\n\n\n\n\nfalse\n\n\nFlag that indicates whether the response body should be in the prettyprint format.\n\n
\n--processIds\n\n\nprocessId\n\n\nfalse\n\n\nProcess IDs from which to retrieve query shape statistics. A processId is a combination of host and port that serves the MongoDB process. The host must be the hostname, FQDN, IPv4 address, or IPv6 address of the host that runs the MongoDB process (`mongod` or `mongos`). The port must be the IANA port on which the MongoDB process listens for requests. To include multiple `processId`, pass the parameter multiple times delimited with an ampersand (`&`) between each `processId`.\n\n
\n--queryShapeHashes\n\n\n$queryStats\n\n\nfalse\n\n\nA list of SHA256 hashes of desired query shapes, output by MongoDB commands like $queryStats and $explain or slow query logs. To include multiple series, pass the parameter multiple times delimited with an ampersand (`&`) between each series. Omit this parameter to return results for all available series.\n\n
\n--series\n\n\n&\n\n\nfalse\n\n\nQuery shape statistics data series to retrieve. A series represents a specific metric about query execution. To include multiple series, pass the parameter multiple times delimited with an ampersand (&) between each series. Omit this parameter to return results for all available series. The `P50_EXECUTION_TIME`, `P90_EXECUTION_TIME`, and `P99_EXECUTION_TIME` series are deprecated as the values they report may be inaccurate. They will be removed in a future release.\n\n
\n--since\n\n\nint\n\n\nfalse\n\n\nDate and time from which to retrieve query shape statistics. This parameter expresses its value in the number of milliseconds that have elapsed since the [UNIX epoch](https://en.wikipedia.org/wiki/Unix_time).\n\n- If you don't specify the **until** parameter, the endpoint returns data covering from the **since** value and the current time.\n\n- If you specify neither the **since** nor the **until** parameters, the endpoint returns data from the previous 24 hours.\n\n
\n--until\n\n\nint\n\n\nfalse\n\n\nDate and time up until which to retrieve query shape statistics. This parameter expresses its value in the number of milliseconds that have elapsed since the [UNIX epoch](https://en.wikipedia.org/wiki/Unix_time).\n\n- If you specify the **until** parameter, you must specify the **since** parameter.\n\n- If you specify neither the **since** nor the **until** parameters, the endpoint returns data from the previous 24 hours.\n\n
\n--version\n\n\nstring\n\n\nfalse\n\n\nAPI version to use when calling the Atlas API endpoints [options: \"2025-03-12\"]. If not set by the user, defaults to the latest version or the profile's api_version config value if set. This value defaults to \"2025-03-12\".\n\n
"} -{"chunk_id": "68fb19f83b754f1e0c7e811f-1", "page_id": "68fb19f83b754f1e0c7e811f", "source_name": "atlas-cli", "product_name": "Atlas CLI", "url": "https://mongodb.com/docs/atlas/cli/current/command/atlas-api-queryShapeInsights-listQueryShapeSummaries", "title": "atlas api queryShapeInsights listQueryShapeSummaries", "text": "## Inherited Options\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\n-P, --profile\n\n\nstring\n\n\nfalse\n\n\nName of the profile to use from your configuration file. To learn about profiles for the Atlas CLI, see https://dochub.mongodb.org/core/atlas-cli-save-connection-settings.\n\n
\n\n## Examples\n\n```shell\natlas api queryShapeInsights listQueryShapeSummaries --version 2025-03-12 --clusterName [clusterName] --groupId 32b6e34b3d91647abb20e7b8\n\n```"} -{"chunk_id": "68a95bd75e79d242619d3746-0", "page_id": "68a95bd75e79d242619d3746", "source_name": "atlas-cli", "product_name": "Atlas CLI", "url": "https://mongodb.com/docs/atlas/cli/current/command/atlas-backups-compliancePolicy-policies", "title": "atlas backups compliancePolicy policies", "text": "# atlas backups compliancePolicy policies\n\nManage the individual policy items of the backup compliance policy for your project.\n\n## Options\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\n-h, --help\n\n\n\n\nfalse\n\n\nhelp for policies\n\n
\n\n## Inherited Options\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\n-P, --profile\n\n\nstring\n\n\nfalse\n\n\nName of the profile to use from your configuration file. To learn about profiles for the Atlas CLI, see https://dochub.mongodb.org/core/atlas-cli-save-connection-settings.\n\n
\n\n## Related Commands\n\n- atlas backups compliancePolicy policies describe - Return the individual policy items of the backup compliance policy for your project.\n\n- atlas backups compliancePolicy policies ondemand - Manage the on-demand policy item of the backup compliance policy for your project.\n\n- atlas backups compliancePolicy policies scheduled - Manage the scheduled policy items of the backup compliance policy for your project."} -{"chunk_id": "68fb19f83b754f1e0c7e7f41-0", "page_id": "68fb19f83b754f1e0c7e7f41", "source_name": "atlas-cli", "product_name": "Atlas CLI", "url": "https://mongodb.com/docs/atlas/cli/current/command/atlas-api-invoices-getCostExplorerUsage", "title": "atlas api invoices getCostExplorerUsage", "text": "# atlas api invoices getCostExplorerUsage\n\nReturns the usage details for a Cost Explorer query, if the query is finished and the data is ready to be viewed.\n\nThe atlas api sub-command is automatically generated from the MongoDB Atlas Admin API and offers full coverage of the Admin API. Admin API capabilities have their own release lifecycle, which you can check via the provided API endpoint documentation link.\n\nIf the data is not ready, a 'processing' response will indicate that another request should be sent later to view the data.\n\nThis command is autogenerated and corresponds 1:1 with the Atlas API endpoint https://www.mongodb.com/docs/api/doc/atlas-admin-api-v2/operation/operation-getorgbillingcostexplorerusage.\n\nFor more information and examples, see the referenced API documentation linked above.\n\n## Syntax\n\n```\natlas api invoices getCostExplorerUsage [options]\n```\n\n## Options\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\n--envelope\n\n\nenvelope\n\n\nfalse\n\n\nFlag that indicates whether Application wraps the response in an envelope JSON object. Some API clients cannot access the HTTP response headers or status code. To remediate this, set envelope=true in the query. Endpoints that return a list of results use the results object as an envelope. Application adds the status parameter to the response body.\n\n
\n-h, --help\n\n\n\n\nfalse\n\n\nhelp for getCostExplorerUsage\n\n
\n--orgId\n\n\n/orgs\n\n\ntrue\n\n\nUnique 24-hexadecimal digit string that identifies the organization that contains your projects. Use the [/orgs](#tag/Organizations/operation/listOrganizations) endpoint to retrieve all organizations to which the authenticated user has access.\n\n
\n-o, --output\n\n\nstring\n\n\ntrue\n\n\npreferred api format, can be [\"csv\", \"json\", go-template]\n\n
\n--outputFile\n\n\nstring\n\n\nfalse\n\n\nfile to write the api output to. This flag is required when the output of an endpoint is binary (ex: gzip) and the command is not piped (ex: atlas command > out.zip)\n\n
\n--token\n\n\nstring\n\n\ntrue\n\n\nUnique 64 digit string that identifies the Cost Explorer query.\n\n
\n--version\n\n\nstring\n\n\nfalse\n\n\nAPI version to use when calling the Atlas API endpoints [options: \"2023-01-01\"]. If not set by the user, defaults to the latest version or the profile's api_version config value if set. This value defaults to \"2023-01-01\".\n\n
\n\n## Inherited Options\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\n-P, --profile\n\n\nstring\n\n\nfalse\n\n\nName of the profile to use from your configuration file. To learn about profiles for the Atlas CLI, see https://dochub.mongodb.org/core/atlas-cli-save-connection-settings.\n\n
\n\n## Examples\n\n```shell\natlas api invoices getCostExplorerUsage --version 2023-01-01 --orgId 4888442a3354817a7320eb61 --token 4ABBE973862346D40F3AE859D4BE96E0F895764EB14EAB039E7B82F9D638C05C\n\n```"} -{"chunk_id": "68a95bd75e79d242619d3917-0", "page_id": "68a95bd75e79d242619d3917", "source_name": "atlas-cli", "product_name": "Atlas CLI", "url": "https://mongodb.com/docs/atlas/cli/current/command/atlas-metrics-databases", "title": "atlas metrics databases", "text": "# atlas metrics databases\n\nList available databases or database metrics for a given host.\n\n## Options\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\n-h, --help\n\n\n\n\nfalse\n\n\nhelp for databases\n\n
\n\n## Inherited Options\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\n-P, --profile\n\n\nstring\n\n\nfalse\n\n\nName of the profile to use from your configuration file. To learn about profiles for the Atlas CLI, see https://dochub.mongodb.org/core/atlas-cli-save-connection-settings.\n\n
\n\n## Related Commands\n\n- atlas metrics databases describe - Return the measurements of a database on the specified host.\n\n- atlas metrics databases list - Return all databases running on the specified host for your project."} -{"chunk_id": "69fed30b9448a5306cad69e9-0", "page_id": "69fed30b9448a5306cad69e9", "source_name": "atlas-operator", "product_name": "MongoDB Atlas Kubernetes Operator", "url": "https://mongodb.com/docs/atlas/operator/current/generated-crds-overview", "title": "Generated Custom Resources", "text": "# Generated Custom Resources\n\nAtlas Kubernetes Operator doesn't support Atlas Infinite Database clusters in public preview. To learn which features Atlas Infinite Database supports in public preview, see Atlas Infinite Database Edition. To learn more about preview features, see Preview Features.## Overview\n\nAtlas Kubernetes Operator provides a set of custom resource definitions (CRDs) that are auto-generated from the MongoDB Atlas Administration API OpenAPI specification. These generated CRDs offer direct parity with the Atlas Administration API and are updated regularly as the API evolves. Over time, generated CRDs will replace the existing custom resources as the standard interface for managing Atlas resources through Atlas Kubernetes Operator.\n\nGenerated CRDs are **not** compatible with the existing set of custom resources. You cannot mix generated and existing CRDs to manage the same Atlas resource. Choose one set of CRDs for each resource you manage through Atlas Kubernetes Operator.\n\n## Choosing Between CRD Sets\n\nBecause Atlas Kubernetes Operator currently offers a limited number of generated CRDs, you should evaluate which set best fits your needs:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nExisting Custom Resources\n\n\nGenerated Custom Resources\n\n
\nFull coverage of Atlas resource types.\n\n\nLimited but expanding coverage of Atlas resource types.\n\n
\nWill be deprecated in a future release.\n\n\nWill become the standard for managing Atlas resources through Atlas Kubernetes Operator.\n\n
\nStable and well-established.\n\n\nClosely tracks the Atlas Administration API OpenAPI specification.\n\n
If the resource you need is available as a generated CRD, consider adopting it now to reduce the future effort of migrating from the existing CRDs. If a generated CRD is not yet available for your resource, continue to use the existing custom resources.\n\n## Available Generated CRDs\n\nAtlas Kubernetes Operator currently supports the following generated CRDs:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nResource\n\n\nDescription\n\n
\n`Group` Custom Resource\n\n\nGroup in Atlas.\n\n
\n`Cluster` Custom Resource\n\n\nCluster in Atlas.\n\n
\n`DatabaseUser` Custom Resource\n\n\nDatabase user in Atlas.\n\n
\n`FlexCluster` Custom Resource\n\n\nFlex cluster in Atlas.\n\n
\n`IpaccessListEntry` Custom Resource\n\n\nIP access list entry in Atlas.\n\n
As the Atlas Administration API OpenAPI specification evolves, additional generated CRDs will become available. Check this page for updates."} -{"chunk_id": "68a95c0c5e79d242619dafaf-0", "page_id": "68a95c0c5e79d242619dafaf", "source_name": "atlas-operator", "product_name": "MongoDB Atlas Kubernetes Operator", "url": "https://mongodb.com/docs/atlas/operator/current", "title": "Atlas Kubernetes Operator", "text": "# Atlas Kubernetes Operator\n\nAtlas Kubernetes Operator doesn't support Atlas Infinite Database clusters in public preview. To learn which features Atlas Infinite Database supports in public preview, see Atlas Infinite Database Edition. To learn more about preview features, see Preview Features.## What is Atlas Kubernetes Operator?\n\nAtlas Kubernetes Operator is a new service that integrates Atlas resources with your Kubernetes cluster. You can now deploy and manage the lifecycle of your cloud-native applications that need data services in a single control plane with secure enterprise platform integration.\n\nTo learn more, see Quick Start.\n\n- Atlas Kubernetes Operator uses custom resource configuration files to manage your Atlas configuration, but as of Atlas Kubernetes Operator 2.0, custom resources you delete in Kubernetes are no longer (by default) deleted in Atlas. Instead, Atlas Kubernetes Operator simply stops managing those resources in Atlas. For example, if you delete an `AtlasProject` Custom Resource in Kubernetes, by default the Atlas Kubernetes Operator no longer automatically deletes the corresponding project from Atlas. This change in behavior is intended to help prevent accidental or unexpected deletions. To learn more, including how to revert this behavior to the default used prior to Atlas Kubernetes Operator 2.0, see New Default: Deletion Protection in Atlas Kubernetes Operator 2.0.\n\n Similarly, Atlas Kubernetes Operator does not delete teams from Atlas if you remove them from an Atlas project in Kubernetes with the Atlas Kubernetes Operator.\n\n- Explicitly define your desired configuration details in order to avoid implicitly using default Atlas configuration values. In some cases, inheriting Atlas defaults may result in a reconciliation loop which can prevent your custom resource from achieving a `READY` state. For example, explicitly defining your desired autoscaling behavior in your `AtlasDeployment` custom resource, as shown in the included example, ensures that a static instance size in your custom resource is not being repeatedly applied to an Atlas deployment which has autoscaling enabled.\n\n ```yaml\n autoScaling:\n diskGB:\n enabled: true\n compute:\n enabled: true\n scaleDownEnabled: true\n minInstanceSize: M30\n maxInstanceSize: M40\n ```\n\n## What Can You Do?\n\nYou can use Atlas Kubernetes Operator to manage resources in Atlas without leaving Kubernetes. You deploy Atlas Kubernetes Operator into Kubernetes clusters. Atlas Kubernetes Operator manages resources in Atlas based on Kubernetes custom resources. It ensures that the state of the projects, database deployments, and database users in Atlas matches the configurations in each `AtlasProject` Custom Resource, `AtlasDeployment` Custom Resource, and `AtlasDatabaseUser` Custom Resource that you create in your Kubernetes cluster.\n\nAtlas Kubernetes Operator supports many advanced features within the Custom Resources, such as X509 authentication, private endpoints in Azure and AWS, and advanced multi-cloud and multi-region clusters.\n\n## New Default: Deletion Protection in Atlas Kubernetes Operator 2.0\n\nBy default with Atlas Kubernetes Operator, custom resources you delete in Kubernetes are no longer deleted in Atlas. Instead, Atlas Kubernetes Operator simply stops managing those resources.\n\nFor example, if you delete an `AtlasProject` Custom Resource in Kubernetes, Atlas Kubernetes Operator no longer automatically deletes the corresponding project from Atlas, preventing accidental or unexpected deletions. This applies to all objects managed using custom resources.\n\nYou can revert this behavior to the default used prior to Atlas Kubernetes Operator 2.0 for your entire deployment or for specific custom resources or subobjects.\n\nUse the following tables to determine the correct behavior for your deployment:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nDeletion Protection\n\n\nNo Deletion Protection\n\n
\nNew default as of Atlas Kubernetes Operator 2.0\n\n\nDefault prior to Atlas Kubernetes Operator 2.0\n\n
\nIf you delete a custom resource or objects from a custom resource, the corresponding objects remain in Atlas but Atlas Kubernetes Operator no longer manages them. You can manage objects decoupled from Atlas Kubernetes Operator only from another interface, such as the Atlas UI.\n\n\nIf you delete a custom resource or objects from a custom resource, Atlas Kubernetes Operator deletes the corresponding objects in Atlas, even objects deployed prior to using Atlas Kubernetes Operator. Changes to a custom resource overwrite changes in Atlas made using another interface, such as the Atlas UI.\n\n
\n\n### Revert New Deletion Protection Default\n\nYou can control the new deletion protection behavior using the `--object-deletion-protection` flag or the `OBJECT_DELETION_PROTECTION` environment variable in the Kubernetes\nDeployment resource that you applied when installing Atlas Kubernetes Operator. This flag and environment variable all default to `true`. Set to `false` to revert to the behavior prior to Atlas Kubernetes Operator 2.1.\n\nYou can also control which behavior to use for individual custom resources using the `atlas-resource-policy` annotations described in Use Annotations to Skip or Override Defaults."} -{"chunk_id": "68a95c0c5e79d242619dafaf-1", "page_id": "68a95c0c5e79d242619dafaf", "source_name": "atlas-operator", "product_name": "MongoDB Atlas Kubernetes Operator", "url": "https://mongodb.com/docs/atlas/operator/current", "title": "Atlas Kubernetes Operator", "text": "## Get Hands-On Experience with Atlas Kubernetes Operator\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nGoal\n\n\nAction\n\n
\nCreate your first cluster in Atlas with Atlas Kubernetes Operator.\n\n\nSee one of the following tutorials:\n\n- Quick Start\n\n- Helm Charts Quick Start\n\n
\nConfigure Atlas Kubernetes Operator access to Atlas.\n\n\nSee Configure Access to Atlas.\n\n
\nManage resources.\n\n\nSee Custom Resources.\n\n
\nCreate and configure a federated database instance, including private endpoints for a federated database instance.\n\n\nConfigure the `AtlasDataFederation` Custom Resource.\n\n
\nSet up X509 authentication.\n\n\nConfigure the `AtlasProject` Custom Resource and `AtlasDatabaseUser` Custom Resource.\n\n
\nManage private endpoints.\n\n\n- For dedicated clusters, specify the spec.privateEndpoints parameter for the `AtlasProject` Custom Resource.\n\n- For Serverless instances, specify the spec.serverlessSpec.privateEndpoints parameter for the `AtlasDeployment` Custom Resource.\n\n- For federated database instances, specify the spec.privateEndpoints parameter for the `AtlasDataFederation` Custom Resource.\n\n
\nSet up network peering.\n\n\nConfigure the `AtlasProject` Custom Resource.\n\n
\nSet up unified access for an AWS (Amazon Web Services) IAM (Identity and Access Management) role.\n\n\nConfigure the `AtlasProject` Custom Resource.\n\n
\nConfigure federated authentication for your Atlas organization.\n\n\nConfigure the `AtlasFederatedAuth` Custom Resource.\n\n
\nCreate or update custom database roles.\n\n\nConfigure the `AtlasProject` Custom Resource.\n\n
\nEncrypt data at rest using a key management service.\n\n\nConfigure the `AtlasProject` Custom Resource and the `AtlasDeployment` Custom Resource.\n\n
\nSet up database auditing.\n\n\nConfigure the `AtlasProject` Custom Resource.\n\n
\nSet up cloud backup.\n\n\nConfigure the `AtlasBackupPolicy` Custom Resource, `AtlasBackupSchedule` Custom Resource, and `AtlasDeployment` Custom Resource.\n\n
\nSet up teams.\n\n\nConfigure the `AtlasTeam` Custom Resource and `AtlasProject` Custom Resource.\n\n
\nConfigure the maintenance window during which Atlas starts weekly maintenance on your database deployments.\n\n\nConfigure the `AtlasProject` Custom Resource.\n\n
\nIntegrate with third-party services.\n\n\nConfigure the `AtlasProject` Custom Resource.\n\n
"} -{"chunk_id": "68a95c0c5e79d242619dafa5-0", "page_id": "68a95c0c5e79d242619dafa5", "source_name": "atlas-operator", "product_name": "MongoDB Atlas Kubernetes Operator", "url": "https://mongodb.com/docs/atlas/operator/current/atlasthirdpartyintegration-custom-resource", "title": "`AtlasThirdPartyIntegration` Custom Resource", "text": "# `AtlasThirdPartyIntegration` Custom Resource\n\nAtlas Kubernetes Operator doesn't support Atlas Infinite Database clusters in public preview. To learn which features Atlas Infinite Database supports in public preview, see Atlas Infinite Database Edition. To learn more about preview features, see Preview Features.The `AtlasThirdPartyIntegration` custom resource configures third party integrations in an Atlas project. These resources allow you to manage third-party integrations with various monitoring services to collect and analyze the performance of your Atlas deployment.\n\n- Atlas Kubernetes Operator uses custom resource configuration files to manage your Atlas configuration, but as of Atlas Kubernetes Operator 2.0, custom resources you delete in Kubernetes are no longer (by default) deleted in Atlas. Instead, Atlas Kubernetes Operator simply stops managing those resources in Atlas. For example, if you delete an `AtlasProject` Custom Resource in Kubernetes, by default the Atlas Kubernetes Operator no longer automatically deletes the corresponding project from Atlas. This change in behavior is intended to help prevent accidental or unexpected deletions. To learn more, including how to revert this behavior to the default used prior to Atlas Kubernetes Operator 2.0, see New Default: Deletion Protection in Atlas Kubernetes Operator 2.0.\n\n Similarly, Atlas Kubernetes Operator does not delete teams from Atlas if you remove them from an Atlas project in Kubernetes with the Atlas Kubernetes Operator.\n\n- Explicitly define your desired configuration details in order to avoid implicitly using default Atlas configuration values. In some cases, inheriting Atlas defaults may result in a reconciliation loop which can prevent your custom resource from achieving a `READY` state. For example, explicitly defining your desired autoscaling behavior in your `AtlasDeployment` custom resource, as shown in the included example, ensures that a static instance size in your custom resource is not being repeatedly applied to an Atlas deployment which has autoscaling enabled.\n\n ```yaml\n autoScaling:\n diskGB:\n enabled: true\n compute:\n enabled: true\n scaleDownEnabled: true\n minInstanceSize: M30\n maxInstanceSize: M40\n ```\n\nAtlas Kubernetes Operator takes one of the following actions using the Atlas\nThird-Party Service Integration API Resource:\n\n- Creates a new third-party service integration.\n\n- Updates an existing third-party service integration.\n\n## Examples\n\n### Basic Example\n\nThe following example shows an `AtlasThirdPartyIntegration` custom resource that defines a Datadog integration within the `my-project` project.\n\n```\napiVersion: atlas.mongodb.com/v1\nkind: AtlasThirdPartyIntegration\nmetadata:\n name: my-atlas-integ\nspec:\n projectRef:\n name: my-project\n namespace: my-operator-namespace\n type: DATADOG\n datadog:\n apiKeySecretRef:\n name: datadog-secret\n region: US\n sendCollectionLatencyMetrics: enabled\n sendDatabaseMetrics: enabled\n```\n\n### Independent CRD Example\n\nThe following example shows an `AtlasThirdPartyIntegration`\nindependent CRD that defines the same Datadog integration defined in the Basic Example. This custom resource definition allows you to create this third-party integration in a project you don't manage in the same instance of Atlas Kubernetes Operator with which you define this resource. To enable independent operation, you must use an `externalProjectRef` instead of a `projectRef`, and you must supply a `connectionSecret` directly since this resource can't inherit API credentials from its parent project.\n\n```\napiVersion: atlas.mongodb.com/v1\nkind: AtlasThirdPartyIntegration\nmetadata:\n name: my-atlas-integ\nspec:\n externalProjectRef:\n projectID: 66e2f2b621571b7e69a89b66\n connectionSecret:\n name: atlas-connection-secret\n type: DATADOG\n datadog:\n apiKeySecretRef:\n name: datadog-secret\n region: US\n sendCollectionLatencyMetrics: enabled\n sendDatabaseMetrics: enabled\n```\n\n## Parameters"} -{"chunk_id": "68a95c0c5e79d242619dafa5-1", "page_id": "68a95c0c5e79d242619dafa5", "source_name": "atlas-operator", "product_name": "MongoDB Atlas Kubernetes Operator", "url": "https://mongodb.com/docs/atlas/operator/current/atlasthirdpartyintegration-custom-resource", "title": "`AtlasThirdPartyIntegration` Custom Resource", "text": "### AtlasThirdPartyIntegration\n\nAtlasThirdPartyIntegration is the Schema for the atlas 3rd party integrations API.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n`Name`\n\n\nType\n\n\nDescription\n\n\nRequired\n\n
\n`apiVersion`\n\n\nstring\n\n\natlas.mongodb.com/v1\n\n\ntrue\n\n
\n`kind`\n\n\nstring\n\n\n`AtlasThirdPartyIntegration`\n\n\ntrue\n\n
\n`metadata`\n\n\nobject\n\n\nRefer to the Kubernetes `API` documentation for the fields of the `metadata` field.\n\n\ntrue\n\n
\n`spec`\n\n\nobject\n\n\n`AtlasThirdPartyIntegrationSpec` contains the expected configuration for an integration **Validations:**\n\n- (has(self.``externalProjectRef``) && !has(self.``projectRef``)) || (!has(self.``externalProjectRef``) && has(self.``projectRef``)): must define only one project reference through `externalProjectRef` or `projectRef`\n\n- (has(self.``externalProjectRef``) && has(self.``connectionSecret``)) || !has(self.``externalProjectRef``): must define a local connection secret when referencing an external project\n\n- has(self.type) && self.type.size() != 0: must define a type of integration\n\n- !has(self.datadog) || (self.type == '`DATADOG`' && has(self.datadog)): only `DATADOG` type may set datadog fields\n\n- !has(self.``microsoftTeams``) || (self.type == '`MICROSOFT_TEAMS`' && has(self.``microsoftTeams``)): only `MICROSOFT_TEAMS` type may set `microsoftTeams` fields\n\n- !has(self.``newRelic``) || (self.type == '`NEW_RELIC`' && has(self.``newRelic``)): only `NEW_RELIC` type may set `newRelic` fields\n\n- !has(self.``opsGenie``) || (self.type == '`OPS_GENIE`' && has(self.``opsGenie``)): only `OPS_GENIE` type may set `opsGenie` fields\n\n- !has(self.prometheus) || (self.type == '`PROMETHEUS`' && has(self.prometheus)): only `PROMETHEUS` type may set prometheus fields\n\n- !has(self.``pagerDuty``) || (self.type == '`PAGER_DUTY`' && has(self.``pagerDuty``)): only `PAGER_DUTY` type may set `pagerDuty` fields\n\n- !has(self.slack) || (self.type == '`SLACK`' && has(self.slack)): only `SLACK` type may set slack fields\n\n- !has(self.``victorOps``) || (self.type == '`VICTOR_OPS`' && has(self.``victorOps``)): only `VICTOR_OPS` type may set `victorOps` fields\n\n- !has(self.webhook) || (self.type == '`WEBHOOK`' && has(self.webhook)): only `WEBHOOK` type may set webhook fields\n\n\nfalse\n\n
\n`status`\n\n\nobject\n\n\n`AtlasThirdPartyIntegrationStatus` holds the `status` of an integration\n\n\nfalse\n\n
\n#### AtlasThirdPartyIntegration.spec\n\nAtlasThirdPartyIntegrationSpec contains the expected configuration for an integration\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n`Name`\n\n\nType\n\n\nDescription\n\n\nRequired\n\n
\n`type`\n\n\nenum\n\n\nType of the integration. *Enum*: `DATADOG`, `MICROSOFT_TEAMS`, `NEW_RELIC`, `OPS_GENIE`, `PAGER_DUTY`, `PROMETHEUS`, `SLACK`, `VICTOR_OPS`, `WEBHOOK`\n\n\ntrue\n\n
\n`connectionSecret`\n\n\nobject\n\n\nName of the secret containing Atlas `API` private and public keys.\n\n\nfalse\n\n
\n`datadog`\n\n\nobject\n\n\nDatadog contains the config fields for Datadog's Integration.\n\n\nfalse\n\n
\n`externalProjectRef`\n\n\nobject\n\n\n`externalProjectRef` holds the parent Atlas project `ID`. Mutually exclusive with the \"`projectRef`\" field.\n\n\nfalse\n\n
\n`microsoftTeams`\n\n\nobject\n\n\n`MicrosoftTeams` contains the config fields for Microsoft Teams's Integration.\n\n\nfalse\n\n
\n`newRelic`\n\n\nobject\n\n\n`NewRelic` contains the config fields for New Relic's Integration.\n\n\nfalse\n\n
\n`opsGenie`\n\n\nobject\n\n\n`OpsGenie` contains the config fields for Ops Genie's Integration.\n\n\nfalse\n\n
\n`pagerDuty`\n\n\nobject\n\n\n`PagerDuty` contains the config fields for `PagerDuty`'s Integration.\n\n\nfalse\n\n
\n`projectRef`\n\n\nobject\n\n\n`projectRef` is a reference to the parent `AtlasProject` resource. Mutually exclusive with the \"`externalProjectRef`\" field.\n\n\nfalse\n\n
\n`prometheus`\n\n\nobject\n\n\nPrometheus contains the config fields for Prometheus's Integration.\n\n\nfalse\n\n
\n`slack`\n\n\nobject\n\n\nSlack contains the config fields for Slack's Integration.\n\n\nfalse\n\n
\n`victorOps`\n\n\nobject\n\n\n`VictorOps` contains the config fields for `VictorOps`'s Integration.\n\n\nfalse\n\n
\n`webhook`\n\n\nobject\n\n\nWebhook contains the config fields for Webhook's Integration.\n\n\nfalse\n\n
\n\n#### AtlasThirdPartyIntegration.spec.connectionSecret\n\nName of the secret containing Atlas API private and public keys.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n`Name`\n\n\nType\n\n\nDescription\n\n\nRequired\n\n
\n`name`\n\n\nstring\n\n\nName of the resource being referred to More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names\n\n\ntrue\n\n
\n\n#### AtlasThirdPartyIntegration.spec.datadog\n\nDatadog contains the config fields for Datadog's Integration.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n`Name`\n\n\nType\n\n\nDescription\n\n\nRequired\n\n
\n`apiKeySecretRef`\n\n\nobject\n\n\nAPIKeySecretRef holds the name of a secret containing the Datadog `API` key.\n\n\ntrue\n\n
\n`region`\n\n\nstring\n\n\nRegion is the Datadog region\n\n\ntrue\n\n
\n`sendCollectionLatencyMetrics`\n\n\nenum\n\n\n`SendCollectionLatencyMetrics` toggles sending collection latency metrics. *Enum*: enabled, disabled *Default*: disabled\n\n\nfalse\n\n
\n`sendDatabaseMetrics`\n\n\nenum"} -{"chunk_id": "68a95c0c5e79d242619dafa5-2", "page_id": "68a95c0c5e79d242619dafa5", "source_name": "atlas-operator", "product_name": "MongoDB Atlas Kubernetes Operator", "url": "https://mongodb.com/docs/atlas/operator/current/atlasthirdpartyintegration-custom-resource", "title": "`AtlasThirdPartyIntegration` Custom Resource", "text": "\n`SendDatabaseMetrics` toggles sending database metrics, including database and collection names *Enum*: enabled, disabled *Default*: disabled\n\n\nfalse\n\n
\n`sendQueryStatsMetrics`\n\n\nenum\n\n\n`SendQueryStatsMetrics` toggles sending query shape metrics that includes query hash and metrics on latency, execution frequency, documents returned, and timestamps. *Enum*: enabled, disabled *Default*: disabled\n\n\nfalse\n\n
\n`sendUserProvidedResourceTags`\n\n\nenum\n\n\n`SendUserProvidedResourceTags` toggles sending user-provided group and cluster resource tags with the Datadog metrics. *Enum*: enabled, disabled *Default*: disabled\n\n\nfalse\n\n
\n\n#### AtlasThirdPartyIntegration.spec.datadog.apiKeySecretRef\n\nAPIKeySecretRef holds the name of a secret containing the Datadog API key.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n`Name`\n\n\nType\n\n\nDescription\n\n\nRequired\n\n
\n`name`\n\n\nstring\n\n\nName of the resource being referred to More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names\n\n\ntrue\n\n
\n\n#### AtlasThirdPartyIntegration.spec.externalProjectRef\n\nexternalProjectRef holds the parent Atlas project ID. Mutually exclusive with the \"projectRef\" field.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n`Name`\n\n\nType\n\n\nDescription\n\n\nRequired\n\n
\n`id`\n\n\nstring\n\n\n`ID` is the Atlas project `ID`.\n\n\ntrue\n\n
\n\n#### AtlasThirdPartyIntegration.spec.microsoftTeams\n\nMicrosoftTeams contains the config fields for Microsoft Teams's Integration.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n`Name`\n\n\nType\n\n\nDescription\n\n\nRequired\n\n
\n`urlSecretRef`\n\n\nobject\n\n\nURLSecretRef holds the name of a secret containing the Microsoft Teams secret `URL`.\n\n\ntrue\n\n
\n\n#### AtlasThirdPartyIntegration.spec.microsoftTeams.urlSecretRef\n\nURLSecretRef holds the name of a secret containing the Microsoft Teams secret URL.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n`Name`\n\n\nType\n\n\nDescription\n\n\nRequired\n\n
\n`name`\n\n\nstring\n\n\nName of the resource being referred to More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names\n\n\ntrue\n\n
\n\n#### AtlasThirdPartyIntegration.spec.newRelic\n\nNewRelic contains the config fields for New Relic's Integration.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n`Name`\n\n\nType\n\n\nDescription\n\n\nRequired\n\n
\n`credentialsSecretRef`\n\n\nobject\n\n\n`CredentialsSecretRef` holds the name of a secret containing new relic's credentials: account id, license key, read and write tokens.\n\n\ntrue\n\n
\n\n#### AtlasThirdPartyIntegration.spec.newRelic.credentialsSecretRef\n\nCredentialsSecretRef holds the name of a secret containing new relic's credentials: account id, license key, read and write tokens.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n`Name`\n\n\nType\n\n\nDescription\n\n\nRequired\n\n
\n`name`\n\n\nstring\n\n\nName of the resource being referred to More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names\n\n\ntrue\n\n
\n\n#### AtlasThirdPartyIntegration.spec.opsGenie\n\nOpsGenie contains the config fields for Ops Genie's Integration.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n`Name`\n\n\nType\n\n\nDescription\n\n\nRequired\n\n
\n`apiKeySecretRef`\n\n\nobject\n\n\nAPIKeySecretRef holds the name of a secret containing Ops Genie's `API` key.\n\n\ntrue\n\n
\n`region`\n\n\nstring\n\n\nRegion is the Ops Genie region.\n\n\ntrue\n\n
\n\n#### AtlasThirdPartyIntegration.spec.opsGenie.apiKeySecretRef\n\nAPIKeySecretRef holds the name of a secret containing Ops Genie's API key.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n`Name`\n\n\nType\n\n\nDescription\n\n\nRequired\n\n
\n`name`\n\n\nstring\n\n\nName of the resource being referred to More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names\n\n\ntrue\n\n
\n\n#### AtlasThirdPartyIntegration.spec.pagerDuty\n\nPagerDuty contains the config fields for PagerDuty's Integration.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n`Name`\n\n\nType\n\n\nDescription\n\n\nRequired\n\n
\n`region`\n\n\nstring\n\n\nRegion is the Pager Duty region.\n\n\ntrue\n\n
\n`serviceKeySecretRef`\n\n\nobject\n\n\n`ServiceKeySecretRef` holds the name of a secret containing Pager Duty service key.\n\n\ntrue\n\n
\n\n#### AtlasThirdPartyIntegration.spec.pagerDuty.serviceKeySecretRef\n\nServiceKeySecretRef holds the name of a secret containing Pager Duty service key.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n`Name`\n\n\nType\n\n\nDescription\n\n\nRequired\n\n
\n`name`\n\n\nstring\n\n\nName of the resource being referred to More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names\n\n\ntrue\n\n
\n\n#### AtlasThirdPartyIntegration.spec.projectRef\n\nprojectRef is a reference to the parent AtlasProject resource. Mutually exclusive with the \"externalProjectRef\" field.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n`Name`\n\n\nType\n\n\nDescription\n\n\nRequired\n\n
\n`name`\n\n\nstring\n\n\nName of the Kubernetes Resource\n\n\ntrue\n\n
\n`namespace`\n\n\nstring\n\n\nNamespace of the Kubernetes Resource\n\n\nfalse\n\n
\n\n#### AtlasThirdPartyIntegration.spec.prometheus\n\nPrometheus contains the config fields for Prometheus's Integration.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n`Name`\n\n\nType\n\n\nDescription\n\n\nRequired\n\n
\n`enabled`\n\n\nstring"} -{"chunk_id": "68a95c0c5e79d242619dafa5-3", "page_id": "68a95c0c5e79d242619dafa5", "source_name": "atlas-operator", "product_name": "MongoDB Atlas Kubernetes Operator", "url": "https://mongodb.com/docs/atlas/operator/current/atlasthirdpartyintegration-custom-resource", "title": "`AtlasThirdPartyIntegration` Custom Resource", "text": "\nEnabled is true when Prometheus integration is enabled.\n\n\ntrue\n\n
\n`prometheusCredentialsSecretRef`\n\n\nobject\n\n\n`PrometheusCredentialsSecretRef` holds the name of a secret containing the Prometheus. username & password\n\n\ntrue\n\n
\n`serviceDiscovery`\n\n\nenum\n\n\n`ServiceDiscovery` to be used by Prometheus. *Enum*: file, http\n\n\ntrue\n\n
\n\n#### AtlasThirdPartyIntegration.spec.prometheus.prometheusCredentialsSecretRef\n\nPrometheusCredentialsSecretRef holds the name of a secret containing the Prometheus. username & password\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n`Name`\n\n\nType\n\n\nDescription\n\n\nRequired\n\n
\n`name`\n\n\nstring\n\n\nName of the resource being referred to More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names\n\n\ntrue\n\n
\n\n#### AtlasThirdPartyIntegration.spec.slack\n\nSlack contains the config fields for Slack's Integration.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n`Name`\n\n\nType\n\n\nDescription\n\n\nRequired\n\n
\n`apiTokenSecretRef`\n\n\nobject\n\n\nAPITokenSecretRef holds the name of a secret containing the Slack `API` token.\n\n\ntrue\n\n
\n`channelName`\n\n\nstring\n\n\n`ChannelName` to be used by Prometheus.\n\n\ntrue\n\n
\n`teamName`\n\n\nstring\n\n\n`TeamName` flags whether Prometheus integration is enabled.\n\n\ntrue\n\n
\n\n#### AtlasThirdPartyIntegration.spec.slack.apiTokenSecretRef\n\nAPITokenSecretRef holds the name of a secret containing the Slack API token.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n`Name`\n\n\nType\n\n\nDescription\n\n\nRequired\n\n
\n`name`\n\n\nstring\n\n\nName of the resource being referred to More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names\n\n\ntrue\n\n
\n\n#### AtlasThirdPartyIntegration.spec.victorOps\n\nVictorOps contains the config fields for VictorOps's Integration.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n`Name`\n\n\nType\n\n\nDescription\n\n\nRequired\n\n
\n`apiKeySecretRef`\n\n\nobject\n\n\nAPIKeySecretRef is the name of a secret containing Victor Ops `API` key.\n\n\ntrue\n\n
\n`routingKey`\n\n\nstring\n\n\n`RoutingKey` holds `VictorOps` routing key.\n\n\ntrue\n\n
\n\n#### AtlasThirdPartyIntegration.spec.victorOps.apiKeySecretRef\n\nAPIKeySecretRef is the name of a secret containing Victor Ops API key.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n`Name`\n\n\nType\n\n\nDescription\n\n\nRequired\n\n
\n`name`\n\n\nstring\n\n\nName of the resource being referred to More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names\n\n\ntrue\n\n
\n\n#### AtlasThirdPartyIntegration.spec.webhook\n\nWebhook contains the config fields for Webhook's Integration.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n`Name`\n\n\nType\n\n\nDescription\n\n\nRequired\n\n
\n`urlSecretRef`\n\n\nobject\n\n\nURLSecretRef holds the name of a secret containing Webhook `URL` and secret.\n\n\ntrue\n\n
\n\n#### AtlasThirdPartyIntegration.spec.webhook.urlSecretRef\n\nURLSecretRef holds the name of a secret containing Webhook URL and secret.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n`Name`\n\n\nType\n\n\nDescription\n\n\nRequired\n\n
\n`name`\n\n\nstring\n\n\nName of the resource being referred to More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names\n\n\ntrue\n\n
\n\n#### AtlasThirdPartyIntegration.status\n\nAtlasThirdPartyIntegrationStatus holds the status of an integration\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n`Name`\n\n\nType\n\n\nDescription\n\n\nRequired\n\n
\n`conditions`\n\n\n[]object\n\n\nConditions holding the status details\n\n\nfalse\n\n
\n`id`\n\n\nstring\n\n\n`ID` of the third party integration resource in Atlas\n\n\nfalse\n\n
\n\n#### AtlasThirdPartyIntegration.status.conditions\n\nCondition contains details for one aspect of the current state of this API Resource.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n`Name`\n\n\nType\n\n\nDescription\n\n\nRequired\n\n
\n`lastTransitionTime`\n\n\nstring\n\n\n`lastTransitionTime` is the last time the condition transitioned from one status to another. This should be when the underlying condition changed. If that is not known, then using the time when the `API` field changed is acceptable. *Format*: date-time\n\n\ntrue\n\n
\n`message`\n\n\nstring\n\n\nmessage is a human readable `message` indicating details about the transition. This may be an empty string.\n\n\ntrue\n\n
\n`reason`\n\n\nstring\n\n\nreason contains a programmatic identifier indicating the `reason` for the condition's last transition. Producers of specific condition types may define expected values and meanings for this field, and whether the values are considered a guaranteed `API`. The value should be a `CamelCase` string. This field may not be empty.\n\n\ntrue\n\n
\n`status`\n\n\nenum\n\n\nstatus of the condition, one of True, False, Unknown. *Enum*: True, False, Unknown\n\n\ntrue\n\n
\n`type`\n\n\nstring\n\n\ntype of condition in `CamelCase` or in foo.example.com/`CamelCase`.\n\n\ntrue\n\n
\n`observedGeneration`\n\n\ninteger"} -{"chunk_id": "68a95c0c5e79d242619dafa5-4", "page_id": "68a95c0c5e79d242619dafa5", "source_name": "atlas-operator", "product_name": "MongoDB Atlas Kubernetes Operator", "url": "https://mongodb.com/docs/atlas/operator/current/atlasthirdpartyintegration-custom-resource", "title": "`AtlasThirdPartyIntegration` Custom Resource", "text": "\n`observedGeneration` represents the .metadata.generation that the condition was set based upon. For instance, if .metadata.generation is currently 12, but the .status.conditions[x].``observedGeneration`` is 9, the condition is out of date with respect to the current state of the instance. *Format*: int64 *Minimum*: 0\n\n\nfalse\n\n
"} -{"chunk_id": "68a95c0c5e79d242619dafab-0", "page_id": "68a95c0c5e79d242619dafab", "source_name": "atlas-operator", "product_name": "MongoDB Atlas Kubernetes Operator", "url": "https://mongodb.com/docs/atlas/operator/current/custom-resources", "title": "Custom Resources", "text": "# Custom Resources\n\nAtlas Kubernetes Operator doesn't support Atlas Infinite Database clusters in public preview. To learn which features Atlas Infinite Database supports in public preview, see Atlas Infinite Database Edition. To learn more about preview features, see Preview Features.Atlas Kubernetes Operator supports the following custom resource definitions:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nResource\n\n\nDescription\n\n\nShort Name\n\n
\n`AtlasBackupCompliancePolicy` Custom Resource\n\n\nConfiguration of a Backup Compliance Policy to protect your backup data.\n\n\nabcp\n\n
\n`AtlasBackupPolicy` Custom Resource\n\n\nBackup policy to back up your cluster Atlas.\n\n\nabp\n\n
\n`AtlasBackupSchedule` Custom Resource\n\n\nBackup schedule to back up your cluster Atlas.\n\n\nabs\n\n
\n`AtlasCustomRole` Custom Resource\n\n\na custom database role to allocate privileges to your database users.\n\n\nacr\n\n
\n`AtlasDeployment` Custom Resource\n\n\nCluster inside some project in Atlas.\n\n\nad\n\n
\n`AtlasDatabaseUser` Custom Resource\n\n\nDatabase user inside some project in Atlas.\n\n\nadu\n\n
\n`AtlasIPAccessList` Custom Resource\n\n\nList of permitted sources for connections to Atlas.\n\n\naal\n\n
\n`AtlasProject` Custom Resource\n\n\nProject in Atlas.\n\n\nap\n\n
\n`AtlasTeam` Custom Resource\n\n\nProject team in Atlas.\n\n\nat\n\n
\n`AtlasDataFederation` Custom Resource\n\n\nfederated database instance and its private endpoints in Atlas.\n\n\nadf\n\n
\n`AtlasNetworkPeering` Custom Resource\n\n\nVPC (Virtual Private Cloud) peering connection between your Atlas project and your cloud provider.\n\n\nanp\n\n
\n`AtlasNetworkContainer` Custom Resource\n\n\nNetwork container supporting VPC (Virtual Private Cloud) peering between your Atlas project and a cloud provider.\n\n\nanc\n\n
\n`AtlasOrgSettings` Custom Resource\n\n\nModify the specific organization settings.\n\n\naos\n\n
\n`AtlasPrivateEndpoint` Custom Resource\n\n\nPrivate endpoint connection from your chosen cloud provider to Atlas.\n\n\nape\n\n
\n`AtlasSearchIndexConfig` Custom Resource\n\n\nIndex for some collection in your Atlas cluster.\n\n\nasic\n\n
\n`AtlasStreamConnection` Custom Resource\n\n\nAtlas Stream Processing connection.\n\n\nasc\n\n
\n`AtlasStreamWorkspace` Custom Resource\n\n\nAtlas Stream Processing workspace.\n\n\nasi\n\n
\n`AtlasFederatedAuth` Custom Resource\n\n\nFederated authentication in Atlas.\n\n\nafa\n\n
\n`Group` Custom Resource\n\n\nGroup in Atlas.\n\n\nN/A\n\n
- Atlas Kubernetes Operator uses custom resource configuration files to manage your Atlas configuration, but as of Atlas Kubernetes Operator 2.0, custom resources you delete in Kubernetes are no longer (by default) deleted in Atlas. Instead, Atlas Kubernetes Operator simply stops managing those resources in Atlas. For example, if you delete an `AtlasProject` Custom Resource in Kubernetes, by default the Atlas Kubernetes Operator no longer automatically deletes the corresponding project from Atlas. This change in behavior is intended to help prevent accidental or unexpected deletions. To learn more, including how to revert this behavior to the default used prior to Atlas Kubernetes Operator 2.0, see New Default: Deletion Protection in Atlas Kubernetes Operator 2.0.\n\n Similarly, Atlas Kubernetes Operator does not delete teams from Atlas if you remove them from an Atlas project in Kubernetes with the Atlas Kubernetes Operator.\n\n- Explicitly define your desired configuration details in order to avoid implicitly using default Atlas configuration values. In some cases, inheriting Atlas defaults may result in a reconciliation loop which can prevent your custom resource from achieving a `READY` state. For example, explicitly defining your desired autoscaling behavior in your `AtlasDeployment` custom resource, as shown in the included example, ensures that a static instance size in your custom resource is not being repeatedly applied to an Atlas deployment which has autoscaling enabled.\n\n ```yaml\n autoScaling:\n diskGB:\n enabled: true\n compute:\n enabled: true\n scaleDownEnabled: true\n minInstanceSize: M30\n maxInstanceSize: M40\n ```\n\n## Managing Atlas Kubernetes Operator with `kubectl`\n\nTo list all Atlas Kubernetes Operator resources in your cluster with `kubectl`, you can run:\n\n```sh\nkubectl get atlas\n```\n\nFor your convenience, to list or describe specific types of Atlas Kubernetes Operator CRDs, you can use the short names listed in the above table. For example, to list all `atlasdatabaseusers` in the `mongodb` namespace, you can run:\n\n```sh\nkubectl get adu -n mongodb\n```\n\n## Atlas Kubernetes Operator Workflow\n\nWhen you use Atlas Kubernetes Operator, you can create a new Atlas project, or you can work with an existing Atlas project.\n\nYou need the following public API key, private API key, and the organization ID information to configure Atlas Kubernetes Operator access to Atlas.\n\n- If you want Atlas Kubernetes Operator to create a new Atlas project, Grant Programmatic Access to an Organization. If your organization requires an IP access list for the Atlas Administration API, you must also configure the API access list.\n\n You must assign the API key the Organization Project Creator organization role or higher.\n\n- If you want to work with an existing Atlas project, Add Project Access from a Project. If your organization requires an IP access list for the Atlas Administration API, you must also configure the API access list.\n\n You must assign the API key the Project Owner project role.\n\nYou can also use Service Accounts as an alternative to API keys.\n\nTo learn more, see Configure Access to Atlas."} -{"chunk_id": "68a95c0c5e79d242619dafab-1", "page_id": "68a95c0c5e79d242619dafab", "source_name": "atlas-operator", "product_name": "MongoDB Atlas Kubernetes Operator", "url": "https://mongodb.com/docs/atlas/operator/current/custom-resources", "title": "Custom Resources", "text": "### Create and Update Process\n\nEach time you change the `spec` field in any of the supported custom resources, the following workflow begins in Atlas Kubernetes Operator:\n\n1. Atlas Kubernetes Operator receives an event about the changed custom resource.\n\n2. Atlas Kubernetes Operator updates the `status.conditions` field to reflect that the resource is not ready:\n\n ```sh\n conditions:\n - lastTransitionTime: \"2021-03-13T16:26:17Z\"\n status: \"False\"\n type: Ready\n ```\n\n3. To connect to the Atlas Administration API, Atlas Kubernetes Operator reads the organization ID and credentials (API (Application Programming Interface) keys or Service Account) from one of the following locations:\n\n - spec.connectionSecretRef.name (if specified in the `AtlasProject` Custom Resource).\n\n By default, Atlas Kubernetes Operator keeps connection secrets in the same namespace as the `AtlasProject` Custom Resource. To store secrets in another namespace, specify the spec.connectionSecretRef.namespace parameter.\n\n - `global` Atlas Kubernetes Operator secret\n `-api-key` (if spec.connectionSecretRef.name is not specified).\n\n4. To create or update resources in Atlas, Atlas Kubernetes Operator uses the connection information to make API (Application Programming Interface) calls to Atlas.\n\n Sometimes Atlas Kubernetes Operator makes multiple API (Application Programming Interface) calls in Atlas during the reconciliation of a custom resource. For example, `AtlasProject` has an IP Access List configuration for calling the matching API.\n\n5. If any errors occur during the reconciliation, `status.conditions` updates to reflect the error.\n\n ```sh\n - lastTransitionTime: \"2021-03-15T14:26:44Z\"\n message: 'POST https://cloud.mongodb.com/api/atlas/v1.0/groups/604a47de73cd8cag77239021/accessList:\n 400 (request \"INVALID_IP_ADDRESS_OR_CIDR_NOTATION\") The address 192.0.2.1dfdfd5\n must be in valid IP address or CIDR notation.'\n reason: ProjectIPAccessListNotCreatedInAtlas\n status: \"False\"\n type: IPAccessListReady\n ```\n\n6. If the update succeeds, `status.conditions` reflects that the resource is ready:\n\n ```sh\n conditions:\n - lastTransitionTime: \"2021-03-13T16:26:17Z\"\n status: \"True\"\n type: Ready\n ```\n\n### Delete Process\n\nAs of Atlas Kubernetes Operator 2.0, when you delete a custom resource from Kubernetes, the object stays in Atlas by default but Atlas Kubernetes Operator\nno longer controls the object. You can revert this default for your entire deployment, or override this default for a specific custom resource with an annotation to allow Atlas Kubernetes Operator to delete the corresponding object from Atlas. If you override with an annotation, the following workflow begins:\n\n1. Atlas Kubernetes Operator receives an event about the deleted custom resource.\n\n2. To connect to the Atlas Administration API, Atlas Kubernetes Operator reads the organization ID and credentials (API (Application Programming Interface) keys or Service Account) from one of the following locations:\n\n - spec.connectionSecretRef.name (if specified in the `AtlasProject` Custom Resource).\n\n By default, Atlas Kubernetes Operator keeps connection secrets in the same namespace as the `AtlasProject` Custom Resource. To store secrets in another namespace, specify the spec.connectionSecretRef.namespace parameter.\n\n - `global` Atlas Kubernetes Operator secret\n `-api-key` (if spec.connectionSecretRef.name is not specified).\n\n3. To delete the resource from Atlas, Atlas Kubernetes Operator uses the connection information to make API (Application Programming Interface) calls to Atlas.\n\n Atlas Kubernetes Operator removes any related objects created in Kubernetes. For example, if you remove `AtlasDatabaseUser`, Atlas Kubernetes Operator removes the related connection secrets.\n\n### Use Annotations to Skip or Override Defaults\n\nYou can use annotations to modify the new default behaviour of Atlas Kubernetes Operator.\n\n- If you add the `mongodb.com/atlas-resource-policy: \"delete\"` annotation to a custom resource's `metadata`, Atlas Kubernetes Operator deletes the corresponding object in Atlas when you delete the Atlas Kubernetes Operator resource.\n\n **Example**\n\n ```yaml\n apiVersion: atlas.mongodb.com/v1\n kind: AtlasProject\n metadata:\n name: my-project\n annotations:\n mongodb.com/atlas-resource-policy: \"delete\"\n ```\n\n- If you have reverted the new delete behavior to the default used prior to Atlas Kubernetes Operator 2.0, you can add the `mongodb.com/atlas-resource-policy: \"keep\"` annotation to a custom resource's `metadata` so Atlas Kubernetes Operator won't delete the resource when you delete the Atlas Kubernetes Operator resource.\n\n- If you add the `mongodb.com/atlas-reconciliation-policy: \"skip\"` annotation to a custom resource's `metadata`, Atlas Kubernetes Operator doesn't start the reconciliation for the resource. This annotation lets you pause the sync with the spec until you remove the annotation. You can use this annotation to make manual changes to a custom resource and avoid Atlas Kubernetes Operator undoing them during a sync. When you remove this annotation, Atlas Kubernetes Operator reconciles the resource and syncs it with the spec.\n\n- If you add the `mongodb.com/atlas-resource-version-policy: \"allow\"` annotation to a custom resource's `metadata`, Atlas Kubernetes Operator lets you use a resource even if its version label doesn't match the version of Atlas Kubernetes Operator that you are using. If your resource version is a major version behind your Atlas Kubernetes Operator version, the latest features might not work. Minor version discrepancies are backward-compatible."} -{"chunk_id": "68a95c0c5e79d242619daf59-0", "page_id": "68a95c0c5e79d242619daf59", "source_name": "atlas-operator", "product_name": "MongoDB Atlas Kubernetes Operator", "url": "https://mongodb.com/docs/atlas/operator/current/ak8so-create-vector-search-index", "title": "Create a Atlas Vector Search Index with Kubernetes", "text": "# Create a Atlas Vector Search Index with Kubernetes\n\nAtlas Kubernetes Operator doesn't support Atlas Infinite Database clusters in public preview. To learn which features Atlas Infinite Database supports in public preview, see Atlas Infinite Database Edition. To learn more about preview features, see Preview Features.Atlas Kubernetes Operator supports Atlas Vector Search indexes on Atlas clusters. To learn more, see How to Index Fields for Vector Search.\n\n## Prerequisites\n\n- Running Kubernetes cluster with Atlas Kubernetes Operator deployed.\n\n- MongoDB version `6.0.11`, `7.0.2`, or higher on any cluster tier.\n\n You can't create more than:\n\n - 3 indexes on `M0` clusters.\n\n - 10 indexes on Flex clusters.\n\n There are no limits to the number of indexes you can create on `M10+` clusters.\n\n- Collection to create the Atlas Vector Search index for.\n\n## Required Access\n\nYou need the `Project Data Access Admin` or higher role to create and manage Atlas Vector Search indexes.\n\n## Procedure\n\n### Configure the `AtlasDeployment` Custom Resource.\n\nConfigure the spec.deploymentSpec.searchIndexes object.\n\nThe following parameters apply to this object:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nParameter\n\n\nDescription\n\n
\n`DBName`\n\n\nHuman-readable label that identifies the existing database that contains the collection with one or more Atlas Search indexes.\n\nIMPORTANT: The database that you specify must already exist. If you don't have an existing database, create one.\n\n
\n`CollectionName`\n\n\nHuman-readable label that identifies the collection that contains one or more Atlas Search indexes.\n\n
\n`Type`\n\n\nType of the index. Atlas accepts the following values:\n\n- `search`\n\n- `vectorSearch`\n\n
To learn more about the available parameters, see `AtlasDeployment` Custom Resource.\n\n**Example:**\n\nRun the following command.\n\n```sh\ncat <\n\n\n`Name`\n\n\n\nType\n\n\n\nDescription\n\n\n\nRequired\n\n\n\n\n\n`apiVersion`\n\n\n\nstring\n\n\n\natlas.mongodb.com/v1\n\n\n\ntrue\n\n\n\n\n\n`kind`\n\n\n\nstring\n\n\n\n`AtlasSearchIndexConfig`\n\n\n\ntrue\n\n\n\n\n\n`metadata`\n\n\n\nobject\n\n\n\nRefer to the Kubernetes `API` documentation for the fields of the `metadata` field.\n\n\n\ntrue\n\n\n\n\n\n`spec`\n\n\n\nobject\n\n\n\n`AtlasSearchIndexConfigSpec` defines the target state of `AtlasSearchIndexConfig`.\n\n\n\nfalse\n\n\n\n\n\n`status`\n\n\n\nobject\n\n\n\n`AtlasSearchIndexConfigStatus` defines the observed state of `AtlasSearchIndexConfig`.\n\n\n\nfalse\n\n\n\n\n#### AtlasSearchIndexConfig.spec\n\nAtlasSearchIndexConfigSpec defines the target state of AtlasSearchIndexConfig.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n`Name`\n\n\nType\n\n\nDescription\n\n\nRequired\n\n
\n`analyzer`\n\n\nenum\n\n\nSpecific pre-defined method chosen to convert database field text into searchable words. This conversion reduces the text of fields into the smallest units of text. These units are called a term or token. This process, known as tokenization, involves a variety of changes made to the text in fields: - extracting words - removing punctuation - removing accents - hanging to lowercase - removing common words - reducing words to their root form (stemming) - changing words to their base form (lemmatization) `MongoDB` Cloud uses the selected process to build the Atlas Search index\n\n*Enum*: lucene.standard, lucene.simple, lucene.whitespace, lucene.keyword, lucene.arabic, lucene.armenian, lucene.basque, lucene.bengali, lucene.brazilian, lucene.bulgarian, lucene.catalan, lucene.chinese, lucene.cjk, lucene.czech, lucene.danish, lucene.dutch, lucene.english, lucene.finnish, lucene.french, lucene.galician, lucene.german, lucene.greek, lucene.hindi, lucene.hungarian, lucene.indonesian, lucene.irish, lucene.italian, lucene.japanese, lucene.korean, lucene.kuromoji, lucene.latvian, lucene.lithuanian, lucene.morfologik, lucene.nori, lucene.norwegian, lucene.persian, lucene.portuguese, lucene.romanian, lucene.russian, lucene.smartcn, lucene.sorani, lucene.spanish, lucene.swedish, lucene.thai, lucene.turkish, lucene.ukrainian\n\n\nfalse\n\n
\n`analyzers`\n\n\n[]object\n\n\nList of user-defined methods to convert database field text into searchable words.\n\n\nfalse\n\n
\n`searchAnalyzer`\n\n\nenum\n\n\nMethod applied to identify words when searching this index. *Enum*: lucene.standard, lucene.simple, lucene.whitespace, lucene.keyword, lucene.arabic, lucene.armenian, lucene.basque, lucene.bengali, lucene.brazilian, lucene.bulgarian, lucene.catalan, lucene.chinese, lucene.cjk, lucene.czech, lucene.danish, lucene.dutch, lucene.english, lucene.finnish, lucene.french, lucene.galician, lucene.german, lucene.greek, lucene.hindi, lucene.hungarian, lucene.indonesian, lucene.irish, lucene.italian, lucene.japanese, lucene.korean, lucene.kuromoji, lucene.latvian, lucene.lithuanian, lucene.morfologik, lucene.nori, lucene.norwegian, lucene.persian, lucene.portuguese, lucene.romanian, lucene.russian, lucene.smartcn, lucene.sorani, lucene.spanish, lucene.swedish, lucene.thai, lucene.turkish, lucene.ukrainian\n\n\nfalse\n\n
\n`storedSource`\n\n\n`JSON`\n\n\nFlag that indicates whether to store all fields (true) on Atlas Search. By default, Atlas doesn't store (false) the fields on Atlas Search. Alternatively, you can specify an object that only contains the list of fields to store (include) or not store (exclude) on Atlas Search. To learn more, see documentation: https://www.mongodb.com/docs/atlas/atlas-search/stored-source-definition/\n\n\nfalse\n\n
\n\n#### AtlasSearchIndexConfig.spec.analyzers\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n`Name`\n\n\nType\n\n\nDescription\n\n\nRequired\n\n
\n`name`\n\n\nstring\n\n\nHuman-readable `name` that identifies the custom analyzer. Names must be unique within an index, and must not start with any of the following strings: \"lucene.\", \"builtin.\", \"mongodb.\"\n\n\ntrue\n\n
\n`tokenizer`\n\n\nobject\n\n\nTokenizer that you want to use to create tokens. Tokens determine how Atlas Search splits up text into discrete chunks for indexing.\n\n\ntrue\n\n
\n`charFilters`\n\n\n`JSON`\n\n\nFilters that examine text one character at a time and perform filtering operations.\n\n\nfalse\n\n
\n`tokenFilters`\n\n\n`JSON`\n\n\nFilter that performs operations such as: - Stemming, which reduces related words, such as \"talking\", \"talked\", and \"talks\" to their root word \"talk\". - Redaction, the removal of sensitive information from public documents\n\n\nfalse\n\n
\n\n#### AtlasSearchIndexConfig.spec.analyzers.tokenizer\n\nTokenizer that you want to use to create tokens. Tokens determine how Atlas Search splits up text into discrete chunks for indexing.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n`Name`\n\n\nType\n\n\nDescription\n\n\nRequired\n\n
\n`type`\n\n\nenum\n\n\nHuman-readable label that identifies this tokenizer type. *Enum*: whitespace, `uaxUrlEmail`, standard, `regexSplit`, `regexCaptureGroup`, `nGram`, keyword, `edgeGram`\n\n\ntrue\n\n
\n`group`\n\n\ninteger\n\n\nIndex of the character `group` within the matching expression to extract into tokens. Use `0` to extract all character groups.\n\n\nfalse\n\n
\n`maxGram`\n\n\ninteger\n\n\nCharacters to include in the longest token that Atlas Search creates.\n\n\nfalse\n\n
\n`maxTokenLength`\n\n\ninteger\n\n\nMaximum number of characters in a single token. Tokens greater than this length are split at this length into multiple tokens.\n\n\nfalse\n\n
\n`minGram`\n\n\ninteger\n\n\nCharacters to include in the shortest token that Atlas Search creates.\n\n\nfalse\n\n
\n`pattern`"} -{"chunk_id": "68a95c0c5e79d242619db000-2", "page_id": "68a95c0c5e79d242619db000", "source_name": "atlas-operator", "product_name": "MongoDB Atlas Kubernetes Operator", "url": "https://mongodb.com/docs/atlas/operator/current/atlassearchindexconfig-custom-resource", "title": "`AtlasSearchIndexConfig` Custom Resource", "text": "\nstring\n\n\nRegular expression to match against.\n\n\nfalse\n\n
\n\n#### AtlasSearchIndexConfig.status\n\nAtlasSearchIndexConfigStatus defines the observed state of AtlasSearchIndexConfig.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n`Name`\n\n\nType\n\n\nDescription\n\n\nRequired\n\n
\n`conditions`\n\n\n[]object\n\n\nConditions is the list of statuses showing the current state of the Atlas Custom Resource\n\n\ntrue\n\n
\n`observedGeneration`\n\n\ninteger\n\n\n`ObservedGeneration` indicates the generation of the resource specification of which the Atlas Operator is aware. The Atlas Operator updates this field to the value of 'metadata.generation' as soon as it starts reconciliation of the resource. *Format*: int64\n\n\nfalse\n\n
\n\n#### AtlasSearchIndexConfig.status.conditions\n\nCondition describes the state of an Atlas Custom Resource at a certain point.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n`Name`\n\n\nType\n\n\nDescription\n\n\nRequired\n\n
\n`status`\n\n\nstring\n\n\nStatus of the condition; one of True, False, Unknown.\n\n\ntrue\n\n
\n`type`\n\n\nstring\n\n\nType of Atlas Custom Resource condition.\n\n\ntrue\n\n
\n`lastTransitionTime`\n\n\nstring\n\n\nLast time the condition transitioned from one status to another. Represented in `ISO` 8601 format. *Format*: date-time\n\n\nfalse\n\n
\n`message`\n\n\nstring\n\n\nA `message` providing details about the transition.\n\n\nfalse\n\n
\n`reason`\n\n\nstring\n\n\nThe `reason` for the condition's last transition.\n\n\nfalse\n\n
"} -{"chunk_id": "6a514d94d727379c91b9eb2a-0", "page_id": "6a514d94d727379c91b9eb2a", "source_name": "atlas-operator", "product_name": "MongoDB Atlas Kubernetes Operator", "url": "https://mongodb.com/docs/atlas/operator/current/ak8so-service-accounts", "title": "Configure Access to Atlas Using Service Accounts", "text": "# Configure Access to Atlas Using Service Accounts\n\nAtlas Kubernetes Operator doesn't support Atlas Infinite Database clusters in public preview. To learn which features Atlas Infinite Database supports in public preview, see Atlas Infinite Database Edition. To learn more about preview features, see Preview Features.## Overview\n\nAtlas API Service Accounts provide a secure, token-based alternative to Programmatic API Keys for authenticating Atlas Kubernetes Operator with the Atlas Administration API. Service Accounts use short-lived access tokens derived from a `clientId` and `clientSecret` pair, reducing the risk of long-lived credential exposure.\n\nMongoDB recommends Service Accounts over Programmatic API Keys for new deployments. Service Accounts offer the following benefits:\n\n- Token-based authentication with automatic token refresh managed by the operator.\n\n- Support for both organization-level and project-level scopes.\n\n- Auditable, distinct identity for your Atlas Kubernetes Operator workloads.\n\nUnlike API Keys, Service Account secrets are **expirable**. You can set a TTL (Time to Live) of up to one year maximum. You must rotate Service Account secrets before they expire to maintain uninterrupted access. Atlas automatically raises a **Service Account Secrets are about to expire** alert as the expiry date approaches. Plan your rotation schedule accordingly.\n\nThis applies to both organization-level and project-level Service Accounts.\n\n## Prerequisites\n\nBefore you begin, ensure you have the following:\n\n- An Atlas account with the **Organization Owner** role for organization-level Service Accounts, or **Project Owner** role for project-level Service Accounts.\n\n- A running Kubernetes cluster with Atlas Kubernetes Operator installed.\n\n- `kubectl` access to the Kubernetes cluster where Atlas Kubernetes Operator runs.\n\n## Procedure\n\n### Create the Service Account in Atlas\n\nCreate a Service Account in Atlas using the Atlas UI or the Atlas Administration API. To learn how to create an organization-level Service Account, see Create a Service Account in an Organization. To learn how to create a project-level Service Account, see Create a Service Account in a Project.\n\nCopy the `clientId` and `clientSecret`. Store them securely because you cannot retrieve the `clientSecret` again after creation.\n\n### Create the Kubernetes Connection Secret\n\nCreate a Kubernetes secret containing the `orgId`, `clientId`, and `clientSecret`.\n\n- For a `global` Atlas Kubernetes Operator secret, run the following commands:\n\n The name of the `global` Atlas Kubernetes Operator secret must conform to the predefined format. The default name of the Atlas Kubernetes Operator deployment is `mongodb-atlas-operator`. So, the secret should be named `mongodb-atlas-operator-service-account`.\n\n ```sh\n kubectl create secret generic mongodb-atlas-operator-service-account \\\n --from-literal=\"orgId=\" \\\n --from-literal=\"clientId=\" \\\n --from-literal=\"clientSecret=\" \\\n -n \n\n kubectl label secret mongodb-atlas-operator-service-account \\\n atlas.mongodb.com/type=credentials \\\n -n mongodb-atlas-system\n ```\n\n- For a `project` Atlas Kubernetes Operator secret, run the following commands:\n\n ```sh\n kubectl create secret generic my-project-connection \\\n --from-literal=\"orgId=\" \\\n --from-literal=\"clientId=\" \\\n --from-literal=\"clientSecret=\" \\\n -n \n\n kubectl label secret my-project-connection \\\n atlas.mongodb.com/type=credentials \\\n -n \n ```\n\n### Reference the Secret from `AtlasProject`\n\nReference the secret from your `AtlasProject` custom resource using spec.connectionSecretRef.name.\n\nIf you created a `global` secret, all projects use it by default and no additional configuration is needed.\n\nIf you created a `project` secret, add the `connectionSecretRef` to your `AtlasProject` custom resource:\n\n```yaml\napiVersion: atlas.mongodb.com/v1\nkind: AtlasProject\nmetadata:\n name: my-project\nspec:\n name: \"My Project\"\n connectionSecretRef:\n name: my-project-connection\n```\n\n### Verify the Operator Uses the Service Account\n\nAfter you configure the secret, verify that Atlas Kubernetes Operator authenticates successfully:\n\n```sh\nkubectl get atlasproject my-project -o jsonpath='{.status.conditions}'\n```\n\nCheck that the `Ready` condition is `True`. If Atlas Kubernetes Operator can't authenticate with the Service Account credentials, the conditions show an error describing the issue.\n\n## YAML Example\n\nThe following example shows a Connection Secret configured for a Service Account:\n\n```yaml\napiVersion: v1\nkind: Secret\nmetadata:\n name: my-project-connection\n namespace: atlas-operator\n labels:\n atlas.mongodb.com/type: credentials\ntype: Opaque\nstringData:\n orgId: \"5d39f0719ccf646554345678\"\n clientId: \"mdb_sa_id_67890abcdef1234567890abc\"\n clientSecret: \"mdb_sa_sk_abcdef1234567890abcdef12\"\n```\n\n## Considerations\n\n### Token Management\n\nAtlas Kubernetes Operator manages access tokens automatically. When the Atlas Kubernetes Operator detects a Service Account Connection Secret, it obtains an access token from the Atlas Administration API and stores it in a separate Kubernetes secret. Do **not** manually edit or delete the Access Token Secret. Atlas Kubernetes Operator refreshes tokens as needed.\n\n### Credential Rotation\n\nWhen you rotate the Service Account secret in Atlas:\n\n1. Update the Kubernetes Connection Secret with the new `clientSecret`.\n\n2. The Atlas Kubernetes Operator detects the change and acquires a new access token on the next reconcile cycle. No restart is required.\n\nService Account secrets have a maximum TTL (Time to Live) of one year. Monitor the **Service Account Secrets are about to expire** alert in Atlas and rotate your secrets before they expire to avoid authentication failures. This applies to both organization-level and project-level Service Accounts.\n\n### IP Access List\n\nThe Service Account's API (Application Programming Interface) access list must include the egress IP (Internet Protocol) address or CIDR (Classless Inter-Domain Routing) block used by the Atlas Kubernetes Operator pod, the same as for Programmatic API Keys. If the operator pod's egress IP is not on the Service Account access list, API (Application Programming Interface) requests fail."} -{"chunk_id": "68a95c0c5e79d242619daf6a-0", "page_id": "68a95c0c5e79d242619daf6a", "source_name": "atlas-operator", "product_name": "MongoDB Atlas Kubernetes Operator", "url": "https://mongodb.com/docs/atlas/operator/current/ak8so-private-link", "title": "Manage Private Endpoints", "text": "# Manage Private Endpoints\n\nAtlas Kubernetes Operator doesn't support Atlas Infinite Database clusters in public preview. To learn which features Atlas Infinite Database supports in public preview, see Atlas Infinite Database Edition. To learn more about preview features, see Preview Features.This feature is not available for any of the following deployments:\n\n- `M0` clusters\n\n- `M2/M5` clusters\n\n- Flex clusters\n\nAtlas Kubernetes Operator supports private endpoints to connect to dedicated clusters and federated database instances.\n\nWhen you use Atlas Kubernetes Operator to configure private links in Atlas, Atlas creates its own VPC (Virtual Private Cloud) or a Private Link service and places dedicated clusters within a region behind a load balancer in the Atlas VPC (Virtual Private Cloud) or Atlas VNet. To learn more, see the Private Endpoint Overview.\n\nTo manage your private endpoints with Atlas Kubernetes Operator, you can specify and update one of the following parameters:\n\n- For dedicated clusters, specify the spec.privateEndpoints parameter for the `AtlasProject` Custom Resource.\n\n- For federated database instances, specify the spec.privateEndpoints parameter for the `AtlasDataFederation` Custom Resource.\n\nEach time you change the `spec` field in any of the supported custom resources, Atlas Kubernetes Operator creates or updates the corresponding Atlas configuration.\n\nCertain considerations and limitations apply to private endpoints. To learn more, see Configure Private Endpoints.\n\n## Procedure\n\nTo enable clients to connect to Atlas dedicated clusters using private endpoints, see the following procedures:\n\n- Manage Private Endpoints for Dedicated Clusters\n\n- Manage Private Endpoints for a Federated Database Instance"} -{"chunk_id": "68a95c0c5e79d242619daf69-0", "page_id": "68a95c0c5e79d242619daf69", "source_name": "atlas-operator", "product_name": "MongoDB Atlas Kubernetes Operator", "url": "https://mongodb.com/docs/atlas/operator/current/ak8so-integrate-third-party", "title": "Integrate with Third-Party Services", "text": "# Integrate with Third-Party Services\n\nAtlas Kubernetes Operator doesn't support Atlas Infinite Database clusters in public preview. To learn which features Atlas Infinite Database supports in public preview, see Atlas Infinite Database Edition. To learn more about preview features, see Preview Features.You can use Atlas Kubernetes Operator to integrate Atlas with third-party services to:\n\n- Receive Atlas alerts in various third-party services.\n\n- View and analyze performance metrics that Atlas collects about your cluster.\n\nTo learn more, see Integrate with Third-Party Services.\n\n## Prerequisites\n\nYou need the following public API key, private API key, and the organization ID information to configure Atlas Kubernetes Operator access to Atlas.\n\n- If you want Atlas Kubernetes Operator to create a new Atlas project, Grant Programmatic Access to an Organization. If your organization requires an IP access list for the Atlas Administration API, you must also configure the API access list.\n\n You must assign the API key the Organization Project Creator organization role or higher.\n\n- If you want to work with an existing Atlas project, Add Project Access from a Project. If your organization requires an IP access list for the Atlas Administration API, you must also configure the API access list.\n\n You must assign the API key the Project Owner project role.\n\nTo learn more, see Configure Access to Atlas.\n\n## Procedure\n\nTo integrate Atlas with a third-party service, configure an `AtlasThirdPartyIntegration` Custom Resource.\n\nTo learn more about the configuration parameters available from the API (Application Programming Interface), see the Atlas Third-Party Integration Settings."} -{"chunk_id": "68a95c0c5e79d242619daf50-0", "page_id": "68a95c0c5e79d242619daf50", "source_name": "atlas-operator", "product_name": "MongoDB Atlas Kubernetes Operator", "url": "https://mongodb.com/docs/atlas/operator/current/ak8so-create-atlas-search-index", "title": "Create an Atlas Search Index with Kubernetes", "text": "# Create an Atlas Search Index with Kubernetes\n\nAtlas Kubernetes Operator doesn't support Atlas Infinite Database clusters in public preview. To learn which features Atlas Infinite Database supports in public preview, see Atlas Infinite Database Edition. To learn more about preview features, see Preview Features.Atlas Kubernetes Operator supports Atlas Search indexes on Atlas clusters. To learn more see Manage MongoDB Search Indexes.\n\n## Prerequisites\n\n- Running Kubernetes cluster with Atlas Kubernetes Operator deployed.\n\n- MongoDB version `4.2` or higher on any cluster tier.\n\n You can't create more than:\n\n - 3 indexes on `M0` clusters.\n\n - 10 indexes on Flex clusters.\n\n There are no limits to the number of indexes you can create on `M10+` clusters.\n\n- Collection to create the Atlas Search index for.\n\n## Required Access\n\nYou must have one of the following roles to create Atlas Search indexes:\n\n- `Project Search Index Editor`\n\n- `Project Data Access Admin`\n\nYou must have at least the `readWriteAnyDatabase` role or readWrite access to the database where you want to create the indexes. To learn more, see Built-In Roles or Built-In Roles.\n\n## Procedure\n\n### Configure an `AtlasSearchIndexConfig` Custom Resource.\n\nThe following example shows an `AtlasSearchIndexConfig` custom resource specification configured for the `lucene.standard` analyzer method.\n\nMultiple `atlasDeployment` custom resources can reference the same `atlasSearchIndexConfiguration` custom resource.\n\n**Example:**\n\nRun the following command:\n\n```\ncat <\n\n\nParameter\n\n\n\nDescription\n\n\n\n\n\n`DBName`\n\n\n\nHuman-readable label that identifies the existing database that contains the collection with one or more Atlas Search indexes.\n\nIMPORTANT: The database that you specify must already exist. If you don't have an existing database, create one.\n\n\n\n\n\n`CollectionName`\n\n\n\nHuman-readable label that identifies the collection that contains one or more Atlas Search indexes.\n\n\n\n\n\n`Type`\n\n\n\nType of the index. Atlas accepts the following values:\n\n- `search`\n\n- `vectorSearch`\n\n\n\n\n\n`search.searchIndexConfigurationRef.name`\n\n\n\nName that references the `AtlasSearchIndexConfig` Custom Resource.\n\n\n\n\n\n`search.searchIndexConfigurationRef.namespace`\n\n\n\nNamespace that contains the `AtlasSearchIndexConfig` Custom Resource.\n\n\n\nTo learn more about the available parameters, see `AtlasDeployment` Custom Resource.\n\n**Example:**\n\nRun the following command.\n\n```sh\ncat <`, with the relevant values for your MongoDB deployment.\n\n### Sample Application\n\nYou can use the following sample application to test the code examples on this page. To use the sample application, perform the following steps:\n\n1. Ensure you have the C driver installed.\n\n2. Copy the following code and paste it into a new `.c` file.\n\n3. Copy a code example from this page and paste it on the specified lines in the file.\n\n```c\n#include \n#include \n#include \n\nint\nmain(void)\n{\n char *str;\n bson_error_t error;\n\n mongoc_init();\n\n mongoc_client_t *client = mongoc_client_new(\"\");\n mongoc_collection_t *collection = mongoc_client_get_collection(client, \"\", \"collection name\");\n\n // Start example code here\n\n // End example code here\n\n mongoc_collection_destroy(collection);\n mongoc_client_destroy(client);\n mongoc_cleanup();\n\n return EXIT_SUCCESS;\n}\n```\n\nFor instructions about how to install the C driver, see Download and Install in the Get Started guide.\n\n## Find Documents\n\nThe following example retrieves a list of documents that match the criteria specified by the given filter:\n\n```c\nbson_t *query = bson_new();\n// Add fields to query here\nmongoc_cursor_t* results = mongoc_collection_find_with_opts(collection, query, NULL, NULL);\nconst bson_t *doc;\n\nwhile (mongoc_cursor_next(results, &doc)) {\n char *str = bson_as_canonical_extended_json(doc, NULL);\n printf(\"%s\\n\", str);\n bson_free(str);\n}\n\nmongoc_cursor_destroy(results);\nbson_destroy(query);\n```\n\nTo learn more about the `mongoc_collection_find_with_opts()` function, see the Find Documents guide.\n\n## Count Documents in a Collection\n\nThe following example returns the number of documents in the specified collection:\n\n```c\nbson_t *query = bson_new();\nint64_t count =\n mongoc_collection_count_documents(collection, query, NULL, NULL, NULL, &error);\n\nprintf(\"%\" PRId64 \"\\n\", count);\nbson_destroy(query);\n```\n\nTo learn more about the `mongoc_collection_count_documents()` function, see the Retrieve an Accurate Count section of the Count Documents guide.\n\n## Count Documents Returned from a Query\n\nThe following example returns the number of documents that match the criteria specified by the given filter:\n\n```c\nbson_t *query = bson_new();\n// Add fields to query here\nint64_t count =\n mongoc_collection_count_documents(collection, query, NULL, NULL, NULL, &error);\n\nprintf(\"%\" PRId64 \"\\n\", count);\n\nbson_destroy(query);\n```\n\nTo learn more about the `mongoc_collection_count_documents()` function, see the Retrieve an Accurate Count section of the Count Documents guide.\n\n## Estimated Document Count\n\nThe following example returns an approximate number of documents in the specified collection based on collection metadata:\n\n```c\nint64_t count =\n mongoc_collection_estimated_document_count(collection, NULL, NULL, NULL, &error);\n\nprintf(\"%\" PRId64 \"\\n\", count);\n```\n\nTo learn more about the `mongoc_collection_estimated_document_count()` function, see the Retrieve an Estimated Count section of the Count Documents guide.\n\n## Retrieve Distinct Values\n\nThe following example returns all distinct values of the specified field name in a given collection:\n\n```c\nbson_t reply;\nbson_t *command = BCON_NEW(\"distinct\",\n BCON_UTF8(\"\"),\n \"key\",\n BCON_UTF8(\"\"));\n\nif (!mongoc_collection_read_command_with_opts(collection, command, NULL, NULL, &reply, &error)) {\n fprintf(stderr, \"An error occurred: %s\\n\", error.message);\n} else {\n char *str = bson_as_canonical_extended_json(&reply, NULL);\n printf(\"%s\\n\", str);\n bson_free(str);\n}\nbson_destroy(&reply);\nbson_destroy(command);\n```\n\nTo learn more about the `distinct` command, see the Retrieve Distinct Field Values guide.\n\n## Monitor Data Changes\n\nThe following example creates a change stream for a given collection and prints out subsequent change events in that collection:\n\n```c\nmongoc_change_stream_t *change_stream;\nbson_t *pipeline = bson_new();\n// Add stages to pipeline here\nconst bson_t *doc;\n\nchange_stream = mongoc_collection_watch(collection, pipeline, NULL);\n\nwhile (mongoc_change_stream_next(change_stream, &doc)) {\n char *str = bson_as_canonical_extended_json(doc, NULL);\n printf(\"Change: %s\\n\", str);\n bson_free(str);\n}\n\nbson_destroy(pipeline);\nmongoc_change_stream_destroy(change_stream);\n```\n\nTo learn more about the `mongoc_collection_watch()` function, see the Monitor Data Changes guide."} -{"chunk_id": "68b296a6965969e81e392b7d-0", "page_id": "68b296a6965969e81e392b7d", "source_name": "c", "product_name": "C Driver", "url": "https://mongodb.com/docs/languages/c/c-driver/current/security/enterprise-authentication", "title": "Enterprise Authentication Mechanisms", "text": "# Enterprise Authentication Mechanisms\n\n## Overview\n\nMongoDB Enterprise Edition includes authentication mechanisms that aren't available in MongoDB Community Edition. In this guide, you can learn how to authenticate to MongoDB by using these authentication mechanisms. To learn about the other authentication mechanisms available in MongoDB, see Authentication Mechanisms.\n\n## Kerberos\n\nThe Generic Security Services API (GSSAPI) provides an interface for Kerberos authentication.\n\nTo authenticate with GSSAPI, you must build the MongoDB C driver with SASL support. If you are building the driver from source, you can enable SASL support with the `ENABLE_SASL` `cmake` option.\n\nComplete the following steps to authenticate with GSSAPI:\n\n### Obtain a Ticket-Granting Ticket\n\nOn Unix environments, you must first run the `kinit` command to obtain and cache an initial ticket-granting ticket. If you're running a Windows environment, you can skip ahead to the next step.\n\nThe following example uses the `kinit` command to obtain a ticket-granting ticket for the principal `mongodbuser@EXAMPLE.COM`. It then uses the `klist` command to display the principal and ticket in the credentials cache.\n\n```sh\n$ kinit mongodbuser@EXAMPLE.COM\nmongodbuser@EXAMPLE.COM's Password:\n$ klist\nCredentials cache: FILE:/tmp/krb5cc_1000\n Principal: mongodbuser@EXAMPLE.COM\n\nIssued Expires Principal\nFeb 9 13:48:51 2013 Feb 9 23:48:51 2013 krbtgt/mongodbuser@EXAMPLE.COM\n```\n\n### Set the Connection Options\n\nNext, set the following connection options:\n\n- `username`: The Kerbos principal to authenticate.\n\n- `authMechanism`: Set to `\"GSSAPI\"`.\n\n- `authMechanismProperties`: Optional. By default, MongoDB uses `mongodb` as the authentication service name. To specify a different service name, set this option to `\"SERVICE_NAME:\"`.\n\nYou can set these options through parameters in your connection URI, as shown in the following example:\n\n```c\nconst char *uri = \"mongodb://mongodbuser%40EXAMPLE.COM@:/?authMechanism=GSSAPI&authMechanismProperties=SERVICE_NAME:\");\nmongoc_client_t *client = mongoc_client_new(uri);\n```\n\nYou must replace the `@` symbol in the principal with `%40`, as shown in the preceding example.\n\nYou cannot specify a property value containing the comma (`,`) character as a `authMechanismProperties` connection string option, even when the comma character is percent-encoded. To specify an `authMechanismProperties` property value that contains a comma, set the option by using the mongoc_uri_set_mechanism_properties() method.\n\n## PLAIN SASL\n\nThe PLAIN Simple Authentication and Security Layer (SASL), as defined by RFC 4616, is a username-password authentication mechanism often used with TLS or another encryption layer. You must compile the C driver with SASL support to use PLAIN SASL authentication.\n\nPLAIN SASL is a clear-text authentication mechanism. We strongly recommend that you use TLS/SSL with certificate validation when using PLAIN SASL to authenticate to MongoDB.\n\nTo authenticate with SASL, set the `authMechanism` connection option to `PLAIN`. You can set this option through a parameter in your connection string, as shown in the following example:\n\n```c\nconst char *uri = \"mongodb://:@:/?authMechanism=PLAIN\");\nmongoc_client_t *client = mongoc_client_new(uri);\n```\n\n## API Documentation\n\nTo learn more about authenticating your application in the C driver, see the following API documentation:\n\n- mongoc_client_t\n\n- mongoc_uri_t"} -{"chunk_id": "69327965e88006792c765cef-0", "page_id": "69327965e88006792c765cef", "source_name": "c", "product_name": "C Driver", "url": "https://mongodb.com/docs/languages/c/c-driver/current/crud/read-write-configuration", "title": "Configure CRUD Operations", "text": "# Configure CRUD Operations\n\n## Overview\n\nIn this guide, you can learn how to use the **write concern**, **read concern**, and **read preference** configurations to modify the way that MongoDB runs create, read, update, and delete (CRUD) operations on replica sets.\n\nYou can set these configurations at the following levels:\n\n1. Client, which sets the default for all operation executions unless overridden\n\n2. Transaction\n\n3. Database\n\n4. Collection\n\nThe preceding list is in increasing order of precedence. For example, if you set read concerns at both the client and the database levels, the read concern specified at the database level overrides the read concern at the client level.\n\n## Write Concern\n\nWrite concern specifies the level of acknowledgement requested from MongoDB for write operations before the operation successfully returns. Operations that don't specify an explicit write concern inherit the global default write concern setting.\n\nYou can set the write concern by calling the following functions:\n\n- `mongoc_client_set_write_concern()` sets the write concern on a client.\n\n- `mongoc_transaction_opts_set_write_concern()` sets the write concern on a transaction.\n\n- `mongoc_database_set_write_concern()` sets the write concern on a databse.\n\n- `mongoc_collection_set_write_concern()` sets the write concern on a collection.\n\nTo specify the level of your write concern, call the `mongoc_write_concern_set_w()` function, and pass in your write concern and one of the following values:\n\n- `MONGOC_WRITE_CONCERN_W_DEFAULT`: The write operation returns after the operation is written to memory.\n\n- `0`: The write operation returns after the primary node processes the write operation.\n\n- `1`: The write operation returns after only the primary node acknowledges the write operation, without waiting for acknowledgement from secondary nodes.\n\n- `MONGOC_WRITE_CONCERN_W_MAJORITY`: The write operation returns after a majority of the replica set members acknowledge the write operation.\n\n- `MONGOC_WRITE_CONCERN_W_TAG`: The write operation returns after the replica set member with the specified tag acknowledges the write operation.\n\nThe following example sets the write concern to `MONGOC_WRITE_CONCERN_W_MAJORITY` for an instance of `mongoc_client_t`:\n\n```c\n// Create a new client instance\nmongoc_client_t *client = mongoc_client_new(\"\");\n\n// Create a new write concern\nmongoc_write_concern_t *write_concern = mongoc_write_concern_new();\nmongoc_write_concern_set_w(write_concern, MONGOC_WRITE_CONCERN_W_MAJORITY);\n\n// Set the write concern on the client\nmongoc_client_set_write_concern(client, write_concern);\n```\n\nThe following example sets the write concern to `MONGOC_WRITE_CONCERN_W_MAJORITY` for a collection:\n\n```c\nmongoc_collection_t *collection = mongoc_client_get_collection(client, \"\", \"\");\n\n// Create a new write concern\nmongoc_write_concern_t *write_concern = mongoc_write_concern_new();\nmongoc_write_concern_set_w(write_concern, MONGOC_WRITE_CONCERN_W_MAJORITY);\n\n// Set the write concern on the collection\nmongoc_collection_set_write_concern(collection, write_concern);\n```\n\n`mongoc_database_t` and `mongoc_collection_t` instances are immutable. When you set the write concern on a database or collection, the method returns a new instance and does not affect the original instance.\n\nFor more information about write concern, see Write Concern in the MongoDB Server manual.\n\n## Read Concern\n\nRead concern specifies the following behaviors:\n\n- Level of causal consistency across replica sets\n\n- Isolation guarantees maintained during a query\n\nYou can specify the read concern by calling the following functions:\n\n- `mongoc_client_set_read_concern()` sets the read concern on a client.\n\n- `mongoc_transaction_opts_set_read_concern()` sets the read concern on a transaction.\n\n- `mongoc_database_set_read_concern()` sets the read concern on a database.\n\n- `mongoc_collection_set_read_concern()` sets the read concern on a collection.\n\nTo specify the level of your read concern, call the `mongoc_read_concern_set_level()` function, and pass in your read concern and one of the following values:\n\n- `MONGOC_READ_CONCERN_LEVEL_LOCAL`: The query returns the instance's most recent data. Provides no guarantee that the data has been written to a majority of the replica set members.\n\n- `MONGOC_READ_CONCERN_LEVEL_AVAILABLE`: The query returns the instance's most recent data. Provides no guarantee that the data has been written to a majority of the replica set members. `ReadConcern.AVAILABLE` is not available for use with causally consistent sessions and transactions.\n\n- `MONGOC_READ_CONCERN_LEVEL_MAJORITY`: The query returns data that has been acknowledged by a majority of the replica set members.\n\n- `MONGOC_READ_CONCERN_LEVEL_LINEARIZABLE`: The query returns data that reflects all successful writes that completed prior to the start of the read operation. `MONGOC_READ_CONCERN_LEVEL_LINEARIZABLE` is not available for use with causally consistent sessions and transactions.\n\n- `MONGOC_READ_CONCERN_LEVEL_SNAPSHOT`: The query returns majority-committed data as it appears across shards, from a specific single point in the recent past.\n\nFor more information about the read concern levels, see Read Concern Levels in the MongoDB Server manual.\n\nThe following example sets the read concern to `MONGOC_READ_CONCERN_LEVEL_MAJORITY` for an instance of `mongoc_client_t`:\n\n```c\nmongoc_client_t *client = mongoc_client_new(\"\");\n\n// Create a new read concern\nmongoc_read_concern_t *read_concern = mongoc_read_concern_new();\n\n// Set the read concern level\nmongoc_read_concern_set_level(read_concern, MONGOC_READ_CONCERN_LEVEL_MAJORITY);\n\n// Set the read concern on the client\nmongoc_client_set_read_concern(client, read_concern);\n```\n\nThe following example sets the read concern to `MONGOC_READ_CONCERN_LEVEL_MAJORITY` for a collection:\n\n```c\n\nmongoc_collection_t *collection = mongoc_client_get_collection(client, \"\", \"\");\n\n// Create a new read concern\nmongoc_read_concern_t *read_concern = mongoc_read_concern_new();\n\n// Set the read concern level\nmongoc_read_concern_set_level(read_concern, MONGOC_READ_CONCERN_LEVEL_MAJORITY);\n\n// Set the read concern on the collection\nmongoc_collection_set_read_concern(collection, read_concern);\n```\n\nTo learn more about read concern, see Read Concern in the MongoDB Server manual."} -{"chunk_id": "69327965e88006792c765cef-1", "page_id": "69327965e88006792c765cef", "source_name": "c", "product_name": "C Driver", "url": "https://mongodb.com/docs/languages/c/c-driver/current/crud/read-write-configuration", "title": "Configure CRUD Operations", "text": "## Read Preference\n\nRead preference determines which member of a replica set MongoDB reads when running a query. You can set the read preference by calling the following functions:\n\n- `mongoc_client_set_read_prefs()` sets the read preference on a client.\n\n- `mongoc_transaction_opts_set_read_prefs()` sets the read preference on a transaction.\n\n- `mongoc_database_set_read_prefs()` sets the read preference on a database.\n\n- `mongoc_collection_set_read_prefs()` sets the read preference on a collection.\n\nTo specify the level of your read preference, call the `mongoc_read_prefs_new()` function, and pass in one of the following values:\n\n- `MONGOC_READ_PRIMARY`: The query returns data from the primary node.\n\n- `MONGOC_READ_PRIMARY_PREFERRED`: The query returns data from the primary node if available. Otherwise, the query returns data from a secondary node.\n\n- `MONGOC_READ_SECONDARY`: The query returns data from a secondary node.\n\n- `MONGOC_READ_SECONDARY_PREFERRED`: The query returns data from a secondary node if available, Otherwise, the query returns data from the primary node.\n\n- `MONGOC_READ_NEAREST`: The query returns data from the node with the lowest network latency.\n\nThe following example sets the read preference to `MONGOC_READ_SECONDARY` for an instance of `mongoc_client_t`:\n\n```c\nmongoc_client_t *client = mongoc_client_new(\"\");\n\n// Create a new read preference\nmongoc_read_prefs_t *read_prefs = mongoc_read_prefs_new(MONGOC_READ_SECONDARY);\n\n// Set the read preference on the client\nmongoc_client_set_read_prefs(client, read_prefs);\n```\n\nThe following example sets the read preference to `MONGOC_READ_SECONDARY` for a collection:\n\n```c\nmongoc_collection_t *collection = mongoc_client_get_collection(client, \"\", \"\");\n\n// Create a new read preference\nmongoc_read_prefs_t *read_prefs = mongoc_read_prefs_new(MONGOC_READ_SECONDARY);\n\n// Set the read preference on the collection\nmongoc_collection_set_read_prefs(collection, read_prefs);\n```\n\nFor more information about read preference, see Read Preference in the MongoDB Server manual.\n\n## Collation\n\nYou can specify a **collation** when you perform read and write operations on a collection.\n\nA collation is a set of language-specific rules for string comparison, such as for letter case and accent marks.\n\nTo specify a collation, pass the collation definition to the `\"collation\"` key in the options of the read or write operation.\n\n### Collation Example\n\nConsider a collection with the following documents:\n\n```json\n{ _id: 1, category: \"caf\u00e9\" },\n{ _id: 2, category: \"cafe\" },\n{ _id: 3, category: \"cafE\" }\n```\n\nThe following example creates a collation that specifies the French locale and ignores differences between case and letter variants. It then uses this collation to find documents in which the `category` field value matches `\"cafe\"`. Because of the specified collation, the query returns all three documents.\n\n```c\nmongoc_collection_t *collection = mongoc_client_get_collection(client, \"\", \"\");\n\nbson_t *opts = BCON_NEW(\n \"collation\", \"{\",\n \"locale\", BCON_UTF8(\"fr\"),\n \"strength\", BCON_INT32(1),\n \"}\"\n);\n\nmongoc_cursor_t *cursor = mongoc_collection_find_with_opts(\n collection,\n BCON_NEW(\"category\", BCON_UTF8(\"cafe\")),\n opts,\n NULL\n);\n\nconst bson_t *doc;\nwhile (mongoc_cursor_next(cursor, &doc))\n{\n char *str = bson_as_canonical_extended_json(doc, NULL);\n printf(\"%s\\n\", str);\n bson_free(str);\n}\n```\n\n```\n{ \"_id\": { \"$oid\" : \"1\" }, \"category\": \"caf\u00e9\" }\n{ \"_id\": { \"$oid\" : \"2\" }, \"category\": \"cafe\" }\n{ \"_id\": { \"$oid\" : \"3\" }, \"category\": \"cafE\" }\n```\n\nTo learn more about collations, see the Collation reference documentation in the MongoDB Server manual.\n\n## API Documentation\n\nTo learn more about any of the functions or types discussed in this guide, see the following API documentation:\n\n- mongoc_write_concern_t\n\n- mongoc_write_concern_set_w\n\n- mongoc_write_concern_new\n\n- mongoc_read_concern_t\n\n- mongoc_read_concern_new\n\n- mongoc_read_concern_set_level\n\n- mongoc_read_prefs_t\n\n- mongoc_read_prefs_new"} -{"chunk_id": "6937bf2fd1b0fc8b0a85c2d7-0", "page_id": "6937bf2fd1b0fc8b0a85c2d7", "source_name": "c", "product_name": "C Driver", "url": "https://mongodb.com/docs/languages/c/c-driver/current/connect/connection-options/stable-api", "title": "Stable API", "text": "# Stable API\n\nThe Stable API feature requires MongoDB Server 5.0 or later.\n\n## Overview\n\nIn this guide, you can learn how to specify **Stable API** compatibility when connecting to a MongoDB deployment.\n\nThe Stable API feature forces the server to run operations with behaviors compatible with the API version you specify. When you update either your driver or server, the API version changes, which can change the way these operations behave. Using the Stable API ensures consistent responses from the server and provides long-term API stability for your application.\n\nThe following sections describe how you can enable and customize Stable API for your MongoDB client. For more information about the Stable API, including a list of the commands it supports, see Stable API in the MongoDB Server manual.\n\n## Enable the Stable API\n\nTo enable the Stable API, perform the following steps:\n\n1. Construct a `mongoc_server_api_t` object and specify a Stable API version. You must use a Stable API version defined in the `mongoc_server_api_t` enum.\n\n2. Construct a `mongoc_client_t` object.\n\n3. Pass the client and the Stable API object to the `mongoc_client_set_server_api` function.\n\nThe following code example shows how to specify Stable API version 1:\n\n```c\n#include \n\nint main()\n{\n bson_error_t error;\n\n mongoc_init();\n\n mongoc_server_api_t *stable_api = mongoc_server_api_new(MONGOC_SERVER_API_V1);\n\n mongoc_client_t *client = mongoc_client_new(\"\");\n if (!mongoc_client_set_server_api(client, stable_api, &error))\n {\n fprintf(stderr, \"Failed to set Stable API: %s\\n\", error.message);\n return EXIT_FAILURE;\n }\n\n // Use the client for operations...\n\n mongoc_server_api_destroy(stable_api);\n mongoc_cleanup();\n\n return EXIT_SUCCESS;\n}\n```\n\nOnce you create a client instance with a specified API version, all commands you run with the client use the specified version. If you need to run commands using more than one version of the Stable API, create a new client.\n\n## Configure the Stable API\n\nThe following table describes the options of the `ServerApi` class. You can use these options to customize the behavior of the Stable API.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nOption Name\n\n\nDescription\n\n
\nstrict\n\n\n**Optional**. When `true`, if you call a command that isn't part of the declared API version, the driver raises an exception.Default: **false**\n\n
\ndeprecation_errors\n\n\n**Optional**. When `true`, if you call a command that is deprecated in the declared API version, the driver raises an exception.Default: **false**\n\n
The following code example shows how you can set both options to `true` when constructing a `ServerApi` object:\n\n```c\nmongoc_server_api_t *stable_api = mongoc_server_api_new(MONGOC_SERVER_API_V1);\nmongoc_server_api_strict(stable_api, true);\nmongoc_server_api_deprecation_errors(stable_api, true);\n\nmongoc_client_t *client = mongoc_client_new(\"\");\nif (!mongoc_client_set_server_api(client, stable_api, &error)) {\n fprintf(stderr, \"Failed to set Stable API: %s\\n\", error.message);\n return EXIT_FAILURE;\n}\n```\n\n## API Documentation\n\nFor more information about using the Stable API with the C driver, see the following API documentation:\n\n- mongoc_server_api_t\n\n- mongoc_server_api_version_t\n\n- mongoc_server_api_new\n\n- mongoc_client_t"} -{"chunk_id": "6a912a094f25feb7b9024b8b-0", "page_id": "6a912a094f25feb7b9024b8b", "source_name": "c", "product_name": "C Driver", "url": "https://mongodb.com/docs/languages/c/c-driver/current/connect/connection-options/network-compression", "title": "Compress Network Traffic", "text": "# Compress Network Traffic\n\n## Overview\n\nMongoDB drivers can compress the messages sent to and received from MongoDB Server. This reduces the amount of data transferred for each operation. Compression can improve performance over constrained networks and lower the data transfer costs associated with running MongoDB Atlas.\n\nCompression operates at the wire protocol level, so it applies to every operation that your application performs. If you specify more than one algorithm, the driver uses the first algorithm in your list that MongoDB Server also supports.\n\n### Compression Algorithms\n\nMongoDB drivers support the following compression algorithms:\n\n- Snappy\n\n- Zlib\n\n- Zstandard\n\n## Network Compression Benefits\n\nMongoDB Atlas charges for data transferred across cloud regions, cloud providers, and between your infrastructure and MongoDB Atlas. Network compression reduces the amount of data that your application sends and receives, which can lower these data transfer costs. To learn more about pricing, see Data Transfer Costs.\n\nNetwork compression also has productivity benefits. Compressed messages take less time to transfer across the network, which can improve your application's response times. Compression also reduces the bandwidth that your MongoDB traffic uses, which leaves more bandwidth available for other applications on the same network.\n\nWhen you choose a compression algorithm, consider the following guidelines:\n\n- Use **Zstandard** for a balance of compression efficiency and resource usage. Zstandard is a good default choice for most applications.\n\n- Use **Snappy** for latency-sensitive applications that require minimal computational overhead.\n\n- Use **Zlib** for broad compatibility across MongoDB drivers and environments.\n\nCompression trades network bandwidth for CPU usage. After you enable network compression, monitor your application's CPU utilization to confirm that the trade-off benefits your workload. To learn more about these trade-offs, see the CPU Utilization and Network Compression in MongoDB blog post.\n\n## Version Compatibility\n\nThe following table lists the minimum supported driver and MongoDB Server version for each compression algorithm:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nCompression Algorithm\n\n\nMinimum Driver Version\n\n\nMinimum Server Version\n\n
\nSnappy\n\n\n1.7\n\n\n4.2\n\n
\nZlib\n\n\n1.7\n\n\n4.2\n\n
\nZstandard\n\n\n1.15\n\n\n4.2\n\n
\n\n## Enable Network Compression\n\nTo enable network compression for your MongoDB connection, build the C driver with the required dependencies and specify the compression algorithms that you want to use.\n\n### Install Dependencies\n\nThe following table lists each algorithm and the dependency it requires, if any:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nCompression Algorithm\n\n\nDependency\n\n
\nSnappy\n\n\nInstall the Snappy library. To view installation instructions, see the snappy GitHub repository.\n\n
\nZlib\n\n\nNone. The driver bundles Zlib by default.\n\n
\nZstandard\n\n\nInstall the Zstandard library. To view installation instructions, see the zstd GitHub repository.\n\n
\n\n### Specify Compression Algorithms\n\nYou can enable compression for the connection to your MongoDB instance by specifying the algorithms in one of the following ways:\n\n- Add the `compressors` parameter to your connection string\n\n- Set the compressors on a `mongoc_uri_t` struct\n\nSelect the Connection String or URI Option tab to view an example that specifies all available compressors:\n\n\n\n\n\n```c\nclient = mongoc_client_new(\"mongodb://:@/?compressors=snappy,zlib,zstd\");\n```\n\n\n\n\n\n```c\nuri = mongoc_uri_new(\"mongodb://localhost:27017\");\nmongoc_uri_set_compressors(uri, \"snappy,zlib,zstd\");\n\nclient = mongoc_client_new_from_uri(uri);\n```\n\n\n\n\n\n### Zlib Compression Level\n\nWhen you use the Zlib algorithm, you can specify a compression level from `-1` to `9`. Lower levels generally provide faster compression with a lower compression ratio, and higher levels provide slower compression with a higher compression ratio.\n\nSelect the Connection String or URI Option tab to view an example that specifies a compression level for the `zlib` compressor:\n\n\n\n\n\n```c\nclient = mongoc_client_new(\"mongodb://:@/?compressors=zlib&zlibCompressionLevel=\n\n\n\n```c\nuri = mongoc_uri_new(\"mongodb://localhost:27017\");\nmongoc_uri_set_option_as_int32(uri, MONGOC_URI_ZLIBCOMPRESSIONLEVEL, );\n\nclient = mongoc_client_new_from_uri(uri);\n```\n\n\n\n\n\n## API Documentation\n\nFor more information about the types and functions used on this page, see the following API documentation:\n\n- mongoc_uri_t\n\n- mongoc_uri_set_compressors"} -{"chunk_id": "69327965e88006792c765d00-0", "page_id": "69327965e88006792c765d00", "source_name": "c", "product_name": "C Driver", "url": "https://mongodb.com/docs/languages/c/c-driver/current/crud/update", "title": "Update Documents", "text": "# Update Documents\n\n## Overview\n\nIn this guide, you can learn how to use the C driver to update documents in a MongoDB collection. You can call the `mongoc_collection_update_one()` function to update a single document or the `mongoc_collection_update_many()` function to update multiple documents.\n\n### Sample Data\n\nThe examples in this guide use the `restaurants` collection in the `sample_restaurants` database from the Atlas sample datasets. To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the MongoDB Get Started guide.\n\n## Update Operations\n\nYou can perform update operations in MongoDB by using the following functions:\n\n- `mongoc_collection_update_one()`, which updates *the first document* that matches the search criteria\n\n- `mongoc_collection_update_many()`, which updates *all documents* that match the search criteria\n\nEach update function accepts the following parameters:\n\n- **Collection**: Specifies the collection to update.\n\n- **Query filter document**: Specifies which collection documents to update. For more information about query filters, see the Query Filter Documents section in the MongoDB Server manual.\n\n- **Update document**: Specifies the **update operator**, or the kind of update to perform, and the fields and values to change. For a list of update operators and their usage, see the Field Update Operators guide in the MongoDB Server manual.\n\n- **Options document**: Specifies options to customize the operation, or `NULL`.\n\n- **Results location**: Specifies a pointer to overwritable storage that will contain operation results, or `NULL`.\n\n- **Error location**: Specifies a location for an error value, or `NULL`.\n\n### Update One Document\n\nUse the following syntax to update a document:\n\n```c\nbson_t *query = BCON_NEW(\"\", BCON_UTF8(\"\"));\nbson_t *update = BCON_NEW(\"$set\", \"{\", \"\", BCON_UTF8(\"\"), \"}\");\nbson_error_t error;\n\nif (!mongoc_collection_update_one(collection, query, update, NULL, NULL, &error)) {\n fprintf(stderr, \"Update one operation failed: %s\\n\", error.message);\n}\n\nbson_destroy(query);\nbson_destroy(update);\n```\n\nThe following example uses the `mongoc_collection_update_one()` function to update the `name` value of a document in the `restaurants` collection from `\"Bagels N Buns\"` to `\"2 Bagels 2 Buns\"`:\n\n```c\nbson_t *query = BCON_NEW(\"name\", BCON_UTF8(\"Bagels N Buns\"));\nbson_t *update = BCON_NEW(\"$set\", \"{\", \"name\", BCON_UTF8(\"2 Bagels 2 Buns\"), \"}\");\nbson_error_t error;\n\nif (!mongoc_collection_update_one(collection, query, update, NULL, NULL, &error)) {\n fprintf(stderr, \"Update one operation failed: %s\\n\", error.message);\n}\n\nbson_destroy(query);\nbson_destroy(update);\n```\n\n### Update Many Documents\n\nUse the following syntax to update several documents:\n\n```c\nbson_t *query = BCON_NEW(\"\", BCON_UTF8(\"\"));\nbson_t *update = BCON_NEW(\"$set\", \"{\", \"\", BCON_UTF8(\"\"), \"}\");\nbson_error_t error;\n\nif (!mongoc_collection_update_many(collection, query, update, NULL, NULL, &error)) {\n fprintf(stderr, \"Update many operation failed: %s\\n\", error.message);\n}\n\nbson_destroy(query);\nbson_destroy(update);\n```\n\nThe following example uses the `mongoc_collection_update_many()` function to update all documents that have a `cuisine` value of `\"Pizza\"`. After the update, the documents have a `cuisine` value of `\"Pasta\"`.\n\n```c\nbson_t *query = BCON_NEW(\"cuisine\", BCON_UTF8(\"Pizza\"));\nbson_t *update = BCON_NEW(\"$set\", \"{\", \"cuisine\", BCON_UTF8(\"Pasta\"), \"}\");\nbson_error_t error;\n\nif (!mongoc_collection_update_many(collection, query, update, NULL, NULL, &error)) {\n fprintf(stderr, \"Update many operation failed: %s\\n\", error.message);\n}\n\nbson_destroy(query);\nbson_destroy(update);\n```\n\n### Customize the Update Operation\n\nYou can modify the behavior of the `mongoc_collection_update_one()` and `mongoc_collection_update_many()` functions by passing a BSON document that specifies option values. The following table describes some options you can set in the document:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nOption\n\n\nDescription\n\n
\n`bypassDocumentValidation`\n\n\nIf set to `true`, allows the write operation to opt out of document-level validation.Defaults to `false`.**Type**: `bool`\n\n
\n`writeConcern`\n\n\nSets the write concern for the operation.Defaults to the write concern of the namespace.**Type**: `mongoc_write_concern_t`\n\n
\n`collation`\n\n\nSpecifies the kind of language collation to use when comparing text. For more information, see Collation in the MongoDB Server manual.**Type**: `bson_t`\n\n
\n`comment`\n\n\nA comment to attach to the operation. For more information, see the insert command fields guide in the MongoDB Server manual.**Type**: `bson_value_t`\n\n
\n`upsert`\n\n\nA comment to attach to the operation. For more information, see the insert command fields guide in the MongoDB Server manual.**Type**: `bson_value_t`\n\n
\n\n### Upsert a Document\n\nThe following example uses the `mongoc_collection_update_many()` function to find all documents that have `borough` value of `\"Manhattan\"`. It then updates the `borough` value in these documents to `\"Manhattan (north)\"`. Because the `upsert` option is set to `true`, the C driver inserts a new document if the query filter doesn't match any existing documents.\n\n```c\nbson_t *query = BCON_NEW(\"borough\", BCON_UTF8(\"Manhattan\"));\nbson_t *update = BCON_NEW(\"$set\", \"{\", \"borough\", BCON_UTF8(\"Manhattan (north)\"), \"}\");\nbson_error_t error;\nbson_t opts;\n\nbson_init(&opts);\nbson_append_bool(&opts, \"upsert\", -1, true);\n\nif (!mongoc_collection_update_many(collection, query, update, &opts, NULL, &error)) {\n fprintf(stderr, \"Update many operation failed: %s\\n\", error.message);\n}\n\nbson_destroy(query);\nbson_destroy(update);\nbson_destroy(&opts);\n```\n\n## Additional Information\n\nTo learn more about creating query filters, see the Specify a Query guide.\n\n### API Documentation\n\nTo learn more about any of the functions discussed in this guide, see the following API documentation:\n\n- mongoc_collection_update_one()\n\n- mongoc_collection_update_many()"} -{"chunk_id": "68b296a6965969e81e392b7c-0", "page_id": "68b296a6965969e81e392b7c", "source_name": "c", "product_name": "C Driver", "url": "https://mongodb.com/docs/languages/c/c-driver/current/security/authentication", "title": "Authentication Mechanisms", "text": "# Authentication Mechanisms\n\n## Overview\n\nThis guide describes the mechanisms you can use in the C driver to authenticate users to MongoDB.\n\nYou must percent-encode a username and password before you include them in a MongoDB URI.\n\n## SCRAM-SHA-256\n\nSCRAM-SHA-256, as defined by RFC 7677, is the default authentication mechanism on MongoDB deployments running MongoDB v4.0 or later.\n\nTo authenticate by using SCRAM-SHA-256, set the following connection options:\n\n- `username`: The username to authenticate. Percent-encode this value before including it in the connection URI.\n\n- `password`: The password to authenticate. Percent-encode this value before including it in the connection URI.\n\n- `authSource`: The MongoDB database to authenticate against. By default, the C driver authenticates against the database in the connection URI, if you include one. If you don't specify an authentication database, it authenticates against the `admin` database.\n\n- `authMechanism`: Set to `SCRAM-SHA-256`.\n\nYou can set these connection options by using either a connection string or the `mongoc_uri_t` API. The following code example shows how to create a MongoDB client that authenticates by using the SCRAM-SHA-256 mechanism:\n\n\n\n\n\n```c\nconst char *uri = \"mongodb://:@:/?authMechanism=SCRAM-SHA-256&authSource=\";\nmongoc_client_t *client = mongoc_client_new(uri);\n```\n\n\n\n\n\n```c\nmongoc_uri_t *uri = mongoc_uri_new(\"mongodb://:@:/\");\n\n// Set the authentication mechanism and properties\nmongoc_uri_set_auth_mechanism(uri, \"SCRAM-SHA-256\");\nmongoc_uri_set_auth_source(uri, \"\");\n\n// Create a client from the URI\nmongoc_client_t *client = mongoc_client_new_from_uri(uri);\n```\n\n\n\n\n\n## SCRAM-SHA-1\n\nSCRAM-SHA-1, as defined by RFC 5802, is the default authentication mechanism on MongoDB deployments running MongoDB v3.6.\n\nTo authenticate with this mechanism, set the following connection options:\n\n- `username`: The username to authenticate. Percent-encode this value before including it in the connection URI.\n\n- `password`: The password to authenticate. Percent-encode this value before including it in the connection URI.\n\n- `authSource`: The MongoDB database to authenticate against. By default, the C driver authenticates against the `admin` database.\n\n- `authMechanism`: Set to `\"SCRAM-SHA-1\"`.\n\nYou can set these connection options by using either a connection string or the `mongoc_uri_t` API. The following code example shows how to create a MongoDB client that authenticates by using the SCRAM-SHA-1 mechanism:\n\n\n\n\n\n```c\nconst char *uri = \"mongodb://:@:/?authMechanism=SCRAM-SHA-1&authSource=\";\nmongoc_client_t *client = mongoc_client_new(uri);\n```\n\n\n\n\n\n```c\nmongoc_uri_t *uri = mongoc_uri_new(\"mongodb://:@:/\");\n\n// Set the authentication mechanism and properties\nmongoc_uri_set_auth_mechanism(uri, \"SCRAM-SHA-1\");\nmongoc_uri_set_auth_source(uri, \"\");\n\n// Create a client from the URI\nmongoc_client_t *client = mongoc_client_new_from_uri(uri);\n```\n\n\n\n\n\n## MONGODB-X509\n\nIf you compile the C driver with TLS support, the C driver can present an X.509 client certificate to MongoDB to prove its identity during the TLS handshake. The MONGODB-X509 authentication mechanism uses this certificate to authenticate the client.\n\nTo authenticate with this mechanism, perform the following steps:\n\n1. Create a `mongoc_ssl_opt_t` structure. On this structure, set the `pem_file` field to the file path of the `.pem` file that contains your client certificate and private key.\n\n2. In your connection URI, set the `authMechanism` connection option to `\"MONGODB-X509\"`.\n\nYou can set this authentication method by using either a connection string or the `mongoc_uri_t` API. The following code example shows how to create a MongoDB client that authenticates by using the MONGODB-X509 mechanism:\n\n\n\n\n\n```c\nmongoc_client_t *client;\nmongoc_ssl_opt_t ssl_opts = {0};\n\nssl_opts.pem_file = \"mycert.pem\";\n\nconst char *uri = \"mongodb://@:/?authMechanism=MONGODB-X509\";\nmongoc_client_t *client = mongoc_client_new(uri);\nmongoc_client_set_ssl_opts(client, &ssl_opts);\n```\n\n\n\n\n\n```c\nmongoc_client_t *client;\nmongoc_ssl_opt_t ssl_opts = {0};\n\nssl_opts.pem_file = \"mycert.pem\";\n\nmongoc_uri_t *uri = mongoc_uri_new(\"mongodb://:@:/\");\n\n// Set the authentication mechanism\nmongoc_uri_set_auth_mechanism(uri, \"MONGODB-X509\");\n\n// Create a client from the URI\nmongoc_client_t *client = mongoc_client_new_from_uri(uri);\n\nmongoc_client_set_ssl_opts(client, &ssl_opts);\n```\n\n\n\n\n\n## MONGODB-AWS\n\nThe MONGODB-AWS authentication mechanism requires MongoDB v4.4 or later.\n\nThe `MONGODB-AWS` authentication mechanism uses AWS IAM (Amazon Web Services Identity and Access Management) or AWS Lambda credentials to authenticate your application. To use this mechanism to authenticate your application, first create a user with an associated Amazon Resource Name (ARN) on the `$external` database. Then, specify the `MONGODB-AWS` authMechanism in the connection URI.\n\nWhen you use the `MONGODB-AWS` mechanism, the C driver attempts to retrieve your AWS credentials from the following sources, in the order listed:\n\n1. Named parameters passed to the connection URI\n\n2. Environment variables\n\n3. AWS EKS AssumeRoleWithWebIdentity request\n\n4. ECS container metadata\n\n5. EC2 instance metadata\n\nThe following sections describe how to use the C driver to retrieve credentials from these sources and use them to authenticate your application."} -{"chunk_id": "68b296a6965969e81e392b7c-1", "page_id": "68b296a6965969e81e392b7c", "source_name": "c", "product_name": "C Driver", "url": "https://mongodb.com/docs/languages/c/c-driver/current/security/authentication", "title": "Authentication Mechanisms", "text": "### Connection URI\n\nFirst, the C driver checks whether you passed AWS credentials to the `mongoc_client_t` constructor as part of the connection URI. To pass your credentials in the connection URI, set the following connection options:\n\n- `username`: The AWS IAM access key ID to authenticate.\n\n- `password`: The AWS IAM secret access key.\n\n- `authMechanism`: Set to `\"MONGODB-AWS\"`.\n\nYou can create a URI containing these connection options by using either a connection string or the `mongoc_uri_t` API. The following code example shows how to create a MongoDB client that authenticates by using the MONGODB-AWS mechanism:\n\n\n\n\n\n```c\nconst char *uri = \"mongodb://:@:/?authMechanism=MONGODB-AWS\";\nmongoc_client_t *client = mongoc_client_new(uri);\n```\n\nYou can also include an AWS session token by passing it into the `authMechanismProperties` parameter:\n\n```cpp\nconst char *uri = \"mongodb://:@:/?authMechanism=MONGODB-AWS&authMechanismProperties=AWS_SESSION_TOKEN:\";\nmongoc_client_t *client = mongoc_client_new(uri);\n```\n\nYou cannot specify a property value containing the comma (`,`) character as a `authMechanismProperties` connection string option, even when the comma character is percent-encoded. To specify an `authMechanismProperties` property value that contains a comma, set the option by using the mongoc_uri_set_mechanism_properties() method.\n\n\n\n\n\n```c\nmongoc_uri_t *uri = mongoc_uri_new(\"mongodb://:@:/\");\n\n// Set the authentication mechanism\nmongoc_uri_set_auth_mechanism(uri, \"MONGODB-AWS\");\n\n// Create a client from the URI\nmongoc_client_t *client = mongoc_client_new_from_uri(uri);\n```\n\nYou can also include an AWS session token by passing it into the `authMechanismProperties` parameter:\n\n```c\nmongoc_uri_t *uri = mongoc_uri_new(\"mongodb://:@:/\");\n\n// Set the authentication mechanism and properties\nmongoc_uri_set_auth_mechanism(uri, \"MONGODB-AWS\");\nbson_t mechanism_properties = BSON_INITIALIZER;\nBSON_APPEND_UTF8(&mechanism_properties, \"AWS_SESSION_TOKEN\", \"\");\nmongoc_uri_set_mechanism_properties(uri, &mechanism_properties)\n\n// Create a client from the URI\nmongoc_client_t *client = mongoc_client_new_from_uri(uri);\n```\n\n\n\n\n\n### Environment Variables\n\nIf you don't include a username and password in your connection URI, the C driver tries to retrieve AWS credentials from the following environment variables:\n\n- `AWS_ACCESS_KEY_ID`\n\n- `AWS_SECRET_ACCESS_KEY`\n\n- `AWS_SESSION_TOKEN` (optional)\n\nTo use these environment variables to authenticate your application, first set them to the AWS IAM values needed for authentication, as shown in the following code example:\n\n```sh\nexport AWS_ACCESS_KEY_ID=\nexport AWS_SECRET_ACCESS_KEY=\nexport AWS_SESSION_TOKEN=\n```\n\nAfter you set these environment variables, set the `authMechanism` parameter in your connection URI to `\"MONGODB-AWS\"` by using either a connection string or the `mongoc_uri_t` API, as shown in the following example:\n\n\n\n\n\n```c\nconst char *uri = \"mongodb://:/?authMechanism=MONGODB-AWS\";\nmongoc_client_t *client = mongoc_client_new(uri);\n```\n\n\n\n\n\n```c\nmongoc_uri_t *uri = mongoc_uri_new(\"mongodb://:/\");\n\n// Set the authentication mechanism\nmongoc_uri_set_auth_mechanism(uri, \"MONGODB-AWS\");\n\n// Create a client from the URI\nmongoc_client_t *client = mongoc_client_new_from_uri(uri);\n```\n\n\n\n\n\n### ECS Metadata\n\nIf your application runs in an Elastic Container Service (ECS) container, the C driver can automatically retrieve temporary AWS credentials from an ECS endpoint. To do so, specify the URI of the ECS endpoint in an environment variable called `AWS_CONTAINER_CREDENTIALS_RELATIVE_URI`, as shown in the following example:\n\n```sh\nexport AWS_CONTAINER_CREDENTIALS_RELATIVE_URI=\n```\n\nAfter you set the environment variable, set the `authMechanism` parameter in your connection URI to `\"MONGODB-AWS\"` by using either a connection string or the `mongoc_uri_t` API, as shown in the following example:\n\n\n\n\n\n```c\nconst char *uri = \"mongodb://:/?authMechanism=MONGODB-AWS\";\nmongoc_client_t *client = mongoc_client_new(uri);\n```\n\n\n\n\n\n```c\nmongoc_uri_t *uri = mongoc_uri_new(\"mongodb://:/\");\n\n// Set the authentication mechanism\nmongoc_uri_set_auth_mechanism(uri, \"MONGODB-AWS\");\n\n// Create a client from the URI\nmongoc_client_t *client = mongoc_client_new_from_uri(uri);\n```\n\n\n\n\n\n### EC2 Instance Metadata\n\nThe C driver can automatically retrieve temporary AWS credentials from an Amazon Elastic Cloud Compute (EC2) instance. To use temporary credentials from within an EC2 instance, set the `authMechanism` parameter in your connection URI to `\"MONGODB-AWS\"` by using either a connection string or the `mongoc_uri_t` API, as shown in the following example:\n\n\n\n\n\n```c\nconst char *uri = \"mongodb://:/?authMechanism=MONGODB-AWS\";\nmongoc_client_t *client = mongoc_client_new(uri);\n```\n\n\n\n\n\n```c\nmongoc_uri_t *uri = mongoc_uri_new(\"mongodb://:/\");\n\n// Set the authentication mechanism\nmongoc_uri_set_auth_mechanism(uri, \"MONGODB-AWS\");\n\n// Create a client from the URI\nmongoc_client_t *client = mongoc_client_new_from_uri(uri);\n```\n\n\n\n\n\nIf you set any of the environment variables from the preceding AWS authentication methods, the C driver attempts to retrieve credentials by using those methods before attempting to retrieve them from an EC2 instance. To attempt to retrieve credentials only from an EC2 instance, ensure that the environment variables are not set.\n\n## OIDC\n\nThe OpenID Connect (OIDC) authentication mechanism allows you to authenticate to MongoDB by using a third-party identity provider, such as Azure or Google Cloud Platform (GCP).\n\nYou can use this mechanism only when authenticating to MongoDB Atlas or MongoDB Enterprise Advanced, and only when authenticating to MongoDB Server v7.0 or later.\n\nTo learn more about configuring MongoDB Atlas for OIDC authentication, see Set up Workforce Identity Federation with OIDC in the MongoDB Server manual.\n\nFor more information about using OIDC authentication with MongoDB, see OpenID Connect Authentication and MongoDB Server Parameters in the MongoDB Server manual.\n\nThe following sections describe how to use OIDC authentication to authenticate from various platforms."} -{"chunk_id": "68b296a6965969e81e392b7c-2", "page_id": "68b296a6965969e81e392b7c", "source_name": "c", "product_name": "C Driver", "url": "https://mongodb.com/docs/languages/c/c-driver/current/security/authentication", "title": "Authentication Mechanisms", "text": "### Azure\n\nIf your application runs on an Azure VM, or otherwise uses the Azure Instance Metadata Service (IMDS), you can authenticate to MongoDB by using the C driver's built-in Azure support.\n\nThe following example initializes a `mongoc_client_t` that uses OIDC authentication with Azure:\n\n```c\n#include \n\n#define ASSERT_WITH_ERROR(stmt, err) \\\n if (!(stmt)) { \\\n fprintf(stderr, \"Error on line %d (%s): %s\\n\", __LINE__, #stmt, err.message); \\\n abort(); \\\n }\n\n#define ASSERT(stmt) \\\n if (!(stmt)) { \\\n fprintf(stderr, \"Error on line %d (%s)\\n\", __LINE__, #stmt); \\\n abort(); \\\n }\n\nint main(void)\n{\n bson_error_t error;\n\n // Create client configured with Azure OIDC:\n mongoc_client_t *client;\n {\n mongoc_uri_t *uri = mongoc_uri_new_with_error(getenv(\"MONGODB_URI\"), &error);\n ASSERT_WITH_ERROR(uri, error);\n mongoc_uri_set_auth_mechanism(uri, \"MONGODB-OIDC\");\n bson_t mechanism_properties = BSON_INITIALIZER;\n BSON_APPEND_UTF8(&mechanism_properties, \"ENVIRONMENT\", \"azure\");\n BSON_APPEND_UTF8(&mechanism_properties, \"TOKEN_RESOURCE\", \"\");\n ASSERT(mongoc_uri_set_mechanism_properties(uri, &mechanism_properties));\n client = mongoc_client_new_from_uri_with_error(uri, &error);\n ASSERT_WITH_ERROR(client, error);\n bson_destroy(&mechanism_properties);\n mongoc_uri_destroy(uri);\n }\n\n // Insert a document:\n {\n bson_t doc = BSON_INITIALIZER;\n mongoc_collection_t *coll = mongoc_client_get_collection(client, \"db\", \"coll\");\n ASSERT_WITH_ERROR(mongoc_collection_insert_one(coll, &doc, NULL, NULL, &error), error);\n mongoc_collection_destroy(coll);\n }\n\n mongoc_client_destroy(client);\n return 0;\n}\n\n```\n\n### GCP\n\nIf your application runs on a Google Compute Engine VM, or otherwise uses the GCP Instance Metadata Service, you can authenticate to MongoDB by using the C driver's built-in GCP support.\n\nThe following example initializes a `mongoc_client_t` that uses OIDC authentication with GCP:\n\n```c\n#include \n\n#define ASSERT_WITH_ERROR(stmt, err) \\\n if (!(stmt)) { \\\n fprintf(stderr, \"Error on line %d (%s): %s\\n\", __LINE__, #stmt, err.message); \\\n abort(); \\\n }\n\n#define ASSERT(stmt) \\\n if (!(stmt)) { \\\n fprintf(stderr, \"Error on line %d (%s)\\n\", __LINE__, #stmt); \\\n abort(); \\\n }\n\nint main(void)\n{\n bson_error_t error;\n\n // Create client configured with GCP OIDC:\n mongoc_client_t *client;\n {\n mongoc_uri_t *uri = mongoc_uri_new_with_error(getenv(\"MONGODB_URI\"), &error);\n ASSERT_WITH_ERROR(uri, error);\n mongoc_uri_set_auth_mechanism(uri, \"MONGODB-OIDC\");\n bson_t mechanism_properties = BSON_INITIALIZER;\n BSON_APPEND_UTF8(&mechanism_properties, \"ENVIRONMENT\", \"gcp\");\n BSON_APPEND_UTF8(&mechanism_properties, \"TOKEN_RESOURCE\", \"\");\n ASSERT(mongoc_uri_set_mechanism_properties(uri, &mechanism_properties));\n client = mongoc_client_new_from_uri_with_error(uri, &error);\n ASSERT_WITH_ERROR(client, error);\n bson_destroy(&mechanism_properties);\n mongoc_uri_destroy(uri);\n }\n\n // Insert a document:\n {\n bson_t doc = BSON_INITIALIZER;\n mongoc_collection_t *coll = mongoc_client_get_collection(client, \"db\", \"coll\");\n ASSERT_WITH_ERROR(mongoc_collection_insert_one(coll, &doc, NULL, NULL, &error), error);\n mongoc_collection_destroy(coll);\n }\n\n mongoc_client_destroy(client);\n return 0;\n}\n\n```\n\n### Kubernetes\n\nIf your application runs on a Kubernetes cluster, you can authenticate to MongoDB by using the C driver's built-in Kubernetes support.\n\nThe following example initializes a `mongoc_client_t` that uses OIDC authentication with Kubernetes:\n\n```c\n#include \n\n#define ASSERT_WITH_ERROR(stmt, err) \\\n if (!(stmt)) { \\\n fprintf(stderr, \"Error on line %d (%s): %s\\n\", __LINE__, #stmt, err.message); \\\n abort(); \\\n }\n\n#define ASSERT(stmt) \\\n if (!(stmt)) { \\\n fprintf(stderr, \"Error on line %d (%s)\\n\", __LINE__, #stmt); \\\n abort(); \\\n }\n\nint main(void)\n{\n bson_error_t error;\n\n // Create client configured with Kubernetes OIDC:\n mongoc_client_t *client;\n {\n mongoc_uri_t *uri = mongoc_uri_new_with_error(getenv(\"MONGODB_URI\"), &error);\n ASSERT_WITH_ERROR(uri, error);\n mongoc_uri_set_auth_mechanism(uri, \"MONGODB-OIDC\");\n bson_t mechanism_properties = BSON_INITIALIZER;\n BSON_APPEND_UTF8(&mechanism_properties, \"ENVIRONMENT\", \"k8s\");\n ASSERT(mongoc_uri_set_mechanism_properties(uri, &mechanism_properties));\n client = mongoc_client_new_from_uri_with_error(uri, &error);\n ASSERT_WITH_ERROR(client, error);\n bson_destroy(&mechanism_properties);\n mongoc_uri_destroy(uri);\n }\n\n // Insert a document:\n {\n bson_t doc = BSON_INITIALIZER;\n mongoc_collection_t *coll = mongoc_client_get_collection(client, \"db\", \"coll\");\n ASSERT_WITH_ERROR(mongoc_collection_insert_one(coll, &doc, NULL, NULL, &error), error);\n mongoc_collection_destroy(coll);\n }\n\n mongoc_client_destroy(client);\n return 0;\n}\n```\n\nIf you specify Kubernetes OIDC as the authentication mechanism, the driver reads the contents of the OIDC token from one of the following locations:\n\n- `AZURE_FEDERATED_TOKEN_FILE` environment variable for applications running on Azure Kubernetes Service (AKS)\n\n- `AWS_WEB_IDENTITY_TOKEN_FILE` environment variable for applications running on Elastic Kubernetes Service (EKS)\n\n- `/var/run/secrets/kubernetes.io/serviceaccount/token` file, the default location for all other applications, including ones that run on Google Kubernetes Engine (GKE)\n\nYou must store your OIDC token in the location that corresponds to the service you use to run your application."} -{"chunk_id": "68b296a6965969e81e392b7c-3", "page_id": "68b296a6965969e81e392b7c", "source_name": "c", "product_name": "C Driver", "url": "https://mongodb.com/docs/languages/c/c-driver/current/security/authentication", "title": "Authentication Mechanisms", "text": "### Custom Callback\n\nYou can also provide a custom callback function to retrieve an OIDC token from your identity provider, as shown in the following example:\n\n```c\n#include \n\n#define ASSERT_WITH_ERROR(stmt, err) \\\n if (!(stmt)) { \\\n fprintf(stderr, \"Error on line %d (%s): %s\\n\", __LINE__, #stmt, err.message); \\\n abort(); \\\n }\n\n#define ASSERT(stmt) \\\n if (!(stmt)) { \\\n fprintf(stderr, \"Error on line %d (%s)\\n\", __LINE__, #stmt); \\\n abort(); \\\n }\n\nstatic mongoc_oidc_credential_t *\noidc_callback_fn(mongoc_oidc_callback_params_t *params)\n{\n FILE *token_file = fopen(\"/tmp/tokens/test_machine\", \"r\");\n ASSERT(token_file);\n\n // Determine length of token:\n ASSERT(0 == fseek(token_file, 0, SEEK_END));\n long token_len = ftell(token_file);\n ASSERT(token_len > 0);\n ASSERT(0 == fseek(token_file, 0, SEEK_SET));\n\n // Read file into buffer:\n char *token = bson_malloc(token_len + 1);\n size_t nread = fread(token, 1, token_len, token_file);\n ASSERT(nread == (size_t)token_len);\n token[token_len] = '\\0';\n fclose(token_file);\n mongoc_oidc_credential_t *cred = mongoc_oidc_credential_new(token);\n bson_free(token);\n return cred;\n}\n\nint main(void)\n{\n bson_error_t error;\n\n // Create client configured with OIDC callback:\n mongoc_client_t *client;\n {\n mongoc_uri_t *uri = mongoc_uri_new_with_error(getenv(\"MONGODB_URI\"), &error);\n ASSERT_WITH_ERROR(uri, error);\n mongoc_uri_set_auth_mechanism(uri, \"MONGODB-OIDC\");\n mongoc_oidc_callback_t *oidc_callback = mongoc_oidc_callback_new(oidc_callback_fn);\n client = mongoc_client_new_from_uri_with_error(uri, &error);\n ASSERT_WITH_ERROR(client, error);\n ASSERT(mongoc_client_set_oidc_callback(client, oidc_callback));\n mongoc_oidc_callback_destroy(oidc_callback);\n mongoc_uri_destroy(uri);\n }\n\n // Insert a document:\n {\n bson_t doc = BSON_INITIALIZER;\n mongoc_collection_t *coll = mongoc_client_get_collection(client, \"db\", \"coll\");\n ASSERT_WITH_ERROR(mongoc_collection_insert_one(coll, &doc, NULL, NULL, &error), error);\n mongoc_collection_destroy(coll);\n }\n\n mongoc_client_destroy(client);\n return 0;\n}\n\n```\n\n## API Documentation\n\nTo learn more about authenticating your application in the C driver, see the following API documentation:\n\n- mongoc_client_t\n\n- mongoc_uri_t"} -{"chunk_id": "69327965e88006792c765cf9-0", "page_id": "69327965e88006792c765cf9", "source_name": "c", "product_name": "C Driver", "url": "https://mongodb.com/docs/languages/c/c-driver/current/crud/replace", "title": "Replace Documents", "text": "# Replace Documents\n\n## Overview\n\nIn this guide, you can learn how to use the C driver to run a **replace operation** on a MongoDB collection. A replace operation performs differently than an update operation. An update operation modifies only the specified fields in a target document. A replace operation removes *all* fields in the target document and replaces them with new ones.\n\nTo replace a document, use the `mongoc_collection_replace_one()` function.\n\n### Sample Data\n\nThe examples in this guide use the `restaurants` collection in the `sample_restaurants` database from the Atlas sample datasets. To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the MongoDB Get Started guide.\n\n## Replace Operation\n\nYou can perform a replace operation by using `mongoc_collection_replace_one()`. This function removes all fields except the `_id` field from the first document that matches the search criteria. It then inserts the fields and values you specify into the document.\n\n### Required Parameters\n\nThe `mongoc_collection_replace_one()` function requires the following parameters:\n\n- Collection: Specifies the collection on which to perform the replace operation.\n\n- Query filter document: Specifies which collection documents to match. The function selects the first matching document to replace. For more information about query filters, see the Query Filter Documents section in the MongoDB Server manual.\n\n- Replacement document: Specifies the fields and values to insert into the new document.\n\n- Options document: Specifies options to customize the operation, or `NULL`.\n\n- Results location: Specifies a pointer to overwritable storage that will contain operation results, or `NULL`.\n\n- Error location: Specifies a location for an error value, or `NULL`.\n\n### Example\n\nThe following example uses the `mongoc_collection_replace_one()` function to replace the fields and values of a document in which the `name` field value is `\"Pizza Town\"` with a document in which the `name` field value is `\"Mongo's Pizza\"`:\n\n```c\nbson_t *query = BCON_NEW(\"name\", \"Pizza Town\");\nbson_t *replace = BCON_NEW(\n \"name\", \"Mongo's Pizza\",\n \"cuisine\", \"Pizza\",\n \"address\", \"{\",\n \"street\", \"123 Pizza St\",\n \"zipCode\", \"10003\",\n \"}\",\n \"borough\", \"Manhattan\"\n);\nbson_error_t error;\n\nif (!mongoc_collection_replace_one(collection, query, replace, NULL, NULL, &error)) {\n fprintf(stderr, \"Replace operation failed: %s\\n\", error.message);\n}\n\nbson_destroy(query);\nbson_destroy(replace);\n```\n\nThe values of `_id` fields are immutable. If your replacement document specifies a value for the `_id` field, it must be identical to the `_id` value of the existing document.\n\n## Modify the Replace Operation\n\nYou can modify the behavior of the `mongoc_collection_replace_one()` function by passing a BSON document that specifies option values. The following table describes some options you can set in the document:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nOption\n\n\nDescription\n\n
\n`upsert`\n\n\nSpecifies whether the replace operation performs an upsert operation if no documents match the query filter. For more information, see the upsert statement in the MongoDB Server manual.Defaults to `false`.\n\n
\n`bypassDocumentValidation`\n\n\nSpecifies whether the replace operation bypasses document validation. This lets you replace documents that don't meet the schema validation requirements, if any exist. For more information about schema validation, see Schema Validation in the MongoDB Server manual.Defaults to `false`.\n\n
\n`collation`\n\n\nSpecifies the kind of language collation to use when comparing text. For more information, see Collation in the MongoDB Server manual.\n\n
\n`hint`\n\n\nGets or sets the index to scan for documents. For more information, see the hint statement in the MongoDB Server manual.\n\n
\n`comment`\n\n\nAttaches a comment to the operation. For more information, see the insert command fields guide in the MongoDB Server manual.\n\n
### Replace Options Example\n\nThe following code uses the `mongoc_collection_replace_one()` function to find the first document in which the `name` field has the value `\"Food Town\"`, then replaces this document with a new document in which the `name` value is `\"Food World\"`. Because the `upsert` option is set to `true`, the driver inserts a new document if the query filter doesn't match any existing documents:\n\n```c\nbson_t *query = BCON_NEW(\"name\", \"Food Town\");\nbson_t *replace = BCON_NEW(\n \"name\", \"Food World\",\n \"cuisine\", \"Mixed\",\n \"address\", \"{\",\n \"street\", \"123 Food St\",\n \"zipCode\", \"10003\",\n \"}\",\n \"borough\", \"Manhattan\"\n);\nbson_error_t error;\n\nbson_t opts;\nbson_init(&opts);\nbson_append_bool(&opts, \"upsert\", -1, true);\n\nif (!mongoc_collection_replace_one(collection, query, replace, &opts, NULL, &error)) {\n fprintf(stderr, \"Replace operation failed: %s\\n\", error.message);\n}\n\nbson_destroy(query);\nbson_destroy(replace);\nbson_destroy(&opts);\n```\n\n## Additional Information\n\nTo learn more about update operations, see the Update Documents guide.\n\nTo learn more about creating query filters, see the Specify a Query guide.\n\n### API Documentation\n\nTo learn more about the `mongoc_collection_replace_one()` function, see the API documentation."} -{"chunk_id": "69327965e88006792c765d29-0", "page_id": "69327965e88006792c765d29", "source_name": "c", "product_name": "C Driver", "url": "https://mongodb.com/docs/languages/c/c-driver/current/reference/release-notes", "title": "Release Notes", "text": "# Release Notes\n\n## Overview\n\nThe MongoDB C Driver consists of two libraries: `libbson` and `libmongoc`. On this page, you can learn about the changes, and deprecations made in each version of the driver libraries.\n\nLearn what's new in:\n\n- Version 2.5.6\n\n- Version 2.5.5\n\n- Version 2.5.4\n\n- Version 2.5.3\n\n- Version 2.5.2\n\n- Version 2.5.1\n\n- Version 2.5.0\n\n- Version 2.4.0\n\n- Version 2.3.3\n\n- Version 2.3.2\n\n- Version 2.3.1\n\n- Version 2.3.0\n\n- Version 2.2.3\n\n- Version 2.2.1\n\n- Version 2.2.0\n\n- Version 2.1.2\n\n- Version 2.1.1\n\n- Version 2.1.0\n\n- Version 2.0.2\n\n- Version 2.0.1\n\n- Version 2.0.0\n\n- Version 1.30.13\n\n- Version 1.30.12\n\n- Version 1.30.10\n\n- Version 1.30.9\n\n- Version 1.30.8\n\n- Version 1.30.6\n\n- Version 1.30.3\n\n- Version 1.30.0\n\n- Version 1.29.0\n\n- Version 1.28.0\n\n- Version 1.27.6\n\n- Version 1.27.5\n\n- Version 1.27.4\n\n- Version 1.27.3\n\n- Version 1.27.2\n\n- Version 1.27.1\n\n- Version 1.27.0\n\n- Version 1.26.2\n\n- Version 1.26.1\n\n- Version 1.26.0\n\n## What's New in 2.5.6\n\nThe 2.5.6 release of the MongoDB C Driver includes the following changes:\n\nC driver v2.5.6 includes fixes for the following security issues:\n\n- CVE-2026-106431\n\n- CVE-2026-106437\n\n- CVE-2026-106438\n\nFor the latest information about MongoDB security updates, see MongoDB Security Bulletins.\n\nFor more information about this release, see the v2.5.6 release notes.\n\n## What's New in 2.5.5\n\nThe 2.5.5 release of the MongoDB C Driver includes the following changes:\n\nC driver v2.5.5 includes a fix for CVE-2026-96746.\n\nFor the latest information about MongoDB security updates, see MongoDB Security Bulletins.\n\nFor more information about this release, see the v2.5.5 release notes.\n\n## What's New in 2.5.4\n\nThe 2.5.4 release of the MongoDB C Driver includes the following changes:\n\nC driver v2.5.4 includes a fix for CVE-2026-93393.\n\nFor the latest information about MongoDB security updates, see MongoDB Security Bulletins.\n\nFor more information about this release, see the v2.5.4 release notes.\n\n## What's New in 2.5.3\n\nThe 2.5.3 release of the MongoDB C Driver includes the following changes:\n\nC driver v2.5.3 includes fixes for the following security issues:\n\n- CVE-2026-82076\n\n- CVE-2026-88035\n\nFor the latest information about MongoDB security updates, see MongoDB Security Bulletins.\n\nFor more information about this release, see the v2.5.3 release notes.\n\n## What's New in 2.5.2\n\nThe 2.5.2 release of the MongoDB C Driver includes the following changes:\n\nC driver v2.5.2 includes fixes for the following security issues:\n\n- CVE-2026-84963\n\n- CVE-2026-84964\n\n- CVE-2026-84965\n\n- CVE-2026-84969\n\nFor the latest information about MongoDB security updates, see MongoDB Security Bulletins.\n\nFor more information about this release, see the v2.5.2 release notes.\n\n## What's New in 2.5.1\n\nThe 2.5.1 release of the MongoDB C Driver includes the following changes:\n\nC driver v2.5.1 includes a fix for CVE-2026-81524.\n\nFor the latest information about MongoDB security updates, see MongoDB Security Bulletins.\n\nFor more information about this release, see the v2.5.1 release notes.\n\n## What's New in 2.5.0\n\nThe following sections describe the changes in the 2.5.0 release of the C driver.\n\n`libbson` has no changes in this release. The version number increases to match the `libmongoc` version.\n\n### libmongoc\n\nThe 2.5.0 release of `libmongoc` includes the following changes:\n\n#### New Features\n\n- When a server response includes a `SystemOverloadedError` with a `baseBackoffMS` value, the driver uses that value instead of its default delay to calculate how long to wait before retrying.\n\n- Adds getters for collection bulk write options.\n\n#### Improvements\n\n- Updates the bundled `utf8proc` library to 2.11.3.\n\nFor more information about this release, see the v2.5.0 release notes.\n\n## What's New in 2.4.0\n\nC driver v2.4.0 contains breaking changes. For more information, see Version 2.4.0 in the Upgrade Driver Versions guide.\n\nThe following sections describe the changes in the 2.4.0 release of the C driver.\n\nIn a future minor release, the minimum supported MongoDB Server version increases from 4.2 to 4.4. To learn more, see MongoDB Software Lifecycle Schedules.\n\n`libbson` has no changes in this release. The version number increases to match the `libmongoc` version.\n\n### libmongoc\n\nThe 2.4.0 release of `libmongoc` includes the following changes:\n\n#### New Features\n\n- The Queryable Encryption `String` algorithm (`MONGOC_ENCRYPT_ALGORITHM_STRING`) is generally available and supports the `prefix`, `suffix`, and `substring` query types.\n\n - The `prefixPreview`, `suffixPreview`, and `substringPreview` query types remain experimental.\n\n- Adds APIs to get and set snapshot times on snapshot sessions.\n\n- Adds support for AWS STS regional endpoints.\n\n#### Improvements\n\n- Raises the required `libmongocrypt` version from 1.15.1 to 1.20.0 to support In-Use Encryption. This requirement corresponds to the `ENABLE_CLIENT_SIDE_ENCRYPTION` CMake option.\n\n#### Deprecations\n\n- Deprecates the Queryable Encryption `Text` APIs in favor of the `String` APIs. Use `mongoc_client_encryption_encrypt_string_*` instead of `mongoc_client_encryption_encrypt_text_*` to match the generally available `String` algorithm.\n\n#### Fixes\n\n- Fixes handling of verbose results in `bulkWrite` replies.\n\n- Fixes handling of SCRAM replies.\n\nFor more information about this release, see the v2.4.0 release notes.\n\n## What's New in 2.3.3\n\nThe following sections describe the changes in the 2.3.3 release of the C driver.\n\n### libmongoc\n\n#### Fixes\n\n- Fixes an error when configuring the driver with CMake 4.4.0.\n\n- Fixes issues when the driver is built with `UNICODE` on Windows.\n\n- Adds stricter validation to HTTP handling.\n\nFor more information about this release, see the v2.3.3 release notes.\n\n## What's New in 2.3.2\n\nThe following sections describe the changes in the 2.3.2 release of the C driver.\n\n### libmongoc\n\n#### Fixes\n\n- Fixes an issue introduced in v2.3.0 where a failed `killCursors` operation caused applications to crash.\n\n- Fixes error handling in SCRAM authentication.\n\nFor more information about this release, see the v2.3.2 release notes.\n\n## What's New in 2.3.1\n\nThe following sections describe the changes in the 2.3.1 release of the C driver.\n\n### libbson\n\n#### Fixes\n\n- Fixes length check in `bson_new_from_buffer`.\n\n- Corrects documentation generation on Sphinx 9.0+.\n\n### libmongoc\n\n#### Improvements\n\n- Improves forward compatibility with OpenSSL 4.0.0 when handling `EAGAIN` errors in old-style read callbacks where `BIO_FLAGS_AUTO_EOF` is enabled.\n\n- Improves decompressed message length constraints.\n\n#### Fixes\n\n- Propagates username to custom OIDC callback.\n\n- Corrects documentation generation on Sphinx 9.0+.\n\nFor more information about this release, see the v2.3.1 release notes.\n\n## What's New in 2.3.0\n\nC driver v2.3.0 contains breaking changes. For more information, see Version 2.3.0 in the Upgrade Driver Versions guide.\n\nThe following sections describe the changes in the 2.3.0 release of the C driver.\n\n### libbson\n\nThe 2.3.0 release of `libbson` includes the following changes:\n\n#### Improvements\n\n- `bson_t` is trivially relocatable.\n\n#### Deprecations\n\n- Deprecates `bson_append_array_begin()`. Use `bson_append_array_builder_begin()` or `bson_append_array_unsafe_begin()` instead."} -{"chunk_id": "69327965e88006792c765d29-1", "page_id": "69327965e88006792c765d29", "source_name": "c", "product_name": "C Driver", "url": "https://mongodb.com/docs/languages/c/c-driver/current/reference/release-notes", "title": "Release Notes", "text": "### libmongoc\n\nThe 2.3.0 release of `libmongoc` includes the following changes:\n\n#### New Features\n\n- Adds support for Intelligent Workload Management (IWM) and ingress connection rate limiting. The driver handles write-blocking scenarios and optimizes connection establishment during high-load conditions to maintain application availability. These features will be available on Atlas clusters running MongoDB 9.0 and later.\n\n - This feature is supported on all commands.\n\n - We recommend upgrading to this driver version to avoid the impact of server changes related to overload errors. If you don't upgrade, adjust your custom retry logic to handle higher rates of overload errors.\n\n - Adds the `maxAdaptiveRetries` URI option to configure the maximum number of retries for operations that fail with a `SystemOverloadedError`. The default value is `2`.\n\n - Adds the `enableOverloadRetargeting` URI option to control whether retries of `SystemOverloadedError` try to use a different server. The default value is `false`.\n\n- Adds support for appending client handshake metadata after initialization, on a per-client or per-pool basis.\n\n - Adds the `mongoc_client_append_metadata()` and `mongoc_client_pool_append_metadata()` functions, which are useful for projects that wrap the C driver to self-identify.\n\n- Adds Kubernetes as a credential provider for `MONGODB-OIDC` authentication.\n\n#### Improvements\n\n- Adds the following improvements to cursor handling on client-side timeouts:\n\n - Sends `killCursors` after a cursor receives a client-side timeout.\n\n - Exits early if a change stream resumes on repeated client-side timeouts.\n\n#### Removals\n\n- Removes support for macOS 13 and older. Use macOS 14 or newer.\n\nFor more information about this release, see the v2.3.0 release notes.\n\n## What's New in 2.2.3\n\nThe 2.2.3 release of the MongoDB C Driver includes the following changes:\n\nMongoDB C Driver v2.2.3 includes a fix for CVE-2026-4359.\n\nFor the latest information about MongoDB security updates, see MongoDB Security Bulletins.\n\n## What's New in 2.2.1\n\nThe 2.2.1 release of the MongoDB C Driver includes the following changes:\n\n- Fixes a timeout error on Azure and GCP KMS requests.\n\n- Handles `bulkWrite` responses from the server that omit the `nModified` parameter.\n\n## What's New in 2.2.0\n\nC driver v2.2.0 contains breaking changes. For more information, see Version 2.2.0 in the Upgrade Driver Versions guide.\n\nThe following sections describe the changes in the 2.2.0 release of the C driver.\n\n### libbson\n\nThe 2.2.0 release of `libbson` includes the following changes:\n\n#### Fixes\n\n- Increases resolution of `bson_get_monotonic_time()` on Windows platforms.\n\n- Removes support for Visual Studio 2015. The minimum supported version is Visual Studio 2017.\n\n#### Deprecations\n\n- Deprecates support for macOS 11 and macOS 12\n\n### libmongoc\n\nThe 2.2.0 release of `libmongoc` includes the following changes:\n\n#### New Features\n\n- Introduces the following `MONGODB-OIDC` authentication mechanism features:\n\n - Adds support for a custom callback with `mongoc_client_set_oidc_callback` and `mongoc_client_pool_set_oidc_callback`.\n\n - Adds support for Azure environment with property `environment:azure`.\n\n - Adds support for GCP environment with property `environment:gcp`.\n\n - Does not support Kubernetes environment in this release.\n\n- Adds the following features to `mongoc_bulkwrite_t`:\n\n - Adds `mongoc_bulkwrite_is_acknowledged` function.\n\n - Adds `mongoc_bulkwriteresult_serverid` function.\n\n - Adds support for Queryable Encryption operations.\n\n- Adds the following support for text indexes for Queryable Encryption:\n\n - Adds `mongoc_client_encryption_encrypt_text_opts_t` type.\n\n - Adds preview support for substring, prefix, and suffix search for experimental workloads only. These features are unstable and their security is not guaranteed until released as Generally Available (GA). The GA version of these features may not be backwards compatible with the preview version.\n\n- Adds support for TLS v1.3 on Windows platforms with Windows Secure Channel.\n\n#### Fixes\n\n- Does not try to resume when iterating a closed change stream.\n\n- Removes support for Visual Studio 2015. The minimum supported version is Visual Studio 2017.\n\n- Raises the required version of libmongocrypt from 1.13.0 to 1.15.0. This supports In-Use Encryption and corresponds to the CMake `ENABLE_CLIENT_SIDE_ENCRYPTION` option.\n\n#### Deprecations\n\n- Deprecates support for macOS 11 and macOS 12.\n\nFor more information about this release, see the v2.2.0 release notes.\n\n## What's New in 2.1.2\n\nThe following sections describe the changes in the 2.1.2 release of the C driver.\n\n### libbson\n\nThis version is incremented to match the `libmongoc` version, but there are no changes since 2.1.1.\n\n### libmongoc\n\nThe 2.1.2 release of `libmongoc` includes the following changes:\n\n#### Fixes\n\n- Fixes the following Common Vulnerabilities and Exposures (CVE) issue: bulk write with options reads invalid memory if passed with large options. To learn more, see the related CVE-2025-12119 issue.\n\nFor more information about this release, see the v2.1.2 release notes.\n\n## What's New in 2.1.1\n\nThe following sections describe the changes in the 2.1.1 release of the C driver.\n\n### libbson\n\nThis version is incremented to match the `libmongoc` version, but there are no changes since 2.1.0.\n\n### libmongoc\n\nThe 2.1.1 release of `libmongoc` includes the following changes:\n\n#### Fixes\n\n- No longer propagates the `-fPIC` flag in CMake targets.\n\n- Applies write command behavior to the `mongoc_collection_create_indexes_with_opts()` function.\n\n- Omits the `saslSupportedMechs` field in single-threaded monitoring commands.\n\nFor more information about this release, see the v2.1.1 release notes.\n\n## What's New in 2.1.0\n\nC driver v2.1.0 contains breaking changes. For more information, see Version 2.1.0 in the Upgrade Driver Versions guide.\n\nThe following sections describe the changes in the 2.1.0 release of the C driver.\n\n### libbson\n\nThe 2.1.0 release of `libbson` includes the following changes:\n\n#### Fixes\n\n- For non-Windows environments, the uninstall script now calls the `find \"$dir\" -maxdepth 1` command to detect non-empty directories instead of the `ls --almost-all` command, which was not supported on macOS.\n\n- For Windows environments, the uninstall script no longer \"succeeds\" with an incorrect, non-zero `%ERRORLABEL%` value.\n\n- Removes support for Debian 9 and Debian 10.\n\n#### Improvements\n\n- Sets CMake policy max version to `4.0`. The max version was previously unset.\n\n### libmongoc\n\nThe 2.1.0 release of `libmongoc` includes the following changes:\n\n#### Fixes\n\n- For non-Windows environments, the uninstall script now calls the `find \"$dir\" -maxdepth 1` command to detect non-empty directories instead of the `ls --almost-all` command, which was not supported on macOS.\n\n- For Windows environments, the uninstall script no longer \"succeeds\" with an incorrect, non-zero `%ERRORLABEL%` value.\n\n- Adds Window Secure Channel support to verify client certificates with newer signatures.\n\n- Replaces use of `rand()` with thread-safe alternatives.\n\n- Removes support for Debian 9 and Debian 10.\n\n#### Improvements\n\n- Updates the minimum supported MongoDB Server version from 4.0 to 4.2.\n\n- Sets CMake policy max version to `4.0`. The max version was previously unset.\n\n- Removes unhelpful long-lived buffers to reduce memory usage.\n\n- Improves error messages produced by Windows APIs.\n\n## What's New in 2.0.2\n\nThe following sections describe the changes in the 2.0.2 release of the C driver."} -{"chunk_id": "69327965e88006792c765d29-2", "page_id": "69327965e88006792c765d29", "source_name": "c", "product_name": "C Driver", "url": "https://mongodb.com/docs/languages/c/c-driver/current/reference/release-notes", "title": "Release Notes", "text": "### libbson\n\nThis release includes several fixes to the `bson_validate` family of functions, with the following minor behavioral changes:\n\n- When you specify the `BSON_VALIDATE_UTF8` setting, the driver rejects invalid UTF-8 sequences instead of accepting them as in previous versions.\n\n- The driver validates the scope document in a deprecated \"code with scope\" element with a fixed set of rules and treats it as an opaque JavaScript object.\n\n- The driver enforces a document nesting limit during validation.\n\n### libmongoc\n\nThe 2.0.2 release of `libmongoc` includes the following changes:\n\n#### Fixes\n\n- Fixes a message of `bson_strerror_r` on Windows.\n\n- Fixes memory leaks with Windows Secure Channel.\n\n- Fixes loading PKCS#8 RSA keys with Windows Secure Channel.\n\nFor more information about this release, see the v2.0.2 release notes.\n\n## What's New in 2.0.1\n\nThe following sections describe the changes in the 2.0.1 release of the C driver.\n\n### libbson\n\nThe 2.0.1 release of `libbson` includes the following changes:\n\n#### Fixes\n\n- Fixes a CMake 4 configuration error on macOS operating systems\n\n### libmongoc\n\nThe 2.0.1 release of `libmongoc` includes the following changes:\n\n#### Fixes\n\n- Fixes a username handling issue for `MONGODB-X509` authentication that occurred when the C driver was configured to use the Secure Transport or Secure Channel library\n\n- No longer populates a `mongoc_bulkwritereturn_t.res` with a partial result when the `mongoc_bulkwrite_execute()` function generates a client error after the first write operation\n\nFor more information about this release, see the v2.0.1 release notes.\n\n## What's New in 2.0.0\n\nC driver v2.0.0 contains breaking changes. For more information, see Version 2.0.0 in the Upgrade Driver Versions guide.\n\nThe following sections describe the changes in the 2.0.0 release of the C driver.\n\nThe 2.0.0 driver release removes many deprecated types and methods. To view a full list of removals, see the **Removals** sections of the v2.0 release notes.\n\n### libbson\n\nThe 2.0.0 release of `libbson` includes the following changes:\n\n#### New Features\n\n- Adds support for the BSON Binary Vector subtype. To learn more, see BSON Binary Vector subtype in the libbson API documentation.\n\n### libmongoc\n\nThe 2.0.0 release of `libmongoc` includes the following changes:\n\n#### New Features\n\n- Supports aggregate operations that include `$lookup` stages for In-Use Encryption. To learn more, see the following references in the MongoDB Server manual:\n\n - $lookup and $graphLookup Behavior for CSFLE\n\n - $lookup and $graphLookup Behavior for QE\n\nFor more information about this release, see the v2.0 release notes.\n\n## What's New in 1.30.6\n\nThe following sections describe the changes in the 1.30.3 release of the C driver.\n\n### libbson\n\nThis version is incremented to match the `libmongoc` version, but there are no changes since 1.30.6.\n\n### libmongoc\n\nThe 1.30.6 release of `libmongoc` includes the following changes:\n\n#### Fixes\n\n- Fixes the following Common Vulnerabilities and Exposures (CVE) issue: bulk write with options reads invalid memory if passed with large options. To learn more, see the related CVE-2025-12119 issue.\n\nFor more information about this release, see the v1.30.6 release notes.\n\n## What's New in 1.30.13\n\nThe 1.30.13 release of the MongoDB C Driver includes the following changes:\n\nC driver v1.30.13 includes fixes for the following security issues:\n\n- CVE-2026-106428\n\n- CVE-2026-106431\n\n- CVE-2026-106437\n\n- CVE-2026-106438\n\nFor the latest information about MongoDB security updates, see MongoDB Security Bulletins.\n\nFor more information about this release, see the v1.30.13 release notes.\n\n## What's New in 1.30.12\n\nThe 1.30.12 release of the MongoDB C Driver includes the following changes:\n\nC driver v1.30.12 includes a fix for CVE-2026-96746.\n\nFor the latest information about MongoDB security updates, see MongoDB Security Bulletins.\n\nFor more information about this release, see the v1.30.12 release notes.\n\n## What's New in 1.30.10\n\nThe 1.30.10 release of the MongoDB C Driver includes the following changes:\n\nC driver v1.30.10 includes fixes for the following security issues:\n\n- CVE-2026-82076\n\n- CVE-2026-88035\n\nFor the latest information about MongoDB security updates, see MongoDB Security Bulletins.\n\n## What's New in 1.30.9\n\nThe 1.30.9 release of the MongoDB C Driver includes the following changes:\n\nMongoDB C Driver v1.30.9 includes fixes for the following security issues:\n\n- CVE-2026-84963\n\n- CVE-2026-84964\n\n- CVE-2026-84965\n\n- CVE-2026-84969\n\nFor the latest information about MongoDB security updates, see MongoDB Security Bulletins.\n\n## What's New in 1.30.8\n\nThe 1.30.8 release of the MongoDB C Driver includes the following changes:\n\nMongoDB C Driver v1.30.8 includes a fix for CVE-2026-4359.\n\nFor the latest information about MongoDB security updates, see MongoDB Security Bulletins.\n\n## What's New in 1.30.3\n\nThe following sections describe the changes in the 1.30.3 release of the C driver.\n\n### libbson\n\nThe 1.30.3 release of `libbson` includes the following changes:\n\n#### New Features\n\n- In anticipation of the v2.0 release, adds new CMake packages and imported targets for `bson` to allow you to support both major versions without modifying your CMake project.\n\n - To import `bson` with the new names, call `find_package` for the `bson` package. The new imported target names are `bson::static`, `bson::shared`, and `bson::bson`.\n\n### libmongoc\n\nThe 1.30.3 release of `libmongoc` includes the following changes:\n\n#### New Features\n\n- In anticipation of the v2.0 release, adds new CMake packages and imported targets for `bson` and `mongoc` to allow you to support both major versions without modifying your CMake project.\n\n - To import `mongoc` with the new names, call `find_package` for the `mongoc` package. The new imported target names are `mongoc::static`, `mongoc::shared`, and `mongoc::mongoc`.\n\n - To import `bson` with the new names, call `find_package` for the `bson` package. The new imported target names are `bson::static`, `bson::shared`, and `bson::bson`.\n\nFor more information about this release, see the v1.30.3 release notes.\n\n## What's New in 1.30.0\n\nThe following sections describe the changes in the 1.30.0 release of the C driver.\n\n### libbson\n\nThe 1.30.0 release of `libbson` includes the following changes:\n\n#### Deprecations\n\n- Deprecates support for Debian 9 and Debian 10\n\n#### Improvements\n\n- Improves the performance of BSON to JSON serialization for nested documents\n\n#### Fixes\n\n- Updates the truncated output of the `bson_as_json_with_opts()` function to no longer split valid UTF-8 sequences\n\n- Updates generated JSON text in the following ways:\n\n - Serializes all empty arrays and documents with one space\n\n - Serializes arrays that the driver omits because of the maximum recursion limit to `[ ... ]` instead of `{ ... }`\n\n - Applies the maximum recursion limit to legacy CodeWScope documents\n\n- Fixes an output parameter leaked after unsuccessful calls to the `bson_append_array_builder_begin()` function"} -{"chunk_id": "69327965e88006792c765d29-3", "page_id": "69327965e88006792c765d29", "source_name": "c", "product_name": "C Driver", "url": "https://mongodb.com/docs/languages/c/c-driver/current/reference/release-notes", "title": "Release Notes", "text": "### libmongoc\n\nThe 1.30.0 release of `libmongoc` includes the following changes:\n\n#### Deprecations\n\n- Deprecates support for Debian 9 and Debian 10\n\n#### New Features\n\n- Adds support for structured logging. To configure this feature, use the `mongoc_client_set_structured_log_opts()` and `mongoc_client_pool_set_structured_log_opts()` functions.\n\n- Adds support for cache lifetime configuration of In-Use Encryption data encryption keys. To configure this feature, use the `mongoc_auto_encryption_opts_set_key_expiration()` and `mongoc_client_encryption_opts_set_key_expiration()` functions.\n\n To learn more about In-Use Encryption, see In-Use Encryption in the MongoDB Server manual.\n\n- Adds support for the `sort` option for update and replace operations.\n\n- Adds support for constructing a `mongoc_bulkwrite_t` type without a client by using the `mongoc_bulkwrite_new()` and `mongoc_bulkwrite_set_client()` functions.\n\n#### Improvements\n\n- Improves the performance of the `mongoc_server_description_new_copy()` function\n\n#### Fixes\n\n- Includes the following APM event fixes required by the SDAM specification:\n\n - After delivering a `server_opening` event, the driver must deliver a corresponding `server_closed` event before delivering `topology_closed`\n\n - Before delivering a `topology_closed` event, the driver delivers a `topology_changed` event that has a `new_description` of type `Unknown`\n\n- Fixes possible crashes when the driver reports the inserted document IDs in the verbose results of client bulk writes\n\nFor more information about this release, see the v1.30 release notes.\n\n## What's New in 1.29.0\n\nC driver v1.29.0 contains breaking changes. For more information, see Version 1.29.0 in the Upgrade Driver Versions guide.\n\nThe 1.29.0 release of the C driver includes several changes.\n\n### libbson\n\nThe 1.29.0 release of `libbson` includes the following changes:\n\n#### Deprecations\n\n- Deprecates the `bson_string_t` and associated functions\n\n- Deprecates compiling with `BSON_MEMCHECK`\n\n- Deprecates `bson_in_range_*()` and `bson_cmp_*()` functions\n\n- Deprecates `bson_atomic_*()` and `bson_thrd-yield()` functions\n\n- Deprecates `bson_as_json()` and `bson_array_as_json()` functions\n\n### libmongoc\n\nThe 1.29.0 release of `libmongoc` includes the following changes:\n\n#### Deprecations\n\n- Deprecates `mongoc_client_command`. Use `mongoc_client_command_simple` instead.\n\n- Deprecates `mongoc_database_command`. Use `mongoc_database_command_simple` instead.\n\n- Deprecates `mongoc_collection_command`. Use `mongoc_collection_command_simple` instead.\n\nFor more information about this release, see the v1.29 release notes.\n\n## What's New in 1.28.0\n\nC driver v1.28.0 contains breaking changes. For more information, see Version 1.28.0 in the Upgrade Driver Versions guide.\n\nThe 1.28.0 release of the C driver includes several changes.\n\n### libbson\n\nThe 1.28.0 release of `libbson` includes the following changes:\n\n#### New Features\n\n- Adds `bson_validate_with_error_and_offset()` function\n\n### libmongoc\n\n#### New Features\n\n- Adds support for In-Use Encryption range queries\n\n- `mongoc_collection_insert_one` includes the insert ID\n\n- Adds new bulk write API `mongoc_bulkwrite_t`\n\n- Adds `serverMonitoringMode` URI option\n\n#### Deprecations\n\n- Deprecates `*_hint` option. Instead, use the `*_server_id` option.\n\n - Deprecates `mongoc_bulk_operation_set_hint`. Instead, use `mongoc_bulk_operation_set_server_id`.\n\n - Deprecates `mongoc_bulk_operation_get_hint`. Instead, use `mongoc_bulk_operation_get_server_id`.\n\n - Deprecates `mongoc_cursor_set_hint`. Instead, use `mongoc_cursor_set_server_id`.\n\n - Deprecates `mongoc_cursor_get_hint`. Instead, use `mongoc_cursor_get_server_id` .\n\n- Deprecates `ENABLE_SSL=LIBRESSL` and `mongoc_stream_tls_libressl_new`.\n\n- Deprecates `ENABLE_SASL=CYRUS` and the `CYRUS_PLUGIN_PATH_PREFIX` option on Windows platforms.\n\nFor more information about this release, see the v1.28 release notes.\n\n## What's New in 1.27.6\n\nThe 1.27.6 release of the C driver includes several changes.\n\n### libbson\n\nThe 1.27.6 release of `libbson` includes the following changes:\n\n#### Fixes\n\n- Fixes handling of malformed extended JSON for special BSON types\n\n### libmongoc\n\nThe 1.27.6 release of `libmongoc` includes the following changes:\n\n#### Fixes\n\n- Fixes TSan warning\n\n- Fixes C23 compile\n\n#### Improvements\n\n- Documents expected behavior of command errors in a transaction\n\n## What's New in 1.27.5\n\nThe 1.27.5 release of the C driver includes several changes.\n\n### libbson\n\nThe 1.27.5 release of `libbson` includes the following changes:\n\n#### Fixes\n\n- Fixes large string handling in `bson_append_utf8`\n\n### libmongoc\n\nThe 1.27.5 release of `libmongoc` includes the following changes:\n\n#### Fixes\n\n- Fixes possible build error in environments where `bool` or `_Bool` is a macro\n\n## What's New in 1.27.4\n\nThe 1.27.4 release of the C driver includes several changes.\n\n### libbson\n\nThe 1.27.4 release of `libbson` includes the following changes:\n\n#### Fixes\n\n- Fixes build issues with Visual Studio 2013\n\n### libmongoc\n\nThe 1.27.4 release of `libmongoc` includes the following changes:\n\n#### Fixes\n\n- Fixes possible crash reading malformed wired protocol message\n\n- Fixes build issues with Visual Studio 2013\n\n## What's New in 1.27.3\n\nThe 1.27.3 release of the C driver includes several changes.\n\n### libbson\n\nThe 1.27.3 release of `libbson` includes the following changes:\n\n#### Changes\n\n- Introduces changes surrounding the development processes, including new code signing and dependency tracking. There are no behavioral or API changes.\n\n### libmongoc\n\nThe 1.27.3 release of `libmongoc` includes the following changes:\n\n#### Fixes\n\n- Upgrades bundled Zlib from 1.2.3 to 1.3.1\n\n## What's New in 1.27.2\n\nThe 1.27.2 release of the C driver includes several changes.\n\n### libbson\n\nThe 1.27.2 release of `libbson` includes the following changes:\n\n#### Fixes\n\n- Fixes parsing of colon in timezone\n\n- Fixes error on failure to initialize a subdocument in `bson_iter_visit_all`\n\n### libmongoc\n\nThe 1.27.2 release of `libmongoc` includes the following changes:\n\n#### Fixes\n\n- Closes leftover connections to remote servers\n\n#### New Features\n\n- Checks environment variable `MONGO_EXPERIMENTAL_SRV_PREFER_TCP` to prefer TCP over SRV lookup\n\n## What's New in 1.27.1\n\nThe 1.27.1 release of the C driver includes several changes.\n\n### libbson\n\nThe 1.27.1 release of `libbson` includes the following changes:\n\n#### Fixes\n\n- Fixes large string handling in `bson_string_new` and `bson_string_append`\n\n### libmongoc\n\nThis version is incremented to match the `libbson` version, but there are no changes since 1.27.0.\n\n## What's New in 1.27.0\n\nC driver v1.27.0 contains breaking changes. For more information, see Version 1.27.0 in the Upgrade Driver Versions guide.\n\nThe 1.27.0 release of the C driver includes several changes.\n\n### libbson\n\nThis version is incremented to match the `libbson` version, but there are no changes since 1.26.2.\n\n### libmongoc\n\nThe 1.27.0 release of `libmongoc` includes the following changes:\n\n#### Fixes\n\n- Fixes possible crash when client is configured with an empty password\n\n#### New Features\n\n- Adds database name to command events `mongoc_apm_command_failed_get_database_name` and `mongoc_apm_command_succeeded_get_database_name`\n\n- Supports delegated KMIP protocol for In-Use Encryption\n\n- Enables setting socket timeout per client\n\n## What's New in 1.26.2\n\nC driver v1.26.2 contains breaking changes. For more information, see Version 1.26.2 in the Upgrade Driver Versions guide.\n\nThe 1.26.2 release of the C driver includes several changes.\n\n### libbson\n\nThe 1.26.2 release of `libbson` includes the following changes:\n\n#### Fixes\n\n- Fixes iteration on `bson_strfreev`"} -{"chunk_id": "69327965e88006792c765d29-4", "page_id": "69327965e88006792c765d29", "source_name": "c", "product_name": "C Driver", "url": "https://mongodb.com/docs/languages/c/c-driver/current/reference/release-notes", "title": "Release Notes", "text": "### libmongoc\n\nThe 1.26.2 release of `libmongoc` includes the following changes:\n\n#### Fixes\n\n- Fixes possible hang if `mongoc_gridfs_file_readv` is called with a corrupt chunk with incomplete data\n\n- Fixes assert with legacy exhaust cursor protocol when connected to MongoDB server versions earlier than 4.2\n\n## What's New in 1.26.1\n\nThe 1.26.1 release of the C driver includes several changes.\n\n### libbson\n\nThe 1.26.1 release of `libbson` includes the following changes:\n\n#### Fixes\n\n- Uses aligned allocation for `bson_array_builder_t`\n\n### libmongoc\n\nThe 1.26.1 release of `libmongoc` includes the following changes:\n\n#### Fixes\n\n- Fixes 32-bit compile with 64-bit `time_t`\n\n## What's New in 1.26.0\n\nThe 1.26.0 release of the C driver includes several changes.\n\n### libbson\n\nThis version is incremented to match the `libmongoc` version, but there are no changes since 1.25.4.\n\n### libmongoc\n\nThe 1.26.0 release of `libmongoc` includes the following changes:\n\n#### New Features\n\n- Supports named KMS providers\n\n- Redirects retries in sharded clusters to another mongos if possible\n\n#### Improvements\n\n- Adds `VERSION_CURRENT` file in source to ease building\n\n- Considers more errors retryable"} -{"chunk_id": "69327965e88006792c765d20-0", "page_id": "69327965e88006792c765d20", "source_name": "c", "product_name": "C Driver", "url": "https://mongodb.com/docs/languages/c/c-driver/current/logging-monitoring/change-streams", "title": "Monitor Data Changes", "text": "# Monitor Data Changes\n\n## Overview\n\nIn this guide, you can learn how to use the C driver to monitor a **change stream**, allowing you to view real-time changes to your data. A change stream is a MongoDB Server feature that publishes data changes on a collection, database, or deployment. Your application can subscribe to a change stream and use events to perform other actions.\n\n### Sample Data\n\nThe examples in this guide use the `restaurants` collection in the `sample_restaurants` database from the Atlas sample datasets. To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the MongoDB Get Started guide.\n\n## Open a Change Stream\n\nTo open a change stream, call one of the following functions that corresponds to the scope of events you want to observe:\n\n- `mongoc_client_watch()`: Monitors all changes in the MongoDB deployment\n\n- `mongoc_database_watch()`: Monitors changes in all collections in the database\n\n- `mongoc_collection_watch()`: Monitors changes in the collection\n\n### Open a Change Stream Example\n\nThe following example opens a change stream on the `restaurants` collection and prints changes as they occur:\n\n```c\nbson_t *pipeline = bson_new();\nconst bson_t *doc;\n\nmongoc_change_stream_t *change_stream =\n mongoc_collection_watch(collection, pipeline, NULL);\n\nwhile (true) {\n bson_error_t error;\n if (mongoc_change_stream_next(change_stream, &doc)) {\n char *str = bson_as_canonical_extended_json(doc, NULL);\n printf(\"Received change: %s\\n\", str);\n bson_free(str);\n } else if (mongoc_change_stream_error_document(change_stream, &error, NULL)) {\n printf(\"Got error on change stream: %s\\n\", error.message);\n break;\n }\n}\n\nbson_destroy(pipeline);\nmongoc_change_stream_destroy(change_stream);\n```\n\nTo begin watching for changes, run the application. Then, in a separate application or shell, perform a write operation on the `restaurants` collection. The following example updates a document in which the value of the `name` field is `\"Blarney Castle\"`:\n\n```c\nbson_t *filter = BCON_NEW(\"name\", BCON_UTF8(\"Blarney Castle\"));\nbson_t *update = BCON_NEW(\"$set\", \"{\", \"cuisine\", BCON_UTF8(\"Irish\"), \"}\");\n\nmongoc_collection_update_one(collection, filter, update, NULL, NULL, NULL);\n```\n\nWhen you update the collection, the change stream application prints the change as it occurs. The printed change event resembles the following:\n\n```json\n{\n \"_id\": { ... },\n \"operationType\": \"update\",\n \"clusterTime\": { ... },\n \"ns\": {\n \"db\": \"sample_restaurants\",\n \"coll\": \"restaurants\"\n },\n \"updateDescription\": {\n \"updatedFields\": {\n \"cuisine\": \"Irish\"\n },\n \"removedFields\": [],\n \"truncatedArrays\": []\n }\n ...\n}\n```\n\n## Modify the Change Stream Output\n\nYou can pass the `pipeline` parameter to any watch function to modify the change stream output. This parameter allows you to watch for only specified change events. Format the parameter as a list of objects, where each object represents an aggregation stage.\n\nYou can specify the following stages in the `pipeline` parameter:\n\n- `$addFields`\n\n- `$match`\n\n- `$project`\n\n- `$replaceRoot`\n\n- `$replaceWith`\n\n- `$redact`\n\n- `$set`\n\n- `$unset`\n\n### Match Specific Events Example\n\nThe following example uses the `pipeline` parameter to include a `$match` stage to open a change stream that records only update operations:\n\n```c\nbson_t *pipeline = BCON_NEW(\n \"pipeline\", \"[\",\n \"{\", \"$match\", \"{\", \"operationType\", BCON_UTF8(\"update\"), \"}\", \"}\",\n \"]\");\nconst bson_t *doc;\n\nmongoc_change_stream_t *change_stream =\n mongoc_collection_watch(collection, pipeline, NULL);\n\nwhile (mongoc_change_stream_next(change_stream, &doc)) {\n char *str = bson_as_canonical_extended_json(doc, NULL);\n printf(\"Received change: %s\\n\", str);\n bson_free(str);\n}\n\nbson_destroy(pipeline);\nmongoc_change_stream_destroy(change_stream);\n```\n\nTo learn more about modifying your change stream output, see the Modify Change Stream Output section in the MongoDB Server manual.\n\n## Modify Watch Behavior\n\nYou can modify any watch function by passing options to the function call. If you don't specify any options, the driver does not customize the operation.\n\nThe following table describes options you can use to customize the behavior of the watch functions:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nOption\n\n\nDescription\n\n
\n`batchSize`\n\n\nThe maximum number of documents that a change stream can return in each batch, which applies to the watch function. By default, watch functions have an initial batch size of `101` documents and a maximum size of 16 mebibytes (MiB) for each subsequent batch. This option can enforce a smaller limit than 16 MiB, but not a larger one. For details, see Cursor Batches in the MongoDB Server manual.\n\n
\n`comment`\n\n\nSpecifies a comment to attach to the operation.\n\n
\n`fullDocument`\n\n\nSets the `fullDocument` value. To learn more, see the Include Pre-Images and Post-Images section of this document.\n\n
\n`fullDocumentBeforeChange`\n\n\nSets the `fullDocumentBeforeChange` value. To learn more, see the Include Pre-Images and Post-Images section of this document.\n\n
\n`maxAwaitTimeMS`\n\n\nSets the maximum await execution time on the server for this operation, in milliseconds.\n\n
For a complete list of options you can use to configure the watch operation, see the watch method guide in the MongoDB Server manual."} -{"chunk_id": "69327965e88006792c765d20-1", "page_id": "69327965e88006792c765d20", "source_name": "c", "product_name": "C Driver", "url": "https://mongodb.com/docs/languages/c/c-driver/current/logging-monitoring/change-streams", "title": "Monitor Data Changes", "text": "### Include Pre-Images and Post-Images\n\nYou can enable pre-images and post-images on collections only if your deployment uses MongoDB v6.0 or later.\n\nBy default, when you perform an operation on a collection, the corresponding change event includes only the delta of the fields modified by that operation. To see the full document before or after a change, specify the `fullDocumentBeforeChange` or the `fullDocument` options in your watch function call.\n\nThe **pre-image** is the full version of a document *before* a change. To include the pre-image in the change stream event, pass one of the following values to the `fullDocumentBeforeChange` option:\n\n- `whenAvailable`: The change event includes a pre-image of the modified document for change events only if the pre-image is available.\n\n- `required`: The change event includes a pre-image of the modified document for change events. If the pre-image is not available, the driver raises an error.\n\nThe **post-image** is the full version of a document *after* a change. To include the post-image in the change stream event, pass one of the following values to the `fullDocument` option:\n\n- `updateLookup`: The change event includes a copy of the entire changed document from some time after the change.\n\n- `whenAvailable`: The change event includes a post-image of the modified document for change events only if the post-image is available.\n\n- `required`: The change event includes a post-image of the modified document for change events. If the post-image is not available, the driver raises an error.\n\nThe following example calls the `mongoc_collection_watch()` function on a collection and includes the post-image of updated documents in the results by specifying the `fullDocument` option:\n\n```c\nbson_t *pipeline = bson_new();\nbson_t *opts = BCON_NEW(\"fullDocument\", BCON_UTF8(\"updateLookup\"));\nconst bson_t *doc;\n\nmongoc_change_stream_t *change_stream =\n mongoc_collection_watch(collection, pipeline, opts);\n\nwhile (true) {\n bson_error_t error;\n if (mongoc_change_stream_next(change_stream, &doc)) {\n char *str = bson_as_canonical_extended_json(doc, NULL);\n printf(\"Received change: %s\\n\", str);\n bson_free(str);\n } else if (mongoc_change_stream_error_document(change_stream, &error, NULL)) {\n printf(\"Got error on change stream: %s\\n\", error.message);\n break;\n }\n}\n\nbson_destroy(pipeline);\nbson_destroy(opts);\nmongoc_change_stream_destroy(change_stream);\n```\n\nWith the change stream application running, updating a document in the `restaurants` collection by using the preceding update example prints a change event resembling the following:\n\n```json\n{\n \"_id\": ...,\n \"operationType\": \"update\",\n \"clusterTime\": ...,\n \"wallTime\": ...,\n \"fullDocument\": {\n \"_id\": {\n ...\n },\n \"address\": ...,\n \"borough\": \"Queens\",\n \"cuisine\": \"Irish\",\n \"grades\": [ ... ],\n \"name\": \"Blarney Castle\",\n \"restaurant_id\": ...\n },\n \"ns\": {\n \"db\": \"sample_restaurants\",\n \"coll\": \"restaurants\"\n },\n \"documentKey\": {\n \"_id\": ...\n },\n \"updateDescription\": {\n \"updatedFields\": {\n \"cuisine\": \"Irish\"\n },\n \"removedFields\": [],\n \"truncatedArrays\": []\n }\n}\n```\n\nTo learn more about pre-images and post-images, see Change Streams with Document Pre- and Post-Images in the MongoDB Server manual.\n\n## Additional Information\n\nTo learn more about change streams, see Change Streams in the MongoDB Server manual.\n\n### API Documentation\n\nTo learn more about any of the functions or types discussed in this guide, see the following API documentation:\n\n- mongoc_client_watch()\n\n- mongoc_database_watch()\n\n- mongoc_collection_watch()\n\n- mongoc_change_stream_t"} -{"chunk_id": "68a95be05e79d242619d7eb5-0", "page_id": "68a95be05e79d242619d7eb5", "source_name": "charts", "product_name": "Atlas Charts", "url": "https://mongodb.com/docs/charts/chart-type-reference/top-item", "title": "Top Item Chart", "text": "# Top Item Chart\n\nTop Item charts show information from the document with the greatest or smallest value for a specified field.\n\nWhen you create a Top Item chart, you specify:\n\n- The field by which to sort your collection.\n\n- Whether you want to sort in ascending or descending order.\n\n- The fields you want to display from the first document returned by your specified sort.\n\n## Top Item Chart Encoding Channels\n\nTop Item charts utilize the following encoding channels:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nEncoding Channel\n\n\nDescription\n\n
\nSort\n\n\nThe field by which to sort the collection. You can specify an ascending or descending sort.\n\n
\nDisplay\n\n\nThe fields to display from the top item in the collection after sorting.\n\n
You cannot perform aggregations on Display fields.\n\n## Use Cases\n\nUse Top Item charts to show information about the most extreme or most recent instance of a particular field value. For example, you can use Top Item charts to show information on:\n\n- The most recent reading from a collection of sensor data, such as temperature readings.\n\n- The highest rated movie in a collection.\n\n- The cheapest available room in a collection of available hotel listings.\n\n- The largest sale recorded in the past month (when combining a Top Item chart with date filters).\n\n## Examples\n\nThe following chart uses a data source containing Sample AirBnB Listing data and shows information on the document with the highest `monthly_price` in the collection:\n\nThe chart sorts the documents based on `monthly_price` in descending order, and returns the first document appearing in the sort.\n\nThe chart displays the following fields:\n\n- `monthly_price`\n\n- `property_type`\n\n- `country`\n\n- `suburb`"} -{"chunk_id": "68a95be05e79d242619d7f6a-0", "page_id": "68a95be05e79d242619d7f6a", "source_name": "charts", "product_name": "Atlas Charts", "url": "https://mongodb.com/docs/charts/tutorial/movie-details/movie-details-tutorial-overview", "title": "Visualizing Movie Details", "text": "# Visualizing Movie Details\n\n`test.movieDetails`*Total Estimated Time to Complete: 15-20 minutes*\n\n## Introduction\n\nThis tutorial explores features and capabilities of Atlas Charts with a data source containing the `Mflix`\nsample data provided by Atlas. This sample data contains information on movies such as release year, cast, and reviews.\n\nThe following is a sample document from the dataset:\n\n```json\n{\n \"_id\": {\n \"$oid\": \"573a1391f29313caabcd9637\"\n },\n \"plot\": \"The ancient vampire Count Dracula arrives in\n England and begins to prey upon the virtuous young Mina.\",\n \"genres\": [\n \"Horror\"\n ],\n \"runtime\": {\n \"$numberInt\": \"85\"\n },\n \"rated\": \"APPROVED\",\n \"cast\": [\n \"Bela Lugosi\",\n \"Helen Chandler\",\n \"David Manners\",\n \"Dwight Frye\"\n ],\n \"num_mflix_comments\": {\n \"$numberInt\": \"1\"\n },\n \"poster\": \"https://m.media-amazon.com/images/M/MV5BZDY2ODZhZWQtNDk0ZS00OGE4LWE4NjAtZjE5MTJhMjExMTRjXkEyXkFqcGdeQXVyNjc1NTYyMjg@._V1_SY1000_SX677_AL_.jpg\",\n \"title\": \"Dracula\",\n \"fullplot\": \"After a harrowing ride through the Carpathian mountains in eastern Europe,\n Renfield enters castle Dracula to finalize the transferral of Carfax Abbey in London to\n Count Dracula, who is in actuality a vampire. Renfield is drugged by the eerily hypnotic\n count, and turned into one of his thralls, protecting him during his sea voyage to London.\n After sucking the blood and turning the young Lucy Weston into a vampire, Dracula turns his\n attention to her friend Mina Seward, daughter of Dr. Seward who then calls in a specialist,\n Dr. Van Helsing, to diagnose the sudden deterioration of Mina's health. Van Helsing,\n realizing that Dracula is indeed a vampire, tries to prepare Mina's fiance, John Harker,\n and Dr. Seward for what is to come and the measures that will have to be taken to prevent\n Mina from becoming one of the undead.\",\n \"languages\": [\n \"English\",\n \"Hungarian\",\n \"Latin\"\n ],\n \"released\": {\n \"$date\": {\n \"$numberLong\": \"-1226966400000\"\n }\n },\n \"directors\": [\n \"Tod Browning\"\n ],\n \"writers\": [\n \"Bram Stoker (by)\",\n \"Hamilton Deane (from the play adapted by)\",\n \"John L. Balderston (from the play adapted by)\",\n \"Garrett Fort (play)\"\n ],\n \"awards\": {\n \"wins\": {\n \"$numberInt\": \"2\"\n },\n \"nominations\": {\n \"$numberInt\": \"1\"\n },\n \"text\": {\n \"2 wins & 1 nomination.\"\n }\n },\n \"lastupdated\": \"2015-08-28 00:30:04.660000000\",\n \"year\": {\n \"$numberInt\": \"1931\"\n },\n \"imdb\": {\n \"rating\": {\n \"$numberDouble\": \"7.6\"\n },\n \"votes\": {\n \"$numberInt\": \"30184\"\n },\n \"id\": {\n \"$numberInt\": \"21814\"\n }\n },\n \"countries\": [\n \"USA\"\n ],\n \"type\": \"movie\",\n \"tomatoes\": {\n \"viewer\": {\n \"rating\": {\n \"$numberDouble\": \"3.7\"\n },\n \"numReviews\": {\n \"$numberInt\": \"44035\"\n },\n \"meter\": {\n \"$numberInt\": \"82\"\n }\n },\n \"dvd\": {\n \"$date\": {\n \"$numberLong\": \"998956800000\"\n }\n },\n \"critic\": {\n \"rating\": {\n \"$numberDouble\": \"7.9\"\n },\n \"numReviews\": {\n \"$numberInt\": \"45\"\n },\n \"meter\": {\n \"$numberInt\": \"91\"\n }\n },\n \"lastUpdated\": {\n \"$date\": {\n \"$numberLong\": \"1442516384000\"\n }\n },\n \"consensus\": \"Bela Lugosi's timeless portrayal of Dracula in this creepy and\n atmospheric 1931 film has set the standard for major vampiric roles since.\",\n \"rotten\": {\n \"$numberInt\": \"4\"\n },\n \"production\": \"Universal Pictures\",\n \"fresh\": {\n \"$numberInt\": \"41\"\n }\n }\n}\n```\n\nWith this tutorial, you will learn how to use filters to refine a large result set down to an easily understandable chart, and use multi-series charts to gain further insight into the data.\n\nIn this tutorial, you'll create two charts: a sorted column chart and a scatter chart.\n\n- The sorted column chart displays columns representing the number of awards won by directors with at least 50 total awards, sorted from highest to lowest and broken down by film genre.\n\n- The scatter chart shows a diagram of movies with at least one award win along with their TomatoMeter rating and their MPAA (Motion Picture Association of America) rating (G, PG, PG-13, or R).\n\n## Table of Contents\n\n- Step 1: Load Movie Details Sample Data\n\n- Step 2: Create a New Movie Insights Dashboard\n\n- Step 3: Column Chart Showing Directors with the Most Awards\n\n- Step 4: Scatter Chart of Award-Nominated Movies with Their TomatoMeter Rating\n\n- Step 5: Arrange the Charts on the Dashboard\n\nTo get started, move ahead to the Load Movie Details Sample Data page."} -{"chunk_id": "68a95be05e79d242619d7ec3-0", "page_id": "68a95be05e79d242619d7ec3", "source_name": "charts", "product_name": "Atlas Charts", "url": "https://mongodb.com/docs/charts/ai-and-data-usage-information", "title": "AI and Data Usage Information", "text": "# AI and Data Usage Information\n\nNatural Language Charts is powered by Generative AI (Gen AI) and might give inaccurate responses. For more information about Gen AI in MongoDB products, see Generative AI FAQ.\n\n## Third Party Providers\n\nNatural Language Charts currently uses the Azure OpenAI Service hosted by Microsoft. This is subject to change in the future.\n\n## How Your Data is Used\n\nWhen you use Natural Language Charts, Atlas Charts sends the following information to MongoDB's backend and/or the third-party AI provider:\n\n- The full text of your natural language prompt.\n\n- The schema of the collection used to generate the chart, including collection names, field names, and field data types.\n\n- Sample field values to improve the quality of chart recommendations.\n\nThe information sent will not be shared with any other third parties or stored by the AI provider. We do not share database connection strings or database credentials. By default, your original query text will be stored by MongoDB for up to one year to help us provide support to customers and improve the service.\n\n## Disable Natural Language Charts\n\n- Charts enables Natural Language Charts once you click the Use Natural Language Mode button. For details on enabling this feature, see Disable AI Features.\n\n- If you no longer want to use Natural Language Charts, you can ignore this button and Charts will not send data to the Generative AI models. If you are a `Project Owner`, you can disable access to Natural Language Charts by navigating to the AI features page in the left navigation menu and setting the toggle to off."} -{"chunk_id": "68a95be05e79d242619d7f50-0", "page_id": "68a95be05e79d242619d7f50", "source_name": "charts", "product_name": "Atlas Charts", "url": "https://mongodb.com/docs/charts/release-notes", "title": "Atlas Charts Release Notes", "text": "# Atlas Charts Release Notes\n\n## Atlas Charts v1.49.0\n\n*Released May 21st, 2024*\n\nImprovements in this release:\n\n- Launches Charts Freemium, where all Atlas users on paid or flex clusters access all of Charts for free. Users who are on M0 clusters will access a limited version of Charts.\n\n## Atlas Charts v1.48.0\n\n*Released April 16th, 2024*\n\nBug fixes in this release:\n\n- Fixes adjustable dynamic table columns.\n\n- Fixes missing charts when navigating between dashboards.\n\n## Atlas Charts v1.47.0\n\n*Released October 27th, 2024*\n\nImprovements in this release:\n\n- A `Project Owner` can prevent users in their project from using AI features.\n\nBug fixes in this release:\n\n- Fixes an issue where users couldn't open a dashboard in a new tab.\n\n- Fixes an issue where invoices older than three months had missing line items.\n\n- Fixes an issue where Natural Language Charts charts sorted by ascending order did not render.\n\n## Atlas Charts v1.46.0\n\n*Released September 9th, 2024*\n\n## Atlas Charts v1.45.3\n\n*Released July 30th, 2024*\n\nImprovements in this release:\n\n- Natural Language Charts is generally available.\n\n## Atlas Charts v1.45.0\n\n*Released July 4th, 2024*\n\nImprovements in this release:\n\n- Developers using the embedded SDK can now use the preFilter() method to elevate the execution of filters in Charts and dashboard embedding.\n\n- Users can use invoices from linked Atlas organizations while setting up the Atlas billing dashboard in Charts.\n\nBug fixes in this release:\n\n- Fixes an issue where you couldn't import a dashboard because the Table Chart in the dashboard has a hyperlink.\n\n- Fixes an issue where a dashboard filter didn't work.\n\n- Fixes an issue where a billing dashboard ingestion didn't work due to the size of the payload.\n\n## Atlas Charts v1.44.0\n\n*Released April 30th, 2024*\n\nImprovements in this release:\n\n- Chart Authors can now create Hyperlinks in table charts.\n\n- Adds the ability to secure access to a public dashboard with a passcode.\n\n- Atlas billing dashboards now support linked organizations in Atlas, cluster tags, and manually entering an organization's details for ingestion.\n\n- A `Project Owner` can now disconnect a database and its corresponding collections from Atlas Charts.\n\nBug fixes in this release:\n\n- Fixes an issue where you couldn't import a dashboard because one of the charts was a Top Line Item chart.\n\n- Fixes an issue where you could bin, sort, and limit options for unwound arrays in Natural Language Charts.\n\n- Fixes an issue where a redundant filter appeared when users toggled between Natural Language mode and Classic mode.\n\n## Atlas Charts v1.43.0\n\n*Released March 11th, 2024*\n\nImprovements in this release:\n\n- Natural Language Charts is in public preview.\n\nBug fixes in this release:\n\n- Fixes an issue where users could get a Charts failed to initialize error.\n\n## Atlas Charts v1.42.0\n\n*Released January 29th, 2024*\n\nImprovements in this release:\n\n- Project Owners can add and remove dashboard owners from dashboards on the Owners page.\n\nBug fixes in this release:\n\n- Fixes an issue where users could incorrectly open the chart builder using a URL.\n\n- Conditional formatting now works correctly for dashboards you duplicate and export.\n\n## Atlas Charts v1.41.0\n\n*Released December 10th, 2023*\n\nImprovements in this release:\n\n- Adds support for the `$median` aggregation pipeline stage.\n\n- You can expand the field panel in the chart builder to show fields with long names.\n\nBug fixes in this release:\n\n- Fixes an issue where Charts could not create reports in some browsers.\n\n## Atlas Charts v1.40.0\n\n*Released October 24th, 2023*\n\nImprovements in this release:\n\n- Supports Natural Language Charts during private preview period.\n\nBug fixes in this release:\n\n- Label override now work correctly for multi-series charts using charts embedding.\n\n- Fixes an issue where the filter icon was disabled on a chart when viewing a dashboard.\n\n- Fixes incorrect documentation links in the embedding and share dashboard pages.\n\n- Conditional formatting now works correctly for decimal fields and strings in table charts.\n\n- Fixes an issue where you could not login to Charts from a different project.\n\n- Embed Chart render function no longer returns an error when chart data takes longer than 30 seconds to load.\n\n## Atlas Charts v1.39.0\n\n*Released August 22th, 2023*\n\nImprovements in this release:\n\n- Charts now supports a new chart type: Candlestick Charts.\n\n- Dashboard viewers can save a dashboard as a PNG (Portable Network Graphic).\n\n- Charts now supports visualizing your Atlas billing data directly inside the Atlas Charts application.\n\n- You can programmatically customize your embedded charts using the new rendering specifications.\n\n- The Charts timeout limit increased to 10 minutes for experimentation.\n\n Please contact MongoDB Support to set up the timeout limit increase.\n\nBug fixes in this release:\n\n- Dashboard filters now work correctly when displaying heterogeneous fields.\n\n## Atlas Charts v1.38.1\n\n*Released May 26th, 2023*\n\nImprovements in this release:\n\n- Dashboard viewers can save a dashboard as a PNG (Portable Network Graphic).\n\nBug fixes in this release:\n\n- Email reports now display properly.\n\n- Dashboard refreshes now work correctly when you select the infinity option.\n\n- Charts that use `ISODate()` queries in the query bar now render properly.\n\n- Fixes an issue when using `ObjectId()` with injected filters in an embedded chart.\n\n## Atlas Charts v1.37\n\n*Released April 6th, 2023*\n\nImprovements in this release:\n\n- Dashboard owners can now schedule reports, sending one-time or recurring PDF (Portable Document Format) or PNG (Portable Network Graphic) dashboard reports by email.\n\n- Chart authors can now see and apply charts suggestions in Chart Builder.\n\n- Charts authors now see a help button with links to documentation.\n\n- Charts can now be activated in two ways:\n\n - Click the Charts tab in the Atlas UI, or\n\n - Click Visualize your Data in the Data Explorer. Visualize your Data now opens the Chart Builder with the collection you chose to visualize configured as a data source.\n\n- Users with the Atlas permission `Project Data Access Read Only` and above may now activate Charts.\n\n- Developers using the embedded SDK can now:\n\n - Download an embedded dashboard as a binary or base64 image.\n\n - Use the `getData()` method to get data from charts in an embedded dashboard.\n\n - Initialize the filters on an embedded dashboard when rendering the dashboard for the first time.\n\n## Atlas Charts v1.36.1\n\n*Released February 22nd, 2023*\n\nImprovements in this release:\n\n- Users can now load various sample dashboards in Atlas Charts, including Product, Sales, Observability, and IoT data dashboards.\n\n- Developers can use the SDK to filter data in embedded dashboards with embedded dashboard filters and user injected filters.\n\n- Developers can now use the SDK to download an embedded chart as a binary or base64 image.\n\n- Charts and Dashboard authors can now enable the embedding setting Allow all fields in the data sources used in this dashboard to quickly allow all the fields in a data source to be used as filters for embedded charts and dashboards.\n\n- In the side navigation panel, Data Usage is now named Data Transfer.\n\n- Improved the process for saving an imported dashboard.\n\nBug fixes in this release:\n\n- `getFilter` and `getHighlight` SDK methods now return values in a consistent format.\n\n- Fixes an issue with bin sizes displaying incorrectly after using array reduction.\n\n- Fixes an issue where applying dashboard filters would render charts blank.\n\n- Fixes an issue where Charts returned a disk use error when refreshing data sources.\n\n- Fields now render correctly when lookup fields have an empty array.\n\n- Nested fields now display correctly inside the dashboard filter pane.\n\n- Arabic and Slovenian dates now display correctly.\n\n- The background colors of charts in embedded dashboards now render correctly."} -{"chunk_id": "68a95be05e79d242619d7f50-1", "page_id": "68a95be05e79d242619d7f50", "source_name": "charts", "product_name": "Atlas Charts", "url": "https://mongodb.com/docs/charts/release-notes", "title": "Atlas Charts Release Notes", "text": "## Atlas Charts v1.35\n\n*Released December 13th, 2022*\n\nImprovements in this release:\n\n- Project Owners can manage viewing permissions on a deployment from the Data Sources page.\n\nBug fixes in this release:\n\n- Fixes an issue where opening a dashboard would update the time it was last modified.\n\n- Fixes an issue with dashboard filter data source details.\n\n- Fixes an issue with replacing array fields in the chart builder.\n\n- Fixes an issue with sorting by value for colored charts.\n\n- Fixes an issue where latitude and longitude fields were lost when editing geospatial heatmap or scatter charts.\n\n- Fixes an issue for Safari where number fields were not displayed correctly in the Encode tab.\n\n- Fixes an issue with the Wrap Text and Column Total rules on table charts.\n\n- Fixes several issues with the query bar, including an overflowing error on the tooltip.\n\n- Fixes an issue with rendering chart titles.\n\n- Dashboards are now correctly imported when `textSize` fields exist with invalid data sources.\n\n- You can now correctly add an embedding provider from the Chart Embedding Settings dialog.\n\n- Geospatial scatter charts now render correctly when using array coordinates.\n\n- Buttons on the Refresh Settings modal now display correctly on small screens.\n\n- Long chart titles now display properly in the Import Dashboard dialog.\n\n- Multi-level lookups in the chart builder Fields list are now displayed properly.\n\n- Sample document details from a data source now display correctly.\n\n- The Regex binning option is now enabled for MongoDB 4.2 and above.\n\n## Atlas Charts v1.34\n\n*Released November 16th, 2022*\n\nImprovements in this release:\n\n- You can now share dashboards across an Atlas organization.\n\nBug fixes in this release:\n\n- Fixes an issue with adding date filters inside the Chart Builder.\n\n- Fixes an issue where filter selections were not saved correctly when building charts.\n\n- Fixes an issue where non-binned dates with null values were not saved correctly when exported as CSV.\n\n- Fixes an issue where the Charts homepage did not load.\n\n## Atlas Charts v1.33.2\n\n*Released October 3rd, 2022*\n\nImprovements in this release:\n\n- You can now use Atlas\n Online Archives as data sources.\n\n## Atlas Charts v1.33.1\n\n*Released September 12, 2022*\n\nImprovements in this release:\n\n- You can now use serverless instances as data sources.\n\n- Improved data source integration in Atlas Charts:\n\n - Atlas collections are automatically available to use in the chart builder. If you don't want a data source to be available, you can disconnect it.\n\n - Updated the Data Sources page.\n\n - You can now create and test pipelines when building Charts views.\n\n - You can now click your data source collection name in the chart builder to see a sample list of fields in that collection.\n\n- You can now programmatically highlight charts inside an embedded dashboard using the Embedding SDK.\n\n- Adds support for the `$searchMeta` and `$unionWith` aggregation pipeline stages.\n\n- Removes support for assigning individual users to the `Viewer` role. This does not affect users already using this feature.\n\n## Atlas Charts v1.32.1\n\n*Released May 16, 2022*\n\nImprovements in this release:\n\n- Adds a new Embedding page that includes guidance for getting started with embedding and lists all your embedded charts and dashboards.\n\n- Moves the Authentication Settings inside the Embedding page. To learn more, see Configure Embedding Authentication Providers.\n\n- Adds a new page to see Charts data usage.\n\n- For developers, updates the Charts Embedding SDK to v2.3.0-beta.1 to support programmatic filtering of charts inside an embedded dashboard.\n\nBug fixes in this release:\n\n- Fixes an issue where Charts appended the `$regularExpression` operator to an aggregation pipeline.\n\n- Supports adding `$search` as the first stage in an aggregation pipeline.\n\n## Atlas Charts v1.31.1\n\n*Released April 1, 2022*\n\nBug fixes in this release:\n\n- Downloading a CSV file now works correctly for unbinned dates and data that includes the \"#\" character.\n\n## Atlas Charts v1.31\n\n*Released March 28, 2022*\n\nImprovements in this release:\n\n- You can now create a sample dashboard from the Add Dashboard menu.\n\nBug fixes in this release:\n\n- Fixes an issue where charts using aggregate functions would stop working.\n\n- Dropdown menus in the chart builder now display options correctly.\n\n- Fixes a bug where a product tours were incorrectly triggered when there were no dashboards on the Dashboards page.\n\n## Atlas Charts v1.30.1\n\n*Released February 24, 2022*\n\nBug fixes in this release:\n\n- Fixes a bug where a lookup field was not added.\n\n## Atlas Charts v1.30\n\n*Released February 21, 2022*\n\nImprovements in this release:\n\n- Adds the Dashboard Embedding feature, which lets you embed an entire dashboard in your website or app.\n\n- Adds the Query Library feature, which lets you reuse queries across multiple charts.\n\n- Adds the ability to download chart data from a public dashboard.\n\nBug fixes in this release:\n\n- Fixes an issue where incorrect binned dates were selected when you used a filter.\n\n- Fixes a bug where there was an issue applying empty queries in the query bar.\n\n- Fixes date filters in dashboard filters to correctly display the timezone when charts refresh.\n\n- Fixes the Import Dashboard dialog to correctly display when you have many data sources.\n\n- Fixes Ignore Filter to work correctly for all charts in the dashboard.\n\n## Atlas Charts v1.29\n\n*Released December 6, 2021*\n\nImprovements in this release:\n\n- Interactive Filtering is now available.\n\n- Improves the query editor, including a new button to collapse the editor.\n\nBug fixes in this release:\n\n- Fixes an issue where importing a dashboard did not work for some users.\n\n- Fixes an issue where sharing a dashboard with Everyone allowed them to make changes to existing roles.\n\n- Fixes an issue where negative numbers were incorrectly binned.\n\n- The Edit Chart button is now disabled for viewers.\n\n- Show Data now correctly displays in table and JSON format.\n\n- Data source names can now be 64 characters long.\n\n- Fixes an issue with donut charts having boolean values.\n\n- Click events now correctly pass event data when clicked in embedded charts.\n\n## Atlas Charts v1.27.0\n\n*Released September 13, 2021*\n\nImprovements in this release:\n\n- Atlas Charts now supports JWKs or JWKS URLs as an authentication provider when embedding charts.\n\n- Adds a new filter icon that indicates when dashboards are impacted by dashboard filters.\n\n- Adds new dashboard share icons to indicate public and internal sharing statuses.\n\n- Updates the dashboard and data source sharing screens.\n\nBug fixes in this release:\n\n- Fixes an issue with highlighting in bar and column charts when converting the time zone of a date field.\n\n- Axis labels are now correctly highlighted for binned dates.\n\n- Improves performance when adding a missed field in the chart builder.\n\n- The Convert type option is now correctly enabled in the chart builder for single-level arrays in documents.\n\n- Fixes an issue where part of the chart builder tour for new users was incorrectly positioned.\n\n- Donut charts with By Series colors now display properly with `null` values.\n\n- Programmatic highlighting now works correctly with single quotes in values.\n\n- The chart aggregation pipeline view is now accessible when a chart is loading.\n\n## Atlas Charts v1.26.1\n\n*Released August 19, 2021*\n\nBug fixes in this release:\n\n- Fixes an issue with disabling interactive filters on some dashboards created before v1.26.0.\n\n- Grouped column charts with secondary axes now render properly.\n\n- Donut charts with By Series colors now display properly when data changes.\n\n- Pressing the 'Enter' key to create a new dashboard now works correctly.\n\n- Fixes an issue where data driven multi-series charts could not be embedded."} -{"chunk_id": "68a95be05e79d242619d7f50-2", "page_id": "68a95be05e79d242619d7f50", "source_name": "charts", "product_name": "Atlas Charts", "url": "https://mongodb.com/docs/charts/release-notes", "title": "Atlas Charts Release Notes", "text": "## Atlas Charts v1.26.0\n\n*Released August 2, 2021*\n\nImprovements in this release:\n\n- Color swatches can now be rearranged in the custom color palette for data-driven multi-series charts.\n\n- Period date filter now allows adding custom past or future periods.\n\n- Adds a new dashboard filter button to enable or disable dashboard-level filtering on a chart.\n\n- Zoomed view now allows viewers to jump to a chart by clicking on the carousel indicators.\n\n- Imported dashboards now show the Just added status when imported.\n\n- Lookup fields can now be removed when sampling fields time out.\n\n- Encoded fields now have inferred type icons.\n\n- Type icons on encoding cards can now reflect the field's original type.\n\n- Charts Embedding SDK has been updated to v2.1.0 to support programmatic highlighting.\n\n- Click Events are no longer in Preview.\n\nBug fixes in this release:\n\n- Improves time series functionality by allowing `$setWindowFields`.\n\n- Fixes an issue where some dashboards were not able to be imported or exported.\n\n- Line series in Combo charts now use the correct formatting.\n\n- Fixes an issue where the editor for chart title and description had incorrect heights.\n\n- Improves `selectionFilter` on non-binned date fields by making them timezone aware.\n\n- Resized charts now display on their tiles correctly.\n\n## Atlas Charts v1.25.1\n\n*Released June 25, 2021*\n\nBug fixes in this release:\n\n- Fixes an issue where data labels did not appear when enabled on some charts.\n\n## Atlas Charts v1.25.0\n\n*Released June 23, 2021*\n\nImprovements in this release:\n\n- Dashboards can now be exported to a file.\n\n- Dashboards can be imported from a previously exported file.\n\n- Single-series charts now only show a single color in the palette customization setting.\n\n- Adds a new series-based color palette editing experience for multi-series charts built from multiple fields.\n\n- Number formatting can now be applied for every field used on a chart's axis.\n\n- Adds a new tour showing how to customize field settings.\n\nBug fixes in this release:\n\n- Embedded charts now automatically repaint if their size or visibility changes.\n\n- Fixes an issue where the magnifier icon in search boxes was very small.\n\n- Improves the behavior of `selectionFilter` in click event payloads for binned date values, making them time-zone aware.\n\n- Fixes an issue where charts did not render when series' names contained single quotes.\n\n## Atlas Charts v1.24.2\n\n*Released May 11, 2021*\n\nImprovements in this release:\n\n- Conditional formatting can now be applied to Table and Number charts.\n\n- Adds the new Combo chart category with Grouped Combo and Stacked Combo chart types.\n\n- Data sources can now be added for federated database instances and multi-cloud Atlas clusters.\n\n- Adds a new choropleth scheme for Dutch provinces.\n\n- Updates the sample dashboard.\n\nBug fixes in this release:\n\n- Disables browser autocomplete in the New Dashboard dialog.\n\n- Hides the Gauge charts Target Label & Value customization option when a Target is not set.\n\n- Gauge charts with a value of `0` no longer show as blank.\n\n- Top Item charts no longer show `undefined` while loading.\n\n- The indicator on the chart builder Filter tab now shows the count for enabled filters only.\n\n- A numeric bin size of `0` is now treated as invalid.\n\n- Fixes an issue where charts would sometimes show two `null` categories.\n\n- Binned string values are now sorted.\n\n- Prevents reordering columns in the Data Sources table.\n\n- Changes the click event role for clicks on a Scatter chart background.\n\n- Click event roles now differentiate between category and axis tick labels.\n\n- Calculated fields that are nested inside objects can now be modified or deleted.\n\n- Swaps the order of colors 18 and 20 in the default color palette.\n\n- Fixes an issue where filters sometimes couldn't be deleted from a chart.\n\n- Text can now be copied from chart titles and descriptions using the browser context menu.\n\n- Donut chart series now render in the same order in the legend and on the chart.\n\n- Charts no longer returns an error if the Show \"All Others\"\n limiting option is on and the chart has no data.\n\n- Logarithmic scale can now be enabled if an axis minimum or maximum is set.\n\n- Fixes an issue where dashboards did not load if a user with dashboard permissions was deleted from MongoDB Cloud.\n\n## Atlas Charts v1.23.0\n\n*Released March 29, 2021*\n\nImprovements in this release:\n\n- Adds the option to drill down into data on a chart by right-clicking chart elements and choosing \"show data for this mark.\"\n\n- Adds the option to pin Table columns to prevent horizontal scrolling.\n\n- Adds the option to select the angle for labels on the X-axis of discrete charts.\n\n- Extends the Embedding Click Events Preview to include Table chart types.\n\n- Developers can now filter click events by role.\n\n- Embedded charts with click events enabled now display the hand cursor over clickable elements.\n\n- Adds a choropleth shape scheme for Italian Regions.\n\n- Updates the default color palette for charts.\n\n- Introduces performance improvements.\n\nBug fixes in this release:\n\n- Improves the chart title and description inline editing experience.\n\n- Iframe embedded charts now accept the `autorefresh=false` parameter.\n\n- Fixes an issue where some read-only users could access the Add Data Source dialog.\n\n- Fixes some corner cases where the embedding `selectionFilter` field returned the wrong value.\n\n## Atlas Charts v1.22.0\n\n*Released February 18, 2021*\n\nImprovements in this release:\n\n- Adds new customization options to:\n\n - Show data labels on donut charts as a percentage.\n\n - Enable various line smoothing options on line and area charts.\n\n- Tooltips for donut and 100% stacked charts now show percentage as well as raw value.\n\n- Extends embedding Click Events Preview to support geospatial chart types and to include `selectionFilter` attribute.\n\n- Adds a new on-chart context menu to save a chart to a file or copy a chart to the clipboard.\n\n- Allows authenticated embedding providers to match Audience values where the JWT (JSON Web Token) contains an array of values.\n\n- Improves messages when `$lookup` is used in the query bar.\n\nBug fixes in this release:\n\n- Geospatial scatter charts now use requested formatting for values in the Color channel.\n\n- Validation errors now properly appear when adding calculated fields.\n\n- Charts built from multiple aggregation fields now show bars in the same order that the fields are encoded.\n\n- You can now select text in the View Aggregation Pipeline dialog.\n\n- Table row and total columns now respect the table text size customization option.\n\n- Chart title and description fields can no longer be edited simultaneously.\n\n- Improved column sorting behavior in tables.\n\n- Fixed some issues where the Top Item chart sometimes displayed incorrect data.\n\n- Data labels no longer appear in the wrong place for fields mapped to the secondary Y axis."} -{"chunk_id": "68a95be05e79d242619d7f50-3", "page_id": "68a95be05e79d242619d7f50", "source_name": "charts", "product_name": "Atlas Charts", "url": "https://mongodb.com/docs/charts/release-notes", "title": "Atlas Charts Release Notes", "text": "## Atlas Charts v1.21.0\n\n*Released December 21, 2020*\n\nImprovements in this release:\n\n- Adds the ability to add a description to a chart.\n\n- Charts no longer allocate space for chart titles or descriptions when they are not present.\n\n- Refreshes the visual styling for Table and Area charts.\n\n- Adds the following new customization options:\n\n - Wrap text in specific columns of a Table chart.\n\n - Choose the font size in a Table chart.\n\n - Enable Trend Lines in Scatter, Continuous Line and Continuous Area charts.\n\n- Adds the option to enable Data labels in Stacked Bar and Stacked Column charts.\n\n- Improves rendering performance on embedded charts.\n\n- Releases Click Events in the Charts Embedding SDK as a Preview feature.\n\nBugs fixed in this release:\n\n- Fixes an issue where donut charts rendered with too many segments after swapping from a different chart type.\n\n- Fixes an issue where embedded charts did not render when the browser is configured to block third-party cookies.\n\n- Fixes an issue where the Get Chart Data dialog was empty if a chart used the Count By Value aggregation.\n\n- Fixes an issue where tables didn't sort correctly when binned dates were used in the Dynamic Columns channel.\n\n- Fixes an issue where values from the Color channel were not always sorted correctly on Scatter charts.\n\n## Atlas Charts v1.20.2\n\n*Released December 1, 2020*\n\nBug fixes in this release:\n\n- Fixes an issue where donut charts constructed from multiple fields failed to render.\n\n- Fixes an issue where series could render in an unpredictable order when using string binning.\n\n- Fixes an issue where area charts showed overlapping segments when some series had no data for some categories.\n\n## Atlas Charts v1.20.1\n\n*Released November 18, 2020*\n\nBug fixes in this release:\n\n- Fixes an issue where the Convert Time Zone toggle couldn't be enabled when customizing a field.\n\n- Fixes an issue where charts wouldn't render if a label contains a single quote and the chart uses a secondary Y axis.\n\n- Improves predictability around ordering of multiple series on a chart.\n\n## Atlas Charts v1.20.0\n\n*Released November 12, 2020*\n\nImprovements in this release:\n\n- Introduces option to show All others when limiting results on a chart.\n\n- Introduces Count by Value aggregation option, which automatically generates series based on the values in a field.\n\n- Provides more detailed error messages in the tooltip when a chart on a public dashboard fails to load.\n\n- New option to use Regular Expressions to choose which string values to use in a bin.\n\n- New chart customization options:\n\n - Plot one or more series on a Secondary Y axis on grouped column, line and area charts.\n\n - Reposition or hide the chart legend.\n\n - Use different dash styles for each series on a line chart.\n\n - Change the size, stroke width and fill opacity of marks on a scatter chart.\n\nBug fixes in this release include:\n\n- System databases and collections can no longer be added as data sources, since they can't be used for charting.\n\n- Popup dialogs in the chart builder no longer close when you click on the background.\n\n- Error state is now properly cleared when the Lookup Field dialog is reopened.\n\n- Improves the resolution of the Countries and Regions choropleth shape scheme, ensuring small countries are visible.\n\n- Charts now render correctly when `NaN` values are included in bins.\n\n- Series now display in a consistent order when string binning is enabled.\n\n- Null and empty string values can now be used successfully in string bins.\n\n- String bins are now retained when binning is disabled and re-enabled.\n\n- Fixes a styling issue where type converted fields were not showing with a green icon in the field panel.\n\n- Changes placement of product tours so they can be dismissed on low resolution displays.\n\n- Binned numbers and dates are no longer infilled when used on a chart's Series channel.\n\n- Null category no longer displays when binned numbers or dates are used on a Series chanel.\n\n- Fixes an issue where charts were not always sorted correctly when binned numbers or dates were used on a Series chanel.\n\n- Fixes an issue where the data in the Get Chart Data dialog was sometimes empty or didn't match the chart.\n\n## Atlas Charts v1.19.0\n\n*Released October 13, 2020*\n\nImprovements in this release:\n\n- Introduces Lookup Fields in the Chart Builder.\n\n- Introduces binning on string-typed fields in category channels. See Bin Data.\n\n- Adds ability to limit the number of documents displayed on Table Charts.\n\n- Adds new tour showing virtual and lookup fields.\n\nBug fixes in this release:\n\n- Field encodings are now correctly retained when swapping between Geo Scatter and Geo Heatmap chart types.\n\n- Calculated fields that return objects can now be modified or deleted.\n\n- Fixes a rendering issue for Area charts when some bins or categories had no values.\n\n- Geospatial charts can now be panned independently.\n\n- Fixes an issue when scatter charts with log scales were panned with the mouse.\n\n- Changes to the Filter Allow list are now immediately picked up by embedded charts.\n\n- Prevents some \"white screen\" errors from occurring in the Chart Builder.\n\n- Allows editing chart titles while a chart is loading.\n\n- Empty arrays now show the `[]` symbol in the Chart Builder field panel.\n\n- Improves the refresh behavior for expired authentication sessions.\n\n- Atlas Charts no longer crashes when geospatial charts are rendered with `NaN` coordinates.\n\n## Atlas Charts v1.18.0\n\n*Released September 15, 2020*\n\nImprovements in this release:\n\n- Adds new Top Item chart type, allowing you to see details of a single item from a collection.\n\n- Allows changing the size of text labels on a chart.\n\n- Adds new Period option on date filters, allowing you to filter by a current or previous period.\n\n- Allows sorting a chart on a specific series when the chart uses multiple series generated from different fields.\n\nBug fixes in this release:\n\n- Array reduction options no longer show on wrong cards after deleting fields.\n\n- Improves performance of queries when absolute date filters are used.\n\n- Improves rendering of multi-series charts containing empty bins.\n\n- Embedded charts no longer blank out when refreshing.\n\n- Zoomed dashboard view now fills the entire screen.\n\n- Tables containing a mixture of unbinned dates and binned values no longer show empty cells where dates should appear.\n\n- Improves rendering consistency across different chart types.\n\n- Charts no longer hang hang during rendering if the number of requested bins was very large."} -{"chunk_id": "68a95be05e79d242619d7f50-4", "page_id": "68a95be05e79d242619d7f50", "source_name": "charts", "product_name": "Atlas Charts", "url": "https://mongodb.com/docs/charts/release-notes", "title": "Atlas Charts Release Notes", "text": "## Atlas Charts v1.17.0\n\n*Released August 20, 2020*\n\nImprovements in this release:\n\n- Introduces product tours for new users.\n\n- Allows users with the Project Read Only role to create dashboards and charts using sample data.\n\n- Introduces a new personal dashboard for new users.\n\n- Introduces new customization option to show Gauge Charts as a percentage of target.\n\n- Improves autocomplete suggestions in the chart builder query bar to be case-insensitive.\n\n- Improves rendering of null values in charts.\n\n- Improves performance of sorting and limiting of chart data by performing sorting and limiting server-side.\n\n - Improves performance of chart rendering and the accuracy of data in the Get Chart Data dialog.\n\n- Increases the number of legend entries that render on a multi-series chart.\n\nBug fixes in this release:\n\n- Embedded number charts no longer display as blank when a zero value was expected.\n\n- Supports adding calculated fields whose values are arrays.\n\n- Chart titles can now be selected and copied from the dashboard view.\n\n- The numeric binning textbox no longer shows non-integer values.\n\n- The string filter card can still be used even if sampling of string values fails.\n\n- Missed Fields can now be added when Sample Mode is enabled.\n\n- Summary of user permissions now show on the Dashboard Overview page.\n\n- The Chart Builder no longer crashes when an empty array is dragged to the filter panel.\n\n- Collection statistics now display for databases that contain views.\n\n- Error codes now display correctly after failures.\n\n- Chart status bar no longer shows a tick if the chart data fails to load.\n\n- Charts no longer render incorrectly when the only category is an empty string.\n\n- Cluster names are no longer truncated in the Data Source Permissions dialog.\n\n- Multi-series charts with some empty date bins now render correctly.\n\n- Blank screen no longer occurs after moving a chart to a different dashboard.\n\n## Atlas Charts v1.16.0\n\n*Released July 24, 2020*\n\nImprovements in this release:\n\n- Adds a welcome experience for new Charts users.\n\n- Adds a sample data source of movie data available to all Charts users for testing and experimentation.\n\n- Enables generating sample dashboards and charts.\n\n- Adds an option to show a running total or change in value on a chart.\n\n- For charts with no category channel encoded, fields in aggregation channels are now used as categories.\n\nBug fixes in this release:\n\n- Fixes an issue where a white screen was displayed when editing the time component of a date filter.\n\n- Fixes an issue where number charts displayed as blank when a zero value was expected.\n\n- Fixes an issue where the Retry option did not appear on charts with errors on public dashboards.\n\n- Fixes an issue where embedded charts using BSON types in filters did not work when using the Atlas App Services authentication provider.\n\n- Fixes an issue where some charts unexpectedly showed a blank entry in the legend.\n\n- Fixes an issue where chart queries did not work if they used the `NumberInt`, `NumberLong` or `NumberDecimal` helpers.\n\n- Improves the performance of rendering large dashboards.\n\n## Atlas Charts v1.15.0\n\n*Released June 23, 2020*\n\nImprovements in this release:\n\n- Enables downloading chart data from the dashboard view of a chart.\n\n- Invalid queries now display detailed error messages in the chart builder.\n\n- Enables setting a delimiter when using the `concat`\n array reduction option.\n\n- Adds new *Week of the Year* option when binning date values.\n\n- Donut charts can now be created from multiple fields.\n\n- Charts with binned numeric or date values now show gaps for empty bins.\n\n- Collection information is now visible when adding data sources.\n\n- Removes the step to set permissions when creating a data source.\n\n- Updates visuals across the Atlas Charts application.\n\nBug fixes in this release:\n\n- Fixes an issue where injected embedding filters were not properly considered when retrieving chart data from the cache.\n\n- Fixes an issue where errors that occurred while sampling fields did not display in the chart builder.\n\n- Fixes an issue where the chart builder query bar did not appear dimmed when a dialog was open.\n\n- Changes the IFrame embedding parameter to `autoRefresh` to improve consistency with SDK property (the previous `autorefresh` syntax still works).\n\n- Fixes an issue where embedded charts sometimes rendered with the incorrect font.\n\n## Atlas Charts v1.14.0\n\n*Released May 28, 2020*\n\nImprovements in this release:\n\n- Adds a new chart status bar that shows details about last and next refresh time and any errors in the chart.\n\n- Adds the ability to refresh a single chart on a dashboard. To learn more, see Refresh Dashboard Data.\n\n- Improves server-side caching of chart data.\n\n- Adds an option to add an authentication provider while embedding a chart.\n\n- Adds new Tooltip Detail channel on Scatter and Geospatial Scatter charts.\n\nBug fixes in this release:\n\n- Embedded tables now have a transparent background.\n\n- Prevents a failure when geospatial charts use decimal type fields for coordinates.\n\n- Fixes sorting of unbinned decimal typed values in chart category channels.\n\n- Fixes an issue where newly added dashboard filters wouldn't show sample string values.\n\n## Atlas Charts v1.13.0\n\n*Released April 30, 2020*\n\nImprovements in this release:\n\n- Embedding SDK now generally available. Adds support for authenticated embedding.\n\n - Charts supports Custom JWT (JSON Web Token), Atlas App Services, and Google authentication providers.\n\n- Adds more detailed error information for embedded charts.\n\n - Embedding errors are now written to browser developer console.\n\n- Includes server-side caching of chart data for improved performance.\n\n- Updates UI for setting dashboard refresh behavior.\n\nBug fixes in this release:\n\n- Error messages no longer render incorrectly in Firefox.\n\n- Field sampling in the chart builder no longer appears to hang if the sample returns no documents.\n\n- Table charts now properly format unbinned dates.\n\n- Queries using $date and a string date can now be used in the query bar.\n\n- Improves the rendering of emphasized series in line, area and scatter charts.\n\n## Atlas Charts v1.12.0\n\n*Released March 31, 2020*\n\nImprovements in this release:\n\n- Allows dashboard filter cards to be renamed.\n\n- Allows filter cards to be expanded and collapsed.\n\n- Visual refresh across the Atlas Charts application.\n\nBug fixes in this release:\n\n- Legends on geospatial charts are no longer cut off.\n\n- Error message no longer appears before an embedded chart is rendered.\n\n- Use Smart Labels on Axis customization option no longer shows on unsupported chart types.\n\n- Unbinned dates used as dynamic columns on a table chart can now be formatted.\n\n- Donut chart data labels are no longer rendered if they are likely to overlap with other labels.\n\n- Users with Atlas organization-level roles now show in permissions dialogs.\n\n- Intercom support widget no longer obscures charts and dashboard filters.\n\n- Sampling a collection in the chart builder no longer appears to hang if no documents are returned from the query.\n\n- Removes excessive padding around table charts.\n\n- Fixes an issue where calculated fields that produce no results could be saved but not removed.\n\n- Charts now automatically reloads after a version upgrade.\n\n- Embedded charts now show the correct error if the chart `id` is incorrect.\n\n- Fixes rendering issues with dashboard filter cards on Firefox browsers.\n\n- Fixes an issue where error messages on public dashboards were illegible in Firefox browsers."} -{"chunk_id": "68a95be05e79d242619d7f50-5", "page_id": "68a95be05e79d242619d7f50", "source_name": "charts", "product_name": "Atlas Charts", "url": "https://mongodb.com/docs/charts/release-notes", "title": "Atlas Charts Release Notes", "text": "## Atlas Charts v1.11.0\n\n*Released March 2, 2020*\n\nImprovements in this release:\n\n- Allows setting the `theme` and `attribution` with the Embedding SDK.\n\n- Adds the Gauge Chart type.\n\n- Enables Dashboard filters on public link-shared dashboards.\n\n- Enables linking Dashboard filter cards to multiple fields from different data sources.\n\n- Adds Smart Labels for dates on the X axis of continuous line, area and scatter charts.\n\n- Enables zooming and panning on Scatter Charts.\n\n- Enables highlighting individual data series by clicking the legend entries.\n\nBug fixes in this release:\n\n- Fixes an issue where Verified Signature embedded charts failed to render when strings in filters contain space characters.\n\n- Fixes an issue where embedded charts failed to render when field names in filters were not quoted.\n\n- Fixed an issue where embedded Choropleth Charts did not render.\n\n- Improved rendering of filter cards in the dashboard filter pane.\n\n## Atlas Charts v1.10.0\n\n*Released February 5, 2020*\n\nImprovements in this release:\n\n- Adds dashboard filtering for authenticated dashboard users.\n\n- Adds support for Embedding JavaScript SDK (Preview) for unauthenticated embedding.\n\n- IFrame embedded charts no longer require Tenant ID.\n\nBug fixes in this release:\n\n- Improves scaling of Number Charts to prevent the text from getting cut off.\n\n- Tables no longer show as blank when dynamic column fields have empty values.\n\n- Improves reliability and performance when duplicating dashboards.\n\n- Prevents stale error messages from appearing in Calculated Fields editor.\n\n## Atlas Charts v1.9.1\n\n*Released December 16, 2019*\n\nBug fixes in this release:\n\n- Removes extra padding around embedded charts.\n\n## Atlas Charts v1.9.0\n\n*Released December 10, 2019*\n\nImprovements in this release:\n\n- Improves dialog for unauthenticated chart embedding.\n\n- Supports dark mode in embedded charts.\n\n- Adds the ability to filter unauthenticated charts based on allowed fields.\n\n- Improves the attribution logo on embedded charts and provides the ability to hide the logo.\n\n- Improves the treatment of errors in the Chart Builder, Dashboards, and embedded charts.\n\nBug fixes in this release:\n\n- 100% stacked charts now show a percentage scale on the axis.\n\n- Fixes an issue with the Retry button for charts on publicly shared dashboards that were returning an error.\n\n- Prevents multiple data source samples from running at once when quickly switching data source in the Chart Builder.\n\n- Grid columns in the Get Chart Data dialog are now in an expected order.\n\n- Tables with a large number of dynamic columns now return an error instead of hanging the browser.\n\n- Fields that include ellipsis button in the Chart Builder now behave as designed on macOS.\n\n- Dashboards can now be scrolled using devices that support touch-screen feature.\n\n- The `existence of value` and `count of occurences` array reductions now succeed even if some documents have null or missing values.\n\n## Atlas Charts v1.8.0\n\n*Released November 11, 2019*\n\nImprovements in this release:\n\n- Add Missed Fields and Calculated fields while building a chart.\n\n- Share dashboards via a public link.\n\n- New design for Data Source Permissions and Dashboard Permissions dialogs.\n\nBug fixes in this release:\n\n- Legends on donut charts should no longer overlap with the donut.\n\n- Long category names are now truncated, maximizing space for the chart.\n\n- Improved error handling for queries with mismatched brackets.\n\n- Embedded charts no longer go blank while refreshing.\n\n- View Source Documents and View Aggregation Pipeline dialogs no longer take unapplied queries into account. Prior to this fix, these dialogs would be affected by queries in the query bar regardless of whether the query was applied to the chart.\n\n## Atlas Charts v1.7.1\n\n*Released October 14, 2019*\n\nBug fixes in this release:\n\n- Fixed an issue that resulted in number formatting not being applied to decimal types in some charts.\n\n- Charts containing type-converted fields now render correctly on dashboards and when embedded.\n\n## Atlas Charts v1.7.0\n\n*Released October 2, 2019*\n\nImprovements in this release:\n\n- New menu in the Chart Builder allows you to view and export chart data:\n\n - View Source Documents from the data source.\n\n - View Aggregation Pipeline used to query the data source.\n\n - Get Chart Data to see the data used on the chart and export to CSV or JSON.\n\n- Adds the ability to change the data type of fields while building a chart, when using MongoDB 4.0 or later.\n\n- Charts can now be placed across the full width of a dashboard on a large monitor.\n\n- A warning now appears when deleting a data source that is in use by at least one chart.\n\nBug fixes in this release:\n\n- Performing a new operation in the Chart Builder now cancels previous operations, preventing the chance of multiple responses coming back in an unexpected order.\n\n- Table row totals correctly display at the far right of the table at all times.\n\n- Encoding cards can now be more reliably swapped across chart channels.\n\n- Singapore is now shown on Choropleth maps using the Countries and Regions scheme.\n\n- Choropleth tooltips are now shown on the largest land mass of a region.\n\n- String Filter card now correctly shows sample values from arrays of documents.\n\n- Null values in chart categories now show as `null`, not 0.\n\n- Improves rendering of dates on continuous chart axes.\n\n- Ellipsis menu is now accessible for data sources at the bottom of the grid.\n\n- Miscellaneous performance, reliability and security improvements.\n\n## Atlas Charts v1.6.0\n\n*Released September 3, 2019*\n\nImprovements in this release:\n\n- New design for Data Sources list.\n\n- New Data Source Name attribute replaces the Alias attribute.\n\n- Data Source owners can now add, edit, or remove an Aggregation Pipeline on a data source, including the ability to join multiple collections using $lookup.\n\n- Version detection to detect unsupported MongoDB versions or disable unsupported chart features.\n\n- Option to enable or disable thousands separators in numbers on charts.\n\nBug fixes in this release:\n\n- Time zone conversions are now correct in Table chart types.\n\n- Support for queries using `{ $not: { $regex: \u2026 } }` structure.\n\n- Miscellaneous performance, reliability and security improvements.\n\n## Atlas Charts v1.5.0\n\n*Released August 7, 2019*\n\nImprovements in this release:\n\n- Option to specify refresh period in embedded charts.\n\n- Option to specify a custom filter in embedded charts using Verified Signature authentication.\n\n- Enabling and disabling of chart filters\n\n- Set preferred time zone when using an absolute date filter.\n\n- Visual refresh of the Chart Builder.\n\nBug fixes in this release:\n\n- Addressed various issues when building and rendering geospatial charts.\n\n- Fixed an issue that could cause charts to appear blank when refreshing large dashboards.\n\n- String filter card shows a more complete set of sample values for large, indexed collections.\n\n- Miscellaneous performance, reliability and security improvements.\n\n## Atlas Charts v1.4.0\n\n*Released June 12, 2019*\n\nGeneral Availability Release\n\nImprovements in this release:\n\n- New geospatial chart types:\n\n - Choropleth\n\n - Geospatial Scatter\n\n - Geospatial Heatmap\n\n- New Data Source permissions model. `Viewer` role allows users to be granted access to data for viewing but not authoring.\n\n- UI improvements to the chart builder.\n\nBug fixes in this release:\n\n- Prevented console errors from being written when embedded charts are rendered.\n\n- Read Preference now shows correctly for newly created data sources.\n\n- Prevented intermittent errors when adding data sources.\n\n- Charts can now be edited or deleted when their data is loading."} -{"chunk_id": "68a95be05e79d242619d7f50-6", "page_id": "68a95be05e79d242619d7f50", "source_name": "charts", "product_name": "Atlas Charts", "url": "https://mongodb.com/docs/charts/release-notes", "title": "Atlas Charts Release Notes", "text": "## Atlas Charts v1.3.0\n\n*Released May 14, 2019*\n\nImprovements in this release:\n\n- New filtering experience in the chart builder.\n\n- Improved Query Bar in the chart builder, allowing the chart author to specify custom aggregation pipeline stages.\n\n- Charts now runs against secondary replica set members by default, and allows Data Source owners to change the read preference.\n\n- Charts now remain visible when changing the dashboard layout and refreshing charts.\n\nBug fixes in this release:\n\n- Duplicating a dashboard no longer breaks embedded charts.\n\n- Tooltips on area charts now show on hover over any part of the area, not just the data points.\n\n## Atlas Charts v1.2.0\n\n*Released Apr 16, 2019*\n\nImprovements in this release:\n\n- Ability to embed charts in external applications.\n\n- Warning now appears if Atlas renders with incomplete data.\n\nBug fixes in this release:\n\n- Fixed bad rendering in some stacked area charts.\n\n- Fixed some cases where binned data could appear in the wrong order.\n\n- Automatic dashboard refresh should work more reliably after resuming from sleep.\n\n## Atlas Charts v1.1.1\n\n*Released Feb 14, 2019*\n\nImprovements in this release:\n\n- New Chart Types:\n\n - 100% Stacked Bar\n\n - 100% Stacked Column\n\n - 100% Stacked Area\n\n- New default sort behavior in charts.\n\n- New filter bar in the chart builder, with increased performance and usability.\n\nBug fixes in this release:\n\n- Changes to filter parsing to better align with MongoDB Shell syntax and Javascript in general. Specifically, filters using `Date()` to represent the current date or `Date(\"2019-01-01\")` to represent a specific date will need to be changed to `new Date()` or `ISODate()` and `new Date(\"2019-01-01\")` or `ISODate(\"2019-01-01\")`, since the Date() function now correctly returns the date as a string representation.\n\n- Fixed rendering issues in certain browser versions relating to the continuous color picker.\n\n- Miscellaneous performance, reliability and security improvements.\n\n## Atlas Charts v1.0.0\n\n*Released Dec 11, 2018*\n\nInitial public release of the Atlas Charts\nSaaS (Software as a Service) application."} -{"chunk_id": "68a95be05e79d242619d7eff-0", "page_id": "68a95be05e79d242619d7eff", "source_name": "charts", "product_name": "Atlas Charts", "url": "https://mongodb.com/docs/charts/data-sources", "title": "Data Sources", "text": "# Data Sources\n\nA data source in Atlas Charts references one of the following:\n\n- A collection or database view in your MongoDB deployment.\n\n- A charts view that you create using a collection.\n\nYou can use the fields in the data source to construct a chart. When you build a chart, you must specify the data source that the chart uses.\n\nDeployments in Atlas Charts reference Atlas deployments that contain valid Charts data sources, including:\n\n- All clusters in your Atlas project for which you have the `Project Data Access Read Only` role or higher.\n\n- All federated database instances in your project, including Online Archives.\n\n## Connect or Disconnect Data Sources and Deployments\n\nAn Atlas `Project Owner` can connect or disconnect data sources and deployments. To learn more, see Manage Data Sources.\n\nCharts connects to all deployments and data sources in your project by default.\n\n## Manage Data Sources\n\nTo manage settings for a data source, see Manage Data Sources. To manage pipelines, see Create and Manage Charts Views.\n\nTo apply a pipeline, use a charts view. You can't apply pipelines to an entire collection.\n\n## Manage Deployments\n\nTo manage settings for the Atlas deployments that contain your data sources, see Manage Deployments.\n\n## Edit a Chart's Data Source\n\nTo edit the data source for an existing chart:\n\n### Go to the Dashboards page.\n\nFor instructions, see Dashboards.\n\n### Select your dashboard.\n\nFrom the Dashboards page, select the dashboard that contains the chart.\n\n### Click Edit on the chart you want to edit.\n\n### Click the button under Data Source on the top left of the chart builder.\n\nThe button says Select if you have not selected a data source, or it says the name of the currently selected data source.\n\n### Click the Project tab.\n\nAll of your connected deployments appear.\n\nA deployment and its data sources won't display on the Select Data Source modal unless they are connected to Charts. Only a `Project Owner` can connect or disconnect deployments and data sources. All deployments and data sources in the project connect to Charts by default.\n\n### Click the name of the deployment that contains the data source.\n\n### Click the name of the database that contains the data source.\n\nThe database's data sources appear. You can click on a data source's name to view a preview of its data.\n\n### Click Select on the data source.\n\nTo learn how to set the data source for a new chart, see Build Charts.\n\n## Try Out Charts with the Sample Data Source\n\nCharts automatically includes the Sample Data: Movies data source in all Charts tenants. The Sample Dashboard uses this data source to show the charts you can create. You can access the sample data source from all dashboards.\n\nYou can't:\n\n- Add, edit, or delete the data in the Sample Data: Movies data source.\n\n- Remove the sample data source.\n\n- Externally share or embed charts that use the sample data."} -{"chunk_id": "68a95be05e79d242619d7f03-0", "page_id": "68a95be05e79d242619d7f03", "source_name": "charts", "product_name": "Atlas Charts", "url": "https://mongodb.com/docs/charts/embedded-dashboards-options/embedded-sdk", "title": "Embedded Dashboard SDK Methods and Options", "text": "# Embedded Dashboard SDK Methods and Options\n\nThe Embedding SDK provides the JavaScript `createDashboard()` method for rendering a dashboard within a web page. You can use options to control many aspects of a dashboard (for example, its height and width).\n\nThe following example demonstrates how to use the `createDashboard` method with options that specify the height and width of the dashboard.\n\n```javascript\nconst dashboard = sdk.createDashboard({\n dashboardId: \"8d4dff93-e7ca-4ccd-a622-e20e8a100197\",\n baseUrl: \"https://charts.mongodb.com/dashboards-embedding-examples-hmewt\",\n height: 300,\n width: 400\n});\n```\n\n## Embedded Dashboard `createDashboard()` Options\n\nThe `createDashboard()` method takes the following options:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nOption\n\n\nType\n\n\nDescription\n\n\nRequired?\n\n
\n`autoRefresh`\n\n\nboolean\n\n\nFlag that specifies whether the dashboard automatically refreshes. If omitted, dashboards don't automatically refresh.\n\nUse this option with the `maxDataAge` option to configure automatic dashboard refresh frequency.\n\n\nno\n\n
\n`background`\n\n\nstring\n\n\nBackground color to apply to your dashboard instead of the `theme` background. You can specify:\n\n- A color hex code\n\n- A CSS (Cascading Style Sheets) color name\n\n- A transparent background using the value `transparent`\n\nIf omitted, the background color defaults to the current `theme`:\n\n- `#F1F5F4` for the `light` theme, or\n\n- `#12212C` for the `dark` theme.\n\n\nno\n\n
\n`baseUrl`\n\n\nstring\n\n\nBase URL of the dashboard.\n\n\nyes\n\n
\n`dashboardId`\n\n\nstring\n\n\nUnique string that identifies the dashboard.\n\n\nyes\n\n
\n`getUserToken`\n\n\nobject\n\n\nFunction that returns a `base64`-encoded JWT (JSON Web Token) token. Charts validates this token to determine whether to render an authenticated dashboard.\n\nIf you enabled authenticated access, Atlas Charts renders the authenticated dashboard view only if Charts can validate the token using the configured authentication providers. If the token is invalid, Charts doesn't render the dashboard.\n\nIf you enabled unauthenticated access, Atlas Charts always renders the unauthenticated dashboard view. To learn more, see Embed an Authenticated Chart using a Custom JWT Provider.\n\n\nno\n\n
\n`height`\n\n\nnumber\n\n\nHeight of the dashboard. If omitted, it defaults to the height of its container. If you provide a value without units, it defaults to pixels (px).\n\n\nno\n\n
\n`maxDataAge`\n\n\nnumber\n\n\nMaximum age of data to load from the cache when loading or refreshing the dashbnoard. If omitted, Atlas Charts renders the dashboard with data from the cache only if the data is less than one hour old.\n\nIf the data from the cache is more than one hour old, Charts queries the data source for the latest data, refreshes the cache, and renders the dashboard using this data.\n\nTo learn how Atlas Charts loads data from the cache when loading or refreshing the dashboard based on the `autoRefresh` and `maxDataAge` values, see Refresh and Data Caching Behavior.\n\n\nno\n\n
\n`showAttribution`\n\n\nboolean\n\n\nSpecifies whether to display the MongoDB logo below the dashboard. Defaults to `true`.\n\n\nno\n\n
\n`theme`\n\n\nstring\n\n\nTheme to use on the dashboard. The following options are valid:\n\n- `light` for a light background with dark text and dashboard elements, or\n\n- `dark` for a dark background with light text and dashboard elements.\n\nIf omitted, it defaults to `light`.\n\n\nno\n\n
\n`width`\n\n\nnumber\n\n\nWidth of the dashboard. If omitted, it defaults to the width of its container. If you specify a value without units, it defaults to pixels (px).\n\n\nno\n\n
After the dashboard is created, you can control the configuration of the dashboard by calling methods on the `Dashboard` instance returned by `DashboardsEmbedSDK.createDashboard({ ... })`.\n\n## Dashboard Configuration Methods\n\nAfter you create a dashboard, you can control the configuration of the dashboard by calling methods on the `Dashboard` instance returned by `DashboardsEmbedSDK.createDashboard({ ... })`.\n\n### `getChart('')`\n\nRetrieves a specific chart from the embedded dashboard using the chart's `chartId` string. After calling this method, you can highlight elements or filter data on the chart.\n\n### `setAutoRefresh()`\n\nFlag that specifies whether the dashboard refreshes automatically. If omitted, dashboards don't refresh automatically.\n\nUse this method with the `setMaxDataAge` method to configure how often the dashboard refreshes.\n\n### `setMaxDataAge()`\n\nMaximum age of data to load from the cache when loading or refreshing the dashboard. If omitted, Atlas Charts renders the dashboard with data from the cache only if the data is less than one hour old.\n\nIf the data from the cache is more than one hour old, Charts queries the data source for the latest data, refreshes the cache, and renders the dashboard using this data.\n\nTo learn how Atlas Charts loads data from the cache when loading or refreshing the dashboard based on the `setAutoRefresh` and `setMaxDataAge` values, see Refresh and Data Caching Behavior.\n\n### `setTheme(theme: 'dark' | 'light')`\n\nCurrent theme of the embedded dashboard. When setting the theme to `dark`, ensure that your dashboard's background color has appropriate contrast so that the information is visible.\n\n- Embedding SDK API Documentation\n\n- Embedding SDK examples\n\n### Dashboard Configuration Example\n\nThe example code snippets configures the following options for a Dashboard instance named `dashboard`:\n\n- The theme to `dark`\n\n- The automatic refresh rate to every 60 seconds\n\n```javascript\ndashboard.setTheme(\"dark\");\ndashboard.setAutoRefresh(true);\ndashboard.setMaxDataAge(60);\n```"} -{"chunk_id": "68a95be05e79d242619d7e94-0", "page_id": "68a95be05e79d242619d7e94", "source_name": "charts", "product_name": "Atlas Charts", "url": "https://mongodb.com/docs/charts/chart-type-reference/combo-charts", "title": "Combo Charts", "text": "# Combo Charts\n\nCombo charts offer a combined column and line view.\n\n## Combo Chart Encoding Channels\n\nCombo charts provide the following encoding channels:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nEncoding Channel\n\n\nDescription\n\n
\nX Axis\n\n\nIn the category axis encoding channel, a column is rendered for each unique value from this field.\n\n
\nColumns\n\n\n- The fields that you use in this channel build the columns in this chart.\n\n- The aggregation axis encoding channel dictates which field to aggregate on and the type of aggregation to perform. This ultimately dictates the size of each column.\n\nYou can map multiple fields to this channel to create a multi-series chart. However, unlike other charts, you can't create a multi-series chart with the Series channel on combo charts. To learn more, see Multiple Field Mappings.\n\n
\nLines\n\n\n- The fields that you use in this channel build one or more lines on this chart.\n\n- The aggregation axis encoding channel dictates which field to aggregate on and the type of aggregation to perform.\n\n
\n\n## Combo Chart Types\n\nCombo charts provide the following sub-types:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nSub-Type Name\n\n\nDescription\n\n
\nGrouped\n\n\nAtlas Charts groups data by the category specified in the category encoding channel, and plots a column for each value in the Columns encoding channel.\n\n
\nStacked\n\n\nAtlas Charts creates a column for each distinct value in the category encoding channel field, and splits each column into segments based on the the Columns encoding channel.\n\n
\n\n## Use Case\n\nCombo charts bring together the useful aspects of both column and line charts into a single chart.\n\n## Customization Options\n\nThe following customization options are specific to combo charts. To see all available customization options, see Customize Charts.\n\nIf the columns and lines in your combo use different scales, consider a Secondary Y Axis. This option appears on the Customize pane in the Fields section for any fields mapped to the Lines channel. Fields mapped to the Columns channel appear only on the primary axis.\n\n### Adjust X-Axis Label Angle\n\nYou can adjust the X-axis label angle to one of the following options:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nOption\n\n\nDescription\n\n
\nVertical\n\n\nLabels right-aligned at a 270 degree angle.\n\n
\nHorizonal\n\n\nLabels center-aligned at a 0 degree angle.\n\n
\nDiagonal\n\n\nLabels right-aligned at a 315 degree angle.\n\n
To set this option:\n\n1. Click the Customize tab for your chart.\n\n2. In the Axes section, select a Label Angle for the X Axis.\n\n### Set Distinct Dash Style per Series\n\nOn combo charts, you can opt to display each series in the chart with a distinct dash style. This option can help make your chart more accessible by distinguishing between series beyond color.\n\nTo set this option:\n\n1. Open the Customize pane for your chart.\n\n2. In the General section, set the Dash Styles per Series toggle switch to the desired setting.\n\n### Smooth Lines\n\nYou can change the way lines are drawn on your chart. To smooth lines:\n\n1. Open the Customize pane for your chart.\n\n2. In the General section, set Line Smoothing to the desired option.\n\nThe following line smoothing options are available:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nOption\n\n\nDescription\n\n
\nNone (Default)\n\n\nDraws straight lines between data points.\n\n
\nSmooth\n\n\nDraws curved lines between data points.\n\n
\nStep Before\n\n\nLines extend horizontally to data points. This is useful for visualizing data that only changes in intervals and is collected at the end of a period, such as daily average temperature.\n\n
\nStep After\n\n\nLines extend horizontally from data points. This is useful for visualizing data that only changes in intervals, such as stock prices.\n\n
\n\n### Show or Hide Data Markers\n\nOn combo charts, you can dictate whether Charts displays visible data markers that represent individual data points along the line. Enabling this option makes it easier to see exactly where your data points lie along a line. Hovering over these markers shows the exact data values in a tooltip, making it easier to view precise measurements.\n\nTo set this option:\n\n1. Open the Customize pane for your chart.\n\n2. In the General section, set the Data Markers toggle switch to the desired setting.\n\nTo customize the formatting of the number in the data marker tooltip, modify the Number Formatting settings for the relevant field.\n\n### Show or Hide Data Value Labels\n\nYou can dictate whether Charts displays text labels for your data **values**. Data value labels show the exact values of your data points.\n\nTo set this option:\n\n1. Open the Customize pane for your chart.\n\n2. In the General section, set the Data Value Labels toggle switch to the desired setting.\n\nTo customize the formatting of the number in the data label, modify the Number Formatting settings for the relevant field.\n\nWhen used with stacked column and bar charts, data labels show the sum of all series in each column or bar.\n\n## Examples\n\n### Grouped Combo Chart\n\nThe following grouped combo chart shows the number of award nominations, wins, and metascores by director.\n\nThe X Axis category of `director` creates a group for each director in the data set, and each group is split by the Columns encoding channel fields of `nominations` and `wins`. The Lines encoding channel field of `metacritic` displays as a line:\n\n### Stacked Combo Chart\n\nThe following stacked combo chart shows the number of award nominations, wins, and metascores by director.\n\nThe X Axis category of `director` creates a column for each director in the data set, limited to only the top 10 as sorted by the aggregated sum of `awards.wins` from Columns. The Columns encoding channel fields of `nominations` and `wins` segment each column. The Lines encoding channel field of `metacritic` displays as a line:\n\n## Limitations\n\nThe maximum query response size for combo charts is 5000 documents."} -{"chunk_id": "68a95be05e79d242619d7eee-0", "page_id": "68a95be05e79d242619d7eee", "source_name": "charts", "product_name": "Atlas Charts", "url": "https://mongodb.com/docs/charts/dashboards/dashboard-access/dashboard-ownership", "title": "View and Manage Dashboard Owners", "text": "# View and Manage Dashboard Owners\n\nYou can view, add, or remove dashboard owners to any dashboard in your project.\n\n## Prerequisites\n\nYou must have the `Project Owner` role.\n\n## View Dashboard Owners\n\nTo view the owners of any dashboard in your project:\n\n### Go to Charts.\n\nIf Atlas Charts is not already displayed, click Visualization under the Services heading in the sidebar of the Atlas UI.\n\nAtlas launches an instance of Charts linked to your project.\n\n### Go to the Manage All Dashboards page for your project.\n\nIf the Manage All Dashboards page isn't already displayed, click Manage All Dashboards under the Settings heading in the sidebar.\n\nThe Manage All Dashboards page displays.\n\n### Review the Owners table.\n\nAtlas Charts displays a table with the following columns:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nColumn Name\n\n\nDescription\n\n
\nDashboard title\n\n\nTitle of the dashboard.\n\n
\nDashboard ID\n\n\n`ID` of the dashboard.\n\n
\nDashboard owners\n\n\nEmail associated with each dashboard owner.\n\nIf an existing dashboard owner was the only owner, and no longer has access to the project anymore, the Dashboard owners column will say `No owners`.\n\n
\nShare setting\n\n\nUsers who can access the dashboard in the project, identified by their level of access.\n\nPossible values are:\n\n- Private: The dashboard owner.\n\n- Project: Select users, or all users in the project.\n\n- Organization: Members in the same organization.\n\n- Public: Anyone with the link.\n\n To view the dashboard, click the button.\n\nTo learn more, see Dashboard Permissions and Sharing.\n\n
You can sort this table by the Dashboard title, or Share setting column.\n\n## Add a Dashboard Owner\n\nTo add a dashboard owner to a dashboard in your project:\n\n### Navigate to view dashboard owners.\n\n### Click the pencil icon for the dashboard you want to add an owner to.\n\n### Type the email of the person you want to make an owner of the dashboard.\n\nThis person must have at least `Viewer` permissions on the dashboard.\n\n### Click Save.\n\n## Remove a Dashboard Owner\n\nTo remove a dashboard owner from a dashboard in your project:\n\n### Navigate to view dashboard owners.\n\n### Click the pencil icon for the dashboard you want to remove an owner from.\n\n### Click the x next to the person's email that you want to remove.\n\nThere must be at least one dashboard owner.\n\n### Click Save."} -{"chunk_id": "68a95be05e79d242619d7edf-0", "page_id": "68a95be05e79d242619d7edf", "source_name": "charts", "product_name": "Atlas Charts", "url": "https://mongodb.com/docs/charts/chart-type-reference/candlestick-chart", "title": "Candlestick Charts", "text": "# Candlestick Charts\n\nYou can use candlestick charts to visualize how a numeric data source changes over time. A candlestick chart consists of vertical columns, or \"candles,\" that represent a range of your data source's opening and closing values over a period of time. If the closing value is higher or lower than the opening value, the column fills a certain color to indicate either a positive or negative change. Each column also might extend in either direction to show the highest and lowest values during the time period.\n\nBy observing the columns in your chart across consecutive periods of time, you can identify patterns in your data and make informed predictions. To learn about when you might use a candlestick chart, see Use Cases. To learn about all column chart types, see Column and Bar Charts.\n\n## Candlestick Chart Encoding Channels\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nEncoding Channel\n\n\nDescription\n\n
\nX Axis\n\n\nThe category encoding channel for your date field.\n\nThis channel creates a segment for each time period along the X axis based on the grouping that you select. By default, Atlas Charts enables binning to group date data into specific time periods. You can choose from the following bins:\n\n- Year\n\n- Month\n\n- Week of Year\n\n- Date of the Month\n\n- Day of the Week\n\n- Hour\n\n- Minute\n\n- Second\n\nFor certain bins, you can enable the Periodic setting to visualize the aggregated results for the time period across your data. To learn more, see Bin, Sort, and Limit Your Data.\n\n
\nY Axis\n\n\nThe value encoding channels for your numeric data. Charts requires the following values:\n\n- High, the highest value during each time period.\n\n- Open, the value at the start of each time period.\n\n- Close, the value at the end of each time period.\n\n- Low, the lowest value during each time period.\n\nTo define these values:\n\n- If you have one field that contains your numeric data, drag the same field onto each of the channels. Charts automatically calculates the high, open, close, and low values to build the chart.\n\n- If you have separate fields that represent the high, open, close, and low values for your data, drag each field onto their respective channel to build the chart.\n\n
\n\n## Use Cases\n\nCandlestick charts are useful for visualizing time series data when you want to analyze a numeric measurement that changes over time. This type of chart is commonly used in financial analysis to track the price of assets such as stocks, commodities, or currencies. However, you can use candlestick charts for various types of data to suit your specific needs.\n\nConsider the following examples:\n\n- A trading firm tracks the stock price of a specific company by hour to make a trading decision.\n\n- A weather company tracks rainfall, snowfall, and temperature by day to predict next week's forecast.\n\n- A store owner tracks the cost of a specific item by month to determine the best time to restock inventory.\n\n## Customization Options\n\nThe following customization options are specific to candlestick charts. To see all available customization options, see Customize Charts.\n\n### Customize Candlestick Color\n\nYou can customize the colors that correspond to a positive or negative change in your chart:\n\n1. Click the Customize tab for your chart.\n\n2. In the General section, enable the Custom Color Palette.\n\n3. In the dropdown next to Positive or Negative, use the color picker to select your desired color. To learn more, see Color Palette Customization.\n\n### Adjust X-Axis Label Angle\n\nYou can adjust the X-axis label angle to one of the following options:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nOption\n\n\nDescription\n\n
\nVertical\n\n\nLabels right-aligned at a 270 degree angle.\n\n
\nHorizonal\n\n\nLabels center-aligned at a 0 degree angle.\n\n
\nDiagonal\n\n\nLabels right-aligned at a 315 degree angle.\n\n
To set this option:\n\n1. Click the Customize tab for your chart.\n\n2. In the Axes section, select a Label Angle for the X Axis.\n\n## Example\n\nThe following chart visualizes the price of Bitcoin in US dollars as it changes every minute. The chart uses a time series collection called `ticker`, where each document in the collection represents a specific financial asset at a point in time. Each document includes information about the asset's ticker symbol, price, and time.\n\nTo show the exact data values in a tooltip, hover over the body of a column in the chart.\n\nThe X Axis category channel, represented by the `ticker.time` field, bins the numeric data by minute. The value encoding channels, represented by the `ticker.price` field, aggregate the high, open, close, and low prices during each minute to create the vertical columns in the chart.\n\nThe chart also uses query filters on the `ticker.symbol` and `ticker.time` fields to include only results with the `BTC-USD` symbol and limit the chart to an hour-long subset of the data.\n\nWhen the asset's closing price is higher than its opening price during a given minute, the column fills green to indicate a positive change. When its closing price is lower than its opening price, the column fills red to indicate a negative change. Each column also might extend in either direction to show the highest and lowest prices during each minute. Based on your analysis of the chart, you might make a decision to purchase, hold, or sell the asset."} -{"chunk_id": "68a95be05e79d242619d7f14-0", "page_id": "68a95be05e79d242619d7f14", "source_name": "charts", "product_name": "Atlas Charts", "url": "https://mongodb.com/docs/charts/embedding-charts", "title": "Embed Charts in Your Web Application", "text": "# Embed Charts in Your Web Application\n\nAs a dashboard Author, you can embed your charts and dashboards in external websites or share them through links. You can embed the following charts or dashboards:\n\n- Embed a chart or dashboard that doesn't require authentication (unauthenticated), which anyone can view.\n\n- Embed a chart or dashboard that requires users to authenticate through an Embedding Authentication Provider.\n\nYou can control embedded charts programmatically with the Embedding SDK, or use static HTML with an iframe.\n\nIf a chart is on a dashboard that has embedding enabled, the Embed Chart option is automatically enabled. Therefore, you can't select the Embed chart option for charts within dashboards that have embedding enabled.\n\nTo learn how to embed charts in a web application, see the Embedding Tutorials.\n\nTo learn about what you can do with an embedded chart, see Embedded Chart Options and Filter Embedded Charts.\n\n## How Authentication Works\n\nWhen you visit a webpage with an embedded chart, the Embedding SDK sends the chart ID and the user's token to Atlas Charts. Atlas Charts then validates the token with an authentication provider.\n\nIf the token is valid for the specified chart ID, Atlas Charts executes pipelines to the Atlas database with any specified injected filters and returns the data back to the user's webpage. If the token is invalid, the user cannot view the embedded chart."} -{"chunk_id": "68a95b1e5e79d242619c7261-0", "page_id": "68a95b1e5e79d242619c7261", "source_name": "cloud-docs", "product_name": "MongoDB Atlas", "url": "https://mongodb.com/docs/atlas/data-federation/supported-unsupported/limitations", "title": "Atlas Data Federation Query and Feature Limitations", "text": "# Atlas Data Federation Query and Feature Limitations\n\nThis page consolidates Atlas Data Federation limitations and operational behaviors with detailed guidance on connections, performance, and provider-specific recommendations.\n\nAtlas Online Archive depends on Atlas Data Federation. For limitations specific to Online Archive, see Limitations.\n\n## General Limitations\n\n### Unsupported Features\n\n- You cannot create indexes on federated data sources.\n\n- Supported authentication methods are limited to SCRAM, X.509 Certificates, OIDC, and AWS IAM .\n\n- Atlas monitoring tools do not cover Federated Database Instances.\n\n- The federated database instance can use object storage from only *one cloud provider* and from only *one account* within that provider.\n\n- Change streams and multi-document ACID transactions are not supported on federated sources.\n\n### Document Size and Result Ordering\n\n- Federated database instances don't support documents larger than 16 MB.\n\n- Returned document order is not guaranteed unless enforced (for example, with `$sort`).\n\n### Source and Region Considerations\n\n- Each federated database instance runs in a specific cloud and region.\n\n- Archived data stays in the provider's private network.\n\n- Object storage sources are *read-only*.\n\n## Connection Limits and Concurrency\n\n### Client Connections per Region\n\n- Up to *120 guaranteed simultaneous client connections* per region are supported.\n\n### Concurrent Queries\n\n- Running more than *30 simultaneous queries* on an federated database instance is not supported.\n\n- If you exceed the simultaneous query limit, Atlas Data Federation returns an error with the `ResourceExhausted` error code (`402`).\n\nIf your aggregation pipeline only contains the $currentOp stage, Atlas Data Federation doesn't enforce the limit on the maximum number of simultaneous queries. You can run queries that only contain the $currentOp stage even after you reach the maximum number of simultaneous queries.\n\n### Query Timeout\n\nQueries sent to MongoDB Atlas Data Federation have a time limit of 6 hours. If maxTimeMS is set up, then the query timeout is the minimum of these two values, for example: `min(maxTimeMS, 6 hours)`.\n\n### Instance Count per Project\n\n- Each project supports up to *25 federated database instances* by default.\n\n- Contact your product representative to increase the limit to up to *100 federated database instances*\n\n## Provider-Specific Recomendations\n\n\n\n\n\n\n\n\n\n\n\n
\nSupported storage\n\n\nAmazon S3\n\n
\n\n
\n\n\n\n\n\n\n\n\n\n
\nSupported storage\n\n\nBlob Storage\n\n
\n\n
\n\n\n\n\n\n\n\n\n\n
\nSupported storage\n\n\nGoogle Cloud Storage.\n\n
\n\n
\n\n
"} -{"chunk_id": "6a30eca24dab95504c2076fc-0", "page_id": "6a30eca24dab95504c2076fc", "source_name": "cloud-docs", "product_name": "MongoDB Atlas", "url": "https://mongodb.com/docs/atlas/metrics-ui-rollout", "title": "New Atlas Metrics UI", "text": "# New Atlas Metrics UI\n\nThe new Metrics UI is rolling out gradually to select new Atlas organizations. During this rollout, the experience is available only for eligible organizations and may continue to evolve.\n\n## Overview\n\nThe new Metrics UI is a major redesign of the project-level Atlas metrics experience that provides a unified view of cluster health and performance. The redesigned interface consolidates hardware metrics, MongoDB process metrics, DBStats, search-node metrics, and sharding metrics from the cluster level down to individual nodes.\n\nKey improvements include:\n\n- **Unified metrics view**: Access hardware, MongoDB, DBStats, search-node, and sharding metrics for the entire cluster in a single, integrated interface. Replaces the previous experience of navigating between separate pages for cluster, shard, and host-level metrics.\n\n- **Enhanced filtering**: Filter metrics by nodes, shards, time ranges, and specific metric categories.\n\n- **Improved navigation**: Navigate to metrics through redesigned cluster-level top navigation alongside updated Real-Time Performance Panel (RTPP) and host-ping navigation.\n\n- **Event overlays**: View database events directly on metric charts to correlate performance changes with system events.\n\n- **Flexible display options**: Toggle between list and table views, adjust chart settings, and customize your monitoring experience.\n\n## Availability\n\nThe new Metrics UI is currently available only for:\n\n- **Select new Atlas organizations**: Organizations created during the gradual rollout automatically use the new Metrics UI.\n\n- **Atlas cloud deployments**: The new Metrics UI applies to Atlas project-level metrics pages. It does not affect Cloud Manager, production government environments, Atlas Internal, or Free or Flex tier metrics pages.\n\nExisting Atlas projects continue to use the legacy Metrics UI. The new Metrics UI will become available to additional organizations and projects over time.\n\n## Switch to the Legacy Metrics UI\n\nIf your organization has access to the new Metrics UI, you can switch back to the legacy Metrics UI on a per-user basis:\n\n### Navigate to the new Metrics UI.\n\nWhen you access the Metrics page for a cluster, an information banner displays with the option to switch to the legacy view.\n\n### Click SWITCH BACK TO LEGACY VIEW.\n\nYou are redirected to the legacy Metrics UI. Your preference is stored in your browser and persists across sessions.\n\nTo use the new Metrics UI again, clear your browser cache or click the option to switch back when viewing the legacy Metrics UI.\n\n## Access the New Metrics UI\n\nTo access metrics using the new UI:\n\n### In Atlas, go to the Clusters page for your project.\n\n- If it's not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.\n\n- If it's not already displayed, select your desired project from the Projects menu in the navigation bar.\n\n- In the sidebar, click Clusters under the Database heading.\n\nThe Clusters page displays.\n\n### Open the cluster metrics.\n\nClick the name of the cluster to open the Cluster sidebar, then click Metrics.\n\nAlternatively, you can Quickly Navigate with Atlas Goto and type `metrics` to navigate directly to the Metrics view for the current cluster.\n\nThe new Metrics UI displays with enhanced navigation and filtering controls at the top of the page.\n\n### Cluster-Level Navigation Changes\n\nWith the Metrics page now available at the cluster level, related monitoring pages are now available from the cluster-level secondary navigation to improve discoverability:\n\nThe Real-Time Performance Panel is now accessible from cluster-level navigation. It includes a node filter to view real-time information per node.\n\nThese pages, previously dependent on metrics page navigation, are now available in the cluster-level secondary navigation.\n\nThe consolidated navigation makes it easier to access all monitoring and performance tools from a single location within each cluster.\n\n## New Features and Capabilities\n\nThe new Metrics UI introduces several enhanced capabilities:\n\n### Chart Legend and Layout\n\nEach chart group displays a legend at the bottom of the group. The legend remains sticky on the page as long as the chart group is in view. Tooltip values appear in descending order for easier comparison.\n\n### Filtering and Selection\n\nFilter metrics to specific shards or individual nodes within your cluster.\n\nFor both sharded clusters and replica set clusters:\n\n- The filter defaults to primary series for first-time users.\n\n- Your selection is retained for subsequent visits.\n\n- Shard and node names use abstracted naming (not full hostnames).\n\n- Select individual nodes or view metrics across all nodes.\n\n- The legacy UI also has a node filter with similar capabilities.\n\nFor search nodes with decoupled search architecture:\n\n- Search nodes appear separately in the selector.\n\n- Search node names follow the pattern: `search-{shardNo}-{randomString}`.\n\n- Search nodes are identified with a distinct icon.\n\n- Select search nodes individually or use Select All for quick selection.\n\nSet custom date and time ranges for metrics display. The interface supports both preset time ranges (last hour, last day, and so on) and custom date or time selection.\n\nAdd or remove metric groups from the dashboard using the metrics selector.\n\n- **Metrics organization**: The metrics selector organizes metric groups into categories, all expanded by default.\n\n- **Default selection**: The Essential category displays by default for first-time users.\n\n- **Persistent selection**: The UI retains your selected metrics for subsequent visits.\n\n- **Add metric groups**: Select a metric group to add a chart card with that group's metrics to the dashboard. Each group typically contains multiple charts.\n\n- **Individual chart selection**: Use the group-level selector within a chart card to add or remove individual charts from the group.\n\n- **Metric descriptions**: Hover over any metric to see its description in the right panel. The default state shows category descriptions.\n\n- **Search functionality**: Search filters all categories except Essential, which contains metrics duplicated from other categories.\n\nControl how metric values are aggregated and displayed:\n\n- **Sum**: Display the sum of metric values.\n\n- **Average**: Display averaged values. The legend, chart, and tooltip update accordingly.\n\n- **Max**: Display maximum values.\n\n- **Sum by shard**: Display the sum of metric values grouped by shard.\n\n- **Average by shard**: Display averaged values grouped by shard.\n\n- **Max by shard**: Display maximum values grouped by shard.\n\nThe \"by shard\" options aggregate data at the shard level and display one series per shard based on your host selections. Changing the display data setting updates all chart displays, legends, and tooltips accordingly.\n\nToggle event overlays to display database events directly on metric charts. The new Metrics UI includes the same event overlays available in the legacy UI:\n\n- **Host Restart**: Displays on the time series line for the affected node.\n\n- **Elections**: Displays on the time series line for the affected node.\n\nEvent details appear in tooltips when you hover on the specific point.\n\n### Display Controls\n\nAccess chart granularity settings through the settings drawer.\n\n## Metrics Coverage\n\nThe new Metrics UI provides comprehensive monitoring across multiple metric categories:\n\n### Hardware Metrics\n\nHardware metrics display system-level performance data for the hosts supporting your cluster:\n\n- CPU utilization and process CPU.\n\n- Memory usage and available memory.\n\n- Disk IOPS, disk space, and disk latency.\n\n- Network throughput (bytes in or out).\n\n- System CPU and normalized CPU metrics.\n\nAll hardware metrics have burst reporting equivalents with distinct configurable alerts. To learn more, see Burst Reporting."} -{"chunk_id": "6a30eca24dab95504c2076fc-1", "page_id": "6a30eca24dab95504c2076fc", "source_name": "cloud-docs", "product_name": "MongoDB Atlas", "url": "https://mongodb.com/docs/atlas/metrics-ui-rollout", "title": "New Atlas Metrics UI", "text": "### MongoDB Metrics\n\nMongoDB process metrics show database server performance:\n\n- Operations per second (opcounters).\n\n- Connections (current and available).\n\n- Query execution metrics.\n\n- Replication lag and oplog metrics.\n\n- Cursor statistics.\n\n- Document metrics for inserted, updated, deleted, and returned documents.\n\n- Cache metrics.\n\n- Queue metrics.\n\n- Assert metrics.\n\n- Page fault metrics.\n\n- MongoDB memory metrics.\n\n- MongoDB network metrics.\n\n### Database Statistics (DBStats)\n\nDatabase-level statistics provide storage and collection metrics:\n\n- Database and collection sizes.\n\n- Index sizes.\n\n- Document counts.\n\n- Data size and storage size.\n\n- Number of collections, indexes, and views.\n\n**Database Selector**: Use the database selector dropdown to choose which database to view metrics for. The `local` database is selected by default.\n\nDatabase statistics are collected at regular intervals. For collection frequency and performance impact information, see Review MongoDB Processes.\n\n### Search Node Metrics\n\nThe new UI displays the full suite of search metrics regardless of search deployment type:\n\n- Search node hardware metrics.\n\n- Search-specific process metrics.\n\n- Search index performance data.\n\n- Resource utilization for search workloads.\n\n- Search opcounters.\n\n- Replication lag for search nodes.\n\n- Index statistics (total number and performance metrics).\n\nFor **dedicated search nodes** (decoupled search architecture), search nodes appear as selectable nodes in the topology selector. You can view hardware metrics for these nodes in addition to search-specific metrics.\n\nFor **colocated search processes**, search metrics display based on the selected host. When you select a host with a colocated `mongot` process, the search metrics reflect that process.\n\n### Analytics Node Metrics\n\nAnalytics node visibility includes:\n\n- Analytics node hardware performance.\n\n- Query performance on analytics nodes.\n\n- Resource consumption metrics.\n\n### Sharding Metrics\n\nFor sharded clusters, a dedicated Sharding Metrics category displays:\n\n- Shard data distribution.\n\n- Shard collection counts.\n\n- Cluster collection counts.\n\n- `mongos` router metrics.\n\nSharded clusters can aggregate metrics by shard using the \"by shard\" display options. The same charts are available for both sharded and replica set clusters.\n\n## Behavioral Differences from Legacy UI\n\nThe new Metrics UI includes several behavioral changes compared to the legacy interface:\n\n### Node and Primary or Secondary Filtering\n\nThe new UI provides consistent node selection across both sharded and replica set clusters:\n\n- Select individual nodes or multiple nodes simultaneously.\n\n- Filter by shard membership.\n\n- Visual indicators show node roles: primary, secondary, or arbiter.\n\n- Both topologies use the same filtering interface with additional hierarchy for sharded clusters.\n\nThe legacy UI's Toggle Members control is replaced with the Shards and Nodes filter.\n\n**Primary or Secondary Series**: Select between viewing metrics for primary or secondary nodes across elections. This option allows you to track metrics consistently for a specific node role, even when nodes change roles during elections. For example, selecting \"Primary Series\" displays metrics for whichever node is currently primary, maintaining continuity across role changes.\n\n**Node Naming**: In the new Metrics UI for Atlas, shard and node names are abstracted rather than showing full hostnames. Abstracted names improve readability and focus on logical cluster structure. For example:\n\n- Shard names appear as `-shard-0`, `-shard-1`, and so on, where the cluster alias may be abbreviated if long.\n\n- Search nodes appear as `search-{shardNo}-{randomString}`.\n\n- Node names use shortened identifiers instead of full Atlas hostnames.\n\nChart legends and tooltips use these abbreviated node names for cleaner displays. You can copy full hostnames using the copy button in the chart legend.\n\n### Event Overlays\n\nEvent overlays can be toggled on or off and synchronize across all charts. The new Metrics UI includes Host Restart and Elections events that display on the time series lines for affected nodes.\n\n### Chart Interaction\n\nEnhanced chart interactions include:\n\n**Zoom Controls**:\n\n- **Zoom in**: Click and drag across a time range on any chart to zoom in.\n\n- **Zoom out**: Use the top-level date and time or time range selectors to adjust the view.\n\n**Chart Group Actions**:\n\n- **Expand/Collapse**: Expand a chart group to show all metrics, or collapse it to save space.\n\n- **Metric Description**: Click the info icon to open a modal with detailed metric descriptions.\n\n- **Close Chart Group**: Remove an entire group of related metrics from the dashboard.\n\n- **Collapsed State**: When collapsed, chart groups show summary information while taking up minimal space.\n\n**Individual Chart Actions**:\n\n- **Close Chart**: Remove an individual chart from a chart group.\n\n**Performance Improvements**:\n\n- Better mobile and tablet responsiveness.\n\n- Smoother chart rendering and transitions.\n\n- Optimized for scrolling through many charts.\n\n### Empty State Messaging\n\nWhen database statistics collection is disabled, the new UI displays:\n\n- Clear empty state messages explaining why data is unavailable.\n\n- Direct links to enable collection in project settings.\n\n- Guidance on the performance impact of enabling collection.\n\n## Limitations and Scope\n\nThe following limitations apply during the gradual rollout:\n\n### Supported Deployment Types\n\n- The new Metrics UI is available for standard Atlas dedicated clusters (M10 and above).\n\n- Free (M0) clusters use separate metrics interfaces.\n\n- Flex clusters have their own dedicated metrics view.\n\n### Environment Scope\n\nThe new Metrics UI applies only to:\n\n- Atlas cloud-hosted deployments.\n\n- Project-level metrics pages.\n\nIt does not affect:\n\n- Cloud Manager metrics interfaces.\n\n- MongoDB production government environments.\n\n- Atlas Internal metrics.\n\n## Next Steps\n\n- Review Replica Set Metrics to learn about monitoring replica set clusters.\n\n- Review Sharded Cluster Metrics to learn about monitoring sharded deployments.\n\n- Review Available Metrics for a complete list of available metrics and their descriptions.\n\n- Configure Alerts to receive notifications when metrics exceed specified thresholds."} -{"chunk_id": "6a800685b5390a970aab5eb9-0", "page_id": "6a800685b5390a970aab5eb9", "source_name": "cloud-docs", "product_name": "MongoDB Atlas", "url": "https://mongodb.com/docs/atlas/backup/cloud-backup/export/google-cloud-storage", "title": "Export Cloud Backup Snapshots to Google Cloud Storage", "text": "# Export Cloud Backup Snapshots to Google Cloud Storage\n\nThis feature is available for `M10` clusters or higher. To learn more about which features are available for Free clusters, see Atlas Free Cluster Limits, and for Flex clusters, see Atlas Flex Limitations.\n\nAtlas lets you export your Cloud Backup snapshots to Google Cloud Storage buckets automatically or manually. To configure and run exports, use the procedure that matches the type of export that you want:\n\n- To automatically export snapshots as your backup policy creates them, see Export Snapshots Automatically.\n\n- To manually export a single existing snapshot, see Export a Single Snapshot Manually.\n\nEach procedure requires the same prerequisites.\n\nFor an overview of how Atlas exports snapshots and the files it uploads, see Export Cloud Backup Snapshots to Object Storage.\n\n## Limitations\n\nYou can't perform the following actions:\n\n- Export fallback snapshots.\n\n- Have more than one active export per snapshot.\n\n- Export view collections, or system collections, except for `.system.js` collections.\n\n- Export snapshots from clusters in an Atlas project that has Encryption at Rest using Customer Key Management enabled with network access restricted to specific IP addresses. This restriction doesn't apply if Atlas reaches your KMS (Key Management Service) through a private endpoint. To learn how to configure a private endpoint to your KMS (Key Management Service), see the AWS instructions or the Azure instructions.\n\n- Export snapshots over Private Endpoints (private exports) for Azure (Microsoft Azure) or Google Cloud clusters.\n\n- Export snapshots taken from MongoDB versions that have reached end of life (EOL). See the MongoDB Software Lifecycle Schedules for version EOL dates.\n\n- Export snapshots to an Azure (Microsoft Azure) storage account if its firewall rules block public access.\n\n## Required Access\n\n- To create or manage a Cloud Backup export schedule or configure a Cloud Backup export bucket in Atlas, you must have `Project Backup Manager` or `Project Owner` to the project.\n\n- To create or manage a Cloud Backup export job, you must have `Project Backup Export Operator` or `Project Owner` access to the project.\n\n- To create or manage a Cloud Backup object storage private endpoint, you must have `Project Owner` access to the project.\n\n## Configure and Run Exports\n\n### Prerequisites\n\nTo export your Cloud Backup snapshots, you need an `M10` or higher Atlas cluster with Cloud Backup enabled. In addition, to set up Atlas access to your object store, you must do the following:\n\n1. Set up Google Cloud Service access.\n\n2. Locate the ID of your Google Cloud service account in Atlas by following the steps in View Authorized Google Cloud Service Accounts.\n\n3. In your Google Cloud console, add the service account ID from the previous step as a principal to your bucket's policy by following the Google Cloud documentation.\n\n This grants the Storage Object User role to the service account for your specific Google Cloud Storage bucket."} -{"chunk_id": "6a800685b5390a970aab5eb9-1", "page_id": "6a800685b5390a970aab5eb9", "source_name": "cloud-docs", "product_name": "MongoDB Atlas", "url": "https://mongodb.com/docs/atlas/backup/cloud-backup/export/google-cloud-storage", "title": "Export Cloud Backup Snapshots to Google Cloud Storage", "text": "### Export Snapshots Automatically\n\nTo create an export policy for automatic exports, run the following procedure:\n\n#### Create an export bucket configuration in Atlas\n\nBefore you can configure an export bucket in Atlas, complete the prerequisites to set up Atlas access to your Google Cloud Storage bucket.\n\nTo enable Atlas to export Cloud Backup snapshots to Google Cloud Storage, create an export bucket configuration in Atlas that references an existing Google Cloud Storage bucket.\n\nTo create the bucket configuration, use the atlas api cloudBackups createExportBucket Atlas CLI command. Include the following fields in the command's request body file:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nRequest Body Field\n\n\nValue\n\n\nNecessity\n\n
\n`cloudProvider`\n\n\n`GCP`\n\n\nRequired\n\n
\n`bucketName`\n\n\nName of the Google Cloud Storage Bucket that is authorized to receive Atlas Cloud Backup snapshots. To set up Atlas access to this bucket, see the Prerequisites section.\n\n\nRequired\n\n
\n`roleId`\n\n\nUnique 24-hexadecimal digit string that identifies the Google Cloud Provider Access Role that Atlas uses to access the Google Cloud Storage bucket.\n\n\nRequired\n\n
The response returns the bucket ID value (`_id`), which you need to reference when you create a snapshot export job or configure automatic snapshot exports.\n\n#### Add an export policy to your Cloud Backup schedule\n\nTo set up automatic exports for your Cloud Backup snapshots, add an export policy to your Cloud Backup schedule. An export policy specifies the export bucket and frequency type for snapshots to export. The frequency type can be `daily`, `weekly`, `monthly`, or `yearly`.\n\nAtlas doesn't export every snapshot automatically. Atlas exports only the snapshots that a backup policy item creates with the same frequency type that you specify in the export policy.\n\nTo create an export policy, use the atlas api cloudBackups updateBackupSchedule command and include the following fields in the request body file:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nRequest Body Field\n\n\nValue\n\n
\n`autoExportEnabled`\n\n\n`true`. This enables Atlas to export Cloud Backup Snapshots to the Export Bucket configured in `export`.\n\n
\n`export.exportBucketId`\n\n\nUnique identifier of the export bucket configuration that references the object storage location to export the backup snapshot to.\n\nTo retrieve the ID for your export bucket configuration, see Manage Snapshot Export.\n\n
\n`export.frequencyType`\n\n\nFrequency associated with the backup policy item that you want to export snapshots from. Value can be `daily`, `weekly`, `monthly`, or `yearly`.\n\n
Consider the following Cloud Backup policy that sets a weekly and monthly snapshot schedule:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nFrequency Unit\n\n\nEvery\n\n\nRetention Time\n\n\nSnapshot Time\n\n
\nWeekly\n\n\nSunday\n\n\n12:30 UTC\n\n\n7 days\n\n
\nMonthly\n\n\nLast day of month\n\n\n12:30 UTC\n\n\n6 weeks\n\n
To enable automatic export of snapshots with a `monthly` frequency type, run the atlas api cloudBackups updateBackupSchedule command with the following request body file:\n\n```json\n{\n \"autoExportEnabled\": true,\n \"export\": {\n \"exportBucketId\": \"32b6e34b3d91647abb20e7b8\",\n \"frequencyType\": \"monthly\"\n }\n}\n```\n\nWith this setup, Atlas exports the snapshot that is taken on the last day of each month because its frequency type matches the `export` frequency type.\n\n#### Create an export bucket configuration in Atlas\n\nBefore you can configure an export bucket in Atlas, complete the prerequisites to set up Atlas access to your Google Cloud Storage bucket.\n\nTo enable Atlas to export Cloud Backup snapshots to Google Cloud Storage, create an export bucket configuration in Atlas that references an existing Google Cloud Storage bucket.\n\nTo create the bucket configuration, send a `POST` request to the Cloud Backup Create One Snapshot Export Bucket endpoint. Include the following fields in your request body:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nRequest Body Field\n\n\nValue\n\n\nNecessity\n\n
\n`cloudProvider`\n\n\n`GCP`\n\n\nRequired\n\n
\n`bucketName`\n\n\nName of the Google Cloud Storage Bucket that is authorized to receive Atlas Cloud Backup snapshots. To set up Atlas access to this bucket, see the Prerequisites section.\n\n\nRequired\n\n
\n`roleId`\n\n\nUnique 24-hexadecimal digit string that identifies the Google Cloud Provider Access Role that Atlas uses to access the Google Cloud Storage bucket.\n\n\nRequired\n\n
The response returns the bucket ID value (`_id`), which you need to reference when you create a snapshot export job or configure automatic snapshot exports.\n\n#### Add an export policy to your Cloud Backup schedule\n\nTo set up automatic exports for your Cloud Backup snapshots, add an export policy to your Cloud Backup schedule. An export policy specifies the export bucket and frequency type for snapshots to export. The frequency type can be `daily`, `weekly`, `monthly`, or `yearly`.\n\nAtlas doesn't export every snapshot automatically. Atlas exports only the snapshots that a backup policy item creates with the same frequency type that you specify in the export policy.\n\nTo create an export policy, send a `PATCH` request to the Cloud Backup Update Group Cluster Backup Schedule endpoint and include the following fields in the request body:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nRequest Body Field\n\n\nValue\n\n
\n`autoExportEnabled`\n\n\n`true`. This enables Atlas to export Cloud Backup Snapshots to the Export Bucket configured in `export`.\n\n
\n`export.exportBucketId`\n\n\nUnique identifier of the export bucket configuration that references the object storage location to export the backup snapshot to.\n\nTo retrieve the ID for your export bucket configuration, see Manage Snapshot Export.\n\n
\n`export.frequencyType`\n\n\nFrequency associated with the backup policy item that you want to export snapshots from. Value can be `daily`, `weekly`, `monthly`, or `yearly`.\n\n
Consider the following Cloud Backup policy that sets a weekly and monthly snapshot schedule:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nFrequency Unit\n\n\nEvery\n\n\nRetention Time\n\n\nSnapshot Time\n\n
\nWeekly\n\n\nSunday"} -{"chunk_id": "6a800685b5390a970aab5eb9-2", "page_id": "6a800685b5390a970aab5eb9", "source_name": "cloud-docs", "product_name": "MongoDB Atlas", "url": "https://mongodb.com/docs/atlas/backup/cloud-backup/export/google-cloud-storage", "title": "Export Cloud Backup Snapshots to Google Cloud Storage", "text": "\n12:30 UTC\n\n\n7 days\n\n
\nMonthly\n\n\nLast day of month\n\n\n12:30 UTC\n\n\n6 weeks\n\n
This policy takes a snapshot every Sunday and on the last day of each month. If the last day of the month falls on a Sunday, the policy takes one snapshot for that day.\n\nTo enable automatic export of snapshots with a `monthly` frequency type, send a `PATCH` request to the Cloud Backup Update Group Cluster Backup Schedule endpoint with the following request body:\n\n```json\n{\n \"autoExportEnabled\": true,\n \"export\": {\n \"exportBucketId\": \"32b6e34b3d91647abb20e7b8\",\n \"frequencyType\": \"monthly\"\n }\n}\n```\n\nWith this setup, Atlas exports the snapshot that is taken on the last day of each month because its frequency type matches the `export` frequency type.\n\n#### In Atlas, go to the Backup details for your project.\n\n- If it's not already displayed, select the organization that contains your project from the Organizations menu in the navigation bar.\n\n- If it's not already displayed, select your project from the Projects menu in the navigation bar.\n\n- In the sidebar, click Backup under the Database heading.\n\n The Backup details display.\n\n- Click the cluster link.\n\n#### Create an export bucket configuration in Atlas.\n\nBefore you can configure an export bucket in Atlas, complete the prerequisites to set up Atlas access to your Google Cloud Storage bucket.\n\nTo enable Atlas to export Cloud Backup snapshots to Google Cloud Storage, create an export bucket configuration in Atlas that references an existing Google Cloud Storage bucket. To learn more about setting up Atlas access to your Google Cloud Storage bucket, see Set Up and Manage Google Cloud Service Account Access.\n\n- In the Backup Policy tab, go to the Snapshot Export Policy section and click + Add Storage Destination.\n\n This displays a dialog box with the cloud provider options for your export bucket configuration.\n\n- Select Google Cloud as the cloud provider and click Next.\n\n- Under Atlas GCP Service Account, select an existing service account.\n\n If you don't have an existing service account, click authorize a new one and complete Google Cloud Provider Access setup. To learn more, see Set Up and Manage Google Cloud Service Account Access.\n\n- Enter the following information and click Next:\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
\n Field\n\n \n Value\n\n \n Necessity\n\n
\n Service Account\n\n \n Name of the Google Cloud Service Account that you created in the prerequisites.\n\n \n Required\n\n
\n GCP bucket name\n\n \n Name of the Google Cloud Storage Bucket that is authorized to receive Atlas Cloud Backup snapshots. To set up Atlas access to this bucket, see the Prerequisites section.\n\n \n Required\n\n
\n\n- On the Attach Policy step, confirm that the bucket access role is granted to your Google Cloud Service Account.\n\n You granted this role when you completed the prerequisites. Compare the commands that Grant bucket access using the Google Cloud Console and Verify access display to the roles granted to your Service Account. If the grants differ, run the commands to update them.\n\n- Select I confirm I completed the required steps and click Add bucket.\n\n Your configuration resembles the following:\n\n ```json\n {\n \"bucketName\": \"\",\n \"cloudProvider\": \"GCP\",\n \"roleId\": \"\"\n }\n ```\n\n This adds the export bucket configuration to your Atlas project.\n\n#### Add an export policy to your Cloud Backup schedule.\n\nTo set up automatic exports for your Cloud Backup snapshots, add an export policy to your Cloud Backup schedule. An export policy specifies the export bucket and frequency type for snapshots to export. The frequency type can be `daily`, `weekly`, `monthly`, or `yearly`.\n\nAtlas doesn't export every snapshot automatically. Atlas exports only the snapshots that a backup policy item creates with the same frequency type that you specify in the export policy.\n\nTo add an export policy:\n\n- In the Backup Policy tab, go to the Snapshot Export Policy section.\n\n- Under Export Schedule, click + Add Export Schedule.\n\n- From the Snapshots dropdown, select the frequency of the snapshots that you want to export.\n\n- From the Export Buckets dropdown, select the export bucket that you want to use.\n\n- Click Review Changes.\n\n- Click Confirm to apply your changes."} -{"chunk_id": "6a800685b5390a970aab5eb9-3", "page_id": "6a800685b5390a970aab5eb9", "source_name": "cloud-docs", "product_name": "MongoDB Atlas", "url": "https://mongodb.com/docs/atlas/backup/cloud-backup/export/google-cloud-storage", "title": "Export Cloud Backup Snapshots to Google Cloud Storage", "text": "### Export a Single Snapshot Manually\n\nTo create an export job for a single snapshot, run the following procedure:\n\n#### Create an export bucket configuration in Atlas\n\nBefore you can configure an export bucket in Atlas, complete the prerequisites to set up Atlas access to your Google Cloud Storage bucket.\n\nTo enable Atlas to export Cloud Backup snapshots to Google Cloud Storage, create an export bucket configuration in Atlas that references an existing Google Cloud Storage bucket.\n\nTo create the bucket configuration, use the atlas api cloudBackups createExportBucket Atlas CLI command. Include the following fields in the command's request body file:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nRequest Body Field\n\n\nValue\n\n\nNecessity\n\n
\n`cloudProvider`\n\n\n`GCP`\n\n\nRequired\n\n
\n`bucketName`\n\n\nName of the Google Cloud Storage Bucket that is authorized to receive Atlas Cloud Backup snapshots. To set up Atlas access to this bucket, see the Prerequisites section.\n\n\nRequired\n\n
\n`roleId`\n\n\nUnique 24-hexadecimal digit string that identifies the Google Cloud Provider Access Role that Atlas uses to access the Google Cloud Storage bucket.\n\n\nRequired\n\n
The response returns the bucket ID value (`_id`), which you need to reference when you create a snapshot export job or configure automatic snapshot exports.\n\n#### Create a snapshot export job\n\nTo export one Atlas backup snapshot, use the atlas api cloudBackups createBackupExport command with the ID of the snapshot to export and the ID of the export bucket from your export bucket configuration. This creates a snapshot export job that exports the specified snapshot to the specified bucket.\n\nTo list possible snapshots to export, use the atlas backups snapshots list command with your cluster name and project ID. To list possible export buckets, use the atlas api cloudBackups listExportBuckets command with your project ID.\n\n#### Create an export bucket configuration in Atlas\n\nBefore you can configure an export bucket in Atlas, complete the prerequisites to set up Atlas access to your Google Cloud Storage bucket.\n\nTo enable Atlas to export Cloud Backup snapshots to Google Cloud Storage, create an export bucket configuration in Atlas that references an existing Google Cloud Storage bucket.\n\nTo create the bucket configuration, send a `POST` request to the Cloud Backup Create One Snapshot Export Bucket endpoint. Include the following fields in your request body:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nRequest Body Field\n\n\nValue\n\n\nNecessity\n\n
\n`cloudProvider`\n\n\n`GCP`\n\n\nRequired\n\n
\n`bucketName`\n\n\nName of the Google Cloud Storage Bucket that is authorized to receive Atlas Cloud Backup snapshots. To set up Atlas access to this bucket, see the Prerequisites section.\n\n\nRequired\n\n
\n`roleId`\n\n\nUnique 24-hexadecimal digit string that identifies the Google Cloud Provider Access Role that Atlas uses to access the Google Cloud Storage bucket.\n\n\nRequired\n\n
The response returns the bucket ID value (`_id`), which you need to reference when you create a snapshot export job or configure automatic snapshot exports.\n\n#### Create a snapshot export job\n\nTo export one Atlas backup snapshot, send a `POST` request to the Cloud Backups Create One Snapshot Export Job endpoint with the ID of the snapshot to export and the ID of your export bucket configuration. This creates a snapshot export job.\n\nTo list the possible snapshots to export, send a `GET` request to the Cloud Backups Return All Snapshots endpoint with your cluster name and project ID. To list possible export buckets and their IDs, send a `GET` request to the Cloud Backups Return All Export Buckets endpoint.\n\n#### In Atlas, go to the Backup details for your project.\n\n- If it's not already displayed, select the organization that contains your project from the Organizations menu in the navigation bar.\n\n- If it's not already displayed, select your project from the Projects menu in the navigation bar.\n\n- In the sidebar, click Backup under the Database heading.\n\n The Backup details display.\n\n- Click the cluster link.\n\n#### Create an export bucket configuration in Atlas.\n\nBefore you can configure an export bucket in Atlas, complete the prerequisites to set up Atlas access to your Google Cloud Storage bucket.\n\nTo enable Atlas to export Cloud Backup snapshots to Google Cloud Storage, create an export bucket configuration in Atlas that references an existing Google Cloud Storage bucket. To learn more about setting up Atlas access to your Google Cloud Storage bucket, see Set Up and Manage Google Cloud Service Account Access.\n\n- In the Backup Policy tab, go to the Snapshot Export Policy section and click + Add Storage Destination.\n\n This displays a dialog box with the cloud provider options for your export bucket configuration.\n\n- Select Google Cloud as the cloud provider and click Next.\n\n- Under Atlas GCP Service Account, select an existing service account.\n\n If you don't have an existing service account, click authorize a new one and complete Google Cloud Provider Access setup. To learn more, see Set Up and Manage Google Cloud Service Account Access.\n\n- Enter the following information and click Next:\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
\n Field\n\n \n Value\n\n \n Necessity\n\n
\n Service Account\n\n \n Name of the Google Cloud Service Account that you created in the prerequisites.\n\n \n Required\n\n
\n GCP bucket name\n\n \n Name of the Google Cloud Storage Bucket that is authorized to receive Atlas Cloud Backup snapshots. To set up Atlas access to this bucket, see the Prerequisites section.\n\n \n Required\n\n
\n\n- On the Attach Policy step, confirm that the bucket access role is granted to your Google Cloud Service Account.\n\n You granted this role when you completed the prerequisites. Compare the commands that Grant bucket access using the Google Cloud Console and Verify access display to the roles granted to your Service Account. If the grants differ, run the commands to update them.\n\n- Select I confirm I completed the required steps and click Add bucket.\n\n Your configuration resembles the following:\n\n ```json\n {\n \"bucketName\": \"\",\n \"cloudProvider\": \"GCP\",\n \"roleId\": \"\"\n }\n ```\n\n This adds the export bucket configuration to your Atlas project.\n\n#### Create a snapshot export job.\n\n- In the Snapshot tab, click the Actions menu for the snapshot that you want to export.\n\n This displays the snapshot details.\n\n- From the dropdown, select Export.\n\n This displays the Export Snapshot dialog box.\n\n- From the Export bucket dropdown, select the export bucket that you want to use.\n\n- Click Export.\n\n This starts the export job and displays the Exports tab.\n\n- Click Refresh to view the export job status."} -{"chunk_id": "68c3ba82bbfe6ebb95f933fb-0", "page_id": "68c3ba82bbfe6ebb95f933fb", "source_name": "cloud-docs", "product_name": "MongoDB Atlas", "url": "https://mongodb.com/docs/atlas/atlas-stream-processing/architecture", "title": "Atlas Stream Processing Architecture", "text": "# Atlas Stream Processing Architecture\n\n## Architecture Fundamentals\n\nThe core abstraction of Atlas Stream Processing is the stream processor. A stream processor is a MongoDB aggregation pipeline that operates continuously on streaming data from a specified source and writes the output to a sink. To learn more, see Structure of a Stream Processor.\n\nStream processing takes place on stream processing workspaces. Each stream processing workspace is an Atlas namespace that associates the following:\n\n- One or more stream processors, each running on its own allocation of RAM and CPUs.\n\n- A default tier, which determines the amount of memory and compute available to each stream processor when you don't specify a tier.\n\n- A maximum tier, which determines the highest amount of memory and compute that you can allocate to a pod within that stream processing workspace.\n\n- A cloud provider and cloud region.\n\n- A **connection registry**, which stores the list of available sources and sinks of streaming data.\n\n- A security context in which to define user authorizations.\n\n- A Connection String to the stream processing workspace itself.\n\n### Tiers\n\nWhen you define a stream processor, it becomes available only for the stream processing workspace in which you define it. Each stream processor runs on resources allocated according to its tier. Atlas Stream Processing bills users for a stream processor only while it's running.\n\nIf you start a stream processor without declaring a tier size, it will run the stream processing workspace's tier. You can start a stream processor of any tier up to and including the maximum tier of the stream processing workspace\n\nYou define a stream processor on a stream processing workspace named `myWorkspace` with a default tier of `SP10`, and a maximum tier of `SP50`. If you start the processor without specifying a tier, Atlas Stream Processing assigns it to an `SP10` pod. However, you can declare any tier from `SP2` up to `SP50` and Atlas Stream Processing will assign the processor to an appropriately sized pod.\n\nYou can adjust a stream processor's tier manually, or you can enable vertical autoscaling to let Atlas Stream Processing change the tier automatically in response to the processor's resource usage.\n\n### Connection Registry\n\nConnection registries store one or more connections. Each connection assigns a name to the combination of networking and security details that allow a stream processor to interact with external services. Connections exhibit the following behavior:\n\n- Only a connection defined in a given stream processing workspace's connection registry can service stream processors hosted on that stream processing workspace.\n\n- Each connection can service an arbitrary number of stream processors\n\n- Only a single connection can serve as a given stream processor's source.\n\n- Only a single connection can serve as a given stream processor's sink.\n\n- A connection is not innately defined as either a source or a sink. Any given connection can serve either function depending on how a stream processor invokes that connection.\n\nAtlas Stream Processing runs each stream processor in a dedicated customer container with VM-level isolation on multi-tenant infrastructure. For more information on MongoDB security and compliance, see the MongoDB Trust Center.\n\n## Checkpoints\n\nAtlas Stream Processing captures the state of a stream processor using checkpoints. Each checkpoint has a unique ID and are subject to the flow of your stream processor logic. After all operators of a stream processor add their state to a checkpoint, Atlas Stream Processing commits the checkpoint, generating two types of records:\n\n- A single commit record that validates the checkpoint ID and the stream processor to which it belongs\n\n- A set of records describing the state of each stateful operation in the relevant stream processor at the instant Atlas Stream Processing committed the checkpoint.\n\nWhen you restart a stream processor after an interruption, Atlas Stream Processing queries the last committed checkpoint and resumes operation from the described state.\n\nCheckpoints record source offsets rather than copies of source documents. For example, Atlas Stream Processing stores oplog resume tokens for change stream sources and partition offsets for Kafka sources. Deleting or expiring source documents after Atlas Stream Processing commits a checkpoint does not prevent the processor from resuming.\n\nIf the oplog resume token that Atlas Stream Processing stored in the last checkpoint is no longer in the source cluster's oplog when you restart the processor, Atlas Stream Processing cannot resume from that checkpoint. To recover, restart the processor with `resumeFromCheckpoint=false`. To reduce the risk of this, configure your source cluster with an adequate oplog window. To learn how to set an oplog window, see Set Minimum Oplog Window.\n\nWhen a member of your source replica set performs its own initial sync, MongoDB truncates the oplog on that member. This oplog truncation can impact processes such as change streams that depend on oplog data. To learn more, see Initial Sync and Change Streams.\n\n### Initial Sync\n\nFor change stream `$source` configurations with `initialSync` enabled, Atlas Stream Processing checkpoints both the initial sync phase, which copies the source collections, and the normal change event processing phase. During initial sync, Atlas Stream Processing records the starting oplog position and divides the source collections into partitions. The processor copies the existing documents through the partitions, then replays change events from the initial recorded position once the copy completes. Atlas Stream Processing creates checkpoints during initial sync, and the processor can resume if an interruption occurs.\n\nAtlas Stream Processing checkpoints initial sync for every supported `_id` type. Collections whose `_id` values Atlas Stream Processing can't read in a predictable order take longer to copy, but they remain as recoverable as collections that use `ObjectId` or ordered `int` or `long` values: an interrupted processor resumes from its last checkpoint rather than restarting the collection copy. For the `_id` types that `initialSync` supports and the oplog sizing that longer operations require, see Atlas Stream Processing Limitations.\n\n### Kafka Sources and Consumer Group Offsets\n\nAfter Atlas Stream Processing commits a checkpoint, it updates the consumer group offsets in Kafka asynchronously. When you use Apache Kafka as a `$source`, the consumer groups track these checkpoints as committed offsets in the Kafka cluster for each partition.\n\nBecause these updates happen periodically and asynchronously, the consumer group's committed offsets can temporarily lag behind the most recent checkpoint. This can cause short-term delays in monitoring and lag metrics for tools that read committed offsets from Kafka, such as the `kafka-consumer-group` CLI tool. These tools may show the consumer group \"behind\" the stream processor's true internal position.\n\nThe amount of lag between internal checkpoints and committed Kafka offsets is not fixed and can vary based on workload and configuration. In typical workloads it is on the order of seconds, but there is no strict upper bound.\n\n## Dead Letter Queue\n\nAtlas Stream Processing supports the use of an Atlas database collection as a dead letter queue (DLQ). When Atlas Stream Processing cannot process a document from your data stream, it writes the content of the document to the DLQ with details of the processing failure. You can assign a collection as a DLQ in your stream processor definitions.\n\nTo learn more about enabling DLQs, see Create a Stream Processor. To learn about the Atlas Stream Processing DLQ schema, see the Monitoring guide."} -{"chunk_id": "68c3ba82bbfe6ebb95f933fb-1", "page_id": "68c3ba82bbfe6ebb95f933fb", "source_name": "cloud-docs", "product_name": "MongoDB Atlas", "url": "https://mongodb.com/docs/atlas/atlas-stream-processing/architecture", "title": "Atlas Stream Processing Architecture", "text": "## Stream Processor States\n\nStream processors transition between different states throughout their lifecycle. Understanding these states helps you monitor and troubleshoot your stream processing operations.\n\nPossible states include:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nState\n\n\nDescription\n\n
\n`STARTED`\n\n\nThe stream processor is actively processing data and operating normally. This is the desired operational state where your processor consumes data from sources, applies transformations, and writes to sinks.\n\n
\n`STOPPED`\n\n\nThe stream processor has been manually stopped and is not processing data. To learn how to start a stream processor, see Start a Stream Processor.\n\n
\n`PROVISIONING`\n\n\nThe stream processor is in the process of allocating resources or scaling infrastructure.\n\n**Common causes include:**\n\n- Starting a new stream processor that requires additional resources\n\n- Scaling operations when using existing resources at capacity.\n\n- Infrastructure rebalancing during peak usage periods\n\n- Automatic resource provisioning triggered by workload demands\n\n- Stream Processing Workspace tier changes requiring resource reallocation\n\n**Potential impacts include:**\n\n- Temporary delay in stream processor startup (typically 2-5 minutes)\n\n- Brief interruption in data processing during transitions\n\nOnce provisioning completes, processes resume automatically. No data loss occurs, as Atlas Stream Processing preserves state through checkpoints.\n\n
\n`FAILED`\n\n\nThe stream processor has encountered an error that prevents it from running. This occurs due to user errors or configuration issues. For detailed information about failure causes and recovery, see Error Handling and Retry Policies.\n\n
Stream processors might appear intermittently in PROVISIONING state in monitoring dashboards as the system allocates resources. This is normal behavior during scaling operations. If a processor remains in PROVISIONING state for extended periods (>10 minutes), check your stream processing workspace resource limits and tier configuration.\n\n## Failover Processors\n\nAtlas Stream Processing provides high availability in the form of failover processors. A failover processor mirrors an active stream processor using checkpoint replication, enabling you to seamlessly resume stream processing from the latest state in the event of service interruption in your stream processing workspace's primary region. Atlas Stream Processing automatically synchronizes any changes you make to the active processor's aggregation pipeline to its failover processors.\n\nTo use failover processors you must:\n\n- Configure your processor with a tier of `SP10` or higher.\n\n- Configure one or more failover regions in the target stream processing workspace.\n\n- Configure the connections in your stream processing workspace to support failover regions. You can do this when you create the connection, or you can modify an existing connection to support failover regions. To learn how each connection type behaves across failover regions, see Failover Connections.\n\n- Configure one or more failover processors for your target stream processor. You can do this when you create the processor, or you can modify an existing processor to use failover processors.\n\nTo ensure that your stream processors continue processing after a failover, use a multi-region cluster with a node in the failover region within the same project as your stream processing workspace. Atlas Stream Processing doesn't block failover for single-region clusters, but MongoDB recommends multi-region clusters.\n\nYou can initiate one of three types of failover event:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nType\n\n\nDescription\n\n
\nGraceful\n\n\nShuts down an active processor, creates and copies a checkpoint, and resumes processing from the most recent checkpoint.\n\n
\nForced\n\n\nActivates the failover processor even if the active processor doesn't stop. By default, the failover processor resumes from the most recent checkpoint. Alternatively, if you can't perform a graceful failover, you can optionally clear the checkpoint.\n\n
\nDry Run\n\n\nTests the failover process without consuming data, allowing you to validate failover configuration before putting it into production.\n\n
\n\n### Failover Considerations\n\nYou can create failover regions for a stream processing workspace when you initially create the workspace, or you can modify an existing stream processing workspace to use failover regions.\n\nYou can trigger failover for individual processors, all processors within a given workspace, or for all processors with failover configured in a specified region.\n\nFailover processors guarantee at-least-once processing semantics.\n\nTo learn more about requirements and limitations of failover processors, see Limitations.\n\nTo learn about failover processor pricing, see the billing documentation.\n\n### Failover Connections\n\nFailover doesn't use a separate connection type. Each connection in your stream processing workspace has a name. For connection types that support regions, you can create a region-specific connection that has the same name and type as the original connection, with its own region and endpoint settings. You can create a region-specific connection only in a failover region configured on your stream processing workspace.\n\nConnections behave across failover regions as follows:\n\n- **Atlas cluster connections** are shared across all regions. You can't create a region-specific Atlas connection.\n\n- **`Apache Kafka `__ connections** are the only connection type that supports regions. Whether you need a region-specific connection depends on the connection's networking:\n\n - If the connection uses public networking, you can use it in every region without a region-specific connection.\n\n - If the connection uses Private Link or VPC peering, you must create a region-specific connection in each failover region that points to that region's endpoint. This includes Private Link connections that use mTLS, because the endpoints and keystores differ in each region.\n\nWhen you add failover regions to an existing stream processing workspace, Atlas Stream Processing assigns a region to your existing Apache Kafka connections.\n\nYou can't modify a connection while any stream processor that uses the connection is running.\n\nTo create a region-specific connection, use the Create One Failover Stream Connection endpoint, the Atlas CLI, Terraform, or the Atlas UI. You can't create or modify connections with `mongosh`.\n\n## Error Handling and Retry Policies\n\nAtlas Stream Processing implements comprehensive error handling and retry policies to ensure reliable stream processing. The system distinguishes between different types of errors and applies appropriate retry strategies based on the error classification."} -{"chunk_id": "68c3ba82bbfe6ebb95f933fb-2", "page_id": "68c3ba82bbfe6ebb95f933fb", "source_name": "cloud-docs", "product_name": "MongoDB Atlas", "url": "https://mongodb.com/docs/atlas/atlas-stream-processing/architecture", "title": "Atlas Stream Processing Architecture", "text": "### Error Classification\n\nAtlas Stream Processing classifies errors into two main categories:\n\n**User Errors**\n\nErrors caused by user configuration, data issues, or external service problems that are outside of Atlas Stream Processing's control. Examples include:\n\n- Invalid connection credentials\n\n- Network connectivity issues to external services\n\n- Malformed data that cannot be processed\n\n- Permission issues accessing external resources\n\n**Internal Errors**\n\nErrors that occur within the Atlas Stream Processing system itself, typically due to temporary infrastructure issues or service disruptions. These are considered the responsibility of the Atlas Stream Processing service to resolve.\n\n### Retry Behavior\n\nThe retry behavior varies based on the error classification:\n\n**User Error Retry Policy**\n\n- Atlas Stream Processing attempts to restart the stream processor a limited number of times over a 5-minute period\n\n- If all retry attempts fail within this timeframe, the stream processor transitions to a `FAILED` state\n\n- Some user errors are classified as non-retryable and immediately cause the processor to fail. Examples include:\n\n - `StreamProcessorWorkerOutOfMemory (418)`: Pipeline exceeds tier memory limits\n\n - `StreamProcessorInvalidOptions (420)`: Invalid pipeline syntax or configuration\n\n- You can manually restart a failed stream processor by calling the `start()` method\n\n**Internal Error Retry Policy**\n\n- Atlas Stream Processing continuously retries internal errors without a time limit\n\n- Internal errors trigger alerts to the Atlas Stream Processing engineering team\n\n- The system relies on automatic retry mechanisms to recover processors after internal issues are resolved\n\n- Stream processors automatically resume from their last checkpoint when restarted\n\n### Recovery Process\n\nWhen a stream processor encounters an error and requires a restart, the recovery process follows these steps:\n\n#### State preservation\n\nThe current state is preserved through the checkpoint mechanism.\n\n#### Restart attempt\n\nAtlas Stream Processing attempts to restart the processor according to the applicable retry policy.\n\n#### State recovery\n\nUpon successful restart, the processor resumes operation from the last committed checkpoint.\n\n#### Continued processing\n\nThe processor continues processing from where it left off, ensuring no data loss.\n\nThis recovery process ensures that temporary failures don't result in data loss or require manual intervention in most cases.\n\n## Stream Processing Timing\n\nIn streaming data processing, documents are subject to two timing systems:\n\n- event time\n\n- processing time\n\nAtlas Stream Processing offers various parameters to control how stream processors interact with these timing systems.\n\n### Event Time\n\nEvent time is the time at which either the source stream generates a document, or the messaging system (e.g. Apache Kafka) receives the document. This is ascertained by the timestamp of the document.\n\nNetwork latency, upstream processing, and other factors can not only cause discrepancies between these times for a given document, but can also cause documents to arrive in a stream processor out of event-time order. In either case, windows can miss documents that you intend for them to capture. Atlas Stream Processing considers such documents **late-arriving**, and sends them to your Dead Letter Queue if you configure one.\n\n**Event Time** is a configurable option for the `boundary` field supported in Tumbling Windows and Hopping Windows."} -{"chunk_id": "68c3ba82bbfe6ebb95f933fb-3", "page_id": "68c3ba82bbfe6ebb95f933fb", "source_name": "cloud-docs", "product_name": "MongoDB Atlas", "url": "https://mongodb.com/docs/atlas/atlas-stream-processing/architecture", "title": "Atlas Stream Processing Architecture", "text": "### Processing Time\n\nProcessing time is the time at which the stream processor consumes a document. This is ascertained by the clock of the system hosting the stream processor.\n\n**Processing Time** is a configurable option for the `boundary` field supported in Tumbling Windows and Hopping Windows. It allows you to create a pipeline with a kind of window which accumulates data based on the wall clock time of the server. Instead of event time windows, processing time windows assign each event a timestamp based on the wall clock time of the server when it arrives at the stream processor.\n\nDocument timestamps and window boundary timestamps are in UTC (Coordinated Universal Time). You can't specify idleTimeout or allowedLateness options when configuring a `processingTime` window.\n\nYou create a pipeline with a 5 minute event time window. An event is added to a source Kafka cluster at `09:33`. Due to some delay in the Kafka cluster, it arrives at the stream processor at `09:37`.\n\nIf the pipeline has a 5 minute event time window, then this event will be assigned to the `09:30-09:35` window. If the pipeline has a 5 minute processing time window, then the event will instead be assigned to the `09:35-09:40` window.\n\n#### Watermarks\n\nA watermark supersedes processing time and updates only when the processor consumes a document with a later event time than any previously-consumed document. Atlas Stream Processing applies watermarks only when a pipeline includes a window stage (`$tumblingWindow`, `$hoppingWindow`, or `$sessionWindow`).\n\n##### Example\n\nYou configure a stream processor with 5-minute windows. You start the processor at `12:00`, so that the first two windows have durations of `12:00-12:05` and `12:05-12:10`. The following table illustrates which windows will capture which events given varying delays, with and without watermarks.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nEvent Time\n\n\nProcessing Time\n\n\nWindow Time (No Watermarks)\n\n\nWindow Time (Watermarks)\n\n
\n12:00\n\n\n12:00\n\n\n12:00-12:05\n\n\n12:00-12:05\n\n
\n12:01\n\n\n12:03\n\n\n12:00-12:05\n\n\n12:00-12:05\n\n
\n12:02\n\n\n12:05\n\n\n12:05-12:10\n\n\n12:00-12:05\n\n
\n12:01\n\n\n12:06\n\n\n12:05-12:10\n\n\n12:00-12:05\n\n
\n12:06\n\n\n12:07\n\n\n12:05-12:10\n\n\n12:05-12:10\n\n
Without watermarks, the `12:00-12:05` window closes at `12:05` according to the system clock of the stream processing workspace, and the `12:05-12:10` window opens immediately. Thus, though the source generated four of the documents during the `12:00-12:05` interval, the relevant window captures only two documents.\n\nWith watermarks, the `12:00-12:05` window doesn't close at `12:05` because among the documents it ingests up to that point, the latest event time\u2014and thus the watermark value\u2014is `12:03`. The `12:00-12:05` window doesn't close until `12:07` on the system clock, when the stream processor ingests a document with an event time of `12:05`, advances the watermark to that time, and opens the `12:05-12:10` window. Each window captures all of the appropriate documents.\n\nWhen reading from Apache Kafka, Atlas Stream Processing waits for all partitions to pass the watermark. If a partition idles and fails to produce events with timestamps later than the watermark, the window doesn't close or output results. To address this, set `partitionIdleTimeout` to ensure that idle partitions don't halt the progression of watermarks. To learn more, see `$source` Stage (Stream Processing).\n\n#### Allowed Lateness\n\nIf the differences between event time and processing time vary sufficiently, documents may arrive in a stream processor after the watermark has advanced enough to close the expected window. To mitigate this, Atlas Stream Processing supports Allowed Lateness, a setting which delays a window closing by a set interval relative to the watermark.\n\nWhile watermarks are properties of stream processors, Allowed Lateness is a property of a window, and only affects when that window closes. If the stream processor's watermark advances to a point that would trigger a new window to open, Allowed Lateness keeps earlier windows open without preventing this.\n\n##### Example\n\nYou configure a stream processor with 5-minute tumbling windows. You start the processor at `12:00`, so that the first two windows will have durations of `12:00-12:05` and `12:05-12:10`. You set an Allowed Lateness of 2 minutes.\n\nThe table below reflects the order in which the stream processor ingests the described documents.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nEvent Time\n\n\nWatermark\n\n\nAllowed Lateness Time\n\n\nWindow Time\n\n
\n12:00\n\n\n12:00\n\n\n11:58\n\n\n12:00-12:05\n\n
\n12:02\n\n\n12:03\n\n\n12:01\n\n\n12:00-12:05\n\n
\n12:01\n\n\n12:04\n\n\n12:02\n\n\n12:00-12:05\n\n
\n12:05\n\n\n12:05\n\n\n12:03\n\n\n12:00-12:05, 12:05-12:10\n\n
\n12:04\n\n\n12:06\n\n\n12:04\n\n\n12:00-12:05, 12:05-12:10\n\n
\n12:07\n\n\n12:07\n\n\n12:05\n\n\n12:05-12:10\n\n
When the watermark advances to `12:05`, the `12:05-12:10` window opens. However, because the Allowed Lateness interval is 2 minutes, from within the `12:00-12:05` window, it is effectively only `12:03`, so it stays open. Only when the watermark advances to `12:07` does the adjusted time reach `12:05`. At this point, the `12:00-12:05` window closes.\n\n#### Idleness Timeout\n\nDecoupling windowing behavior from processing time by default improves stream processing correctness in most cases. However, a streaming data source may have periods of extended idleness. In this scenario, a window may capture events before the period of idleness and be unable to return processed results while waiting for the watermark to advance enough to close."} -{"chunk_id": "68c3ba82bbfe6ebb95f933fb-4", "page_id": "68c3ba82bbfe6ebb95f933fb", "source_name": "cloud-docs", "product_name": "MongoDB Atlas", "url": "https://mongodb.com/docs/atlas/atlas-stream-processing/architecture", "title": "Atlas Stream Processing Architecture", "text": "Atlas Stream Processing allows users to configure an idleness timeout for windows to mitigate these scenarios using processing time. An idleness timeout is an interval that begins when processing time passes the end of an open window's interval, and the stream processor's source is idle. If the source remains idle for an interval equal to the idleness timeout, the window closes and the watermark advances independent of any document ingestion.\n\n##### Example\n\nYou configure a tumbling window with a 3-minute interval and a 1-minute idleness timeout. The following table illustrates the effects of the idleness timeout during and after a window's interval.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nProcessing Time\n\n\nEvent Time or Status\n\n\nWatermark\n\n\nWindow Time\n\n
\n12:00\n\n\n12:00\n\n\n12:00\n\n\n12:00-12:03\n\n
\n12:01\n\n\nSource idle\n\n\n12:00\n\n\n12:00-12:03\n\n
\n12:02\n\n\nSource idle\n\n\n12:00\n\n\n12:00-12:03\n\n
\n12:03\n\n\nSource idle\n\n\n12:00\n\n\n12:00-12:03\n\n
\n12:04\n\n\n12:02\n\n\n12:02\n\n\n12:00-12:03\n\n
\n12:05\n\n\n12:05\n\n\n12:05\n\n\n12:03-12:06\n\n
\n12:06\n\n\nSource idle\n\n\n12:05\n\n\n12:03-12:06\n\n
\n12:07\n\n\nSource idle\n\n\n12:00\n\n\n12:06-12:09\n\n
\n12:08\n\n\nSource idle\n\n\n12:00\n\n\n12:06-12:09\n\n
\n12:09\n\n\n12:09\n\n\n12:09\n\n\n12:09-12:12\n\n
During the `12:00-12:03` interval, the source idles for three minutes, but the stream processor doesn't close the window because processing time is not past the end of the window's interval, and the source does not remain idle after the window's interval ends. When the watermark advances to `12:05`, the window closes normally, and the `12:03-12:06` window opens.\n\nWhen the source goes idle at `12:06`, it remains idle through `12:07`, triggering the idleness timeout and advancing the watermark to `12:06`."} -{"chunk_id": "68de188f90a7f51ca9113eee-0", "page_id": "68de188f90a7f51ca9113eee", "source_name": "cloud-docs", "product_name": "MongoDB Atlas", "url": "https://mongodb.com/docs/atlas/ai-integrations/n8n", "title": "Integrate MongoDB with n8n", "text": "# Integrate MongoDB with n8n\n\nYou can integrate MongoDB with n8n to build automations and agentic workflows using their no-code visual interface. This page provides an overview of the integration and describes the different types of nodes that you can use in your workflows.\n\n## Get Started with n8n\n\nTo install n8n, refer to the n8n documentation or run the following command using npm to quickly get started:\n\n```\nnpx n8n\n```\n\nTo learn how to build a basic AI agent using n8n and MongoDB, see Build an AI Agent with MongoDB and n8n.\n\nAll MongoDB n8n nodes require you to configure your MongoDB credentials in n8n. To learn more, see MongoDB Credentials.\n\n## MongoDB Node\n\nThe MongoDB node allows you to automate work in MongoDB and integrate MongoDB with other nodes in your n8n workflows.\n\n### Usage\n\nUse the MongoDB node in any of your custom n8n workflows.\n\n### Operations\n\nThe MongoDB node supports the following operations:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nCategory\n\n\nOperation\n\n\nDescription\n\n
\n**Document Operations**\n\n\nAggregate Documents\n\n\nPerform aggregation operations to process and transform data using MongoDB aggregation pipelines.\n\n
\n\n\nFind Documents\n\n\nQuery and retrieve documents from your MongoDB collections with flexible filtering options.\n\n
\n\n\nInsert Documents\n\n\nAdd new documents to your MongoDB collections.\n\n
\n\n\nUpdate Documents\n\n\nModify existing documents in your collections.\n\n
\n\n\nDelete Documents\n\n\nRemove documents from your collections.\n\n
\n\n\nFind and Replace Documents\n\n\nSearch for documents and replace them with new content.\n\n
\n\n\nFind and Update Documents\n\n\nSearch for documents and update specific fields.\n\n
\n**Search Index Operations**\n\n\nCreate Search Indexes\n\n\nCreate new search and vector search indexes on your collections.\n\n
\n\n\nList Search Indexes\n\n\nRetrieve information about existing search indexes.\n\n
\n\n\nUpdate Search Indexes\n\n\nModify existing search index configurations.\n\n
\n\n\nDrop Search Indexes\n\n\nRemove search indexes that are no longer needed.\n\n
To learn more, see n8n MongoDB node documentation\n\n## MongoDB Atlas Vector Store Node\n\nThe MongoDB Atlas Vector Store node enables you to use MongoDB Vector Search in your agentic workflows.\n\nBefore you can start using this node, configure the MongoDB Vector Search Index.\n\n### Usage\n\nUse the MongoDB Vector Store node in the following workflow patterns:\n\n\n\n\n\nConnect directly to an AI agent as a tool to perform agentic RAG.\n\n```text\nAI Agent (tools connector) \u2192 MongoDB Vector Store\n```\n\nFor a tutorial, see Build an AI Agent with MongoDB and n8n.\n\nTo learn more about AI agents in n8n, see AI agent node.\n\n\n\n\n\nUse the MongoDB Atlas Vector Store as a regular node to insert or retrieve documents in your custom workflows:\n\n```text\nTrigger \u2192 MongoDB Vector Store (Insert/Get) \u2192 Next Node\n```\n\nTo learn more, see Nodes.\n\n\n\n\n\nUse the node as a retriever in a question-answering chain:\n\n```text\nQuestion and Answer Chain \u2192 Vector Store Retriever \u2192 MongoDB Vector Store\n```\n\nTo learn more about Q&A in n8n, see Question and Answer Chain node.\n\n\n\n\n\nUse the node as a question-answering tool for an AI agent:\n\n```text\nAI Agent \u2192 Vector Store Question Answer Tool \u2192 MongoDB Vector Store\n```\n\nTo learn more about the question-answering tool in n8n, see Vector Store Question Answer Tool node.\n\n\n\n\n\n### Operation Modes\n\nThe MongoDB Vector Store node supports the following operation modes. The retrieve document mode is only available in certain workflow patterns.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nOperation Mode\n\n\nDescription\n\n
\nGet Many\n\n\nRetrieve multiple documents using similarity search based on a prompt. Returns documents with similarity scores.\n\n
\nInsert Documents\n\n\nAdd new documents with vector embeddings to your collection.\n\n
\nRetrieve Documents (As Vector Store for Chain/Tool)\n\n\nOnly available when you use the node as a retriever or a tool. Must be connected to a retriever node or root node.\n\n
\nRetrieve Documents (As Tool for AI Agent)\n\n\nOnly available when you use the node as a tool for an AI agent. The agent uses this vector store when the name and description are relevant to the prompt.\n\n
"} -{"chunk_id": "68de188f90a7f51ca9113eee-1", "page_id": "68de188f90a7f51ca9113eee", "source_name": "cloud-docs", "product_name": "MongoDB Atlas", "url": "https://mongodb.com/docs/atlas/ai-integrations/n8n", "title": "Integrate MongoDB with n8n", "text": "### Parameters\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nCategory\n\n\nSetting\n\n\nOperation Mode\n\n\nDescription\n\n
\n**Common Parameters**\n\n\nMongoDB Collection\n\n\nAll\n\n\nName of the MongoDB collection to use.\n\n
\n\n\nVector Index Name\n\n\nAll\n\n\nName of the Vector Search index in your MongoDB collection.\n\n
\n\n\nEmbedding Field\n\n\nAll\n\n\nField name in your documents that contains the vector embeddings.\n\n
\n\n\nMetadata Field\n\n\nAll\n\n\nField name in your documents that contains the text metadata.\n\n
\n**Mode-Specific Parameters**\n\n\nName\n\n\nRetrieve Documents (As Tool for AI Agent)\n\n\nName of the vector store tool for the AI agent.\n\n
\n\n\nDescription\n\n\nRetrieve Documents (As Tool for AI Agent)\n\n\nExplanation for the LLM about what this tool does.\n\n
\n\n\nLimit\n\n\nRetrieve Documents (As Tool for AI Agent)\n\n\nNumber of results to retrieve from the vector store.\n\n
\n**Additional Options**\n\n\nMetadata Filter\n\n\nGet Many, Retrieve Documents (As Tool for AI Agent), Retrieve Documents (As Vector Store for Chain/Tool)\n\n\nFilter results based on metadata criteria.\n\n
\n\n\nRerank Results\n\n\nGet Many, Retrieve Documents (As Tool for AI Agent), Retrieve Documents (As Vector Store for Chain/Tool)\n\n\nEnable result reranking (requires connecting a reranker node).\n\n
\n\nTo learn more, see n8n MongoDB Vector Store node documentation\n\n## MongoDB Chat Memory Node\n\nThe MongoDB Chat Memory node allows you to use MongoDB as a memory store for storing chat history in your AI workflows. This enables persistent conversation context across workflow executions.\n\n### Usage\n\nYou must use the MongoDB Chat Memory node as a sub-node by adding it to the Memory section of an AI agent node. For a tutorial, see Build an AI Agent with MongoDB and n8n.\n\nIf you add multiple MongoDB Chat Memory nodes to your workflow, all nodes access the same memory instance by default. For separate memory instances, use different session IDs in each memory node.\n\n### Parameters\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nParameter\n\n\nDescription\n\n
\nSession ID\n\n\nMethod for determining how the session key is identified. You can define the session key through a connected trigger, or you can define the key manually.\n\n
\nSession Key\n\n\nUnique identifier for the chat session.\n\n
\nCollection Name\n\n\nName of the collection to store chat history. MongoDB creates the collection if it doesn't exist. Defaults to `n8n_chat_histories`.\n\n
\nDatabase Name\n\n\nName of the database to store chat history. If not provided, n8n uses the database from credentials.\n\n
\nContext Window Length\n\n\nNumber of previous interactions to consider for context.\n\n
\n\nTo learn more, see n8n MongoDB Chat Memory node documentation\n\n## Additional n8n Resources\n\nTo learn more about n8n, use the following resources:\n\n- n8n Documentation\n\n- n8n Integrations"} -{"chunk_id": "68a95b1e5e79d242619c716c-0", "page_id": "68a95b1e5e79d242619c716c", "source_name": "cloud-docs", "product_name": "MongoDB Atlas", "url": "https://mongodb.com/docs/atlas/cloud-providers-regions", "title": "Cloud Providers and Regions", "text": "# Cloud Providers and Regions\n\nAtlas Infinite is available as a public preview. During the public preview, Atlas Infinite clusters deploy on AWS (Amazon Web Services) in the supported regions, not on Google Cloud or Azure (Microsoft Azure).\n\n\u2605The choice of cloud provider and region affects network latency for clients accessing your cluster and the cost of running the cluster. For clusters, this choice also affects the configuration options for the available cluster tiers. The region refers to the physical location of your MongoDB cluster.\n\nAtlas supports deploying Atlas Flex on a subset of each cloud provider's regions.\n\nFor a list of supported regions, see:\n\n- Amazon Web Services (AWS)\n\n- Google Cloud\n\n- Microsoft Azure\n\nIn the Create New Cluster page:\n\n- Regions marked as \u2605 are Recommended regions that provide higher availability compared to other regions.\n\n- Regions marked as are available for dedicated clusters only.\n\nFor more information, see:\n\n- AWS Recommended Regions\n\n- Google Cloud Recommended Regions\n\n- Azure Recommended Regions\n\nFor more information on multi-region configurations for increased availability, see Configure High Availability and Workload Isolation.\n\n## Cloud Providers and Regions for Dedicated Search Nodes\n\nAtlas supports deploying separate Search Nodes for `M10` and higher clusters to a subset of AWS (Amazon Web Services), Google Cloud, or Azure (Microsoft Azure) regions.\n\nFor more information, see:\n\n- AWS Dedicated Search Nodes\n\n- Google Cloud Dedicated Search Nodes\n\n- Azure Dedicated Search Nodes"} -{"chunk_id": "68a95b1e5e79d242619c7252-0", "page_id": "68a95b1e5e79d242619c7252", "source_name": "cloud-docs", "product_name": "MongoDB Atlas", "url": "https://mongodb.com/docs/atlas/data-federation/supported-unsupported/administration-commands", "title": "Administration Commands", "text": "# Administration Commands\n\n## `collMod`\n\nAtlas Data Federation supports the `collMod` command only for modifying view definitions. You can't use the `collMod` command to add options to a collection.\n\n## `hello`\n\nAtlas Data Federation supports the hello command, which is used to describe the role of the `mongod` instance. In the document returned by the `hello` command, the `isWritablePrimary` field is set to `true`.\n\nAtlas Data Federation supports the optional `saslSupportedMechs` field set to the ``.\n\n## `killCursors`\n\nThe killCursors command kills the specified cursor or cursors for a collection.\n\n## `listCollections`\n\nThe listCollections command retrieves information about the collections in a database, such as collection names and options. The response contains information that can be used to create a cursor to the collection information. Results are ordered alphabetically by collection name.\n\nAtlas Data Federation supports the following options:\n\n- `filter` (Exact match only.)\n\n- `nameOnly`\n\n- `authorizedCollections`\n\n## `listDatabases`\n\nThe listDatabases command provides a list of all existing databases in alphabetical order. You must use the `admin` database to run the `listDatabases` command.\n\nThe following options are supported:\n\n- `filter` (Exact match only.)\n\n- `nameOnly`\n\n- `authorizedDatabases`\n\nThe `listDatabases` command always returns `sizeOnDisk: 0` and `empty: false` so it can return quickly, without scanning all the files in the S3 (Simple Storage Service) buckets."} -{"chunk_id": "68a95b1e5e79d242619c6f81-0", "page_id": "68a95b1e5e79d242619c6f81", "source_name": "cloud-docs", "product_name": "MongoDB Atlas", "url": "https://mongodb.com/docs/atlas/atlas-stream-processing/manage-stream-processor", "title": "Develop and Manage Stream Processors", "text": "# Develop and Manage Stream Processors\n\nAn Atlas Stream Processing stream processor applies the logic of a uniquely named stream aggregation pipeline to your streaming data. Atlas Stream Processing saves each stream processor definition to persistent storage so that it can be reused. You can only use a given stream processor in the stream processing workspace in which its definition is stored.\n\nTo let Atlas Stream Processing adjust a processor's tier automatically in response to resource usage, enable vertical autoscaling.\n\n## Prerequisites\n\nTo create and manage a stream processor, you must have:\n\n- A stream processing workspace\n\n- A database user with the `atlasAdmin` role to create and run stream processors\n\n- An Atlas cluster\n\n## Considerations\n\nMany stream processor commands require you to specify the name of the relevant stream processor in the method invocation. The syntax described in the following sections assumes strictly alphanumeric names. If your stream processor's name includes non-alphanumeric characters such as hyphens (`-`) or full stops (`.`), you must enclose the name in square brackets (`[]`) and double quotes (`\"\"`) in the method invocation, as in `sp[\"special-name-stream\"].stats()`.\n\n## Create a Stream Processor Interactively\n\nYou cannot create a stream processor interactively using the Atlas Administration API. To learn how to create a stream processor interactively using `mongosh`, select MongoDB Shell from the Interface dropdown.\n\nYou cannot create a stream processor interactively using the Atlas UI. To learn how to create a stream processor interactively using `mongosh`, select MongoDB Shell from the Interface dropdown.\n\nYou cannot create a stream processor interactively using the Atlas CLI. To learn how to create a stream processor interactively using `mongosh`, select MongoDB Shell from the Interface dropdown.\n\nYou can create a stream processor interactively with the `sp.process()` method in `mongosh`. Stream processors that you create interactively exhibit the following behavior:\n\n- Write output and dead letter queue documents to the shell\n\n- Begin running immediately upon creation\n\n- Run until one of the following occurs: They return the number of documents set by the `options.limit` field, 10 minutes elapse, or the user stops them\n\n- Don't persist after stopping\n\nStream processors that you create interactively are intended for prototyping. To create a persistent stream processor, see Create a Stream Processor.\n\n`sp.process()` has the following syntax:\n\n```sh\nsp.process(, )\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nField\n\n\nType\n\n\nNecessity\n\n\nDescription\n\n
\n`pipeline`\n\n\narray\n\n\nRequired\n\n\nStream aggregation pipeline the stream processor applies to your streaming data.\n\n
\n`options`\n\n\nobject\n\n\nOptional\n\n\nObject that defines optional settings for your stream processor.\n\n
\n`options.limit`\n\n\ninteger\n\n\nOptional\n\n\nMaximum number of documents to return to your terminal. `sp.process()` ends the session after it returns this number of documents.\n\n
\n`options.tier`\n\n\nstring\n\n\nOptional\n\n\nTier to assign to the stream processor. Tier names are case-insensitive. If you omit this field, the stream processor uses the default tier for your stream processing workspace. Must be one of the following values:\n\n- `SP2`\n\n- `SP5`\n\n- `SP10`\n\n- `SP30`\n\n- `SP50`\n\nTo learn more, see Tiers.\n\n
To create a stream processor interactively:\n\n### Connect to your stream processing workspace.\n\nUse the connection string associated with your stream processing workspace to connect using `mongosh`.\n\nThe following command connects to a stream processing workspace as a user named `streamOwner` using x.509 authentication:\n\n```sh\nmongosh \"mongodb://atlas-stream-78xq9gi1v4b4288x06a73e9f-zi30g.virginia-usa.a.query.mongodb-qa.net/?authSource=%24external&authMechanism=MONGODB-X509\" \\\\\n--tls --authenticationDatabase admin --username streamOwner\n```\n\nProvide your user password when prompted.\n\n### Define a pipeline.\n\nIn the `mongosh` prompt, assign an array containing the aggregation stages you want to apply to a variable named `pipeline`.\n\nThe following example uses the `stuff` topic in the `myKafka` connection in the connection registry as the `$source`, matches records where the `temperature` field has a value of `46` and emits the processed messages to the `output` topic of the `mySink` connection in the connection registry:\n\n```sh\npipeline = [\n {$source: {\"connectionName\": \"myKafka\", \"topic\": \"stuff\"}},\n {$match: { temperature: 46 }},\n {\n \"$emit\": {\n \"connectionName\": \"mySink\",\n \"topic\" : \"output\",\n }\n }\n]\n```\n\n### Create a stream processor.\n\nThe following command creates a stream processor that applies the logic defined in `pipeline`.\n\n```sh\nsp.process(pipeline)\n```\n\n## Create a Stream Processor\n\nThe Atlas Administration API provides an endpoint for creating a stream processor.\n\nCreate One Stream Processor\n\nTo create a stream processor in the Atlas UI, go to the Stream Processing page for your Atlas project and click Manage in the pane for your stream processing workspace.\n\nYou can choose between using the Visual Builder or the JSON (Javascript Object Notation) editor to configure your stream processor:\n\n\n\n\n\n### Open the Visual Builder.\n\nClick Stream Processors in the left-hand navigation menu, then click Create stream processor.\n\nThe Create Stream Processor screen opens with a form where you can configure your stream processor.\n\n### Add a source connection.\n\nIn the Build Pipeline section, select the connection that your stream processor reads data from in the Source drop-down list.\n\nThis opens a JSON (Javascript Object Notation) text box that contains the `$source` stage for your stream processor. In the text box, set `db` to the name of your database and `coll` to the name of the collection in that database. To learn more about `$source` stage syntax, see `$source`.\n\n### Optional: Add aggregation stages to the pipeline.\n\nIn the Pipeline field, select the aggregation stages that you want your stream processor to apply. To add these stages later, leave this field empty.\n\nTo learn more about stream processing aggregation stages and their syntax, see Aggregation Pipeline Stages for Stream Processing.\n\nThe following `$match` stage matches all documents in the pre-configured `sample_stream_solar` stream where the `obs.watts` field is greater than `300`:\n\n```json\n{\n \"$match\": {\n \"obs.watts\": { \"$gt\": 300 }\n }\n}\n```\n\n### Add a sink connection.\n\nIn the Sink field, select the connection that your stream processor writes processed data to.\n\nThis opens a JSON (Javascript Object Notation) text box that contains the `$merge` stage for your stream processor. In the text box, set `db` to the name of your database and `coll` to the name of the collection in that database. To learn more about `$merge` stage syntax, see `$merge`.\n\nThe following `$merge` stage writes processed data to the `demoDb.demoColl` collection in a connection named `demoConnection`:\n\n```json\n{\n \"$merge\": {\n \"into\": {\n \"connectionName\": \"demoConnection\",\n \"db\": \"demoDb\",\n \"coll\": \"demoColl\"\n }\n }\n}\n```"} -{"chunk_id": "68a95b1e5e79d242619c6f81-1", "page_id": "68a95b1e5e79d242619c6f81", "source_name": "cloud-docs", "product_name": "MongoDB Atlas", "url": "https://mongodb.com/docs/atlas/atlas-stream-processing/manage-stream-processor", "title": "Develop and Manage Stream Processors", "text": "### Enter your stream processor details.\n\nIn the Enter processor details section, do the following:\n\n- In the Stream processor name field, enter a name for your stream processor.\n\n- Select the data processing tier for your stream processor. The default tier is `SP10`. To learn more, see Tiers.\n\n- Specify whether to start your stream processor when Atlas Stream Processing creates it.\n\n### (Optional) Add a dead letter queue.\n\nSpecify a destination for your dead letter queue.\n\n### (Optional) Create failover processors.\n\nIn the Advanced settings pane, toggle Create failover processor(s) to create one or more failover processors.\n\nIMPORTANT: This feature is only available in stream processing workspaces configured with failover regions. To learn more, see Limitations.\n\n### Click Create stream processor.\n\nAtlas Stream Processing creates the stream processor and lists it on the Stream Processors tab of the Stream Processing page.\n\n\n\n\n\n### Click Use JSON editor.\n\nIf there are existing stream processors in your stream processing workspace, click the + Create stream processor button, then select JSON editor from the drop-down options.\n\nThe JSON editor opens with a text box where you can configure your stream processor in JSON (Javascript Object Notation) format.\n\n### (Optional) Upload a file to populate the editor.\n\nClick Upload File and select a JSON file that contains your stream processor definition. The file must use the same JSON (Javascript Object Notation) format that the Create One Stream Processor endpoint requires. Your uploaded file replaces the default editor content.\n\n### Define the stream processor.\n\nSpecify the JSON (Javascript Object Notation) definition for your stream processor in the JSON editor text box. This definition must include a name for your stream processor and an aggregation pipeline that starts with a `$source` stage and ends with the `$merge` stage. You can include any number of additional aggregation stages between the `$source` and `$merge` stages.\n\nTo learn more about stream processing aggregation stages and their syntax, see Aggregation Pipeline Stages for Stream Processing.\n\nThe following JSON (Javascript Object Notation) definition creates a stream processor named `solarDemo` that uses a `$tumblingWindow` stage with a nested `$group` stage to aggregate real-time data from the pre-configured `sample_stream_solar` connection over 10-second intervals, and writes the processed data to a collection in a connection named `mongodb1`.\n\n```json\n{\n \"name\": \"solarDemo\",\n \"pipeline\": [\n {\n \"$source\": {\n \"connectionName\": \"sample_stream_solar\"\n }\n },\n {\n \"$tumblingWindow\": {\n \"interval\": {\n \"size\": 10,\n \"unit\": \"second\"\n },\n \"pipeline\": [\n {\n \"$group\": {\n \"_id\": \"$group_id\",\n \"max_watts\": { \"$max\": \"$obs.watts\" },\n \"min_watts\": { \"$min\": \"$obs.watts\" }\n }\n }\n ]\n }\n },\n {\n \"$merge\": {\n \"into\": {\n \"connectionName\": \"mongodb1\",\n \"db\": \"solarDb\",\n \"coll\": \"solarColl\"\n }\n }\n }\n ]\n}\n```\n\n### (Optional) Create failover processors.\n\nIn the Advanced settings pane, toggle Create failover processor(s) to create one or more failover processors.\n\nIMPORTANT: This feature is only available in stream processing workspaces configured with failover regions. To learn more, see Limitations."} -{"chunk_id": "68a95b1e5e79d242619c6f81-2", "page_id": "68a95b1e5e79d242619c6f81", "source_name": "cloud-docs", "product_name": "MongoDB Atlas", "url": "https://mongodb.com/docs/atlas/atlas-stream-processing/manage-stream-processor", "title": "Develop and Manage Stream Processors", "text": "### Click Create stream processor.\n\nAtlas Stream Processing creates the stream processor and lists it on the Stream Processors tab of the Stream Processing page.\n\n\n\n\n\nTo create one stream processor within the stream processing workspace you specify using the Atlas CLI, run the following command:\n\n```sh\n\natlas api streams createStreamProcessor [options]\n\n```\n\nTo learn more about the command syntax and parameters, see the Atlas CLI documentation for atlas api streams createStreamProcessor.\n\nTo create a new stream processor with `mongosh`, use the `sp.createStreamProcessor()` method. It has the following syntax:\n\n```sh\nsp.createStreamProcessor(, , )\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nArgument\n\n\nType\n\n\nNecessity\n\n\nDescription\n\n
\n`name`\n\n\nstring\n\n\nRequired\n\n\nLogical name for the stream processor. This must be unique within the stream processing workspace. This name should contain only alphanumeric characters.\n\n
\n`pipeline`\n\n\narray\n\n\nRequired\n\n\nStream aggregation pipeline you want to apply to your streaming data.\n\n
\n`options`\n\n\nobject\n\n\nOptional\n\n\nObject defining various optional settings for your stream processor.\n\n
\n`options.dlq`\n\n\nobject\n\n\nConditional\n\n\nObject assigning a dead letter queue for your stream processing workspace. This field is necessary if you define the `options` field.\n\n
\n`options.dlq.connectionName`\n\n\nstring\n\n\nConditional\n\n\nHuman-readable label that identifies a connection in your connection registry. This connection must reference an Atlas cluster. This field is necessary if you define the `options.dlq` field.\n\n
\n`options.dlq.db`\n\n\nstring\n\n\nConditional\n\n\nName of an Atlas database on the cluster specified in `options.dlq.connectionName`. This field is necessary if you define the `options.dlq` field.\n\n
\n`options.dlq.coll`\n\n\nstring\n\n\nConditional\n\n\nName of a collection in the database specified in `options.dlq.db`. This field is necessary if you define the `options.dlq` field.\n\n
\n`options.tier`\n\n\nstring\n\n\nOptional\n\n\nThe tier of the pod to which Atlas Stream Processing assigns the processor. If you do not declare this option, Atlas Stream Processing assigns the processor to a pod of the stream processing workspace's default tier. To learn more, see Tiers.\n\n
\n`options.failover`\n\n\nboolean\n\n\nOptional\n\n\nFlag that specifies whether to create the processor in every failover region configured for your stream processing workspace in addition to the default region. If you omit this field, Atlas Stream Processing creates the processor only in the default region.\n\n
### Connect to your stream processing workspace.\n\nUse the connection string associated with your stream processing workspace to connect using `mongosh`.\n\n- In the pane for your stream processing workspace, click Connect.\n\n- In the Connect to your workspace dialog, select the Shell tab.\n\n- Copy the connection string displayed in the dialog. It has the following format, where `` is the URL of your stream processing workspace and `` is the username of a database user with the `atlasAdmin` role:\n\n ```sh\n mongosh \"mongodb:///\"\n --tls --authenticationDatabase admin --username \n --password \n ```\n\n- Paste the connection string into your terminal and replace the `` placeholder with the credentials for the user. Press Enter to run it to connect to your stream processing workspace.\n\nThe following command connects to a stream processing workspace as a user named `streamOwner` using x.509 authentication.\n\n```sh\nmongosh \"mongodb://atlas-stream-78xq9gi1v4b4288x06a73e9f-zi30g.virginia-usa.a.query.mongodb-qa.net/?authSource=%24external&authMechanism=MONGODB-X509\" \\\\\n--tls --authenticationDatabase admin --username streamOwner\n```\n\nProvide your user password when prompted.\n\n### Define a pipeline.\n\nIn the `mongosh` prompt, assign an array containing the aggregation stages you want to apply to a variable named `pipeline`.\n\nThe following example pipeline uses the `stuff` topic in the `myKafka` connection in the connection registry as the `$source`, matches records where the `temperature` field has a value of `46` and emits the processed messages to the `output` topic of the `mySink` connection in the connection registry:\n\n```sh\npipeline = [\n {$source: {\"connectionName\": \"myKafka\", \"topic\": \"stuff\"}},\n {$match: { temperature: 46 }},\n {\n \"$emit\": {\n \"connectionName\": \"mySink\",\n \"topic\" : \"output\",\n }\n }\n]\n```\n\n### (Optional) Define a DLQ.\n\nIn the `mongosh` prompt, assign an object containing the following properties of your DLQ:\n\n- Connection name\n\n- Database name\n\n- Collection name\n\nThe following example defines a DLQ over the `cluster01` connection, in the `metadata.dlq` database collection.\n\n```sh\ndeadLetter = {\n dlq: {\n connectionName: \"cluster01\",\n db: \"metadata\",\n coll: \"dlq\"\n }\n}\n```\n\n### Create a stream processor.\n\nThe following command creates a stream processor named `proc01` that applies the logic defined in `pipeline`. Documents that throw errors in processing are written to the DLQ defined in `deadLetter`.\n\n```sh\nsp.createStreamProcessor(\"proc01\", pipeline, deadLetter)\n```"} -{"chunk_id": "68a95b1e5e79d242619c6f81-3", "page_id": "68a95b1e5e79d242619c6f81", "source_name": "cloud-docs", "product_name": "MongoDB Atlas", "url": "https://mongodb.com/docs/atlas/atlas-stream-processing/manage-stream-processor", "title": "Develop and Manage Stream Processors", "text": "## Start a Stream Processor\n\nAtlas Stream Processing discards the internal state of stream processors which have been `stopped` for 45 days or more. When you start such a processor, it operates and reports statistics identically to its initial run.\n\nThe Atlas Administration API provides the Start One Stream Processor and Start One Stream Processor with Options endpoints for starting a stream processor.\n\n- To start a stream processor without options, use Start One Stream Processor\n\n- To start a stream processor and modify properties of the `$source` stage, use Start One Stream Processor with Options This endpoint supports modifying either the `startAfter` or `startAtOperationTime` properties.\n\nTo start a stream processor in the Atlas UI, go to the Stream Processing page for your Atlas project and click Manage in the pane for your stream processing workspace to view the list of stream processors defined for it.\n\nThen, click the Start icon for your stream processor.\n\nTo start one stream processor within the stream processing workspace you specify using the Atlas CLI, run the following command:\n\n```sh\n\natlas api streams startStreamProcessor [options]\n\n```\n\nTo learn more about the command syntax and parameters, see the Atlas CLI documentation for atlas api streams startStreamProcessor.\n\nTo start a stream processor with `mongosh`, use the `sp.processor.start()` method. It has the following syntax:\n\n```sh\nsp.processor.start()\n```\n\nWhere `` is a generic, optional document whose fields are passed to the underlying start command. To learn more about the command options, see `sp.createStreamProcessor()`. For example, to start a stream processor named `proc01`, run the following command:\n\n```shell\nsp.proc01.start()\n```\n\n```shell\n{ \"ok\" : 1 }\n```\n\nThis method returns `{ \"ok\": 1 }` if the stream processor exists and isn't currently running. If you invoke `sp.processor.start()` for a stream processor that is not `STOPPED`, `mongosh` returns an error.\n\n## Stop a Stream Processor\n\nAtlas Stream Processing discards the internal state of stream processors which have been `stopped` for 45 days or more. When you start such a processor, it operates and reports statistics identically to its initial run.\n\nThe Atlas Administration API provides an endpoint for stopping a stream processor.\n\nStop One Stream Processor\n\nTo stop a stream processor in the Atlas UI, go to the Stream Processing page for your Atlas project and click Manage in the pane for your stream processing workspace to view the list of stream processors defined for it.\n\nThen, click the Stop icon for your stream processor.\n\nTo stop one stream processor within the stream processing workspace you specify using the Atlas CLI, run the following command:\n\n```sh\n\natlas api streams stopStreamProcessor [options]\n\n```\n\nTo learn more about the command syntax and parameters, see the Atlas CLI documentation for atlas api streams stopStreamProcessor.\n\nTo stop an existing stream processor with `mongosh`, use the `sp.processor.stop()` method. It has the following syntax:\n\n```sh\nsp.processor.stop()\n```\n\nWhere `` is a generic, optional document whose fields are passed to the underlying stop command.\n\nFor example, to stop a stream processor named `proc01`, run the following command:\n\n```shell\nsp.proc01.stop()\n```\n\n```shell\n{ \"ok\" : 1 }\n```\n\nThis method returns `{ \"ok\": 1 }` if the stream processor exists and is currently running. If you invoke `sp.processor.stop()` for a stream processor that is not `running`, `mongosh` returns an error.\n\n## Modify a Stream Processor\n\nYou can modify the following elements of an existing stream processor:\n\n- Name\n\n- Pipeline\n\n- Dead Letter Queue\n\nTo modify a stream processor, do the following:\n\nThe Atlas Administration API provides an endpoint for modifying a stream processor.\n\nModify One Stream Processor\n\n### Click Stream Processors in the left-hand navigation menu.\n\n### Select the stream processor that you want to modify.\n\nFrom the list of stream processors, click the one that you want to modify. The View Stream Processor screen opens.\n\n### Click Edit Processor.\n\nThe stream processor fields become editable.\n\n### Make your changes to the stream processor.\n\nYou can edit any of the fields available for your stream processor.\n\n### Click Save changes.\n\nTo modify one existing stream processor within the stream processing workspace you specify using the Atlas CLI, run the following command:\n\n```sh\n\natlas api streams updateStreamProcessor [options]\n\n```\n\nTo learn more about the command syntax and parameters, see the Atlas CLI documentation for atlas api streams updateStreamProcessor.\n\nRequires `mongosh` v2.3.4+.\n\nUse the `sp..modify()` command to modify an existing stream processor. `` must be the name of a stopped stream processor defined for the current stream processing workspace.\n\nFor example, to modify a stream processor named `proc01`, run the following command:\n\n```javascript\n sp.proc1.modify(, {\n resumeFromCheckpoint: bool, // optional\n name: string, // optional\n dlq: string, // optional\n failover: bool, // optional\n})\n```\n\nThe `failover` option controls whether the processor runs in the failover regions configured for your stream processing workspace:\n\n- Set `failover` to `true` to read the processor definition from the default region and create that processor in every failover region that doesn't already have it.\n\n- Set `failover` to `false` to disable failover for a processor that has failover regions configured and revert it to running in a single region.\n\n### Add a Stage to an Existing Pipeline\n\n```javascript\n sp.createStreamProcessor(\"foo\", [\n {$source: {\n connectionName: \"StreamsAtlasConnection\",\n db: \"test\",\n coll: \"test\"\n }},\n {$merge: {\n into: {\n connectionName: \"StreamsAtlasConnection\",\n db: \"testout\",\n coll: \"testout\"\n }\n }}\n])\nsp.foo.start();\n```\n\n```javascript\nsp.foo.stop();\nsp.foo.modify([\n {$source: {\n connectionName: \"StreamsAtlasConnection\",\n db: \"test\",\n coll: \"test\"\n }},\n {$match: {\n operationType: \"insert\"\n }},\n {$merge: {\n into: {\n connectionName: \"StreamsAtlasConnection\",\n db: \"testout\",\n coll: \"testout2\"\n }\n }}\n]);\nsp.foo.start();\n```\n\n### Modify the Input Source of a Stream Processor\n\n```javascript\nsp.foo.modify([\n {$source: {\n connectionName: \"StreamsAtlasConnection\",\n db: \"test\",\n coll: \"test\",\n config: {\n startAtOperationTime: new Date(now.getTime() - 5 * 60 * 1000)\n }\n }},\n {$match: {\n operationType: \"insert\"\n }},\n {$merge: {\n into: {\n connectionName: \"StreamsAtlasConnection\",\n db: \"testout\",\n coll: \"testout2\"\n }\n }}\n], {resumeFromCheckpoint: false});\n```\n\n### Remove a Dead Letter Queue from a Stream Processor\n\n```javascript\nsp.foo.stop();\nsp.foo.modify({dlq: {}})\nsp.foo.start();\n```"} -{"chunk_id": "68a95b1e5e79d242619c6f81-4", "page_id": "68a95b1e5e79d242619c6f81", "source_name": "cloud-docs", "product_name": "MongoDB Atlas", "url": "https://mongodb.com/docs/atlas/atlas-stream-processing/manage-stream-processor", "title": "Develop and Manage Stream Processors", "text": "### Modify a Stream Processor with a Window\n\n```javascript\nsp.foo.stop();\nsp.foo.modify([\n {$source: {\n connectionName: \"StreamsAtlasConnection\",\n db: \"test\",\n coll: \"test\"\n }},\n {$replaceRoot: {newRoot: \"$fullDocument\"}},\n {$match: {cost: {$gt: 500}}},\n {$tumblingWindow: {\n interval: {unit: \"day\", size: 1},\n pipeline: [\n {$group: {_id: \"$customerId\", sum: {$sum: \"$cost\"}, avg: {$avg: \"$cost\"}}}\n ]\n }},\n {$merge: {\n into: {\n connectionName: \"StreamsAtlasConnection\",\n db: \"testout\",\n coll: \"testout\"\n }\n }}\n], {resumeFromCheckpoint: false});\nsp.foo.start();\n```\n\nBy default, modified processors restore from the last checkpoint. Alternatively, you can set `resumeFromCheckpoint=false`, in which case the processor only retains summary stats. When you modify a processor with open windows, the windows are entirely recomputed on the updated pipeline.\n\nIf you change the name of a stream processor for which you had configured the Stream Processor State is failed alert by using an Operator (which contains matcher expressions like `is`, `contains`, and more), Atlas won't trigger alerts for the renamed stream processor if the matcher expression doesn't match the new name. To monitor the renamed stream processor, reconfigure the alert.\n\n### Limitations\n\nWhen the default setting `resumeFromCheckpoint=true` is enabled, the following limitations apply:\n\n- You can't modify the `$source` stage.\n\n- You can't modify the interval of your window.\n\n- You can't remove a window.\n\n- You can only modify a pipeline with a window if that window has either a `$group` or `$sort` stage in its inner pipeline.\n\n- You can't change an existing window type. For example, you can't change from a `$tumblingWindow` to a `$hoppingWindow` or vice versa.\n\n- Processors with windows may reprocess some data as a product of recalculating the windows.\n\n- Per-operator statistics are not retained after a modify operation.\n\n## Initiate Failover for One Stream Processor\n\nTo initiate failover of an individual stream processor, use the Start One Stream Processor With Options endpoint. In the `failover` field of the request body, provide the name of the cloud region in which the target failover processor lives. Initializing the failover processor will also deactivate the primary processor.\n\n### In Atlas, go to the Stream Processing page for your project.\n\n- If it's not already displayed, select the organization that contains your project from the Organizations menu in the navigation bar.\n\n- If it's not already displayed, select your project from the Projects menu in the navigation bar.\n\n- In the sidebar, click Stream Processing under the Streaming Data heading.\n\nThe Stream Processing page displays.\n\n### Initiate failover.\n\n- Locate the overview panel of the stream processing workspace that hosts the target processor.\n\n- Click the ellipsis Manage button.\n\n- Click Stream Processors in the left-hand navigation menu.\n\n- Locate the target processor from the list of processors in the workspace and click the arrow to expand that processor's region list. Locate the region to which you want to initiate failover and click the Failover button In the Actions column.\n\n- In the modal window, select the failover type. To perform a Forced failover, type `Force` in the confirmation prompt. For a Forced failover, select Clear checkpoint to skip resuming from the most recent checkpoint. By default, this checkbox is cleared.\n\n- Click the Activate [TYPE] failover button, where `[TYPE]` is your chosen failover type.\n\nTo start one stream processor with optional parameters set using the Atlas CLI, run the following command:\n\n```sh\n\natlas api streams startStreamProcessorWith [options]\n\n```\n\nTo learn more about the command syntax and parameters, see the Atlas CLI documentation for atlas api streams startStreamProcessorWith.\n\nTo initiate failover for an individual stream processor with `mongosh`, use the `sp.processor.start()` method and pass the `failover` option. Starting the failover processor also stops the processor in the currently active region.\n\nThe `failover` option has the following syntax:\n\n```sh\nsp..start({\n failover: {\n region: \"\",\n mode: \"\",\n dryRun: \n }\n})\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nField\n\n\nType\n\n\nNecessity\n\n\nDescription\n\n
\n`failover`\n\n\nobject\n\n\nOptional\n\n\nObject defining the failover event you want to initiate.\n\n
\n`failover.region`\n\n\nstring\n\n\nRequired\n\n\nName of the cloud region in which the target failover processor lives. This region must be one of the failover regions configured for your stream processing workspace. To check which failover regions your stream processing workspace uses, see View stream processing workspaces. For the regions that Atlas Stream Processing supports, see Atlas Stream Processing Regions.\n\n
\n`failover.mode`\n\n\nstring\n\n\nOptional\n\n\nType of failover event you want to initiate. Value must be either `GRACEFUL` or `FORCED`. To learn more, see Failover Processors.\n\n
\n`failover.dryRun`\n\n\nboolean\n\n\nOptional\n\n\nFlag that specifies whether to test the failover process without consuming data. Set this field to `true` to validate your failover configuration before you initiate a failover event in production.\n\n
`GRACEFUL` mode takes a checkpoint and confirms that the active processor has stopped before it initiates failover. `FORCED` mode also attempts to stop the active processor, but initiates failover even if the processor doesn't stop. By default, a `FORCED` failover starts the processor in the target region using the most recent checkpoint.\n\nTo start the target processor without recovering from a checkpoint for a `FORCED` failover, set `clearCheckpoints` to `true`:\n\n```sh\nsp..start({\n failover: {\n region: \"\",\n mode: \"FORCED\"\n },\n clearCheckpoints: true\n})\n```\n\nWhen you clear checkpoints, the target processor starts from the current position in the stream instead of recovering its most recent checkpoint. Clearing checkpoints might cause duplicate or missing records in the output.\n\nFor example, to initiate a graceful failover of a stream processor named `proc01` to the `us-west-2` region, run the following command:\n\n```sh\nsp.proc01.start({\n failover: {\n region: \"us-west-2\",\n mode: \"GRACEFUL\",\n dryRun: false\n }\n})\n```\n\nTo stop a stream processor, use the `sp.processor.stop()` method. You don't have to stop the active processor before you initiate failover.\n\n## Drop a Stream Processor\n\nThe Atlas Administration API provides an endpoint for deleting a stream processor.\n\nDelete One Stream Processor\n\n### Click Stream Processors in the left-hand navigation menu.\n\n### Select the stream processor that you want to delete.\n\nFrom the list of stream processors, click the one that you want to delete.\n\nIf your stream processor has a status of `STARTED`, click the stop button in the Actions column to stop it first.\n\n### Click the ellipsis () button in the Actions column."} -{"chunk_id": "68a95b1e5e79d242619c6f81-5", "page_id": "68a95b1e5e79d242619c6f81", "source_name": "cloud-docs", "product_name": "MongoDB Atlas", "url": "https://mongodb.com/docs/atlas/atlas-stream-processing/manage-stream-processor", "title": "Develop and Manage Stream Processors", "text": "### Select Delete stream processor from the menu.\n\nIn the confirmation dialog that appears, type the name of the stream processor to confirm that you want to delete it, then click Delete.\n\nTo delete one stream processor within the stream processing workspace you specify using the Atlas CLI, run the following command:\n\n```sh\n\natlas api streams deleteStreamProcessor [options]\n\n```\n\nTo learn more about the command syntax and parameters, see the Atlas CLI documentation for atlas api streams deleteStreamProcessor.\n\nTo delete an existing stream processor with `mongosh`, use the `sp.processor.drop()` method. It has the following syntax:\n\n```sh\nsp.processor.drop()\n```\n\nWhere `` is a generic, optional document whose fields are passed to the underlying drop command.\n\nFor example, to drop a stream processor named `proc01`, run the following command:\n\n```sh\nsp.proc01.drop()\n```\n\nThis method returns:\n\n- `true` if the stream processor exists.\n\n- `false` if the stream processor doesn't exist.\n\nWhen you drop a stream processor, all resources that Atlas Stream Processing provisioned for it are destroyed, along with all saved state.\n\n## List Available Stream Processors\n\nThe Atlas Administration API provides an endpoint for listing all available stream processors.\n\nList Stream Processors\n\nTo view the list of stream processors defined for your stream processing workspace in the Atlas UI, go to the Stream Processing page for your Atlas project and click Manage in the pane for your stream processing workspace.\n\nThe list of stream processors and their statuses displays.\n\nTo return all stream processors within the stream processing workspace you specify using the Atlas CLI, run the following command:\n\n```sh\n\natlas api streams getStreamProcessors [options]\n\n```\n\nTo learn more about the command syntax and parameters, see the Atlas CLI documentation for atlas api streams getStreamProcessors.\n\nTo list all available stream processors on the current stream processing workspace with `mongosh`, use the `sp.listStreamProcessors()` method. This returns a list of documents containing the name, start time, current state, and pipeline associated with each stream processor. It has the following syntax:\n\n```sh\nsp.listStreamProcessors()\n```\n\n`` is a document specifying which field(s) to filter the list by.\n\nThe following example shows a return value for an unfiltered request:\n\n```sh\nsp.listStreamProcessors()\n```\n\n```json\n{\n id: '0135',\n name: \"proc01\",\n last_modified: ISODate(\"2023-03-20T20:15:54.601Z\"),\n state: \"RUNNING\",\n error_msg: '',\n pipeline: [\n {\n $source: {\n connectionName: \"myKafka\",\n topic: \"stuff\"\n }\n },\n {\n $match: {\n temperature: 46\n }\n },\n {\n $emit: {\n connectionName: \"mySink\",\n topic: \"output\",\n }\n }\n ],\n lastStateChange: ISODate(\"2023-03-20T20:15:59.442Z\")\n},\n{\n id: '0218',\n name: \"proc02\",\n last_modified: ISODate(\"2023-03-21T20:17:33.601Z\"),\n state: \"STOPPED\",\n error_msg: '',\n pipeline: [\n {\n $source: {\n connectionName: \"myKafka\",\n topic: \"things\"\n }\n },\n {\n $match: {\n temperature: 41\n }\n },\n {\n $emit: {\n connectionName: \"mySink\",\n topic: \"results\",\n }\n }\n ],\n lastStateChange: ISODate(\"2023-03-21T20:18:26.139Z\")\n}\n```\n\nIf you run the command again on the same stream processing workspace, filtering for a `\"state\"` of `\"running\"`, you see the following output:\n\n```sh\nsp.listStreamProcessors({\"state\": \"running\"})\n```\n\n```json\n{\n id: '0135',\n name: \"proc01\",\n last_modified: ISODate(\"2023-03-20T20:15:54.601Z\"),\n state: \"RUNNING\",\n error_msg: '',\n pipeline: [\n {\n $source: {\n connectionName: \"myKafka\",\n topic: \"stuff\"\n }\n },\n {\n $match: {\n temperature: 46\n }\n },\n {\n $emit: {\n connectionName: \"mySink\",\n topic: \"output\",\n }\n }\n ],\n lastStateChange: ISODate(\"2023-03-20T20:15:59.442Z\")\n}\n```\n\n## List Workspace Defaults\n\nThe List Stream Workspace Details endpoint lists the details of a stream processing workspace, including the `defaultTierSize` and `maxTierSize`.\n\nTo view the `defaultTierSize` and `maxTierSize` of a stream processing workspace in the Atlas UI, go to the Stream Processing page for your Atlas project.\n\nThe `defaultTierSize` and `maxTierSize` are listed at the bottom of the stream processing workspace card.\n\nTo return details of one stream processing workspace you specify using the Atlas CLI, run the following command:\n\n```sh\n\natlas api streams getStreamWorkspace [options]\n\n```\n\nTo learn more about the command syntax and parameters, see the Atlas CLI documentation for atlas api streams getStreamWorkspace.\n\nTo view the `defaultTierSize` and `maxTierSize` of a stream processing workspace using `mongosh`, use the `sp.listWorkspaceDefaults()` method.\n\n```sh\nsp.listWorkspaceDefaults()\n```\n\nThis method returns:\n\n- `defaultTierSize`\n\n- `maxTierSize`\n\n## Sample from a Stream Processor\n\nTo return an array of sampled results from an existing stream processor to `STDOUT` with `mongosh`, use the `sp.processor.sample()` method. For example, the following command samples from a stream processor named `proc01`.\n\n```sh\nsp.proc01.sample()\n```\n\nThis command runs continuously until you cancel it by using `CTRL-C`, or until the returned samples cumulatively reach 40 MB in size. The stream processor reports invalid documents in the sample in a `_dlqMessage` document of the following form:\n\n```json\n :copyable: false\n {\n _dlqMessage: {\n errInfo: {\n reason: \"\"\n },\n doc: {\n _id: ObjectId(''),\n ...\n },\n processorName: '',\n workspaceName: '',\n dlqTime: ISODate('2024-09-19T20:04:34.263+00:00')\n }\n}\n```\n\nYou can use these messages to diagnose data hygiene issues without defining a dead letter queue collection."} -{"chunk_id": "68a95b1e5e79d242619c6f81-6", "page_id": "68a95b1e5e79d242619c6f81", "source_name": "cloud-docs", "product_name": "MongoDB Atlas", "url": "https://mongodb.com/docs/atlas/atlas-stream-processing/manage-stream-processor", "title": "Develop and Manage Stream Processors", "text": "## View Statistics of a Stream Processor\n\nAtlas Stream Processing discards the internal state of stream processors which have been `stopped` for 45 days or more. When you start such a processor, it operates and reports statistics identically to its initial run.\n\nFor a description of the metrics that Atlas Stream Processing reports for a stream processor, see Stream Processor Metrics.\n\nThe Atlas Administration API provides an endpoint for viewing the statistics of a stream processor.\n\nGet One Stream Processor\n\nTo view monitoring for your stream processor, go to the Stream Processing page for your Atlas project and open the Monitoring tab. Then, select your stream processor from the Stream processor drop-down list at the top left of the page.\n\nTo return a document summarizing the current status of an existing stream processor with `mongosh`, use the `sp.processor.stats()` method. It has the following syntax:\n\n```sh\nsp..stats({options: {}})\n```\n\nWhere `options` is an optional document. To learn more about the command options and output fields, see `sp.processor.stats()`.\n\nFor a description of every field in the output document, see Stream Processor Metrics.\n\nFor example, the following shows the status of a stream processor named `proc01` on a stream processing workspace named `inst01` with item sizes displayed in KB:\n\n```sh\nsp.proc01.stats(1024)\n\n{\n ok: 1,\n ns: 'inst01',\n stats: {\n name: 'proc01',\n status: 'running',\n scaleFactor: Long(\"1\"),\n inputMessageCount: Long(\"706028\"),\n inputMessageSize: 958685236,\n outputMessageCount: Long(\"46322\"),\n outputMessageSize: 85666332,\n dlqMessageCount: Long(\"0\"),\n dlqMessageSize: Long(\"0\"),\n stateSize: Long(\"2747968\"),\n watermark: ISODate(\"2023-12-14T14:35:32.417Z\"),\n addedParallelism: 7,\n ok: 1\n },\n}\n```\n\nThe example shows the overall statistics for the stream processor.\n\nTo see how individual operators behave or how much traffic each target handles, call `sp..stats()` with the `verbose` option and inspect `stats.operatorStats` and, for some operators, `stats.operatorStats.targetStats`.\n\nFor example, for a source operator, `stats.operatorStats.targetStats` collects the `inputMessageCount` and `inputMessageSize` fields for every unique `db`/`coll` or every unique topic:\n\n```sh\n{\n \"name\" : \"KafkaConsumerOperator\",\n \"inputMessageCount\" : NumberLong(100),\n \"inputMessageSize\" : 100352,\n \"targetStats\" : [\n {\n \"topic\" : \"outputTopic1\",\n \"inputMessageCount\" : NumberLong(100),\n \"inputMessageSize\" : 100352\n }\n ],\n ...\n}\n```\n\nAnd for a sink operator, `stats.operatorStats.targetStats` collects the `outputMessageCount` and `outputMessageSize` fields for every unique `db`/`coll` or every unique topic:\n\n```sh\n{\n \"name\" : \"MergeOperator\",\n \"inputMessageCount\" : NumberLong(10),\n \"inputMessageSize\" : 1744,\n \"targetStats\" : [\n {\n \"db\" : \"cust1\",\n \"coll\" : \"outColl1\",\n \"outputMessageCount\" : NumberLong(3),\n \"outputMessageSize\" : 1748\n },\n {\n \"db\" : \"cust2\",\n \"coll\" : \"outColl2\",\n \"outputMessageCount\" : NumberLong(4),\n \"outputMessageSize\" : 2241\n }\n ],\n ...\n}\n```"} -{"chunk_id": "6abbeb4ec55cf82488ba666e-0", "page_id": "6abbeb4ec55cf82488ba666e", "source_name": "cloud-docs", "product_name": "MongoDB Atlas", "url": "https://mongodb.com/docs/atlas/cluster-autoscaling-operations", "title": "Auto-Scaling Operations and Alerts", "text": "# Auto-Scaling Operations and Alerts\n\nThis page covers auto-scaling operations: reviewing auto-scaling activity, configuring auto-scaling alerts, enhancing auto-scaling with effective fields, and getting support for auto-scaling.\n\n## Review Auto-Scaling Activity Feed\n\nYou can view Activity Feed to review the events for each Atlas project. When any auto-scaling event occurs, Atlas logs the event in the project Activity Feed.\n\nAtlas uses the following audit auto-scaling events.\n\nEach auto-scaling event in the Activity Feed includes detailed information about what triggered the scaling action, including:\n\n- The specific metric that triggered the auto-scaling event (such as CPU utilization, memory usage, or disk space).\n\n- The threshold value that was exceeded.\n\n- Whether the scaling was triggered by reactive auto-scaling (in response to current resource usage) or predictive auto-scaling (in anticipation of forecasted demand).\n\nTo view or download only auto-scaling events:\n\nIn Atlas, go to the Project Activity Feed page.\n\n- If it's not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.\n\n- If it's not already displayed, select your desired project from the Projects menu in the navigation bar.\n\n- In the sidebar, click Activity Feed under the Security header.\n\n The Project Activity Feed page displays.\n\n### Filter the activity feed for Atlas events.\n\nIn the Activity Feed, click the Filter by event(s) menu and check Atlas.\n\n### Search for auto-scaling events.\n\nIn the search box above the list, start typing `auto-scaling`.\n\nIn the right-hand side of the menu, all auto-scaling events display. Deselect any that you don't want to see. The feed list automatically updates with each change you make.\n\n## Configure Alerts for Auto-Scaling Events\n\nIn early August 2024, Atlas replaced legacy auto-scaling notification emails with configurable auto-scaling events. By default, Atlas continues to send all alert notifications to the project owners. You can customize your auto-scaling alert distribution to change alert recipients or a distribution method.\n\nAuto-scaling activities are a subset of Atlas alerts. Each time Atlas triggers any of the auto-scaling events, you receive default Atlas alerts.\n\nYou can opt out of or change alert configuration for some or all auto-scaling events at a project level.\n\nAuto-scaling alerts apply to all clusters in a project. You cannot scope alerts to specific clusters. Alert notifications identify which cluster triggered the event by cluster name and ID.\n\nTo modify an alert configuration, in the Category section, select Atlas Auto Scaling and then select the Condition/Metric from the list. You can then modify roles for alert recipients, change a notification method, such as email or SMS, and add a notifier, such as Slack. To learn more, see Configure an Auto-Scaling Alert.\n\n## Enhance Auto-Scaling with Effective Fields in Terraform\n\nThis feature only applies to dedicated clusters in the `M10` tier and upwards, and it is not supported for Flex clusters.\n\nWhen auto-scaling is enabled on a cluster, Atlas automatically adjusts instance sizes and storage capacity based on workload.\n\nIf you use MongoDB & HashiCorp Terraform for your cluster instance sizing and storage configurations, you can specify effective fields for a subset of cluster sizing values. We recommend this approach, this way:\n\n- Spec attributes remain exactly as you defined in your Terraform configuration.\n\n- Default and auto-scaled values are available separately in effective specs (for example, `effectiveElectableSpecs`), and no resource drift occurs when Atlas auto-scales your cluster.\n\n- Your configuration stays clean and represents your intent, while effective specs show the reality of what Atlas has provisioned.\n\nEffective fields ignore only changes to fields managed by specific types of auto-scaling. The following table details the fields ignored when effective fields and specific types of auto-scaling are enabled:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nType of Auto-Scaling Enabled\n\n\nSpecs\n\n\nIgnored Fields\n\n\nNode Type\n\n
\nCompute or Storage\n\n\n`electableSpecs`\n\n\n`instanceSize`, `diskSizeGB`, `diskIOPS`\n\n\nElectable node\n\n
\nCompute or Storage\n\n\n`readOnlySpecs`\n\n\n`instanceSize`, `diskSizeGB`, `diskIOPS`\n\n\nRead-only node\n\n
\nAnalytics\n\n\n`analyticsSpecs`\n\n\n`instanceSize`\n\n\nAnalytics node\n\n
You cannot use effective fields for search nodes.\n\n### Enable Effective Fields\n\n\n\n\n\nTo enable effective fields, include the following header in the API request:\n\n```bash\n--header \"Use-Effective-Instance-Fields: true\"\n```\n\n\n\n\n\nSet the `use_effective_fields` argument to `true` in your resource definition for the cluster as the following example shows:\n\n```bash\n resource \"mongodbatlas_advanced_cluster\" \"this\" {\n project_id = mongodbatlas_project.this.id\n name = var.cluster_name\n cluster_type = var.cluster_type\n use_effective_fields = true\n replication_specs = var.replication_specs\n tags = var.tags\n }\n```\n\nTo learn more, see Effective Fields Module Example.\n\nIf you don't enable effective fields, you must manually configure a `lifecycle.ignore_changes` block to prevent resource drift when auto-scaling occurs. **We do not recommend this approach** . To learn more, see Auto-Scaling in the Terraform documentation.\n\n\n\n"} -{"chunk_id": "6abbeb4ec55cf82488ba666e-1", "page_id": "6abbeb4ec55cf82488ba666e", "source_name": "cloud-docs", "product_name": "MongoDB Atlas", "url": "https://mongodb.com/docs/atlas/cluster-autoscaling-operations", "title": "Auto-Scaling Operations and Alerts", "text": "### Behavior of Effective Fields\n\nOverall, effective fields behaviour falls into one of three scenarios:\n\n```json\n :copyable: true\n {\n \"replicationSpecs\": [\n {\n \"regionConfigs\": [\n {\n \"analyticsAutoScaling\": {\n \"compute\": {\n \"maxInstanceSize\": \"M30\",\n \"minInstanceSize\": \"M10\",\n \"enabled\": true,\n \"scaleDownEnabled\": true\n },\n \"diskGB\": {\n \"enabled\": true\n }\n },\n \"autoScaling\": {\n \"compute\": {\n \"maxInstanceSize\": \"M30\",\n \"minInstanceSize\": \"M10\",\n \"enabled\": true,\n \"scaleDownEnabled\": true\n },\n \"diskGB\": {\n \"enabled\": true\n }\n },\n \"effectiveAnalyticsSpecs\": {\n \"instanceSize\": \"M30\",\n \"diskIOPS\": 3000,\n \"diskSizeGB\": 100.0,\n \"ebsVolumeType\": \"STANDARD\",\n \"nodeCount\": 0\n },\n \"effectiveElectableSpecs\": {\n \"instanceSize\": \"M30\",\n \"diskIOPS\": 3000,\n \"diskSizeGB\": 100.0,\n \"ebsVolumeType\": \"STANDARD\",\n \"nodeCount\": 3\n },\n \"effectiveReadOnlySpecs\": {\n \"instanceSize\": \"M30\",\n \"diskIOPS\": 3000,\n \"diskSizeGB\": 100.0,\n \"ebsVolumeType\": \"STANDARD\",\n \"nodeCount\": 0\n },\n \"electableSpecs\": {\n \"instanceSize\": \"M20\",\n \"diskSizeGB\": 50.0,\n \"nodeCount\": 3\n },\n \"priority\": 7,\n \"providerName\": \"AWS\",\n \"regionName\": \"US_EAST_1\"\n }\n ],\n \"zoneId\": \"6924a70c67695449ba5625ce\",\n \"zoneName\": \"Zone 1\"\n }\n ]\n}\n```\n\n```json\n :copyable: true\n {\n \"replicationSpecs\": [\n {\n \"regionConfigs\": [\n {\n \"effectiveAnalyticsSpecs\": {\n \"instanceSize\": \"M30\",\n \"diskIOPS\": 3000,\n \"diskSizeGB\": 100.0,\n \"ebsVolumeType\": \"STANDARD\",\n \"nodeCount\": 0\n },\n \"effectiveElectableSpecs\": {\n \"instanceSize\": \"M30\",\n \"diskIOPS\": 3000,\n \"diskSizeGB\": 100.0,\n \"ebsVolumeType\": \"STANDARD\",\n \"nodeCount\": 3\n },\n \"effectiveReadOnlySpecs\": {\n \"instanceSize\": \"M30\",\n \"diskIOPS\": 3000,\n \"diskSizeGB\": 100.0,\n \"ebsVolumeType\": \"STANDARD\",\n \"nodeCount\": 0\n },\n \"electableSpecs\": {\n \"instanceSize\": \"M30\",\n \"diskSizeGB\": 100.0,\n \"nodeCount\": 3\n },\n \"priority\": 7,\n \"providerName\": \"AWS\",\n \"regionName\": \"US_EAST_1\"\n }\n ],\n \"zoneId\": \"6924a70c67695449ba5625ce\",\n \"zoneName\": \"Zone 1\"\n }\n ]\n}\n```\n\nIf you don't enable effective fields, you must manually configure a `lifecycle.ignore_changes` block to prevent resource drift when auto-scaling occurs. **We do not recommend this approach** . To learn more, see Auto-Scaling in the Terraform documentation.\n\n```json\n{\n \"replicationSpecs\": [\n {\n \"regionConfigs\": [\n {\n \"analyticsAutoScaling\": {\n \"compute\": {\n \"maxInstanceSize\": \"M30\",\n \"minInstanceSize\": \"M10\",\n \"enabled\": true,\n \"scaleDownEnabled\": true\n },\n \"diskGB\": {\n \"enabled\": true\n }\n },\n \"autoScaling\": {\n \"compute\": {\n \"maxInstanceSize\": \"M30\",\n \"minInstanceSize\": \"M10\",\n \"enabled\": true,\n \"scaleDownEnabled\": true\n },\n \"diskGB\": {\n \"enabled\": true\n }\n },\n \"effectiveAnalyticsSpecs\": {\n \"instanceSize\": \"M30\",\n \"diskIOPS\": 3000,\n \"diskSizeGB\": 100.0,\n \"ebsVolumeType\": \"STANDARD\",\n \"nodeCount\": 0\n },\n \"effectiveElectableSpecs\": {\n \"instanceSize\": \"M30\",\n \"diskIOPS\": 3000,\n \"diskSizeGB\": 100.0,\n \"ebsVolumeType\": \"STANDARD\",\n \"nodeCount\": 3\n },\n \"effectiveReadOnlySpecs\": {\n \"instanceSize\": \"M30\",\n \"diskIOPS\": 3000,\n \"diskSizeGB\": 100.0,\n \"ebsVolumeType\": \"STANDARD\",\n \"nodeCount\": 0\n },\n \"analyticsSpecs\": {\n \"instanceSize\": \"M30\",\n \"diskIOPS\": 3000,\n \"diskSizeGB\": 100.0,\n \"ebsVolumeType\": \"STANDARD\",\n \"nodeCount\": 0\n },\n \"electableSpecs\": {\n \"instanceSize\": \"M30\",\n \"diskIOPS\": 3000,\n \"diskSizeGB\": 100.0,\n \"ebsVolumeType\": \"STANDARD\",\n \"nodeCount\": 3\n },\n \"readOnlySpecs\": {\n \"instanceSize\": \"M30\",\n \"diskIOPS\": 3000,\n \"diskSizeGB\": 100.0,\n \"ebsVolumeType\": \"STANDARD\",\n \"nodeCount\": 0\n },\n \"priority\": 7,\n \"providerName\": \"AWS\",\n \"regionName\": \"US_EAST_1\"\n }\n ],\n \"zoneId\": \"6924a70c67695449ba5625ce\",\n \"zoneName\": \"Zone 1\"\n }\n ]\n }\n```\n\n#### Adjust the Auto-Scaling Range with Effective Fields\n\nIf you enable effective fields, Atlas validates any new auto-scaling range against the cluster's current effective instance size. Atlas rejects a request that sets a range that doesn't contain the current effective instance size. This behavior applies to operational nodes and analytics nodes that use auto-scaling.\n\nThe request fails with a validation error in either of these cases:\n\n- The new minimum instance size is larger than the effective instance size.\n\n- The new maximum instance size is smaller than the effective instance size.\n\nIf the new range still contains the current effective instance size, you can change the bounds in a single request.\n\nIf the current effective instance size falls outside the new range, use the following procedure to move it into the new range before you change the bounds. If you update the instance size in the same request as the range change, Atlas doesn't apply the new instance size while auto-scaling is enabled with effective fields, so the request still fails.\n\n\n\n\n\n##### Disable compute auto-scaling.\n\nSet `compute.enabled` to `false`.\n\n##### Set the instance size to a value inside the intended new range.\n\nSet `instanceSize` to the target value, then send the request.\n\n##### Re-enable compute auto-scaling.\n\nSet `compute.enabled` to `true`.\n\n##### Set the new range bounds.\n\nSet `minInstanceSize` and `maxInstanceSize` to the new bounds, then send the request.\n\n\n\n\n\nTo adjust the auto-scaling range with Terraform, see Adjusting the Auto-Scaling Range with use_effective_fields in the Terraform provider documentation.\n\n\n\n\n\n## MongoDB Support for Atlas Auto-Scaling\n\nIf you have any questions or concerns, contact support."} -{"chunk_id": "698c1edf8ef09cee81a63906-0", "page_id": "698c1edf8ef09cee81a63906", "source_name": "cloud-docs", "product_name": "MongoDB Atlas", "url": "https://mongodb.com/docs/atlas/atlas-stream-processing/sp-agg-setStreamMeta", "title": "`$setStreamMeta` Aggregation Stage (Stream Processing)", "text": "# `$setStreamMeta` Aggregation Stage (Stream Processing)\n\n## Definition\n\n`$setStreamMeta`\nThe `$setStreamMeta` stage sets metadata fields for incoming documents. You can use this metadata to perform selective operations on documents based on specific values without altering the content of the documents themselves.\n\n## Syntax\n\nA `$setStreamMeta` stage has the following prototype form:\n\n```json\n{\n $setStreamMeta: {\n \"\": \n }\n}\n```\n\nThe `$setStreamMeta` stage takes a document with the following fields:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nField\n\n\nType\n\n\nNecessity\n\n\nDescription\n\n
\n``\n\n\nexpression\n\n\nRequired\n\n\nMetadata field to apply to documents. You must set both the key and value:\n\n- The key must be a string beginning with `stream.`.\n\n- The value must be an expression.\n\nIf evaluating the expression fails, Atlas Stream Processing sends the document to the DLQ.\n\nTo learn more, see the Examples.\n\n
\n\n## Behavior\n\n`$setStreamMeta` must come after your `$source` stage and before your $emit or $merge stage.\n\n## Examples\n\nA streaming data source generates a document for each order made with an e-commerce platform. The documents take the following form:\n\n```json\n{\n orderId: 1,\n productId: \"A\",\n qty: 2\n}\n```\n\nAn Atlas database contains a `products` collection with documents of the following form:\n\n```json\n[\n {_id: \"A\", name: \"Laptop\", category: \"tech\"},\n {_id: \"B\", name: \"Shirt\", category: \"clothing\"}\n]\n```\n\nThe following aggregation has six stages:\n\n1. The `$source` stage ingests order documents from the e-commerce platform, exposing each record as it is ingeste to the subsequent aggregation stages.\n\n2. The $lookup stage joins the incoming order documents to a `products` collection in the `shop` database on the `_id` field. The resulting array field is called `product`.\n\n3. The `$unwind` stage turns the single-element array value of `product` into a document.\n\n4. The `$setStreamMeta` stage sets a metadata field called `stream.coll` equal to the value of `product.category`.\n\n5. The `$unset` stage removes the `product` field, returning the source document to its original form.\n\n6. The $merge stage merges the document into a collection dynamically determined by the value of `stream.coll`.\n\n```json\n{\n $source: {\n documents: [\n {\n orderId: 1,\n productId: \"A\",\n qty: 2\n },\n {\n orderId: 2,\n productId: \"B\",\n qty: 1\n },\n {\n orderId: 3,\n productId: \"A\",\n qty: 5\n }\n ]\n }\n},\n{\n $lookup: {\n from: {\n connectionName: \"atlas\",\n db: \"shop\",\n coll: \"products\"\n },\n localField: \"productId\",\n foreignField: \"_id\",\n as: \"product\"\n }\n},\n{\n $unwind: \"$product\"\n},\n{\n $setStreamMeta: {\n \"stream.coll\": \"$product.category\"\n }\n},\n{\n $unset: [\n \"product\"\n ]\n},\n{\n $merge: {\n into: {\n connectionName: \"atlas\",\n db: \"shop\",\n coll: {\n $meta: \"stream.coll\"\n }\n }\n }\n}\n```"} -{"chunk_id": "68a95c4f5e79d242619e3889-0", "page_id": "68a95c4f5e79d242619e3889", "source_name": "cloud-manager", "product_name": "MongoDB Cloud Manager", "url": "https://mongodb.com/docs/cloud-manager/reference/api/performance-advisor/get-dropped-index-suggestions", "title": "Get Index Removal Suggestions", "text": "# Get Index Removal Suggestions\n\nRetrieves index removal suggestions as determined by the Performance Advisor.\n\nBase URL: `https://cloud.mongodb.com/api/public/v1.0`\n\n## Resource\n\n```http\nGET /groups/{PROJECT-ID}/performanceAdvisor/dropIndexSuggestions\n```\n\n### Request Path Parameters\n\n\n\n\n\n\n\n\n\n\n\n\n
\nParameter\n\n\nType\n\n\nDescription\n\n
\nPROJECT-ID\n\n\nstring\n\n\n*(Required)* Unique identifier of the project that owns this MongoDB deployment. Groups and projects are synonymous terms. Your group ID is the same as your project ID.\n\n
\n\n### Request Query Parameters\n\nEither `clusterId` or `hostId` is required.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nParameter\n\n\nType\n\n\nDescription\n\n
\npretty\n\n\nboolean\n\n\nIndicates whether the response body should be in a prettyprint format.\n\n
\nenvelope\n\n\nboolean\n\n\nIndicates whether or not to wrap the response in an envelope.\n\n
\nclusterId\n\n\nstring\n\n\nUnique identifier of a replica set or sharded cluster. Set this parameter to `null` if you want index removal suggestions for a standalone instance using `hostId`.\n\n
\nhostId\n\n\nstring\n\n\nUnique identifier of the standalone instance for which you want index removal suggestions. Required if `clusterId` is `null`.\n\n
\n\n### Request Body Parameters\n\nThis endpoint doesn't use HTTP request body parameters.\n\n## Response\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nDescription\n\n
\n`unusedIndexes`\n\n\narray of documents\n\n\nInformation about unused indexes considered candidates for removal.\n\n
\n`hiddenIndexes`\n\n\narray of documents\n\n\nInformation about hidden indexes that are candidates for removal.\n\n
\n`redundantIndexes`\n\n\narray of documents\n\n\nInformation about redundant indexes that might overlap with existing ones and are considered for removal.\n\n
\n\n## Example Request\n\n```sh\ncurl --user '{PUBLIC-KEY}:{PRIVATE-KEY}' --digest \\\n --header 'Accept: application/json' \\\n --include \\\n --request GET 'https://cloud.mongodb.com/api/public/v1.0/groups/{PROJECT-ID}/performanceAdvisor/dropIndexSuggestions?clusterId={clusterId}&pretty=true'\n```\n\n## Example Response\n\n```json\n{\n \"hiddenIndexes\": [\n {\n \"shardIds\": [\"shard-0\"],\n \"accessCount\": 0,\n \"index\": [\n {\n \"_fts\": \"text\"\n },\n {\n \"_ftsx\": 1\n }\n ],\n \"name\": \"product_description_reviews_text\",\n \"namespace\": \"inventory.products\",\n \"since\": \"2024-10-02T18:02:22Z\",\n \"sizeBytes\": 4096\n },\n {\n \"shardIds\": [\"shard-0\"],\n \"accessCount\": 0,\n \"index\": [\n {\n \"unseenFeature\": 1\n }\n ],\n \"name\": \"unseenFeature_1\",\n \"namespace\": \"inventory.products\",\n \"since\": \"2024-10-02T18:02:22Z\",\n \"sizeBytes\": 4096\n }\n ],\n \"redundantIndexes\": [\n {\n \"shardIds\": [\"shard-0\"],\n \"accessCount\": 0,\n \"index\": [\n {\n \"category\": 1\n }\n ],\n \"name\": \"category_1\",\n \"namespace\": \"inventory.products\",\n \"relatedIndexes\": [\n {\n \"accessCount\": 1,\n \"index\": [\n {\n \"category\": 1\n },\n {\n \"price\": -1\n }\n ],\n \"name\": \"category_1_price_-1\",\n \"namespace\": \"inventory.products\",\n \"since\": \"2024-10-02T18:02:22Z\",\n \"sizeBytes\": 4096\n }\n ],\n \"since\": \"2024-10-02T18:02:22Z\",\n \"sizeBytes\": 4096\n }\n ],\n \"unusedIndexes\": []\n}\n```"} -{"chunk_id": "68a95c4f5e79d242619e3829-0", "page_id": "68a95c4f5e79d242619e3829", "source_name": "cloud-manager", "product_name": "MongoDB Cloud Manager", "url": "https://mongodb.com/docs/cloud-manager/reference/api/identity-provider-return-one-metadata", "title": "Return One Identity Provider's Metadata", "text": "# Return One Identity Provider's Metadata\n\nThe `federationSettings` resource allows you to return the contents of the SAML metadata XML file for one identity provider in the specified federation.\n\n## Required Roles\n\nYou must have the `Organization Owner` role for at least one connected organization in the federation configuration to call this endpoint.\n\n## Resource\n\n```http\nGET /federationSettings/{FEDERATION-SETTINGS-ID}/identityProviders/{IDP-ID}/metadata.xml\n```\n\n### Request Path Parameters\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nDescription\n\n
\n`FEDERATION-SETTINGS-ID`\n\n\nstring\n\n\nUnique 24-hexadecimal digit string that identifies the federated authentication configuration.\n\n
\n`IDP-ID`\n\n\nstring\n\n\nUnique 20-hexadecimal digit string that identifies the IdP (Identity Provider).\n\n
\n\n### Request Query Parameters\n\nThe following query parameters are optional:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nNecessity\n\n\nDescription\n\n\nDefault\n\n
\npretty\n\n\nboolean\n\n\nOptional\n\n\nFlag indicating whether to return the response body in a prettyprint format.\n\n\n`false`\n\n
\nenvelope\n\n\nboolean\n\n\nOptional\n\n\nFlag that indicates whether to wrap the response in an envelope.\n\nSome API (Application Programming Interface) clients can't access the HTTP (Hypertext Transfer Protocol) response headers or status code. To remediate this, set **envelope=true** in the query.\n\nFor endpoints that return one result, the response body includes:\n\n- `status`: HTTP (Hypertext Transfer Protocol) response code\n\n- `content`: Expected response body\n\n\n`false`\n\n
\n\n### Request Body Parameters\n\nThis endpoint doesn't use HTTP request body parameters.\n\n## Response\n\n\n\n\n\n\n\n\n\n\n
\nFile Type\n\n\nDescription\n\n
\nXML\n\n\nMetadata for the IdP (Identity Provider).\n\n
\n\n## Example Request\n\n```sh\ncurl --user \"{PUBLIC-KEY}:{PRIVATE-KEY}\" --digest \\\n --header \"Accept: application/xml\" \\\n --header \"Content-Type: application/xml\" \\\n --include \\\n --request GET \"https://cloud.mongodb.com/api/public/v1.0/federationSettings/{FEDERATION-SETTINGS-ID}/identityProviders/{IDP-ID}/metadata.xml?pretty=true\"\n```\n\n## Example Response\n\n```xml\n\nMIIDpjCCAo6gAwIBAgIGAWqTiVlwMA0GCSqGSIb3DQEBCwUAMIGTMQswCQYDVQQGEwJVUzETMBEG\nA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNU2FuIEZyYW5jaXNjbzENMAsGA1UECgwET2t0YTEU\nMBIGA1UECwwLU1NPUHJvdmlkZXIxFDASBgNVBAMMC21vbmdvZGItZGV2MRwwGgYJKoZIhvcNAQkB\nFg1pbmZvQG9rdGEuY29tMB4XDTE5MDUwNzE4MjIzM1oXDTI5MDUwNzE4MjMzM1owgZMxCzAJBgNV\nBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQHDA1TYW4gRnJhbmNpc2NvMQ0wCwYD\nVQQKDARPa3RhMRQwEgYDVQQLDAtTU09Qcm92aWRlcjEUMBIGA1UEAwwLbW9uZ29kYi1kZXYxHDAa\nBgkqhkiG9w0BCQEWDWluZm9Ab2t0YS5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB\nAQCXHOJx/t+zFgbJzloBRpGhMFxccmvMShn2OQHinrW/s7J49YGbkj0NBWpW+Y6yTZfzGm04mYe+\n/1+m7+ERJpypvlF+tkNcevMmYtxTPjYvGk+GslkjdfDJFSygbtiQkLCQTbpPnGTtVvx+YSg83Rq0\na7QPQ0QeU7utE2NiTOGakIzTLd6Okb2VjBb/cv92P1fcrrY7aDbb27V2+ZBsdv8fg55xrwlMm2uv\nm32ZSRWfWwYgOoUtYZxEQZoOv45MPKf0O5Ok7ICyNZAd5+zI+gS+7keKAE6mF9ux7MfokashORgf\nUN2K77/xYk/1y4XSlKF1vb6+yfZr9MTkyrSCaS/tAgMBAAEwDQYJKoZIhvcNAQELBQADggEBAH+k\niR2cvXUlxOLG6gpMCuZlDdvkayBBwRNprawhEr2LLI8yGV3hRsWxsi2GoXXOCHZ62/rsn3Lg8mvQ\nYAW3knId2ZsEh6mWlUljIjAtUZ5s6067KQV4u/70sO3wBQ0kcs/WnJPfz3Obb7uQ8cv0aa68IJrb\nu8w5NqwWqA3FP1iuG3mfHNh6GI7DhzaVnzm9F5m7pL6hohKHMxF7n/dtuRMPTpc+UvpbnNAz/0kS\n2d9fEHuMo4DXuzFZMy2ZKyFNnsVAwasAN3vdWY2S9ysGoUmCr98dS+nh4mMPSUHoPWj2myP53E08\n+ZRsuZ13zI2C25+U4rgerB8XsxU7OER2CEk=MIIDpjCCAo6gAwIBAgIGAWqTiVlwMA0GCSqGSIb3DQEBCwUAMIGTMQswCQYDVQQGEwJVUzETMBEG\nA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNU2FuIEZyYW5jaXNjbzENMAsGA1UECgwET2t0YTEU\nMBIGA1UECwwLU1NPUHJvdmlkZXIxFDASBgNVBAMMC21vbmdvZGItZGV2MRwwGgYJKoZIhvcNAQkB\nFg1pbmZvQG9rdGEuY29tMB4XFKDLJFHwNzE4MjIzM1oXDTI5MDUwNzE4MjMzM1owgZMxCzAJBgNV\nBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQHDA1TYW4gRnJhbmNpc2NvMQ0wCwYD\nVQQKDARPa3RhMRQwEgYDVQQLDAtTU09Qcm92aWRlcjEUMBIGA1UEAwwLbW9uZ29kYi1kZXYxHDAa\nBgkqhkiG9w0BCQEWDWluZm9Ab2t0YS5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB\nAQCXHOJx/t+zFgbJzloBRpGhMFxccmvMShn2OQHinrW/s7J49YGbkj0NBWpW+Y6yTZfzGm04mYe+\n/1+m7+ERJpypvlF+tkNcevMmYtxTPjYvGk+GQmZSLKJDJAygbtiQkLCQTbpPnGTtVvx+YSg83Rq0\na7QPQ0QeU7utE2NiTOGakIzTLd6Okb2VjBb/cv92P1fcrrY7aDbb27V2+ZBsdv8fg55xrwlMm2uv\nm32ZSRWfWwYgOoUtYZxEQZoOv45MPKf0O5Ok7ICyNZAd5+zI+gS+7keKAE6mF9ux7MfokashORgf\nUN2K77/xYk/1y4XSlKF1vb6+yfZr9MTkyrSCaS/tAgMBAAEwDQYJKoZIhvcNAQELBQADggEBAH+k\niR2cvXUlxOLG6gpMCuZlDdvkayBBwRNprawhEr2LLI8yGV3hRsWxsi2GoXXOCHZ62/rsn3Lg8mvQ\nYAW3knId2ZsEh6mWlUljIjAtUZ5s6067KQV4u/70sO3wBQ0kcs/WnJPfz3Obb7uQ8cv0aa68IJrb\nu8w5NqwWqA3FP1iuG3mfHNh6GI7DhzaVnzm9F5m7pL6hohKHMxF7n/dtuRMPTpc+UvpbnNAz/0kS\n2d9fEHuMo4DXuzFZMy2ZKyFNnsVAwasAN3vdWY2S9ysGoUmCr98dS+nh4mMPSUHoPWj2myP53E08\nl:lang=\"en\">http://www.mongodb.com/\n```"} -{"chunk_id": "6a514d8ed727379c91b9e78f-0", "page_id": "6a514d8ed727379c91b9e78f", "source_name": "cloud-manager", "product_name": "MongoDB Cloud Manager", "url": "https://mongodb.com/docs/cloud-manager/reference/api/service-accounts/org/get-org-sa-access-list", "title": "Get All Access List Entries for One Organization Service Account", "text": "# Get All Access List Entries for One Organization Service Account\n\nBase URL: `https://cloud.mongodb.com/api/public/v1.0`\n\nRetrieve information on all access list entries for the specified service account.\n\n## Resource\n\n```http\nGET /orgs/{ORG-ID}/serviceAccounts/{CLIENT-ID}/accessList\n```\n\n### Request Path Parameters\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nDescription\n\n
\n`ORG-ID`\n\n\nstring\n\n\nUnique identifier for the organization to which the target service account belongs. Request the /orgs endpoint to retrieve all organizations to which the authenticated user has access.\n\n
\n`CLIENT-ID`\n\n\nstring\n\n\nUnique identifier for the service account for which you want to retrieve access list entries. Request the /orgs/{ORG-ID}/serviceAccounts endpoint to retrieve all service accounts for the specified organization to which the authenticated user has access.\n\n
\n\n### Request Query Parameters\n\nThe following query parameters are optional:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nDescription\n\n\nDefault\n\n
\npageNum\n\n\ninteger\n\n\nPage number (1-index based).\n\n\n`1`\n\n
\nitemsPerPage\n\n\ninteger\n\n\nNumber of items to return per page, up to a maximum of 500.\n\n\n`100`\n\n
\npretty\n\n\nboolean\n\n\nIndicates whether to return the response body in a prettyprint format.\n\n\n`false`\n\n
\nenvelope\n\n\nboolean\n\n\nIndicates whether to wrap the response in an envelope.\n\nSome API (Application Programming Interface) clients can't access the HTTP (Hypertext Transfer Protocol) response headers or status code. To remediate this, set `\"envelope\" : true` in the query.\n\nFor endpoints that return one result, response body includes:\n\n- `status`: HTTP (Hypertext Transfer Protocol) response code\n\n- `content`: Expected response body\n\nFor endpoints that return a list of results, the `results` object is an envelope. Cloud Manager adds the `status` field to the response body.\n\n\nNone\n\n
\n\n### Request Body Parameters\n\nThis endpoint doesn't use HTTP request body parameters.\n\n## Response\n\n### Response Document\n\nThe response JSON (Javascript Object Notation) document includes an array of result objects, an array of link objects and a count of the total number of result objects retrieved.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nDescription\n\n
\n`results`\n\n\narray\n\n\nArray includes one object for each item detailed in the `results` Embedded Document section.\n\n
\n`links`\n\n\narray\n\n\nArray includes one or more links to sub-resources and/or related resources. The relations between URL (Uniform Resource Locator)s are explained in the Web Linking Specification.\n\n
\n`totalCount`\n\n\nnumber\n\n\nInteger count of the total number of items in the result set. It may be greater than the number of objects in the results array if the entire result set is paginated.\n\n
\n\n### `results` Embedded Document\n\nEach **result** is one access list entry.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nDescription\n\n
\n`cidrBlock`\n\n\nstring\n\n\nCIDR-notated range of IP addresses in the access list.\n\n
\n`requestCount`\n\n\nnumber\n\n\nTotal number of requests that have originated from this IP address.\n\n
\n`createdAt`\n\n\ndate\n\n\nDate this IP address was added to the access list.\n\n
\n`ipAddress`\n\n\nstring\n\n\nIP address in the access list.\n\n
\n`lastUsedAt`\n\n\ndate\n\n\nDate of the most recent request that originated from this IP address. This field only appears if at least one request has originated from this IP address, and is only updated when a resource is retrieved from the access list.\n\n
\n`lastUsedAddress`\n\n\nstring\n\n\nIP address from which the last call to the API was issued. This field only appears if at least one request has originated from this IP address.\n\n
\n`links`\n\n\narray\n\n\nAn array of documents, representing a link to one or more sub-resources and/or related resources such as list pagination. See Linking for more information.\n\n
\n\n## Example Request\n\n```sh\ncurl --user \"{PUBLIC-KEY}:{PRIVATE-KEY}\" --digest \\\n --header \"Accept: application/json\" \\\n --header \"Content-Type: application/json\" \\\n --request GET \"https://cloud.mongodb.com/api/public/v1.0/orgs/{ORG-ID}/serviceAccounts/{CLIENT-ID}/accessList?pretty=true\"\n```\n\n## Example Response\n\n### Response Header\n\n```http\nHTTP/1.1 401 Unauthorized\nContent-Type: application/json;charset=ISO-8859-1\nDate: {dateInUnixFormat}\nWWW-Authenticate: Digest realm=\"MMS Public API\", domain=\"\", nonce=\"{nonce}\", algorithm=MD5, op=\"auth\", stale=false\nContent-Length: {requestLengthInBytes}\nConnection: keep-alive\n```\n\n```http\nHTTP/1.1 200 OK\nVary: Accept-Encoding\nContent-Type: application/json\nStrict-Transport-Security: max-age=300\nDate: {dateInUnixFormat}\nConnection: keep-alive\nContent-Length: {requestLengthInBytes}\nX-MongoDB-Service-Version: gitHash={gitHash}; versionString={ApplicationVersion}\n```\n\n### Response Body\n\n```json\n{\n \"links\" : [ {\n \"href\" : \"https://cloud.mongodb.com/api/public/v1.0/orgs/{ORG-ID}/serviceAccounts/{CLIENT-ID}/accessList/?pretty=true&pageNum=1&itemsPerPage=100\",\n \"rel\" : \"self\"\n } ],\n \"results\" : [ {\n \"cidrBlock\" : \"147.58.184.16/32\",\n \"requestCount\" : 0,\n \"createdAt\" : \"2019-01-24T16:34:57Z\",\n \"ipAddress\" : \"147.58.184.16\",\n \"lastUsed\" : \"2019-01-24T20:18:25Z\",\n \"lastUsedAddress\": \"147.58.184.16\"\n }, {\n \"cidrBlock\" : \"84.255.48.125/32\",\n \"requestCount\" : 0,\n \"createdAt\" : \"2019-01-24T16:26:37Z\",\n \"ipAddress\" : null,\n \"lastUsed\" : \"2019-01-24T20:18:25Z\",\n \"lastUsedAddress\": \"84.255.48.125\"\n } ],\n \"totalCount\" : 2\n}\n```"} -{"chunk_id": "68a95c4f5e79d242619e39d7-0", "page_id": "68a95c4f5e79d242619e39d7", "source_name": "cloud-manager", "product_name": "MongoDB Cloud Manager", "url": "https://mongodb.com/docs/cloud-manager/security/manage-role-mapping", "title": "Manage Mapping Cloud Manager Roles to IdP Groups", "text": "# Manage Mapping Cloud Manager Roles to IdP Groups\n\nYou can map your IdP (Identity Provider) groups to Cloud Manager roles. This streamlines authorization setup. You can grant one IdP (Identity Provider) group one or more roles to simplify their access to Cloud Manager organizations, projects, and clusters.\n\nYou can't edit roles for specific users on the Access Manager page if you configure role mappings for IdP (Identity Provider) groups.\n\n## Role Mapping Process\n\n1. Cloud Manager applies the role mappings when you log in.\n\n2. Cloud Manager compares the IdP (Identity Provider) groups named **memberOf** to role mappings defined for your organizations. These organizations must use the same IdP (Identity Provider) that the user did to authenticate.\n\n - Cloud Manager applies the mapped roles to federated users if you defined role mappings.\n\n - Cloud Manager applies the default role if:\n\n - You haven't defined role mappings, or\n\n - Role mappings would result in a user without any roles.\n\n - Organization role mappings define federated users' Cloud Manager access. If a federated user logs in but doesn't belong to an IdP (Identity Provider) group mapped to a desired organization, Cloud Manager removes the mapped role from the user in that organization and its projects. The federated user may still belong to other IdP (Identity Provider) groups.\n\n Consider a scenario where a user belongs to the **admin** IdP (Identity Provider) group. You have configured a role mapping of **admin** to the `Organization Owner` in **Organization A**. If you remove that user from the **admin** IdP (Identity Provider) group, Cloud Manager deletes that users' `Organization Owner` role when the user next logs in.\n\n - Every project must have at least one user that has the `Project Owner` role. Cloud Manager won't remove a role if removing the role removes the last owner from a project.\n\n - Every organization must have at least one user that has the `Organization Owner` role. Cloud Manager won't remove a role if removing the role removes the last owner from an organization.\n\n## Prerequisites\n\nTo complete this tutorial, you must have:\n\n- Created an IdP (Identity Provider) application. This application must have a SAML (Security Assertion Markup Language) attribute named to **memberOf**. Map this attribute to the IdP (Identity Provider) source attributes for groups. This attribute links the IdP (Identity Provider) groups with your MongoDB Atlas roles.\n\n- Linked an IdP to Cloud Manager.\n\n- Mapped an organization to your IdP (Identity Provider).\n\n- Created at least one group in your IdP (Identity Provider).\n\n- Added at least one user in your IdP (Identity Provider) application to a group you created.\n\n## Add Role Mappings in Your Organization and its Projects\n\n### In MongoDB Cloud Manager, go to the Organization Settings page.\n\n- If it's not already displayed, select your desired organization from the Organizations menu in the navigation bar.\n\n- In the sidebar, click Organization Settings.\n\n The Organization Settings page displays.\n\n### Open the Federation Management Console.\n\nIn Manage Federation Settings, click Visit Federation Management App.\n\n### Choose an organization in which you want to map roles.\n\n- Click Manage Organizations.\n\n Cloud Manager displays all organizations where you are an `Organization Owner` in a table.\n\n - Organizations connected to federated authentication display in the Actions column.\n\n - Organizations unconnected to federated authentication display Connect in the Actions column.\n\n- To map roles in an organization:\n\n - Click Connect to enable federated authentication for that organization if needed.\n\n - Click and select View.\n\n### Navigate to the Create Role Mapping For Your Users page.\n\n- Click Create Role Mappings.\n\n Cloud Manager displays the Organization Role Mappings page.\n\n- Click Create A Role Mapping.\n\n Cloud Manager displays the Create Role Mapping For Your Users page.\n\nAssign Cloud Manager organization roles to the desired IdP group. At the Map Group and Assign Roles stage:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nSection\n\n\nAction\n\n
\nEnter Group Name\n\n\nType the name of the group as it is displayed in your IdP (Identity Provider) in this field. Cloud Manager assigns this group to your Cloud Manager role.\n\nIf the IdP (Identity Provider) group doesn't exist, you can't enter a new group name to create a new IdP (Identity Provider) group.\n\nIf you use Azure (Microsoft Azure) as your IdP (Identity Provider) and you selected Group Id as your source attribute, enter the group's Object ID in this field instead of the group's name. To learn more, see :ref:cm-configure-azuread-idp`.\n\n
\nAssign Organization Roles\n\n\nClick on each Cloud Manager organization role that you want to assign to the IdP (Identity Provider) group.\n\n
- If you don't need to assign any Cloud Manager project roles to this IdP (Identity Provider) group, click Finish. You can skip the rest of this procedure.\n\n- If you need to assign Cloud Manager project roles to this IdP (Identity Provider) group, click Next.\n\n### Assign project roles to the desired IdP group.\n\nThe Assign Project Roles stage displays a table. This table includes project names and the roles you can assign for those projects. For each project, click the project roles that you want to assign to the IdP (Identity Provider) group.\n\n- If you don't need to review the roles assigned to this IdP (Identity Provider) group, click Finish. You can skip the rest of this procedure.\n\n- If you need to review the roles assigned to this IdP (Identity Provider) group, click Next.\n\n### Verify which roles have been assigned to the desired IdP group.\n\nThe Review and Confirm stage displays the organization and project roles assigned to the IdP (Identity Provider) group.\n\n- If you agree with the roles assigned to this IdP (Identity Provider) group, click Finish.\n\n- If you need to change the roles assigned to this IdP (Identity Provider) group, click . Cloud Manager returns to the Map Group and Assign Roles stage, described in step 4.\n\n## Edit Role Mappings in Your Organization and its Projects\n\n### In MongoDB Cloud Manager, go to the Organization Settings page.\n\n- If it's not already displayed, select your desired organization from the Organizations menu in the navigation bar.\n\n- In the sidebar, click Organization Settings.\n\n The Organization Settings page displays.\n\n### Open the Federation Management Console.\n\nIn Manage Federation Settings, click Visit Federation Management App.\n\n### Choose an organization in which you want to edit role mappings.\n\n- Click Manage Organizations.\n\n Cloud Manager displays all organizations where you are an `Organization Owner` in a table.\n\n- Click next to the desired IdP (Identity Provider)\n Group Name and select View."} -{"chunk_id": "68a95c4f5e79d242619e39d7-1", "page_id": "68a95c4f5e79d242619e39d7", "source_name": "cloud-manager", "product_name": "MongoDB Cloud Manager", "url": "https://mongodb.com/docs/cloud-manager/security/manage-role-mapping", "title": "Manage Mapping Cloud Manager Roles to IdP Groups", "text": "### Navigate to the Create Role Mapping For Your Users page.\n\n- Click Create Role Mappings.\n\n Cloud Manager displays the Organization Role Mappings page.\n\n- Click to the right of the IdP (Identity Provider) group you want to change.\n\n Cloud Manager displays the Edit Your Role Mapping For This Organization page.\n\nAssign Cloud Manager organization roles to the desired IdP group. At the Map Group and Assign Roles stage:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nSection\n\n\nAction\n\n
\nEnter Group Name\n\n\nType the name of the group as it is displayed in your IdP (Identity Provider) in this field. Cloud Manager assigns this group to your Cloud Manager role.\n\nIf the IdP (Identity Provider) group doesn't exist, you can't enter a new group name to create a new IdP (Identity Provider) group.\n\nIf you use Azure (Microsoft Azure) as your IdP (Identity Provider) and you selected Group Id as your source attribute, enter the group's Object ID in this field instead of the group's name. To learn more, see :ref:cm-configure-azuread-idp`.\n\n
\nAssign Organization Roles\n\n\nClick on each Cloud Manager organization role that you want to assign to the IdP (Identity Provider) group.\n\n
- If you don't need to assign any Cloud Manager project roles to this IdP (Identity Provider) group, click Finish. You can skip the rest of this procedure.\n\n- If you need to assign Cloud Manager project roles to this IdP (Identity Provider) group, click Next.\n\n### Assign project roles to the desired IdP group.\n\nThe Assign Project Roles stage displays a table. This table includes project names and the roles you can assign for those projects. For each project, click the project roles that you want to assign to the IdP (Identity Provider) group.\n\n- If you don't need to review the roles assigned to this IdP (Identity Provider) group, click Finish. You can skip the rest of this procedure.\n\n- If you need to review the roles assigned to this IdP (Identity Provider) group, click Next.\n\n### Verify which roles have been assigned to the desired IdP group.\n\nThe Review and Confirm stage displays the organization and project roles assigned to the IdP (Identity Provider) group.\n\n- If you agree with the roles assigned to this IdP (Identity Provider) group, click Finish.\n\n- If you need to change the roles assigned to this IdP (Identity Provider) group, click . Cloud Manager returns to the Map Group and Assign Roles stage, described in step 4.\n\n## Remove One Role Mapping in Your Organization and its Projects\n\n### In MongoDB Cloud Manager, go to the Organization Settings page.\n\n- If it's not already displayed, select your desired organization from the Organizations menu in the navigation bar.\n\n- In the sidebar, click Organization Settings.\n\n The Organization Settings page displays.\n\n### Open the Federation Management Console.\n\nIn Manage Federation Settings, click Visit Federation Management App.\n\n### Choose an organization in which you want to map roles.\n\n- Click Manage Organizations.\n\n Cloud Manager displays all organizations where you are an `Organization Owner` in a table.\n\n - Organizations connected to federated authentication display in the Actions column.\n\n - Organizations unconnected to federated authentication display Connect in the Actions column.\n\n- To map roles in an organization:\n\n - Click Connect to enable federated authentication for that organization if needed.\n\n - Click and select View.\n\n### Navigate to the Organization Role Mappings page.\n\n- Click Create Role Mappings.\n\n Cloud Manager displays the Organization Role Mappings page.\n\n- Click to the right of the IdP (Identity Provider) group you want to remove.\n\n Cloud Manager displays the Delete role mappings for this group modal.\n\n- Click Delete to remove all role mappings from this IdP (Identity Provider) group.\n\n If you don't want to remove all role mappings, click Cancel."} -{"chunk_id": "68a95c4f5e79d242619e3aab-0", "page_id": "68a95c4f5e79d242619e3aab", "source_name": "cloud-manager", "product_name": "MongoDB Cloud Manager", "url": "https://mongodb.com/docs/cloud-manager/tutorial/stop-restart-terminate-backup", "title": "Stop, Restart, or Terminate a Backup", "text": "# Stop, Restart, or Terminate a Backup\n\nWhen you stop backups for a replica set or sharded cluster Cloud Manager stops taking new snapshots but retains existing snapshots until their listed expiration date.\n\nIf you later restart backups for replica set or cluster, Cloud Manager might perform an inital sync, depending on how much time has elapsed.\n\nIf you **terminate** a backup, Cloud Manager immediately **deletes all the backup's snapshots.**\n\n## Stop Backup for a Deployment\n\n### In MongoDB Cloud Manager, go to the Continuous Backup page for your project.\n\n- If it is not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.\n\n- If it's not already displayed, select your desired project from the Projects menu in the navigation bar.\n\n- In the sidebar, click Continuous Backup under the Database heading.\n\n The Continuous Backup page displays.\n\n### Click the Overview tab.\n\n### On the line listing the process, click the ellipsis icon and click Stop.\n\n### Click the Stop button.\n\nIf prompted for an authentication code, enter the code and click Verify. Click Stop again.\n\n## Restart Backup for a Deployment\n\n### In MongoDB Cloud Manager, go to the Continuous Backup page for your project.\n\n- If it is not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.\n\n- If it's not already displayed, select your desired project from the Projects menu in the navigation bar.\n\n- In the sidebar, click Continuous Backup under the Database heading.\n\n The Continuous Backup page displays.\n\n### Click the Overview tab.\n\n### On the line listing the process, click the ellipsis icon and click Restart.\n\n### Select a Sync source and click Restart.\n\n## Terminate a Deployment's Backups\n\nIf you terminate a backup, Cloud Manager immediately deletes the backup's snapshots. The next backup job runs as a full backup rather than an incremental backup.\n\n### In MongoDB Cloud Manager, go to the Continuous Backup page for your project.\n\n- If it is not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.\n\n- If it's not already displayed, select your desired project from the Projects menu in the navigation bar.\n\n- In the sidebar, click Continuous Backup under the Database heading.\n\n The Continuous Backup page displays.\n\n### Click the Overview tab.\n\n### Click the next to the backup.\n\n### Click the Stop button.\n\nIf prompted for an authentication code, enter the code and click Verify. Click Stop again.\n\n### Once the backup has stopped, click the backup's ellipsis icon and click Terminate.\n\n### Click the Terminate button."} -{"chunk_id": "68a95c4f5e79d242619e387f-0", "page_id": "68a95c4f5e79d242619e387f", "source_name": "cloud-manager", "product_name": "MongoDB Cloud Manager", "url": "https://mongodb.com/docs/cloud-manager/reference/api/organizations/organization-get-all-projects", "title": "Get All Projects in an Organization", "text": "# Get All Projects in an Organization\n\nBase URL: `https://cloud.mongodb.com/api/public/v1.0`\n\n## Resource\n\n```http\nGET /orgs/{ORG-ID}/groups\n```\n\n## Request Parameters\n\n### Request Path Parameters\n\n\n\n\n\n\n\n\n\n\n\n\n
\nPath Element\n\n\nType\n\n\nDescription\n\n
\nORG-ID\n\n\nRequired.\n\n\nThe unique identifier for the organization whose information you want to retrieve.\n\n
\n\n### Request Query Parameters\n\nThe following query parameters are optional:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nDescription\n\n\nDefault\n\n
\n`pageNum`\n\n\ninteger\n\n\nPage number (1-based).\n\n\n`1`\n\n
\n`itemsPerPage`\n\n\ninteger\n\n\nNumber of items to return per page, up to a maximum of 500.\n\n\n`100`\n\n
\n`pretty`\n\n\nboolean\n\n\nDisplays response in a prettyprint format.\n\n\n`false`\n\n
\n`envelope`\n\n\nboolean\n\n\nSpecifies whether or not to wrap the response in an envelope.\n\n\n`false`\n\n
\n`name`\n\n\nstring\n\n\nHuman-readable label of the project to use to filter the returned list. Performs a case-insensitive search for a project, which is prefixed by the specified `name`, within the organization.\n\nFor example, if you specify a `name` query parameter of `project1`, Cloud Manager returns the project named `project1`, but would not return a project named `project123`.\n\n\nNone\n\n
\n\n### Request Body Parameters\n\nThis endpoint doesn't use HTTP request body parameters.\n\n## Response\n\n### Response Document\n\nThe response JSON (Javascript Object Notation) document includes an array of result objects, an array of link objects and a count of the total number of result objects retrieved.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nDescription\n\n
\n`results`\n\n\narray\n\n\nArray includes one object for each item detailed in the `results` Embedded Document section.\n\n
\n`links`\n\n\narray\n\n\nArray includes one or more links to sub-resources and/or related resources. The relations between URL (Uniform Resource Locator)s are explained in the Web Linking Specification.\n\n
\n`totalCount`\n\n\nnumber\n\n\nInteger count of the total number of items in the result set. It may be greater than the number of objects in the results array if the entire result set is paginated.\n\n
\n\n### `results` Embedded Document\n\nEach **result** is one project.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nDescription\n\n
\nactiveAgentCount\n\n\ninteger\n\n\nThe number of active monitoring, automation, and Backups in the project.\n\n
\nhostCounts\n\n\nDocument\n\n\nDescribes the host types and number of each host type for the cluster.\n\n
\nhostCounts.arbiter\n\n\ninteger\n\n\nThe number of arbiter hosts in the cluster.\n\n
\nhostCounts.config\n\n\ninteger\n\n\nThe number of sharded cluster configuration server hosts in the cluster.\n\n
\nhostCounts.mongos\n\n\ninteger\n\n\nThe number of `mongos` hosts in the cluster.\n\n
\nhostCounts.primary\n\n\ninteger\n\n\nThe number of primary hosts in the cluster.\n\n
\nhostCounts.secondary\n\n\ninteger\n\n\nThe number of secondary hosts in the cluster.\n\n
\nid\n\n\nstring\n\n\nThe unique identifier for the project.\n\n
\nlinks\n\n\nobject array\n\n\nOne or more links to sub-resources and/or related resources. All `links` arrays in responses include at least one link called `self`. The relationships between URL (Uniform Resource Locator)s are explained in the Web Linking Specification.\n\n
\nname\n\n\nstring\n\n\nThe name of the cluster.\n\n
\norgId\n\n\nstring\n\n\nThe unique identifier for the parent organization of the project.\n\n
\npublicApiEnabled\n\n\nboolean\n\n\nThe status of API access to the cluster.\n\n
\nreplicaSetCount\n\n\ninteger\n\n\nThe number of replica sets in the cluster.\n\n
\nshardCount\n\n\ninteger\n\n\nThe number of shards in the cluster.\n\n
\n\n## Example Request\n\n```shell\ncurl --user \"{username:apiKey}\" \\\n --include \\\n --header \"Content-Type: application/json\" \\\n --digest GET \"https://cloud.mongodb.com/api/public/v1.0/orgs/{ORG-ID}/groups\"\n```\n\n## Example Response\n\n### Response Header\n\n```http\nHTTP/1.1 401 Unauthorized\nContent-Type: application/json;charset=ISO-8859-1\nDate: {dateInUnixFormat}\nWWW-Authenticate: Digest realm=\"MMS Public API\", domain=\"\", nonce=\"{nonce}\", algorithm=MD5, op=\"auth\", stale=false\nContent-Length: {requestLengthInBytes}\nConnection: keep-alive\n```\n\n```http\nHTTP/1.1 200 OK\nVary: Accept-Encoding\nContent-Type: application/json\nStrict-Transport-Security: max-age=300\nDate: {dateInUnixFormat}\nConnection: keep-alive\nContent-Length: {requestLengthInBytes}\nX-MongoDB-Service-Version: gitHash={gitHash}; versionString={ApplicationVersion}\n```\n\n### Response Body\n\n```http\n{\n \"links\": [{\n\n }],\n \"results\": [{\n \"activeAgentCount\": 0,\n \"hostCounts\": {\n \"arbiter\": 0,\n \"config\": 0,\n \"mongos\": 0,\n \"primary\": 1,\n \"secondary\": 2\n },\n \"id\": \"{PROJECT-ID}\",\n \"links\": [{\n\n }],\n \"name\": \"Production Cluster\",\n \"orgId\": \"{ORG-ID}\",\n \"publicApiEnabled\": true,\n \"replicaSetCount\": 1,\n \"shardCount\": 0\n },\n {\n \"activeAgentCount\": 0,\n \"hostCounts\": {\n \"arbiter\": 0,\n \"config\": 0,\n \"mongos\": 0,\n \"primary\": 1,\n \"secondary\": 2\n },\n \"id\": \"{PROJECT-ID}\",\n \"lastActiveAgent\": \"2017-10-26T02:39:59Z\",\n \"links\": [{\n\n }],\n \"name\": \"Staging Cluster\",\n \"orgId\": \"{ORG-ID}\",\n \"publicApiEnabled\": true,\n \"replicaSetCount\": 1,\n \"shardCount\": 0\n }\n ],\n \"totalCount\": 2\n}\n```"} -{"chunk_id": "68a95c4f5e79d242619e377d-0", "page_id": "68a95c4f5e79d242619e377d", "source_name": "cloud-manager", "product_name": "MongoDB Cloud Manager", "url": "https://mongodb.com/docs/cloud-manager/reference/api/automation-config/update-backup-log-attributes", "title": "Update Backup Configuration Settings", "text": "# Update Backup Configuration Settings\n\n## Required Roles\n\nThis resource requires the `Project Automation Admin` role.\n\n## Resource\n\nBase URL: `https://cloud.mongodb.com/api/public/v1.0`\n\n```http\nPUT /groups/{PROJECT-ID}/automationConfig/backupAgentConfig\n```\n\n## Request\n\n### Path Parameters\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nNecessity\n\n\nDescription\n\n
\nPROJECT-ID\n\n\nstring\n\n\nRequired\n\n\nUnique 24-hexadecimal digit string that identifies the project that owns the configuration.\n\n
\n\n### Query Parameters\n\nThe following query parameters are optional:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nNecessity\n\n\nDescription\n\n\nDefault\n\n
\npretty\n\n\nboolean\n\n\nOptional\n\n\nFlag indicating whether to return the response body in a prettyprint format.\n\n\n`false`\n\n
\nenvelope\n\n\nboolean\n\n\nOptional\n\n\nFlag that indicates whether to wrap the response in an envelope.\n\nSome API (Application Programming Interface) clients can't access the HTTP (Hypertext Transfer Protocol) response headers or status code. To remediate this, set **envelope=true** in the query.\n\nFor endpoints that return one result, the response body includes:\n\n- `status`: HTTP (Hypertext Transfer Protocol) response code\n\n- `content`: Expected response body\n\n\n`false`\n\n
\n\n### Body Parameters\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nParameter\n\n\nType\n\n\nNecessity\n\n\nDescription\n\n
\nconfigOverrides\n\n\nobject\n\n\nOptional\n\n\nList of MongoDB Agent settings that you need to change because your backup settings differ from those of the MongoDB Agent. Configure this option when upgrading from legacy agents to the MongoDB Agent.\n\n- `mmsGroupId`: string\n\n- `mmsApiKey`: string\n\n- `mothership`: string\n\n- `mothershipResponseHeaderTimeout`: integer\n\n- `https`: boolean\n\n- `httpProxy`: string\n\n- `krb5Principal`: string\n\n- `krb5Keytab`: string\n\n- `krb5ConfigLocation`: string\n\n- `gsapiServiceName`: string\n\n- `sslClientCertificate`: string\n\n- `sslClientCertificatePassword`: string\n\n- `sslTrustedServerCertificates`: string\n\n- `sslRequireValidServerCertificates`: boolean\n\n- `sslTrustedMMSBackupServerCertificate`: string\n\n
\nlogPath\n\n\nstring\n\n\nOptional\n\n\nAbsolute file path to which this MongoDB Agent writes its logs. If this is not specified, the log writes to standard error (`stderr`) on UNIX- and Linux-based systems and to the Event Log on Windows systems.\n\n
\nlogRotate\n\n\nobject\n\n\nOptional\n\n\nThresholds after which this MongoDB Agent rotates the backup log.\n\n
\nlogRotate.sizeThresholdMB\n\n\ninteger\n\n\nOptional\n\n\nMaximum size, in MB, of a log file before this MongoDB Agent rotates the logs.\n\n
\nlogRotate.timeDurationHrs\n\n\ninteger\n\n\nOptional\n\n\nNumber of hours after which this MongoDB Agent rotates the log file.\n\n
\nusername\n\n\nstring\n\n\nOptional\n\n\nMongoDB user in the application database that manages the backup logs.\n\nIf you use the API (Application Programming Interface) to enable authentication for the MongoDB Agent, set this parameter to **mms-automation** when executing this endpoint.\n\n
\n\n## Response\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nParameter\n\n\nType\n\n\nNecessity\n\n\nDescription\n\n
\nconfigOverrides\n\n\nobject\n\n\nOptional\n\n\nList of MongoDB Agent settings that you need to change because your backup settings differ from those of the MongoDB Agent. Configure this option when upgrading from legacy agents to the MongoDB Agent.\n\n- `mmsGroupId`: string\n\n- `mmsApiKey`: string\n\n- `mothership`: string\n\n- `mothershipResponseHeaderTimeout`: integer\n\n- `https`: boolean\n\n- `httpProxy`: string\n\n- `krb5Principal`: string\n\n- `krb5Keytab`: string\n\n- `krb5ConfigLocation`: string\n\n- `gsapiServiceName`: string\n\n- `sslClientCertificate`: string\n\n- `sslClientCertificatePassword`: string\n\n- `sslTrustedServerCertificates`: string\n\n- `sslRequireValidServerCertificates`: boolean\n\n- `sslTrustedMMSBackupServerCertificate`: string\n\n
\nlogPath\n\n\nstring\n\n\nOptional\n\n\nAbsolute file path to which this MongoDB Agent writes its logs. If this is not specified, the log writes to standard error (`stderr`) on UNIX- and Linux-based systems and to the Event Log on Windows systems.\n\n
\nlogRotate\n\n\nobject\n\n\nOptional\n\n\nThresholds after which this MongoDB Agent rotates the backup log.\n\n
\nlogRotate.sizeThresholdMB\n\n\ninteger\n\n\nOptional\n\n\nMaximum size, in MB, of a log file before this MongoDB Agent rotates the logs.\n\n
\nlogRotate.timeDurationHrs\n\n\ninteger\n\n\nOptional\n\n\nNumber of hours after which this MongoDB Agent rotates the log file.\n\n
\nusername\n\n\nstring\n\n\nOptional\n\n\nMongoDB user in the application database that manages the backup logs.\n\nIf you use the API (Application Programming Interface) to enable authentication for the MongoDB Agent, set this parameter to **mms-automation** when executing this endpoint.\n\n
\n\n## Example Request\n\n```sh\ncurl --user \"{publicApiKey}:{privateApiKey}\" --digest \\\n --header \"Accept: application/json\" \\\n --header \"Content-Type: application/json\" \\\n --include \\\n --request PUT \"https://cloud.mongodb.com/api/public/v1.0/groups/{PROJECT-ID}/automationConfig/backupAgentConfig?pretty=true\" \\\n --data '{\n \"configOverrides\" : {\n \"mmsBaseUrl\" : \"http://new.example.org\"\n },\n \"logPath\": \"/var/log/mongodb-mms-automation/backup-agent.log\",\n \"logRotate\": {\n \"sizeThresholdMB\": 1000,\n \"timeThresholdHrs\": 12\n },\n \"username\": \"mms-automation\"\n }'\n```\n\n## Example Response"} -{"chunk_id": "68a95c4f5e79d242619e377d-1", "page_id": "68a95c4f5e79d242619e377d", "source_name": "cloud-manager", "product_name": "MongoDB Cloud Manager", "url": "https://mongodb.com/docs/cloud-manager/reference/api/automation-config/update-backup-log-attributes", "title": "Update Backup Configuration Settings", "text": "### Response Header\n\n```http\nHTTP/1.1 401 Unauthorized\nContent-Type: application/json;charset=ISO-8859-1\nDate: {dateInUnixFormat}\nWWW-Authenticate: Digest realm=\"MMS Public API\", domain=\"\", nonce=\"{nonce}\", algorithm=MD5, op=\"auth\", stale=false\nContent-Length: {requestLengthInBytes}\nConnection: keep-alive\n```\n\n```http\nHTTP/1.1 200 OK\nVary: Accept-Encoding\nContent-Type: application/json\nStrict-Transport-Security: max-age=300\nDate: {dateInUnixFormat}\nConnection: keep-alive\nContent-Length: {requestLengthInBytes}\nX-MongoDB-Service-Version: gitHash={gitHash}; versionString={ApplicationVersion}\n```\n\n### Response Body\n\nThis endpoint returns an empty JSON (Javascript Object Notation) object."} -{"chunk_id": "68a95c4f5e79d242619e3885-0", "page_id": "68a95c4f5e79d242619e3885", "source_name": "cloud-manager", "product_name": "MongoDB Cloud Manager", "url": "https://mongodb.com/docs/cloud-manager/reference/api/organizations/organization-get-one-invoice", "title": "Get One Organization Invoice", "text": "# Get One Organization Invoice\n\nBase URL: `https://cloud.mongodb.com/api/public/v1.0`\n\n## Resource\n\n```http\nGET /orgs/{ORG-ID}/invoices/{INVOICE-ID}\n```\n\n### Request Path Parameters\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nDescription\n\n
\n`ORG-ID`\n\n\nstring\n\n\nUnique identifier of the organization.\n\n
\n`INVOICE-ID`\n\n\nstring\n\n\nUnique identifier of the invoice. Charges are typically posted the next day.\n\n
\n\n### Request Query Parameters\n\nThe following query parameters are optional:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nNecessity\n\n\nDescription\n\n\nDefault\n\n
\npageNum\n\n\nnumber\n\n\nOptional\n\n\nOne-based integer that returns a subsection of results.\n\n\n`1`\n\n
\nitemsPerPage\n\n\nnumber\n\n\nOptional\n\n\nNumber of items to return per page, up to a maximum of 500.\n\n\n`100`\n\n
\npretty\n\n\nboolean\n\n\nOptional\n\n\nFlag that indicates whether the response body should be in a prettyprint format.\n\n\n`false`\n\n
\nenvelope\n\n\nboolean\n\n\nOptional\n\n\nFlag that indicates whether or not to wrap the response in an envelope.\n\nSome API (Application Programming Interface) clients cannot access the HTTP (Hypertext Transfer Protocol) response headers or status code. To remediate this, set `envelope : true` in the query.\n\nFor endpoints that return a list of results, the `content` object is an envelope. Cloud Manager adds the `status` field to the response body.\n\n\n`false`\n\n
\nbackupJobsEnabledOnly\n\n\nboolean\n\n\nOptional\n\n\nFlag indicating whether to exclude daemons not enabled for backing up databases from the response. Set this to `false` to include daemon configurations with the `backupJobsEnabled` flag set to `false`.\n\n\n`true`\n\n
\n\n### Request Body Parameters\n\nThis endpoint doesn't use HTTP request body parameters."} -{"chunk_id": "68a95c4f5e79d242619e3885-1", "page_id": "68a95c4f5e79d242619e3885", "source_name": "cloud-manager", "product_name": "MongoDB Cloud Manager", "url": "https://mongodb.com/docs/cloud-manager/reference/api/organizations/organization-get-one-invoice", "title": "Get One Organization Invoice", "text": "## Response\n\nIf you set the query element `envelope` to `true`, the response is wrapped by the `content` object.\n\nThe HTTP response returns a JSON document that includes the following objects:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nDescription\n\n
\n`amountBilledCents`\n\n\nnumber\n\n\nAmount billed in this invoice, calculated as **subtotalCents** + **salesTaxCents** - **startingBalanceCents**\n\n
\n`amountPaidCents`\n\n\nnumber\n\n\nAmount paid for this invoice.\n\n
\n`created`\n\n\nstring\n\n\nTimestamp in ISO 8601 date and time format in UTC (Coordinated Universal Time) when this invoice was created.\n\n
\n`creditsCents`\n\n\nnumber\n\n\nAmount credited by MongoDB, in USD cents.\n\n
\n`endDate`\n\n\nstring\n\n\nTimestamp in ISO 8601 date and time format in UTC (Coordinated Universal Time) when the billing period for this invoice ended.\n\n
\n`groupId`\n\n\nstring\n\n\nUnique identifier of the project with which the invoice is associated. *Does not appear on all invoices.*\n\n
\n`id`\n\n\nstring\n\n\nUnique identifier for this invoice.\n\n
\n`lineItems`\n\n\nobject array\n\n\nLine items in the invoice. This information is also found in the Usage Details section of the Invoice page in the Cloud Manager UI.\n\nEach object in the array includes the following fields:\n\n- `clusterName`: The name of the cluster that incurred the charge.\n\n- `created`: Timestamp in ISO 8601 date and time format in UTC (Coordinated Universal Time) when the line item was posted to the invoice.\n\n- `endDate`: Timestamp in ISO 8601 date and time format in UTC (Coordinated Universal Time) when the period for which the line item applies ended.\n\n- `discountCents`: Amount discounted, in USD cents. *Displays when applicable.*\n\n- `groupId`: ID of the project with which the line item is associated.\n\n- `note`: Note regarding the line item.\n\n- `percentDiscount`: Percent of discount. *Displays when applicable.*\n\n- `quantity`: Number of units of the line item (such as GB or hours).\n\n- `replicaSetName`: Name of the replica set with which the line item is associated.\n\n- `sku`: Description of the line item. This could be the instance type, a support charge, advanced security, and so on.\n\n- `startDate`: Timestamp in ISO 8601 date and time format in UTC (Coordinated Universal Time) when the period for which the line item applies began.\n\n- `totalPriceCents`: Total price for the line item, in USD cents. Equal to\n\n ```none\n unitPriceDollars * quantity * 100\n ```\n\n- `unitPriceDollars`: Cost of the item, in dollars.\n\n
\n`links`\n\n\nobject array\n\n\nOne or more links to sub-resources and/or related resources. The relation-types between URLs are explained in the Web Linking Specification.\n\n
\n`orgId`\n\n\nstring\n\n\nUnique identifier for the organization that received this invoice.\n\n
\n`payments`\n\n\nobject array\n\n\nPayments applied to the invoice. Objects in the `payments` array include the following fields:\n\n- `amountBilledCents`: The amount of the invoice, in USD cents.\n\n- `amountPaidCents`: The amount that the customer paid, in USD cents.\n\n- `created`: Timestamp in ISO 8601 date and time format in UTC (Coordinated Universal Time) of the date the payment was recorded.\n\n- `id`: Unique identifier of the payment.\n\n- `salesTaxCents`: Amount of sales tax paid, in USD cents.\n\n- `statusName`: State of the payment.\n\n - `CANCELLED`: The payment has been canceled.\n\n - `FAILED`: The attempt to charge the credit card failed.\n\n - `FORGIVEN`: The payment was created, but was subsequently forgiven.\n\n - `NEW`: The payment has been created, but no attempt has been made to charge the credit card.\n\n - `PAID`: The payment was successful.\n\n- `subtotalCents`: Sum of all positive invoice line items, in USD cents.\n\n- `updated`: Timestamp in ISO 8601 date and time format in UTC (Coordinated Universal Time) that the object was last updated.\n\n
\n`refunds`\n\n\nobject array\n\n\nRefunds issued for the invoice. Objects in the `refunds` array include the following fields:\n\n- `amountCents`: The amount of the refund, in USD cents.\n\n- `created`: Timestamp in ISO 8601 date and time format in UTC (Coordinated Universal Time) of the date the refund was recorded.\n\n- `reason`: Reason for the refund.\n\n- `paymentId`: Unique identifier of the payment.\n\n
\n`salesTaxCents`\n\n\nnumber\n\n\nAmount of taxes levied on **subtotalCents**.\n\n
\n`startDate`\n\n\nstring\n\n\nTimestamp in ISO 8601 date and time format in UTC (Coordinated Universal Time) of the starting date for this invoice.\n\n
\n`statusName`\n\n\nstring\n\n\nState of this invoice. Accepted values are:\n\n- `CLOSED`: All charges for the subscription cycle have been finalized, the balance is more than zero, and the customer has not been charged yet.\n\n- `FAILED`: An attempt to charge the credit card for the amount due failed.\n\n- `FORGIVEN`: The customer has been charged, but the charge has been forgiven.\n\n- `FREE`: The amount turned out to be zero, so the customer is not charged.\n\n- `PAID`: The funds have been transferred to MongoDB, Inc.\n\n- `PENDING`: Includes charges for the current subscription cycle. A customer should never have more than one invoice in this state.\n\n- `PREPAID`: The customer is on a prepaid plan, so the customer is not charged.\n\n
\n`subtotalCents`\n\n\nnumber\n\n\nSum of all positive invoice line items in USD cents.\n\n
\n`updated`\n\n\nstring\n\n\nTimestamp in ISO 8601 date and time format in UTC (Coordinated Universal Time) when the invoice was last updated.\n\n
\n\n## Example Request\n\n```sh\ncurl --user \"{PUBLIC-KEY}:{PRIVATE-KEY}\" --digest \\\n --header \"Accept: application/json\" \\\n --include \\\n --request GET \"https://cloud.mongodb.com/api/public/v1.0/orgs/{ORG-ID}/invoices/{INVOICE-ID}\"\n```"} -{"chunk_id": "68a95c4f5e79d242619e3885-2", "page_id": "68a95c4f5e79d242619e3885", "source_name": "cloud-manager", "product_name": "MongoDB Cloud Manager", "url": "https://mongodb.com/docs/cloud-manager/reference/api/organizations/organization-get-one-invoice", "title": "Get One Organization Invoice", "text": "## Example Response\n\nIn the following sample response, the `lineItems` array has been truncated for ease of viewing.\n\n```text\n{\n \"amountBilledCents\" : 240,\n \"amountPaidCents\" : 240,\n \"created\" : \"2018-04-01T06:14:31Z\",\n \"endDate\" : \"2018-05-01T00:00:00Z\",\n \"id\" : \"{INVOICE-ID}\",\n \"lineItems\" : [ {\n \"clusterName\" : \"{CLUSTER-NAME}\",\n \"created\" : \"2018-05-01T04:05:31Z\",\n \"endDate\" : \"2018-05-01T00:00:00Z\",\n \"groupId\" : \"{PROJECT-ID}\",\n \"quantity\" : 72.0,\n \"replicaSetName\": \"rs0\",\n \"sku\" : \"CLOUD_MANAGER_BASIC\",\n \"startDate\" : \"2018-04-30T00:00:00Z\",\n \"totalPriceCents\" : 0,\n \"unitPriceDollars\" : 0.0\n }, {\n \"clusterName\" : \"{CLUSTER-NAME}\",\n \"created\" : \"2018-04-30T04:05:19Z\",\n \"endDate\" : \"2018-04-30T00:00:00Z\",\n \"groupId\" : \"{PROJECT-ID}\",\n \"quantity\" : 72.0,\n \"replicaSetName\": \"rs0\",\n \"sku\" : \"CLOUD_MANAGER_BASIC\",\n \"startDate\" : \"2018-04-29T00:00:00Z\",\n \"totalPriceCents\" : 0,\n \"unitPriceDollars\" : 0.0\n },\n ... ,\n {\n \"clusterName\" : \"{CLUSTER-NAME}\",\n \"created\" : \"2018-04-02T06:05:07Z\",\n \"endDate\" : \"2018-04-02T00:00:00Z\",\n \"groupId\" : \"{PROJECT-ID}\",\n \"quantity\" : 72.0,\n \"replicaSetName\": \"rs0\",\n \"sku\" : \"CLOUD_MANAGER_BASIC\",\n \"startDate\" : \"2018-04-01T00:00:00Z\",\n \"totalPriceCents\" : 0,\n \"unitPriceDollars\" : 0.0\n } ],\n \"links\" : [ {\n \"href\" : \"https://cloud.mongodb.com/api/public/v1.0/orgs/{ORG-ID}\",\n \"rel\" : \"http://mms.mongodb.com/org\"\n }, {\n \"href\" : \"https://cloud.mongodb.com/api/public/v1.0/orgs/{ORG-ID}/invoices/{INVOICE-ID}\",\n \"rel\" : \"self\"\n } ],\n \"orgId\" : \"{ORG-ID}\",\n \"payments\" : [ {\n \"amountBilledCents\" : 240,\n \"amountPaidCents\" : 240,\n \"created\" : \"2018-05-01T04:05:14Z\",\n \"id\" : \"{PAYMENT-ID}\",\n \"salesTaxCents\" : 19,\n \"statusName\" : \"PAID\",\n \"subtotalCents\" : 221,\n \"updated\" : \"2018-05-01T07:00:46Z\"\n } ],\n \"refunds\" : [ ],\n \"salesTaxCents\" : 19,\n \"startDate\" : \"2018-04-01T00:00:00Z\",\n \"startingBalanceCents\" : 0,\n \"statusName\" : \"PAID\",\n \"subtotalCents\" : 221,\n \"updated\" : \"2018-05-01T07:00:46Z\"\n```"} -{"chunk_id": "68a95c4f5e79d242619e387d-0", "page_id": "68a95c4f5e79d242619e387d", "source_name": "cloud-manager", "product_name": "MongoDB Cloud Manager", "url": "https://mongodb.com/docs/cloud-manager/reference/api/organizations", "title": "Organizations", "text": "# Organizations\n\nThe `orgs` resource provides access to return, update, or remove MongoDB Cloud Manager organizations.\n\nBase URL: `https://cloud.mongodb.com/api/public/v1.0`\n\n## Endpoints\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nMethod\n\n\nEndpoint\n\n\nDescription\n\n
\nGET\n\n\n/orgs\n\n\nReturn the list of all organizations to which the authenticated user belongs.\n\n
\nGET\n\n\n/orgs/{ORG-ID}\n\n\nReturn information about the organization associated with `{ORG-ID}`.\n\n
\nGET\n\n\n/orgs/{ORG-ID}/groups\n\n\nReturn all projects in the organization associated with `{ORG-ID}`.\n\n
\nGET\n\n\n/orgs/{ORG-ID}/users\n\n\nReturn all users in the specified organization.\n\n
\nDELETE\n\n\n/orgs/{ORG-ID}/users/{USER-ID}\n\n\nRemove the user associated with `{USER-ID}` in the organization associated with `{ORG-ID}`.\n\n
\nPUT\n\n\n/orgs/{ORG-ID}/users/{USER-ID}/roles\n\n\nUpdate organization roles for one user.\n\n
\nPATCH\n\n\n/orgs/{ORG-ID}\n\n\nUpdate one organization.\n\n
\nDELETE\n\n\n/orgs/{ORG-ID}\n\n\nRemove the organization associated with `{ORG-ID}`.\n\n
\nPOST\n\n\n/orgs/{ORG-ID}/invites/{INVITATION-ID}\n\n\nCreate one invitation.\n\n
\nDELETE\n\n\n/orgs/{ORG-ID}/invites/{INVITATION-ID}\n\n\nRemove one invitation.\n\n
\nGET\n\n\n/orgs/{ORG-ID}/invites\n\n\nReturn the list of all invitations.\n\n
\nGET\n\n\n/orgs/{ORG-ID}/invites/{INVITATION-ID}\n\n\nReturn one invitation.\n\n
\nPATCH\n\n\n/orgs/{ORG-ID}/invites/{INVITATION-ID}\n\n\nUpdate one invitation by ID.\n\n
\nPATCH\n\n\n/orgs/{ORG-ID}/invites\n\n\nUpdate one invitation.\n\n
"} -{"chunk_id": "68a95c4f5e79d242619e37af-0", "page_id": "68a95c4f5e79d242619e37af", "source_name": "cloud-manager", "product_name": "MongoDB Cloud Manager", "url": "https://mongodb.com/docs/cloud-manager/reference/api/databases", "title": "Databases", "text": "# Databases\n\nBase URL: `https://cloud.mongodb.com/api/public/v1.0`\n\n## Endpoints\n\nThe following endpoints are available for `databases`.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nMethod\n\n\nEndpoint\n\n\nDescription\n\n
\nGET\n\n\n/groups/{PROJECT-ID}/hosts/{HOST-ID}/databases\n\n\nRetrieve all MongodDB processes running on the specified host.\n\n
\nGET\n\n\n/groups/{PROJECT-ID}/hosts/{HOST-ID}/databases/{DATABASE-NAME}\n\n\nRetrieve a single MongoDB process from the specified host by name.\n\n
"} -{"chunk_id": "68a95b1f5e79d242619c75d4-0", "page_id": "68a95b1f5e79d242619c75d4", "source_name": "cloudgov", "product_name": "MongoDB Atlas for Government", "url": "https://mongodb.com/docs/atlas/government/tutorial/create-mongodb-user-for-cluster", "title": "Create a Database User for Your Cluster", "text": "# Create a Database User for Your Cluster\n\nYou must create a database user to access your cluster. For security purposes, AtlasGov requires clients to authenticate as MongoDB database users to access clusters.\n\nDatabase users are separate from AtlasGov users:\n\n- Database users can access databases hosted in AtlasGov.\n\n- AtlasGov users can log in to MongoDB Atlas for Government but do not have access to MongoDB databases.\n\n## Atlas for Government Considerations\n\nDatabase users who authenticate with SCRAM must use `SCRAM-SHA-256`.\n\n## Procedure\n\nTo add a `SCRAM-SHA-256`-authenticated database user to your cluster:\n\n### Click Connect.\n\nIn the Clusters view, click Connect for the cluster to which you want to connect.\n\nAtlasGov highlights the Setup connection security step.\n\n### Set the new user's Username and Password.\n\nYou'll use this username and password combination to grant a user access to databases and collections in your cluster in this AtlasGov project.\n\nTo use a password auto-generated by AtlasGov, click Autogenerate Secure Password.\n\nIf you use special characters in your password, you will need to escape them later in the connection string that you will use to connect to your cluster. To learn more, see Special Characters in Connection String Password.\n\n### Click Create Database User.\n\nTo learn more about configuring database users or to add a user with an alternative authentication method, see Configure Database Users.\n\n## Next steps\n\nTo connect and insert data into your cluster as a database user, follow the Atlas procedures:\n\n1. Connect to Your Cluster\n\n2. Insert and View Data in Your Cluster\n\nTo import existing data from `JSON` or `CSV` files, see Load File with mongoimport."} -{"chunk_id": "68a95b1f5e79d242619c75a3-0", "page_id": "68a95b1f5e79d242619c75a3", "source_name": "cloudgov", "product_name": "MongoDB Atlas for Government", "url": "https://mongodb.com/docs/atlas/government/clusters/monitoring", "title": "Monitoring, Logging and Alerts", "text": "# Monitoring, Logging and Alerts\n\n## Monitoring\n\nYou must have the `Project Owner` role to configure a third-party monitoring integration.\n\nAtlasGov user roles are the same as Atlas User Roles.\n\nSee the Atlas documentation to Integrate with Third-Party Monitoring Services\n\n### Datadog\n\nWhen integrated with Datadog, AtlasGov uses the Datadog for Government site (US1-FED).\n\nTo learn more about US1-FED, see the Datadog documentation.\n\n## Logging\n\nIn addition to the standard Atlas logging, AtlasGov logs the username and IP address associated with all failed login attempts, temporary lockouts and failed API (Application Programming Interface) digest authentications.\n\nSee the Atlas documentation to View and Download MongoDB Logs\n\n## Alerts and Communications\n\nYou receive emails from a different MongoDB account depending on the region to which your resources are deployed and the type of communication.\n\n### AWS GovCloud and GCP Assured Workloads Regions\n\n- Alerts come from `mongodb-atlasgov-alerts@mongodb.com`.\n\n- All other emails come from `mongodb-atlasgov-support@mongodb.com`.\n\n### AWS Commercial\n\n- Alerts come from `mongodb-cloud-alerts@mongodb.com`.\n\n- All other emails come from `mongodb-cloud-support@mongodb.com`.\n\nSee the Atlas documentation to Configure and Resolve Alerts"} -{"chunk_id": "68a95b1f5e79d242619c75d6-0", "page_id": "68a95b1f5e79d242619c75d6", "source_name": "cloudgov", "product_name": "MongoDB Atlas for Government", "url": "https://mongodb.com/docs/atlas/government/tutorial/create-project", "title": "Create a Project", "text": "# Create a Project\n\nWhen you create a project, you are added as an `Project Owner` for the project.\n\n## Prerequisites\n\nTo create a project for an organization, you must be either an `Organization Owner` or an `Organization Project Creator`.\n\n## Atlas for Government Considerations\n\nYou must designate projects for either standard or government (`gov`) region usage upon creation. You cannot deploy clusters across government and standard regions in the same project.\n\nGCP (Google Cloud Platform) is only available in *government region use* projects.\n\n## Procedure\n\nTo create a project for an organization:\n\n### Navigate to the Create a Project page.\n\n- Select an organization for which to create a project from the Organizations menu in the navigation bar.\n\n- Click the Leaf icon in the upper left corner of the page or expand the Projects menu in the navigation bar.\n\n- Click New Project.\n\n### Enter the name for your new project.\n\n### Designate your project for standard or government region use.\n\n- Check Designate as a Gov Cloud regions-only project if you want to deploy clusters only to `gov` regions. Otherwise, you may deploy AWS (Amazon Web Services) clusters only to standard regions. You can't deploy clusters from other cloud providers in this project.\n\n- Click Next.\n\n### Add members.\n\n- For existing AtlasGov users, enter the email that the person used to register.\n\n- For new AtlasGov users, enter their email address to send an invitation.\n\n### Specify the access for the members.\n\n### Click Create Project.\n\nTo learn more about projects, including how to move and delete them, see Projects.\n\n## Next Steps\n\nAfter you create a project, create a cluster in that project."} -{"chunk_id": "68a95b1f5e79d242619c75cc-0", "page_id": "68a95b1f5e79d242619c75cc", "source_name": "cloudgov", "product_name": "MongoDB Atlas for Government", "url": "https://mongodb.com/docs/atlas/government/tutorial/create-cluster", "title": "Create a Cluster", "text": "# Create a Cluster\n\nMongoDB Atlas for Government-managed Atlas deployments, or \"clusters\", can be either a replica set or a sharded cluster. This tutorial walks you through creating a replica set.\n\n## Atlas for Government Considerations\n\n- AtlasGov clusters must be tier `M20` or higher. Atlas doesn't support Free and Flex clusters.\n\n- You must designate projects for either standard or government (`gov`) region usage upon creation. You cannot deploy clusters across government and standard regions in the same project.\n\n## Procedure\n\nTo deploy a cluster in MongoDB Atlas for Government:\n\n### Navigate to the Clusters page for your project.\n\nClick the Context drop down in the top left corner to select the project in which to deploy your cluster.\n\nTo learn more about creating and managing organizations and projects, see Manage Organizations and Manage Projects.\n\n### Click Create a New Cluster.\n\n### Select your preferred Cloud Provider & Region.\n\nFrom the Cloud Provider & Region section, you can also choose to deploy your cluster across multiple regions. Multi-region clusters can better withstand data center outages and may contain dedicated geographic regions for localized reads, thereby improving performance.\n\nYou cannot deploy clusters across government and standard regions.\n\nTo learn more about multi-region clusters, see High Availability and Workload Isolation Options.\n\n### Select a Cluster Tier.\n\nThe selected tier dictates the memory, storage, and IOPS (Input/Output Operations per Second) specification for each data-bearing server in the cluster.\n\nMongoDB Atlas for Government clusters support Cluster Auto-Scaling. When auto-scaling is enabled, AtlasGov automatically scales your cluster tier, storage capacity, or both in response to cluster usage. Consider enabling auto-scaling to allow your cluster to adapt to your current workload and reduce the need to make manual optimizations.\n\n- Cluster storage scaling automatically increases your cluster storage capacity when 90% of disk capacity is used. This setting is on by default to help ensure that your cluster can always support sudden influxes of data.\n\n- Cluster tier scaling automatically scales your cluster tier up or down in response to various cluster metrics. You must manually opt-in to cluster tier scaling.\n\n When you enable cluster tier scaling, you set:\n\n - A maximum cluster tier to which your cluster can automatically scale up, and\n\n - *(Optional)* A minimum tier to which your cluster can scale down.\n\nTo learn more about selecting appropriate cluster tier and storage settings for your workload, see Cluster Tiers and Customize Atlas Core Cluster Storage.\n\n### Set any Additional Settings.\n\n- Select the MongoDB Version of the Cluster\n\n- Configure Backup Options for the Cluster\n\n- Deploy a Sharded Cluster\n\n- Configure the Number of Shards\n\n- Manage Your Own Encryption Keys\n\n- Configure Additional Options\n\n### Enter a Cluster Name.\n\nThis is the cluster name as it appears in MongoDB Atlas for Government. You cannot change the cluster name once AtlasGov deploys the cluster.\n\n### Deploy your cluster.\n\nClick Create Cluster below the form to deploy your cluster.\n\nFor replica sets, the data-bearing servers are the servers hosting the replica set nodes. For sharded clusters, the data-bearing servers are the servers hosting the shards. For sharded clusters, AtlasGov also deploys servers for the config servers; these are charged at a rate separate from the cluster costs.\n\n## Next Steps\n\nTo access your cluster, you must allow your IP address."} -{"chunk_id": "68a95b1f5e79d242619c7585-0", "page_id": "68a95b1f5e79d242619c7585", "source_name": "cloudgov", "product_name": "MongoDB Atlas for Government", "url": "https://mongodb.com/docs/atlas/government/atlas-access", "title": "AtlasGov User Access", "text": "# AtlasGov User Access\n\nThis page covers MongoDB Atlas for Government user accounts. AtlasGov users are separate from database users. Database users can access MongoDB databases, while AtlasGov users can access the AtlasGov application itself.\n\n## Create an AtlasGov Account\n\nMongoDB Atlas for Government is available by invitation only. To create a AtlasGov account, you must either:\n\n- Purchase a subscription and activate an account, or\n\n- Accept an invitation from an existing user in an existing organization.\n\nIf your organization uses federated authentication, AtlasGov adds eligible federated users directly to the organization as active members instead of sending invitations. AtlasGov sends these users a notification email that doesn't require acceptance. To learn more, see the Atlas documentation on inviting federated users.\n\n### Purchase and Activate a Subscription\n\nTo purchase and activate a AtlasGov subscription, see Subscriptions and Billing.\n\n### Accept an Invitation to an Organization\n\nAtlasGov invitations are sent by email. To accept an invitation to an organization:\n\n#### Click Accept Invite in the MongoDB Atlas for Government email you receive.\n\n#### Provide information about yourself.\n\nProvide the following information about yourself:\n\n- First Name\n\n- Last Name\n\n- Password\n\n- Country\n\nYou cannot change your email address or the organization to which you are invited.\n\n#### Accept the MongoDB Atlas for Government Privacy Policy and Terms of Service.\n\n#### Click Sign Up.\n\n### Invite a New User to an Organization\n\nYou must be an `Organization Owner` to invite users to your organization.\n\nTo invite a user to your organization:\n\n#### Navigate to the Organization Access Manager.\n\n- Select your organization from the dropdown menu in the top navigation bar.\n\n- Click Access Manager in the left navigation column.\n\n#### Click Invite Users.\n\n#### Add new organization members and set permissions for each.\n\nFor each new user you want to add to your organization:\n\n- Provide the email address of the person to invite.\n\n- Select organization-level permissions to grant that person from the dropdown menu next to their email address.\n\n#### Click Invite to Organization.\n\nInvitations are sent to the email addresses you provide. Your pending invitations are displayed in the Organization Access Manager.\n\nIf you want to revoke a pending invitation, click the icon next to that invitation.\n\n## Account Limitations\n\n- You cannot register for an AtlasGov account through the login page or create an AtlasGov account using the API (Application Programming Interface). You must receive an activation code from MongoDB Sales or be invited to an existing organization.\n\n- You cannot sign up or log in with third-party accounts, such as Google, GitHub, Apple, or Facebook credentials.\n\n## Account Security\n\n### Passwords\n\n- AtlasGov passwords expire after 60 days.\n\n- You can only change your password once each day.\n\n- When you change your password, you cannot use any of your previous 24 passwords.\n\n- AtlasGov requires that passwords contain:\n\n - At least 14 characters\n\n - Unique characters, numbers, or symbols\n\n### Accounts\n\nAfter 3 failed login attempts, AtlasGov locks your account for 30 minutes, which prevents more login attempts. You can contact MongoDB Support to unlock your account. To learn more, see Support.\n\nAtlasGov automatically suspends user accounts after a period of inactivity for the following accounts:\n\n- For password and Multi-Factor Authentication (MFA) accounts, AtlasGov suspends your account if you don't log in for 35 consecutive days.\n\n- For federated accounts (SAML/OIDC), AtlasGov suspends your account if you don't log in for 90 consecutive days.\n\nTo restore access to a password account suspended due to inactivity, do one of the following steps:\n\n- Reset your password from the AtlasGov login page.\n\n- Contact MongoDB Support through the AtlasGov Support Portal to perform account recovery.\n\nTo restore access to a federated account suspended due to inactivity:\n\n1. Your organization's identity provider (IdP) administrator must ensure your account remains active in the IdP and that any required inactive account policy is configured according to your organization's compliance requirements.\n\n2. After your IdP account is active, sign in again using your federated login. AtlasGov unsuspends your account when you successfully authenticate.\n\n### User Sessions\n\nAtlasGov ends your session after 15 minutes of inactivity, requiring you to log in again. You are prompted to continue your current session after 10 minutes of inactivity.\n\n## Organizations and Projects\n\nSee the Atlas documentation to learn more about using Organizations and Projects to manage AtlasGov user access."} -{"chunk_id": "6ab4c2f96e308268f6d2d8c2-0", "page_id": "6ab4c2f96e308268f6d2d8c2", "source_name": "cloudgov", "product_name": "MongoDB Atlas for Government", "url": "https://mongodb.com/docs/atlas/government/billing/focus-report", "title": "Access the FOCUS Cost and Usage Report in AtlasGov", "text": "# Access the FOCUS Cost and Usage Report in AtlasGov\n\nThe FinOps Open Cost and Usage Specification (FOCUS) establishes uniform requirements for technology billing datasets. MongoDB Atlas for Government provides billing cost and usage data in the FOCUS 1.3 format. You can generate a FOCUS report from the Invoices page in the AtlasGov console or with the FOCUS Data API.\n\nAtlasGov supports the FOCUS cost and usage report in the same way as Atlas, except that the FOCUS Data API uses a different base URL. To learn about the FOCUS format and the report columns, see the Atlas documentation: Access the FOCUS Cost and Usage Report.\n\n## Download a FOCUS Report from the Console\n\nYou can download the FOCUS cost and usage report for an invoice from the Invoices page in the AtlasGov console. Select CSV FOCUS Cost & Usage Report when you choose the invoice format.\n\nTo download the report for the current billing period, see Download Your Current Invoice. To download the report for a past billing period, see Download Past Invoices.\n\nTo view and download billing data, you must have the `Organization Billing Admin`, `Organization Owner`, or `Organization Billing Viewer` role.\n\n## FOCUS Data API Base URL\n\nThe AtlasGov FOCUS Data API uses the following base URL:\n\n```none\nhttps://cloud.mongodbgov.com/api/atlas/v2\n```\n\nThe endpoints, request parameters, and responses are otherwise the same as in Atlas.\n\n### Authentication\n\nThe AtlasGov FOCUS Data API extends the Atlas Administration API and uses the same authentication methods. To learn more, see AtlasGov Programmatic Access.\n\n## Considerations\n\nAtlasGov is designed with additional security, compliance, and operational considerations. To learn how these considerations affect feature availability, see Atlas for Government Considerations.\n\n## Support and Feedback\n\nFor questions about the FOCUS cost and usage report, contact your MongoDB account team."} -{"chunk_id": "68a95b1f5e79d242619c75cb-0", "page_id": "68a95b1f5e79d242619c75cb", "source_name": "cloudgov", "product_name": "MongoDB Atlas for Government", "url": "https://mongodb.com/docs/atlas/government/support", "title": "Support", "text": "# Support\n\nYour MongoDB Atlas for Government subscription entitles you to a premium support plan.\n\n## Support Guarantees\n\nThe same support guarantees that apply to Atlas apply to MongoDB Atlas for Government, including a 99.995% uptime Service Level Agreement (SLA). To learn more about commercial Atlas support, see Support.\n\nMongoDB Atlas for Government projects have guaranteed support from US persons on US soil.\n\n## Request Support\n\n### Organization Support\n\nOnly `Organization Owners` can open a support case at the organization level. Organizations with no projects cannot open a support case.\n\n1. Select your organization from the Organizations menu in the navigation bar.\n\n2. Click Support in the sidebar.\n\n### Project Support\n\n1. Select your organization from the Organizations menu in the navigation bar.\n\n2. Select your project from the Projects menu in the navigation bar.\n\n3. Next to the Projects menu, expand the Options menu, then click Project Support.\n\n## Required Roles\n\nTo raise and view support cases, you must have the appropriate role:\n\nAtlasGov user roles are the same as Atlas User Roles.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nSupport Cases\n\n\nScope\n\n\nRole\n\n
\nCan View\n\n\nProject\n\n\nAny user with any role in the project\n\n
\nCan Raise\n\n\nProject\n\n\nAll user with any project role except the `Project Read Only` role\n\n
\nCan View and Raise\n\n\nOrganization and Project\n\n\nAny user with the `Organization Owner` for the organization\n\n
"} -{"chunk_id": "68a95b1f5e79d242619c759e-0", "page_id": "68a95b1f5e79d242619c759e", "source_name": "cloudgov", "product_name": "MongoDB Atlas for Government", "url": "https://mongodb.com/docs/atlas/government/clusters/backup-restore-data", "title": "Backup and Restore Cluster Data", "text": "# Backup and Restore Cluster Data\n\nBackups are copies of your data that encapsulate the state of your cluster at a given time. Backups provide a safety measure in the event of data loss.\n\nYou must have the `Project Owner` role for an AtlasGov project to manage backups for or to restore a backup to clusters in that project.\n\nAtlasGov user roles are the same as Atlas User Roles.\n\nRestores between standard projects and Gov region-only projects are not allowed. If a backup is created from a cluster in a Gov region-only (AWS GovCloud or GCP Assured Workloads) project, the data can only be restored to a cluster in a Gov region-only project. The same restriction applies to standard projects, where backups in standard regions can only be restored to clusters in standard projects.\n\nCross-cloud restore is supported between AWS GovCloud and GCP Assured Workloads regions.\n\nFor a list of regions by cloud provider, see Supported Cloud Providers and Regions.\n\nSee the Atlas documentation to configure Cloud Backups"} -{"chunk_id": "68a95b1f5e79d242619c75cf-0", "page_id": "68a95b1f5e79d242619c75cf", "source_name": "cloudgov", "product_name": "MongoDB Atlas for Government", "url": "https://mongodb.com/docs/atlas/government/tutorial/allow-ip", "title": "Add Your Connection IP Address to IP Access List", "text": "# Add Your Connection IP Address to IP Access List\n\nAn IP (Internet Protocol) is a unique numeric identifier for a device connecting to a network. In MongoDB Atlas for Government, you can only connect to a cluster from a trusted IP address. Within AtlasGov, you can create a list of trusted IP addresses, referred to as a IP access list, that can be used to connect to your cluster and access your data.\n\nData Explorer in Atlas does not respect data plane IP access restrictions. If you do not want Atlas Users to be able to view or modify data via the Atlas UI, disable Data Explorer in Atlas. To learn more, see:\n\n- Disable Data Interaction in Atlas\n\n- Disable Data Interaction in Ops Manager\n\n- Disable Data Interaction in Cloud Manager\n\n## Procedure\n\nYou must add your IP address to the IP access list before you can connect to your cluster. To add your IP address to the IP access list:\n\n### Click Connect.\n\nIn the Clusters view, click Connect for the cluster to which you want to connect.\n\nAtlas highlights the Setup connection security step.\n\n### Click Add Your Current IP Address.\n\nTo secure your AtlasGov cluster, limit access to specified IP addresses.\n\nThe menu expands to show the Add a connection IP address modal.\n\n### Click Add IP Address.\n\nConfigure IP Access List Entries\n\n## Next Steps\n\nAfter allowing your IP address, you must create a database user to connect to your cluster."} -{"chunk_id": "68a95b1f5e79d242619c75c6-0", "page_id": "68a95b1f5e79d242619c75c6", "source_name": "cloudgov", "product_name": "MongoDB Atlas for Government", "url": "https://mongodb.com/docs/atlas/government/security", "title": "Security", "text": "# Security\n\n## Preconfigured Security Features\n\n### TLS (Transport Layer Security)\n\nMongoDB Atlas for Government and databases hosted in AtlasGov use TLS (Transport Layer Security) 1.2 to encrypt connections. This cannot be disabled, and AtlasGov does not allow TLS (Transport Layer Security) versions less than 1.2.\n\n### FIPS (Federal Information Processing Standard) 140-2\n\nAtlasGov automatically enables FIPS (Federal Information Processing Standard) 140-2 Level 2 for all databases.\n\n## Required Security Features\n\nYou *must* configure the following security features:\n\n- IP access list, and\n\n- Database user authentication.\n\n## Optional Security Features\n\nA subset of commercial Atlas\noptional security features are available in AtlasGov with some limitations.\n\n### Encryption at Rest\n\n- You must use KMS keys in AWS GovCloud and GCP Assured Workloads regions to encrypt data in AWS GovCloud and GCP Assured Workloads region-only projects. You must use KMS keys in AWS Commercial regions to encrypt data in AWS Commercial region-only projects.\n\nSee the Atlas documentation to configure Customer Key Management with AWS KMS and Manage Customer Keys with Google Cloud KMS.\n\n### VPC (Virtual Private Cloud) Peering\n\n- You can only peer AWS GovCloud regions with MongoDB clusters in AWS GovCloud regions. You can only peer AWS Commercial regions with MongoDB clusters in AWS Commercial regions.\n\n- You can only peer GCP Assured Workloads regions with MongoDB clusters in GCP Assured Workloads regions.\n\nSee the Atlas documentation to Set up a Network Peering Connection\n\n### Private Endpoints\n\n- You can only link AWS GovCloud regions with MongoDB clusters in AWS GovCloud regions. You can only link AWS Commercial regions with MongoDB clusters in AWS Commercial regions.\n\n- You can only link GCP Assured Workloads regions with MongoDB clusters in GCP Assured Workloads regions.\n\nSee the Atlas documentation to Set up a Private Endpoint.\n\n### Backup Compliance Policy\n\nSee the Atlas documentation to Configure a Backup Compliance Policy.\n\n### Outbound IP Addresses\n\nYou can use the following endpoints:\n\n- Use the Return All IP Addresses for One Project endpoint to retrieve all outbound IP addresses for the clusters in your project. To use this endpoint, your API key must have the `Project Read Only` role.\n\n- Use the Return All Control Plane IP Addresses endpoint to retrieve all outbound IP addresses for the Atlas control plane, categorized by cloud provider."} -{"chunk_id": "68a95be35e79d242619d8152-0", "page_id": "68a95be35e79d242619d8152", "source_name": "compass", "product_name": "MongoDB Compass", "url": "https://mongodb.com/docs/compass/documents/delete-multiple", "title": "Delete Multiple Documents", "text": "# Delete Multiple Documents\n\nMongoDB Compass Readonly Edition will be deprecated in a future release. To replicate the read-only behavior in a standard Compass edition, assign users `read` access at the database level and enable the readOnly option in Compass.You can perform bulk delete operations on multiple documents in Compass by using the Delete Documents modal. This helps you visualize deletes before applying them.\n\n## About this Task\n\nDeleting documents is a permanent action and cannot not be undone. Validate documents in the Preview of the Delete Documents modal before confirming the delete operation.\n\n## Steps\n\n### Apply a query filter.\n\nFrom the Documents tab, input a query into the Query Bar to filter deleted documents. To delete all documents in the collection, leave the Query Bar blank.\n\n### Open the bulk delete modal.\n\nOn the Documents tab, either right-click the query bar or its surrounding whitespace and select Bulk delete from the dropdown, or click the Bulk drop-down menu and select Bulk delete documents, to display the Delete Documents modal. The modal contains the following information:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nUI Element\n\n\nDescription\n\n
\nQuery\n\n\nAny filter criteria specified on the Query Bar applies to the Delete Documents modal. To update the Query, exit the Delete Documents modal and modify the query in the Query Bar.\n\n
\nExport\n\n\nOpens the Export Delete Query To Language modal, where you can convert the query to a supported driver language.\n\n
\nPreview\n\n\nA preview of the documents that will be deleted.\n\n
\n\n### (Optional) Export the delete query.\n\nYou can export the Delete query to a supported driver language using the Export button on the Delete Documents modal.\n\n- On the Delete Documents modal, click Export. The Export Delete Query To Language modal displays with the delete syntax populated under My Delete Query.\n\n- Select a programming language from the drop-down under Exported Delete Query. You can convert the command to C#, Go, Java, Node, PHP, Python, Ruby, or Rust. The field below displays the converted syntax.\n\n- (Optional) Click the Include Import Statements checkbox to include the required import statements for the selected programming language.\n\n- Click the icon to copy the converted syntax.\n\n- Click Close.\n\n### Delete your documents.\n\nOn the Delete Documents modal, click Delete Documents and confirm the operation on the next modal.\n\nCompass deletes the documents that match the filter expression.\n\n## Example\n\nThe following example deletes two documents from the `movies` collection in the sample_mflix dataset.\n\nIn the Query Bar, enter a filter for movies with a `year` of `1919`.\n\n```javascript\n{ 'year' : 1919 }\n```\n\nClick the Bulk drop-down menu and select Bulk delete documents. The Delete Documents modal displays.\n\nThe Preview pane shows the documents included in the delete operation.\n\nClick Delete Documents. A confirmation modal displays.\n\nClick the red Delete Documents button to confirm the operation.\n\n## Learn More\n\n- Modify Multiple Documents"} -{"chunk_id": "68a95be35e79d242619d8142-0", "page_id": "68a95be35e79d242619d8142", "source_name": "compass", "product_name": "MongoDB Compass", "url": "https://mongodb.com/docs/compass/connect/favorite-connections/import-export-ui/import", "title": "Import Saved Connections in Compass", "text": "# Import Saved Connections in Compass\n\nMongoDB Compass Readonly Edition will be deprecated in a future release. To replicate the read-only behavior in a standard Compass edition, assign users `read` access at the database level and enable the readOnly option in Compass.You can import saved connections in MongoDB Compass. This lets you use saved connections from other workspaces or connections used by other team members.\n\n## Prerequisite\n\nBefore you import saved connections, you must export the connections.\n\n## Procedure\n\nTo import saved connections from a JSON file into Compass:\n\nOn the Connect screen, hover over Saved Connections in the left-side navigation and click the Ellipses (...) button.\n\n### Select Import saved connections.\n\n### Under Source File, click Select a file.\n\n### Select the exported JSON file you want to import.\n\nIf your file is encrypted with a password, enter the passphrase under Decryption Password.\n\n### Select the connection names you want to import.\n\nIf the connection name already exists under your saved connections, Compass overwrites the existing connection with the imported connection.\n\n### Click Import.\n\n## Results\n\nAfter the connections are imported, they appear on the left-side navigation of the Connect screen under Saved Connections."} -{"chunk_id": "68a95be35e79d242619d81d7-0", "page_id": "68a95be35e79d242619d81d7", "source_name": "compass", "product_name": "MongoDB Compass", "url": "https://mongodb.com/docs/compass/settings/specify-read-preference-tags", "title": "Specify Read Preference and Tags", "text": "# Specify Read Preference and Tags\n\nMongoDB Compass Readonly Edition will be deprecated in a future release. To replicate the read-only behavior in a standard Compass edition, assign users `read` access at the database level and enable the readOnly option in Compass.You can use the `forceConnectionOptions` option to set required connection option values on Compass. By setting required connection options such as read preference, you can restrict how users connect to your MongoDB deployment and ensure that their read operations don't impact the availability of replica set primaries.\n\n## Procedure\n\nIn this example, you limit read operations to read only from `SECONDARY` replica set members with the `ANALYTICS` and `READ_ONLY` tags. You can specify these options on the command line or in a configuration file.\n\n### Command Line Example\n\nThe following command starts MongoDB Compass from the command line and uses `--forceConnectionOptions` to set the `readPreference` and `readPreferenceTags` options:\n\n```sh\n \\\n--forceConnectionOptions.readPreference=secondary \\\n--forceConnectionOptions.readPreferenceTags=nodeType:ANALYTICS \\\n--forceConnectionOptions.readPreferenceTags=nodeType:READ_ONLY\n```\n\nThe name and filepath of the Compass executable depend on your operating system.\n\n### Configuration File Example\n\nYou can specify the Compass configuration file in either EJSON or YAML format. To set the `readPreference` and `readPreferenceTags`, use `--forceConnectionOptions`:\n\n#### EJSON\n\n```json\n{\n \"forceConnectionOptions\": [\n [\"readPreference\", \"secondary\"],\n [\"readPreferenceTags\", \"nodeType:ANALYTICS\"],\n [\"readPreferenceTags\", \"nodeType:READ_ONLY\"]\n ]\n}\n```\n\n#### YAML\n\n```yaml\nforceConnectionOptions:\n - readPreference: secondary\n - readPreferenceTags: nodeType:ANALYTICS\n - readPreferenceTags: nodeType:READ_ONLY\n```\n\n## Learn More\n\nTo learn more about the MongoDB Compass configuration file, see Configuration File Settings."} -{"chunk_id": "68a95be35e79d242619d81a1-0", "page_id": "68a95be35e79d242619d81a1", "source_name": "compass", "product_name": "MongoDB Compass", "url": "https://mongodb.com/docs/compass/query-with-natural-language/prompt-natural-language-query", "title": "Prompt a Natural Language Query", "text": "# Prompt a Natural Language Query\n\nMongoDB Compass Readonly Edition will be deprecated in a future release. To replicate the read-only behavior in a standard Compass edition, assign users `read` access at the database level and enable the readOnly option in Compass.You can use MongoDB Compass to generate queries using natural language. Compass uses AI to generate queries based on prompts you provide. Querying with natural language can be a helpful starting point and assist you in learning to write MongoDB queries.\n\n## About this Task\n\nWhen you query your data using natural language in Compass, the text of your prompts and details about your MongoDB schemas are sent to Microsoft and OpenAI for processing. Your data is not stored on any third party storage systems or used to train AI models.\n\nThis software uses generative artificial intelligence. It is experimental and may give inaccurate results.\n\n- You can query with natural language to create both queries and aggregations. If your prompt results in an aggregation, you are automatically redirected to the Aggregations tab and a pop-up displays indicating your prompt requires aggregation stages.\n\n- You can also provide natural language prompts on the aggregations tab.\n\n- This page uses the sample_mflix.movies collection from the Atlas sample dataset.\n\n- It can be difficult to predict the complexity of the query or pipeline returned by the Compass AI. You may need to adjust the MAX TIME MS query bar option to either allow longer query processing time or prevent long-running queries. For details, see Adjust Maximum Time for Query Operations.\n\n## Before you Begin\n\nYou must enable natural language querying in Compass.\n\n## Steps\n\n### Navigate to the Natural Language Query Bar\n\n- Select the Documents tab.\n\n- Click the Generate query button.\n\nThe Natural Language Query Bar displays.\n\n### Type a question about your collection\n\nType a natural language prompt for your collection into the query bar. For example: `Which movies were released in 2000?`\n\n- Press enter or click the Generate query button.\n\n- A filter query populates in the Filter bar.\n\nIt is also possible to paste SQL or queries from application code into the Natural Language Query Bar.\n\n### Run the query\n\n- Before running the query, make sure to thoroughly review the syntax in the Filter bar. Ensure the returned query has the fields and operators that match your desired use case.\n\n- Press enter or click the Find button to execute the query.\n\nThe results populate in the documents view.\n\nYou can optionally provide feedback by clicking the or icon by the Natural Language Query Bar and provide details on your experience.\n\nYour feedback **is not** used to train any AI models.\n\n## Example\n\nBelow are examples of prompts to help you understand expected results when using natural language prompts.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nPrompt\n\n\nResponse\n\n
\n`Which movies have a \"PG\" rating?`\n\n\n```json\n{\"rated\": \"PG\"}\n```\n\n
\n`Which movies include \"David Mamet\" in the writers array field?`\n\n\n```json\n{\"writers\": \"David Mamet\"}\n```\n\n
\n`Which movies have a runtime greater than 90?`\n\n\n```json\n{\"runtime\": {$gt: 90}}\n```\n\n
\n\n## Next Steps\n\nPrompt a Natural Language Aggregation\n\n## Learn More\n\nQuery with Natural Language"} -{"chunk_id": "68a95be35e79d242619d81b1-0", "page_id": "68a95be35e79d242619d81b1", "source_name": "compass", "product_name": "MongoDB Compass", "url": "https://mongodb.com/docs/compass/query/queries", "title": "Manage Saved Queries in Compass", "text": "# Manage Saved Queries in Compass\n\nMongoDB Compass Readonly Edition will be deprecated in a future release. To replicate the read-only behavior in a standard Compass edition, assign users `read` access at the database level and enable the readOnly option in Compass.After you connect to your cluster, you can load saved queries from the My Queries view. This page explains how to add and view favorite queries.\n\n## Save a Favorite Query\n\nYou can favorite a query so that you can find it later. If you load a favorite query, you can change it without changing the original saved copy.\n\nTo add a query to your favorites:\n\n### Open query history\n\nClick the History button on the query bar in the Documents pane.\n\n### Select favorites\n\nHover over your query and click the Star button.\n\n### Name your query\n\nEnter a name for your query.\n\n### Click Save.\n\n## View Saved Queries\n\nAfter you connect to your cluster, you can view your saved queries and aggregation pipelines on the My Queries tab.\n\nTo learn how to save and view aggregation pipelines, see:\n\n- Save a Pipeline\n\n- Open a Saved Pipeline\n\n### Use the My Queries Tab\n\nWhen you click a saved or favorite query tile, Compass opens the Documents tab with the filter loaded.\n\nIn the My Queries tab, you can also click a saved aggregation pipeline tile to open the Aggregations tab with the pipeline loaded.\n\n### Use the Favorites Tab\n\nYou can also view favorite queries from the Favorites tab from in the Documents view. To open the Favorites tab:\n\n#### Open query history\n\nClick the History button at the top of the Documents tab.\n\n#### Click the Favorites button in the past queries pane.\n\nSelect your favorited operation.\n\n- If your favorited operation is a query, only a Filter statement displays in the Favorites list view along with copy and delete icons.\n\n Clicking a favorited query in the Favorites list view populates your Query Bar with that query.\n\n- If your favorited operation is a bulk update statement, a Filter and Update statement display in the Favorites list view along with copy , delete , and open in modal icons.\n\n Clicking the icon opens the bulk update statement and the filter criteria in the Update Documents modal. For details on bulk update statements in Compass, see Modify Multiple Documents.\n\n## View Query History\n\nFor details on how to view query history see viewing recent query history."} -{"chunk_id": "68a95be35e79d242619d818a-0", "page_id": "68a95be35e79d242619d818a", "source_name": "compass", "product_name": "MongoDB Compass", "url": "https://mongodb.com/docs/compass/keyboard-shortcuts", "title": "Keyboard Shortcuts", "text": "# Keyboard Shortcuts\n\nMongoDB Compass Readonly Edition will be deprecated in a future release. To replicate the read-only behavior in a standard Compass edition, assign users `read` access at the database level and enable the readOnly option in Compass.Keyboard shortcuts enable you to easily navigate Compass.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nCategory\n\n\nDescription\n\n\nWindows\n\n\nMac\n\n
\nMenu\n\n\nOnline help\n\n\nF1\n\n\nF1\n\n
\nMenu\n\n\nQuit application\n\n\nCtrl + Q\n\n\nCmd + Q\n\n
\nMenu\n\n\nShow settings\n\n\nCtrl + ,\n\n\nCmd + ,\n\n
\nMenu\n\n\nHide window\n\n\nCtrl + H\n\n\nCmd + H\n\n
\nMenu\n\n\nHide other windows\n\n\nCtrl + Shift + H\n\n\nCmd + Shift + H\n\n
\nMenu\n\n\nOpen a new Compass window\n\n\nCtrl + N\n\n\nCmd + N\n\n
\nMenu\n\n\nClose current window\n\n\n`Ctrl` + `Shift` + `W`\n\n\n`Cmd` + `Shift` + `W`\n\n
\nMenu\n\n\nShare schema as JSON\n\n\nAlt + Ctrl + S\n\n\nAlt + Cmd + S\n\n
\nMenu\n\n\nReload screen\n\n\nCtrl + Shift + R\n\n\nCmd + Shift + R\n\n
\nMenu\n\n\nReload data\n\n\nCtrl + R\n\n\nCmd + R\n\n
\nMenu\n\n\nToggle sidebar\n\n\nCtrl + Shift + D\n\n\nCmd + Shift + D\n\n
\nMenu\n\n\nActual size\n\n\nCtrl + 0\n\n\nCmd + 0\n\n
\nMenu\n\n\nZoom in\n\n\nCtrl + =\n\n\nCmd + =\n\n
\nMenu\n\n\nZoom out\n\n\nCtrl + -\n\n\nCmd + -\n\n
\nMenu\n\n\nToggle DevTools\n\n\nAlt + Ctrl + I\n\n\nAlt + Cmd + I\n\n
\nMenu\n\n\nMinimize\n\n\nCtrl + M\n\n\nCmd + M\n\n
\nGeneral\n\n\nUndo\n\n\nCtrl + Z\n\n\nCmd + Z\n\n
\nGeneral\n\n\nRedo\n\n\nCtrl + Shift + Z\n\n\nCmd + Shift + Z\n\n
\nGeneral\n\n\nCut\n\n\nCtrl + X\n\n\nCmd + X\n\n
\nGeneral\n\n\nCopy\n\n\nCtrl + C\n\n\nCmd + C\n\n
\nGeneral\n\n\nPaste\n\n\nCtrl + V\n\n\nCmd + V\n\n
\nGeneral\n\n\nSelect all\n\n\nCtrl + A\n\n\nCmd + A\n\n
\nGeneral\n\n\nFind\n\n\nCtrl + F\n\n\nCmd + F\n\n
\nWorkspace\n\n\nNavigate to next tab\n\n\nCtrl + Shift + ]\n\n\nCmd + Shift + ]\n\n
\nWorkspace\n\n\nNavigate to previous tab\n\n\nCtrl + Shift + [\n\n\nCmd + Shift + [\n\n
\nWorkspace\n\n\nClose current tab\n\n\nCtrl + Shift + W\n\n\nCmd + Shift + W\n\n
\nWorkspace\n\n\nOpen new tab\n\n\nCtrl + T\n\n\nCmd + T\n\n
\nAggregation Focus Mode\n\n\nAdd a new stage after current one\n\n\nCtrl + Shift + B\n\n\nCmd + Shift + B\n\n
\nAggregation Focus Mode\n\n\nAdd a new stage before current one\n\n\nCtrl + Shift + A\n\n\nCmd + Shift + A\n\n
\nAggregation Focus Mode\n\n\nNavigate to next stage\n\n\nCtrl + Shift + 9\n\n\nCmd + Shift + 9\n\n
\nAggregation Focus Mode\n\n\nNavigate to previous stage\n\n\nCtrl + Shift + 0\n\n\nCmd + Shift + 0\n\n
\nPipeline text editor\n\n\nComment out code\n\n\nCtrl + /\n\n\nCmd + /\n\n
\nAll text editors\n\n\nPrettify code\n\n\nCtrl + Shift + B\n\n\nCtrl + Shift + B\n\n
\nQuery bar\n\n\nSubmit query\n\n\nEnter (from the query bar)\n\n\nEnter (from the query bar)\n\n
\nWeb Shell\n\n\nDeletes the next character\n\n\nCtrl + D\n\n\nCtrl + D\n\n
\nWeb Shell\n\n\nMoves the cursor to the end of the line\n\n\nCtrl + E\n\n\nCtrl + E\n\n
\nWeb Shell\n\n\nMoves the cursor forward one character\n\n\nCtrl + F\n\n\nCtrl + F\n\n
\nWeb Shell\n\n\nErases one character, similar to hitting backspace\n\n\nCtrl + H\n\n\nCmd + H\n\n
\nWeb Shell\n\n\nClears the screen, similar to the clear command\n\n\nCtrl + L\n\n\nCmd + L\n\n
\nWeb Shell\n\n\nSwap the last two characters before the cursor\n\n\nCtrl + T\n\n\nCtrl + T\n\n
\nWeb Shell\n\n\nCycle backwards through command history\n\n\n\u2191"} -{"chunk_id": "68a95be35e79d242619d818a-1", "page_id": "68a95be35e79d242619d818a", "source_name": "compass", "product_name": "MongoDB Compass", "url": "https://mongodb.com/docs/compass/keyboard-shortcuts", "title": "Keyboard Shortcuts", "text": "\n\u2191\n\n
\nWeb Shell\n\n\nCycle forwards through command history\n\n\n\u2193\n\n\n\u2193\n\n
"} -{"chunk_id": "68a95be35e79d242619d819f-0", "page_id": "68a95be35e79d242619d819f", "source_name": "compass", "product_name": "MongoDB Compass", "url": "https://mongodb.com/docs/compass/connect/disconnect", "title": "Disconnect from MongoDB", "text": "# Disconnect from MongoDB\n\nMongoDB Compass Readonly Edition will be deprecated in a future release. To replicate the read-only behavior in a standard Compass edition, assign users `read` access at the database level and enable the readOnly option in Compass.Disconnecting from a MongoDB deployment closes the Compass connection to the active deployment and returns the Compass view to the initial connection dialog. When you disconnect, Compass safely ends your session with the database server. This process ensures that any open transactions are closed and resources are freed on both the client and server sides.\n\nDisconnecting is helpful when you want to switch between different MongoDB deployments, update your connection settings, or end your current session for security reasons. After disconnecting, you can always reconnect to the same deployment or connect to a different one.\n\n## Steps\n\n### Click Connect in the menu bar.\n\n### Select Disconnect from the dropdown menu.\n\n## Learn more\n\nTo create a new connection, see Connect Compass to MongoDB."} -{"chunk_id": "68a95be35e79d242619d81b0-0", "page_id": "68a95be35e79d242619d81b0", "source_name": "compass", "product_name": "MongoDB Compass", "url": "https://mongodb.com/docs/compass/query/project", "title": "Set Which Fields Are Returned", "text": "# Set Which Fields Are Returned\n\nMongoDB Compass Readonly Edition will be deprecated in a future release. To replicate the read-only behavior in a standard Compass edition, assign users `read` access at the database level and enable the readOnly option in Compass.If the query bar displays the Project option, you can specify which fields to return in the resulting data. By default, all fields are returned.\n\nTo set a projection:\n\n1. In the Query Bar, click Options.\n\n2. Enter the projection document into the Project field.\n\n Specify the field name and set to `1` in the project document.\n\n ```javascript\n { year: 1, name: 1 }\n ```\n\n Only the fields specified in the project document are returned. The `_id` field is returned unless it is set to `0` in the Project document.\n\n Specify the field name and set to `0` in the project document.\n\n ```javascript\n { year: 0, name: 0 }\n ```\n\n All fields except for the fields specified in the project document are returned.\n\n As you type, the Find button is disabled and the Project label turns red until a valid query is entered.\n\n3. Click Find to run the query and view the updated results.\n\n For query result sets larger than 1000 documents, Compass shows a subset of the results. Otherwise, Compass shows the entire result set.\n\n For details on sampling, see Sampling.\n\n## How Does the Compass Query Compare to MongoDB and SQL Queries?\n\n`$project` corresponds to choosing specific fields to return in a SQL (Structured Query Language) `SELECT` statement.\n\nYou have 3,235 articles. You would like to see only the headlines and authors of those articles.\n\n```sql\nSELECT headline, author FROM article;\n```\n\n```javascript\ndb.article.aggregate(\n { $project : { headline : 1, author : 1 } }\n);\n```\n\n```javascript\n{ headline : 1, author : 1 }\n```\n\n## Learn More\n\nTo learn how project works, see the `project` entry in the MongoDB Manual."} -{"chunk_id": "68fc6b2a3b754f1e0ca17196-0", "page_id": "68fc6b2a3b754f1e0ca17196", "source_name": "compass", "product_name": "MongoDB Compass", "url": "https://mongodb.com/docs/compass/data-modeling/modify-collections", "title": "Modify Collections in Your Compass Entity-Relationship Diagram", "text": "# Modify Collections in Your Compass Entity-Relationship Diagram\n\nMongoDB Compass Readonly Edition will be deprecated in a future release. To replicate the read-only behavior in a standard Compass edition, assign users `read` access at the database level and enable the readOnly option in Compass.You can modify your existing entity-relationship diagram in Compass to plan changes to your data model *without* affecting your actual data.\n\n## About this Task\n\nIn the Data Modeling tab, you can:\n\n- Add or remove collections\n\n- Rename collections\n\nAny changes you make to your entity-relationship diagram won't affect your actual database.\n\n## Before You Begin\n\nYou must have an existing entity-relationship diagram in Compass to modify the fields. To create a new diagram, see Generate an Entity-Relationship Diagram in Compass.\n\n## Steps\n\n### Add a New Collection\n\nTo add a new collection to your entity-relationship diagram:\n\n#### Open the Data Modeling tab\n\nIn the left sidebar, click Data Modeling.\n\n#### Open your entity-relationship diagram\n\nFrom the Data Modeling tab, open your diagram.\n\n#### Add a new collection\n\nTo add a new collection, click the icon in the upper-left corner of the diagram canvas. Clicking this icon opens a drop-down menu with two options:\n\n- Add a new collection\n\n- Select from database\n\nIf you click Select from database, a dialog box opens that allows you to select existing collections from your database that aren't included in your diagram.\n\nIf you imported your diagram or you aren't connected to the database used to generate your diagram, Compass prompts you to select a database connection.\n\n### Rename a Collection\n\nTo rename a collection in your entity-relationship diagram:\n\n#### Open the Data Modeling tab\n\nIn the left sidebar, click Data Modeling.\n\n#### Open your entity-relationship diagram\n\nFrom the Data Modeling tab, open your diagram.\n\n#### Open the Collection Properties side panel\n\nClick one of your collections in the diagram. The collection side panel opens on the right side of the screen.\n\n### Remove a Collection\n\nTo delete a collection from your diagram:\n\n#### Open the Data Modeling tab\n\nIn the left sidebar, click Data Modeling.\n\n#### Open your entity-relationship diagram\n\nFrom the Data Modeling tab, open your diagram.\n\n#### Open the Collection Properties side panel\n\nClick one of your collections in the diagram. The collection side panel opens on the right side of the screen.\n\n#### Delete the collection\n\nIn the side panel, click the icon.\n\n## Next Steps\n\n- Modify Fields in Your Compass Entity-Relationship Diagram\n\n- Manage Relationships in Your Compass Entity-Relationship Diagram\n\n- Export Your Entity-Relationship Diagram from Compass\n\n- Import an Entity-Relationship Diagram in Compass\n\n## Learn More\n\n- Data Modeling in MongoDB\n\n- Data Modeling in MongoDB Compass"} -{"chunk_id": "68a95be35e79d242619d81c7-0", "page_id": "68a95be35e79d242619d81c7", "source_name": "compass", "product_name": "MongoDB Compass", "url": "https://mongodb.com/docs/compass/settings", "title": "Customize Compass", "text": "# Customize Compass\n\nMongoDB Compass Readonly Edition will be deprecated in a future release. To replicate the read-only behavior in a standard Compass edition, assign users `read` access at the database level and enable the readOnly option in Compass.To customize user access and privacy in MongoDB Compass, you can configure your Compass settings on the Compass interface, the command line, or a configuration file.\n\n## Use Cases\n\nYou can specify Compass settings and behaviors to customize your Compass experience. For administrators, you can modify the Compass settings to restrict the actions users can take.\n\nFor example:\n\n- If you need to hide credentials from users connecting to MongoDB, you can set the `protectConnectionStrings` option.\n\n- If you want to automate the launch of Compass without any input required from users, you can use the command line to launch Compass with specified configuration options.\n\n- If you have multiple team members using Compass, you can use a common configuration file to ensure a consistent user experience.\n\n## Tasks\n\n- Block Outgoing Network Connections\n\n- Display the Kerberos Password Field\n\n- Secure Your Connection String\n\n- Restrict Write Operations to MongoDB\n\n- Specify Read Preference and Tags\n\n- Toggle Chrome DevTools\n\n## Learn more\n\n- Interface Settings\n\n- Command Line Options\n\n- Configuration File Settings"} -{"chunk_id": "68a95c305e79d242619e008e-0", "page_id": "68a95c305e79d242619e008e", "source_name": "cpp-driver", "product_name": "C++ Driver", "url": "https://mongodb.com/docs/languages/cpp/cpp-driver/current/run-command", "title": "Run a Command", "text": "# Run a Command\n\n## Overview\n\nIn this guide, you can learn how to run a database command with the C++ driver. You can use database commands to perform a variety of administrative and diagnostic tasks, such as fetching server statistics, initializing a replica set, or running an aggregation pipeline.\n\nThe driver provides wrapper methods for many database commands. We recommend using driver methods instead of executing database commands when possible.\n\nTo perform administrative tasks, use the MongoDB Shell instead of the C++ driver. Calling the `db.runCommand()` method inside the shell is the preferred method to issue database commands, as it provides a consistent interface between the shell and drivers.\n\n## Execute a Command\n\nTo run a database command, call the `run_command()` execution method on a `mongocxx::database` instance and pass in a document that specifies the command and any relevant arguments. The method returns the result of the command as a `bsoncxx::document::value` object.\n\nYou can use the `run_command()` method with any database command. For a full list of database commands and corresponding parameters, see Database Commands in the MongoDB Server manual.\n\nThe following example shows how you can use the `run_command()` method to run the `hello` command on a database, which returns information about the current member's role in the replica set:\n\n```cpp\nauto db = client[\"my_database\"];\n\nauto command = make_document(kvp(\"hello\" , 1));\nauto result = db.run_command(command.view());\n\nstd::cout << bsoncxx::to_json(result) << std::endl;\n```\n\n```cli\n{\n \"topologyVersion\" : {\n \"processId\" : ...,\n \"counter\" : ...\n },\n \"hosts\" : [ ... ],\n \"setName\" : ...,\n \"setVersion\" : ...,\n \"isWritablePrimary\" : ...,\n \"secondary\" : ...,\n \"primary\" : ...,\n \"tags\" : {\n \"region\" : ...,\n \"availabilityZone\" : ...,\n \"provider\" : ...,\n \"workloadType\" : ...,\n \"nodeType\" : ...,\n \"diskState\" : ...\n },\n \"me\" : ...,\n \"electionId\" : ...,\n \"lastWrite\" : ...,\n \"lastWriteDate\" : ...,\n \"majorityOpTime\" : ...,\n \"majorityWriteDate\" : ...,\n \"maxBsonObjectSize\" : ...,\n \"maxMessageSizeBytes\" : ...,\n \"maxWriteBatchSize\" : ...,\n \"localTime\" : ...,\n \"logicalSessionTimeoutMinutes\" : ...,\n \"connectionId\" : ...,\n \"minWireVersion\" : ...,\n \"maxWireVersion\" : ...,\n \"readOnly\" : ...,\n \"ok\" : ...,\n \"$clusterTime\" : ...,\n \"signature\" : ...\n }\n```\n\n## Command Options\n\nTo customize command execution behavior, you can set options in the command document that you pass to the `run_command()` method. To learn more about a command and the options that it accepts, locate the command and follow the corresponding link on the Database Commands page in the MongoDB Server manual.\n\nFor example, you can instruct the `connectionStatus` command to return the full set of privileges that currently-authenticated users possess by setting the `showPrivileges` option to `true` in the command document:\n\n```cpp\nauto db = client[\"my_database\"];\n\nauto command = make_document(kvp(\"connectionStatus\" , 1), kvp(\"showPrivileges\", true));\nauto result = db.run_command(command.view());\n\nstd::cout << bsoncxx::to_json(result) << std::endl;\n```\n\n```cli\n{\n \"authInfo\" : { \"authenticatedUsers\" : [ { \"user\" : ..., \"db\" : ... } ],\n \"authenticatedUserRoles\" : [ { \"role\" : ..., \"db\" : ... } ],\n \"authenticatedUserPrivileges\" : [\n { \"resource\" : { \"db\" : \"\", \"collection\" : \"\" }, \"actions\" : [ ... ] },\n { \"resource\" : { \"db\" : \"config\", \"collection\" : \"system.sessions\" }, \"actions\" : [ ... ] },\n ...,\n { \"resource\" : { \"db\" : \"\", \"collection\" : \"\" }, \"actions\" : [ ... ] }\n ]\n},\n \"ok\" : 1\n}\n```\n\n## Response\n\nThe `run_command()` method returns a `bsoncxx::document::value` object that contains the response from the database after the command has been executed. Each database command performs a different function, so the response content can vary across commands. However, every response contains documents with the following fields:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nField\n\n\nDescription\n\n
\n\n\n\nProvides fields specific to the database command. For example, `count` returns the `n` field and `explain` returns the `queryPlanner` field.\n\n
\n`ok`\n\n\nIndicates whether the command has succeeded (`1`) or failed (`0`).\n\n
\n`operationTime`\n\n\nIndicates the logical time of the operation. MongoDB uses the logical time to order operations.\n\n
\n`$clusterTime`\n\n\nProvides a document that returns the signed cluster time. Cluster time is a logical time used for ordering of operations.\n\nThe document contains the following fields:\n\n- `clusterTime`, which is the timestamp of the highest known cluster time for the member.\n\n- `signature`, which is a document that contains the hash of the cluster time and the ID of the key used to sign the cluster time.\n\n
\n\n## Additional Information\n\nFor more information about the concepts in this guide, see the following documentation:\n\n- db.runCommand()\n\n- Database Commands\n\n- hello Command\n\n- connectionStatus Command\n\nTo learn more about the methods or types discussed in this guide, see the following API documentation:\n\n- run_command()"} -{"chunk_id": "6a1e766bcafdea8421866195-0", "page_id": "6a1e766bcafdea8421866195", "source_name": "cpp-driver", "product_name": "C++ Driver", "url": "https://mongodb.com/docs/languages/cpp/cpp-driver/current/security/tls", "title": "Configure Transport Layer Security (TLS)", "text": "# Configure Transport Layer Security (TLS)\n\n## Overview\n\nIn this guide, you can learn how to use the TLS protocol to secure your connection to a MongoDB deployment.\n\nWhen you enable TLS for a connection, the C++ driver performs the following actions:\n\n- Uses TLS to connect to the MongoDB deployment\n\n- Verifies the deployment's certificate\n\n- Ensures that the certificate certifies the deployment\n\nTo learn how to configure your MongoDB deployment for TLS, see the TLS configuration guide in the MongoDB Server manual.\n\nThis page assumes prior knowledge of TLS/SSL and access to valid certificates. A full description of TLS/SSL, PKI (Public Key Infrastructure) certificates, and Certificate Authorities (CAs) is beyond the scope of this documentation.\n\nThe C++ driver delegates most TLS behavior to the MongoDB C Driver. For information about how the C driver handles TLS, including configuration steps and expected behavior, see Configuring TLS in the C driver Documentation.\n\n## Enable TLS\n\nTo enable TLS for the connection to your MongoDB instance, set the `tls` connection option to `true` in your connection string, as shown in the following example:\n\n```cpp\nmongocxx::uri uri(\"mongodb://:/?tls=true\");\n```\n\nIf your connection string includes the `+srv` modification, which specifies the SRV connection format, TLS is enabled on your connection by default.\n\nTo learn more about the SRV connection format, see SRV Connection Format in the MongoDB Server documentation.\n\n## Specify a CA File\n\nDuring the TLS handshake, the MongoDB deployment presents a certificate key file to your application to establish its identity. Usually, a deployment's certificate has been signed by a well-known CA, and your application relies on this CA to validate the certificate.\n\nDuring testing, however, you might want to act as your own CA. In this case, you must instruct the C++ driver to use your CA certificates instead of ones signed by another CA.\n\nTo do so, specify the path to a `.pem` file containing the root certificate chain. You can do this in two ways: by setting a property on a `mongocxx::options::tls` object, or by using the `tlsCAFile` parameter in your connection string.\n\n\n\n\n\n```cpp\nmongocxx::options::client client_options;\nmongocxx::options::tls tls_options;\n\ntls_options.pem_file(\"/path/to/file.pem\");\nclient_options.tls_opts(tls_options);\n\nmongocxx::uri uri(\"mongodb://:/?tls=true\");\nmongocxx::client client(uri, client_options);\n```\n\n\n\n\n\n```cpp\nmongocxx::uri uri(\"mongodb://:/?tls=true&tlsCAFile=/path/to/file.pem\");\n```\n\n\n\n\n\n### Specify a CA Directory\n\nIf you are using OpenSSL or LibreSSL (`libtls`) for TLS support, you can also instruct the C++ driver to search for a CA file within a directory. The driver searches this directory if it doesn't find a CA file at the path specified in the `tlsCAFile` or `pem_file` option.\n\nThe following code example shows how to use the `ca_dir` option to specify the directory that the driver should search:\n\n```cpp\nmongocxx::options::client client_options;\nmongocxx::options::tls tls_options;\n\ntls_options.ca_dir(\"/path/to/search/\");\nclient_options.tls_opts(tls_options);\n\nmongocxx::uri uri(\"mongodb://:/?tls=true\");\nmongocxx::client client(uri, client_options);\n```\n\nThis option corresponds to the OpenSSL SSL_CTX_load_verify_locations parameter and the LibreSSL tls_config_set_ca_path parameter.\n\n## Check Certificate Revocation\n\nWhen an X.509 certificate is no longer trustworthy\u2014for example, if its private key has been compromised\u2014the CA revokes the certificate. The C++ driver includes two ways to check whether a server's certificate has been revoked.\n\n### OCSP\n\nThe Online Certificate Status Protocol (OCSP) process varies depending on the version of MongoDB Server you're connecting to:\n\n- **MongoDB v4.4 or later:** The server staples a time-stamped OCSP response to its certificate. The C++ driver validates the certificate against the OCSP response. If the CA has revoked the certificate, or if the OCSP response is otherwise invalid, the TLS handshake fails.\n\n- **MongoDB v4.3 or earlier:** The server supplies an OCSP endpoint, which the C++ driver contacts directly. The C++ driver then validates the certificate against the OCSP response. If the CA hasn't revoked the certificate, the TLS handshake continues, even if the OCSP response is invalid or malformed.\n\nLet's Encrypt has ended OCSP support for newer certificates. New certificates issued by Let's Encrypt might not include an OCSP responder URL. OCSP revocation checking occurs only when a certificate contains an OCSP URI, so a missing OCSP URL is expected and doesn't necessarily indicate a problem with your MongoDB deployment.\n\nTo stop the C++ driver from contacting the OCSP endpoint, set the `tlsDisableOCSPEndpointCheck` connection option to `true` in your connection string, as shown in the following code example:\n\n```cpp\nmongocxx::uri uri(\"mongodb://:/?tls=true&tlsDisableOCSPEndpointCheck=true\");\n```\n\n### Certificate Revocation List\n\nInstead of using OCSP, you can instruct the C++ driver to check the server's certificate against a Certificate Revocation List (CRL) published by the CA.\n\nThe following code example shows how to use the `crl_file` option to specify the path to specify the path to a `.pem` file from the CA:\n\n```cpp\nmongocxx::options::client client_options;\nmongocxx::options::tls tls_options;\n\ntls_options.crl_file(\"/path/to/file.pem\");\nclient_options.tls_opts(tls_options);\n\nmongocxx::uri uri(\"mongodb://:/?tls=true\");\nmongocxx::client client(uri, client_options);\n```\n\nYou can specify a CRL file in either the `.pem` or `.der` format.\n\n## Present a Client Certificate\n\nSome MongoDB deployments require every connecting application to present a client certificate that proves its identity. To specify the client certificate for the C++ driver to present, specify the file path of the `.pem` file that contains your certificate and private key.\n\nYou can do this in two ways: by setting a property on a `mongocxx::options::tls` object, or by using the `tlsCertificateKeyFile` parameter in your connection string.\n\n\n\n\n\n```cpp\nmongocxx::options::client client_options;\nmongocxx::options::tls tls_options;\n\ntls_options.pem_file(\"/path/to/file.pem\");\nclient_options.tls_opts(tls_options);\n\nmongocxx::uri uri(\"mongodb://:/?tls=true\");\nmongocxx::client client(uri, client_options);\n```\n\n\n\n\n\n```cpp\nmongocxx::uri uri(\"mongodb://:/?tls=true&tlsCertificateKeyFile=/path/to/file.pem\");\n```\n\n\n\n\n\nYour client certificate and private key must be in the same `.pem` file. If they are stored in different files, you must concatenate them. The following example shows how to concatenate a key file and a certificate file into a third file called `combined.pem` on a Unix system:\n\n```sh\n$ cat key.pem cert.pem > combined.pem\n```\n\n### Provide a Key Password\n\nIf the private key in your certificate file is encrypted, you must provide the password. You can do this in two ways: by setting a property on a `mongocxx::options::tls` object, or by using the `tlsCertificateKeyFilePassword` parameter in your connection string.\n\n\n\n\n\n```cpp\nmongocxx::options::client client_options;\nmongocxx::options::tls tls_options;\n\ntls_options.pem_file(\"/path/to/file.pem\");\ntls_options.pem_password(\"\");\nclient_options.tls_opts(tls_options);\n\nmongocxx::uri uri(\"mongodb://:/?tls=true\");\nmongocxx::client client(uri, client_options);\n```\n\n\n\n\n\n```cpp\nmongocxx::uri uri(\"mongodb://:/?tls=true&tlsCertificateKeyFile=/path/to/file.pem&tlsCertificateKeyFilePassword=\");\n```\n\n\n\n"} -{"chunk_id": "6a1e766bcafdea8421866195-1", "page_id": "6a1e766bcafdea8421866195", "source_name": "cpp-driver", "product_name": "C++ Driver", "url": "https://mongodb.com/docs/languages/cpp/cpp-driver/current/security/tls", "title": "Configure Transport Layer Security (TLS)", "text": "## Allow Insecure TLS\n\nWhen TLS is enabled, the C++ driver automatically verifies the certificate that the server presents. When testing your code, you can disable this verification. This is known as *insecure TLS.*\n\nWhen insecure TLS is enabled, the driver requires only that the server present an X.509 certificate. The driver accepts a certificate even if any of the following are true:\n\n- The hostname of the server and the subject name (or subject alternative name) on the certificate don't match.\n\n- The certificate is expired or not yet valid.\n\n- The certificate doesn't have a trusted root certificate in the chain.\n\n- The certificate purpose isn't valid for server identification.\n\nEven when insecure TLS is enabled, communication between the client and server is encrypted with TLS.\n\nTo enable insecure TLS, set the `tlsInsecure` connection option to `true` in your connection string, as shown in the following code example:\n\n```cpp\nmongocxx::uri uri(\"mongodb://:/?tls=true&tlsInsecure=true\");\n```\n\nTo disable only certificate validation, set the `tlsAllowInvalidCertificates` option to `true`, and set the `tlsInsecure` option to `false` (or omit it):\n\n\n\n\n\n```cpp\nmongocxx::options::client client_options;\nmongocxx::options::tls tls_options;\n\ntls_options.allow_invalid_certificates(true);\nclient_options.tls_opts(tls_options);\n\nmongocxx::uri uri(\"mongodb://:/?tls=true\");\nmongocxx::client client(uri, client_options);\n```\n\n\n\n\n\n```cpp\nmongocxx::uri uri(\"mongodb://:/?tls=true&tlsAllowInvalidCertificates=true\");\n```\n\n\n\n\n\nTo disable only hostname verification, set the `tlsAllowInvalidHostnames` option to `true`, and set the `tlsInsecure` option to `false` (or omit it):\n\n```cpp\nmongocxx::uri uri(\"mongodb://:/?tls=true&tlsAllowInvalidHostnames=true\");\n```\n\nAlways set the `tlsInsecure`, `tlsAllowInvalidCertificates`, and `tlsAllowInvalidHostnames` options to `false` in production.\n\nSetting any of these options to `true` in a production environment makes your application insecure and potentially vulnerable to expired certificates and to foreign processes posing as valid client instances.\n\n## API Documentation\n\nTo learn more about configuring TLS for the C++ driver, see the following API documentation:\n\n- mongocxx::client\n\n- mongocxx::uri\n\n- mongocxx::instance\n\n- mongocxx::options::client\n\n- mongocxx::options::tls"} -{"chunk_id": "68a95c305e79d242619e001c-0", "page_id": "68a95c305e79d242619e001c", "source_name": "cpp-driver", "product_name": "C++ Driver", "url": "https://mongodb.com/docs/languages/cpp/cpp-driver/current/connect/client", "title": "Create a MongoDB Client", "text": "# Create a MongoDB Client\n\n## Overview\n\nTo connect to a MongoDB deployment, you need two things:\n\n- A **connection URI**, also known as a *connection string*, which tells the C++ driver which MongoDB deployment to connect to.\n\n- A **mongocxx::client** object, which creates the connection to the MongoDB deployment and lets you perform operations on it.\n\nYou can also use either of these components to customize the way the C++ driver behaves while connected to MongoDB.\n\nThis guide shows you how to create a connection string and use a `mongocxx::client` object to connect to MongoDB.\n\nThe code examples on this page assume that you've already created a `mongocxx::instance` object elsewhere in your application.\n\nTo learn more about creating an instance, see Create a Driver Instance.\n\n## Connection URI\n\nA standard connection string includes the following components:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nComponent\n\n\nDescription\n\n
\n`mongodb://`\n\n\nRequired. A prefix that identifies this as a string in the standard connection format.\n\n
\n`db_username:db_password`\n\n\nOptional. Authentication credentials. If you include these, the client authenticates the user against the database specified in `authSource`. For more information about the `authSource` connection option, see Authentication Options.\n\n
\n`host[:port]`\n\n\nRequired. The host and optional port number where MongoDB is running. If you don't include the port number, the driver uses the default port, `27017`.\n\n
\n`/defaultauthdb`\n\n\nOptional. The authentication database to use if the connection string includes `db_username:db_password@` authentication credentials but not the `authSource` option. If you don't include this component, the client authenticates the user against the `admin` database.\n\n
\n`?`\n\n\nOptional. A query string that specifies connection-specific options as `=` pairs. See Specify Connection Options for a full description of these options.\n\n
For more information about creating a connection string, see Connection Strings in the MongoDB Server documentation.\n\n## Create a `mongocxx::client`\n\nTo create a connection to MongoDB, construct an instance of the `mongocxx::uri` class, passing the connection URI as a string to the constructor. Then, pass the instance of the `mongocxx::uri` class to the `mongocxx::client` constructor.\n\nIn the following example, the driver uses a sample connection URI to connect to a MongoDB deployment on port `27017` of `localhost`:\n\n```cpp\n#include \n#include \n#include \n\nint main()\n{\n mongocxx::instance instance;\n mongocxx::uri uri(\"mongodb://localhost:27017\");\n mongocxx::client client(uri);\n}\n```\n\nBecause each `mongocxx::client` object represents a pool of connections to the database, most applications require only a single instance of `mongocxx::client`, even across multiple requests.\n\n## API Documentation\n\nTo learn more about creating a `mongocxx::client` object in C++ driver, see the following API documentation:\n\n- mongocxx::client"} -{"chunk_id": "6a1e766bcafdea84218660eb-0", "page_id": "6a1e766bcafdea84218660eb", "source_name": "cpp-driver", "product_name": "C++ Driver", "url": "https://mongodb.com/docs/languages/cpp/cpp-driver/current/crud/gridfs", "title": "Store Large Files by Using GridFS", "text": "# Store Large Files by Using GridFS\n\n## Overview\n\nIn this guide, you can learn how to store and retrieve large files in MongoDB by using **GridFS**. GridFS is a specification implemented by the C++ driver that describes how to split files into chunks when storing them and reassemble those files when retrieving them. The driver's implementation of GridFS is an abstraction that manages the operations and organization of the file storage.\n\nUse GridFS if the size of your files exceeds the BSON document size limit of 16MB. For more detailed information about whether GridFS is suitable for your use case, see GridFS in the MongoDB Server manual.\n\n## How GridFS Works\n\nGridFS organizes files in a **bucket**, a group of MongoDB collections that contain the chunks of files and information describing them. The bucket contains the following collections, named using the convention defined in the GridFS specification:\n\n- `chunks` collection, which stores the binary file chunks\n\n- `files` collection, which stores the file metadata\n\nThe driver creates the GridFS bucket, if it doesn't exist, when you first write data to it. The bucket contains the preceding collections prefixed with the default bucket name `fs`, unless you specify a different name. To ensure efficient retrieval of the files and related metadata, the driver creates an index on each collection. The driver ensures that these indexes exist before performing read and write operations on the GridFS bucket.\n\nFor more information about GridFS indexes, see GridFS Indexes in the MongoDB Server manual.\n\nWhen using GridFS to store files, the driver splits the files into smaller chunks, each represented by a separate document in the `chunks` collection. It also creates a document in the `files` collection that contains a file ID, file name, and other file metadata. You can upload the file by passing a stream to the C++ driver to consume or by creating a new stream and writing to it directly.\n\nThe following diagram shows how GridFS splits files when they are uploaded to a bucket:\n\nWhen retrieving files, GridFS fetches the metadata from the `files` collection in the specified bucket and uses the information to reconstruct the file from documents in the `chunks` collection. You can read the file by writing its contents to an existing stream or by creating a new stream that points to the file.\n\n## Create a GridFS Bucket\n\nTo begin storing or retrieving files from GridFS, call the `gridfs_bucket()` method on your database. This method accesses an existing bucket or creates a new bucket if one does not exist.\n\nThe following example calls the `gridfs_bucket()` method on the `db` database:\n\n```cpp\nauto bucket = db.gridfs_bucket();\n```\n\n### Customize the Bucket\n\nYou can customize the GridFS bucket configuration by passing an instance of the `mongocxx::options::gridfs::bucket` class as an optional argument to the `gridfs_bucket()` method. The following table describes the fields you can set in a `mongocxx::options::gridfs::bucket` instance:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nField\n\n\nDescription\n\n
\n`bucket_name`\n\n\nSpecifies the bucket name to use as a prefix for the files and chunks collections. The default value is `\"fs\"`.**Type**: `std::string`\n\n
\n`chunk_size_bytes`\n\n\nSpecifies the chunk size that GridFS splits files into. The default value is `261120`.**Type**: `std::int32_t`\n\n
\n`read_concern`\n\n\nSpecifies the read concern to use for bucket operations. The default value is the database's read concern.**Type**: `mongocxx::read_concern`\n\n
\n`read_preference`\n\n\nSpecifies the read preference to use for bucket operations. The default value is the database's read preference.**Type**: `mongocxx::read_preference`\n\n
\n`write_concern`\n\n\nSpecifies the write concern to use for bucket operations. The default value is the database's write concern.**Type**: `mongocxx::write_concern`\n\n
The following example creates a bucket named `\"myCustomBucket\"` by setting the `bucket_name` field of a `mongocxx::options::gridfs::bucket` instance:\n\n```cpp\nmongocxx::options::gridfs::bucket opts;\nopts.bucket_name(\"myCustomBucket\");\n\nauto bucket = db.gridfs_bucket(opts);\n```\n\n## Upload Files\n\nYou can upload files to a GridFS bucket by using the following methods:\n\n- open_upload_stream(): Opens a new upload stream to which you can write file contents\n\n- upload_from_stream(): Uploads the contents of an existing stream to a GridFS file\n\n### Write to an Upload Stream\n\nUse the `open_upload_stream()` method to create an upload stream for a given file name. The `open_upload_stream()` method allows you to specify configuration information in an `options::gridfs::upload` instance, which you can pass as a parameter.\n\nThis example uses an upload stream to perform the following actions:\n\n- Sets the `chunk_size_bytes` field of an options instance\n\n- Opens a writable stream for a new GridFS file named `\"my_file\"` and applies the `chunk_size_bytes` option\n\n- Calls the `write()` method to write data to `my_file`, which the stream points to\n\n- Calls the `close()` method to close the stream pointing to `my_file`\n\n```cpp\nmongocxx::options::gridfs::upload opts;\nopts.chunk_size_bytes(1048576);\nauto uploader = bucket.open_upload_stream(\"my_file\", opts);\n\n// ASCII for \"HelloWorld\"\nstd::uint8_t bytes[10] = {72, 101, 108, 108, 111, 87, 111, 114, 108, 100};\n\nfor (auto i = 0; i < 5; ++i) {\n uploader.write(bytes, 10);\n}\n\nuploader.close();\n```\n\n### Upload an Existing Stream\n\nUse the `upload_from_stream()` method to upload the contents of a stream to a new GridFS file. The `upload_from_stream()` method allows you to specify configuration information in an `options::gridfs::upload` instance, which you can pass as a parameter.\n\nThis example performs the following actions:\n\n- Opens a file located at `/path/to/input_file` as a stream in binary read mode\n\n- Calls the `upload_from_stream()` method to upload the contents of the stream to a GridFS file named `\"new_file\"`\n\n```cpp\nstd::ifstream file(\"/path/to/input_file\", std::ios::binary);\nbucket.upload_from_stream(\"new_file\", &file);\n```\n\n## Retrieve File Information\n\nIn this section, you can learn how to retrieve file metadata stored in the `files` collection of the GridFS bucket. The metadata contains information about the file it refers to, including:\n\n- The `_id` of the file\n\n- The name of the file\n\n- The length/size of the file\n\n- The upload date and time\n\n- A `metadata` document in which you can store other information\n\nTo retrieve files from a GridFS bucket, call the `mongocxx::gridfs::bucket::find()` method on your bucket. The method returns a `mongocxx::cursor` instance from which you can access the results. To learn more about cursors, see the Access Data From a Cursor guide."} -{"chunk_id": "6a1e766bcafdea84218660eb-1", "page_id": "6a1e766bcafdea84218660eb", "source_name": "cpp-driver", "product_name": "C++ Driver", "url": "https://mongodb.com/docs/languages/cpp/cpp-driver/current/crud/gridfs", "title": "Store Large Files by Using GridFS", "text": "### Example\n\nThe following code example shows how to retrieve and print file metadata from files in a GridFS bucket. It uses a `for` loop to iterate through the returned cursor and display the contents of the files uploaded in the Upload Files examples:\n\n```cpp\nauto cursor = bucket.find({});\nfor (auto&& doc : cursor) {\n std::cout << bsoncxx::to_json(doc) << std::endl;\n}\n```\n\n```\n{ \"_id\" : { \"$oid\" : \"...\" }, \"length\" : 13, \"chunkSize\" : 261120, \"uploadDate\" :\n{ \"$date\" : ... }, \"filename\" : \"new_file\" }\n{ \"_id\" : { \"$oid\" : \"...\" }, \"length\" : 50, \"chunkSize\" : 1048576, \"uploadDate\" :\n{ \"$date\" : ... }, \"filename\" : \"my_file\" }\n```\n\nThe `find()` method accepts various query specifications. You can use its `mongocxx::options::find` parameter to specify the sort order, maximum number of documents to return, and the number of documents to skip before returning. To view a list of available options, see the API documentation.\n\n## Download Files\n\nYou can download files from a GridFS bucket by using the following methods:\n\n- open_download_stream(): Opens a new download stream from which you can read the file contents\n\n- download_to_stream(): Writes the entire file to an existing download stream\n\n### Read From a Download Stream\n\nYou can download files from your MongoDB database by using the `open_download_stream()` method to create a download stream.\n\nThis example uses a download stream to perform the following actions:\n\n- Retrieves the `_id` value of the GridFS file named `\"new_file\"`\n\n- Passes the `_id` value to the `open_download_stream()` method to open the file as a readable stream\n\n- Creates a `buffer` vector to store the file contents\n\n- Calls the `read()` method to read the file contents from the `downloader` stream into the vector\n\n```cpp\nauto doc = db[\"fs.files\"].find_one(make_document(kvp(\"filename\", \"new_file\")));\nauto id = doc->view()[\"_id\"].get_value();\n\nauto downloader = bucket.open_download_stream(id);\n\nstd::vector buffer(downloader.file_length());\ndownloader.read(buffer.data(), buffer.size());\n```\n\n### Download to an Existing Stream\n\nYou can download the contents of a GridFS file to an existing stream by calling the `download_to_stream()` method on your bucket.\n\nThis example performs the following actions:\n\n- Opens a file located at `/path/to/output_file` as a stream in binary write mode\n\n- Retrieves the `_id` value of the GridFS file named `\"new_file\"`\n\n- Passes the `_id` value to `download_to_stream()` to download the file to the stream\n\n```cpp\nstd::ofstream output_file(\"/path/to/output_file\", std::ios::binary);\n\nauto doc = db[\"fs.files\"].find_one(make_document(kvp(\"filename\", \"new_file\")));\nauto id = doc->view()[\"_id\"].get_value();\nbucket.download_to_stream(id, &output_file);\n```\n\n## Delete Files\n\nUse the `delete_file()` method to remove a file's collection document and associated chunks from your bucket. This effectively deletes the file. You must specify the file by its `_id` field rather than its file name.\n\nThe following example shows how to delete a file named `\"my_file\"` by passing its `_id` value to `delete_file()`:\n\n```cpp\nauto doc = db[\"fs.files\"].find_one(make_document(kvp(\"filename\", \"my_file\")));\nauto id = doc->view()[\"_id\"].get_value();\n\nbucket.delete_file(id);\n```\n\nThe `delete_file()` method supports deleting only one file at a time. If you want to delete each file revision, or files with different upload times that share the same file name, collect the `_id` values of each revision. Then, pass each `_id` value in separate calls to the `delete_file()` method.\n\n## API Documentation\n\nTo learn more about using the C++ driver to store and retrieve large files, see the following API documentation:\n\n- gridfs_bucket()\n\n- mongocxx::options::gridfs::bucket\n\n- open_upload_stream()\n\n- upload_from_stream()\n\n- find()\n\n- open_download_stream()\n\n- download_to_stream()\n\n- delete_file()"} -{"chunk_id": "6a1e766bcafdea842186617a-0", "page_id": "6a1e766bcafdea842186617a", "source_name": "cpp-driver", "product_name": "C++ Driver", "url": "https://mongodb.com/docs/languages/cpp/cpp-driver/current/security/authentication/kerberos", "title": "Kerberos (GSSAPI) Authentication", "text": "# Kerberos (GSSAPI) Authentication\n\n## Overview\n\nGSSAPI authentication is available only in the MongoDB Enterprise Edition.\n\nThe Generic Security Services API (GSSAPI) authentication mechanism allows you to use your Kerberos principal name to authenticate to a MongoDB deployment configured for Kerberos authentication.\n\nTo use Kerberos from the C++ driver, your MongoDB deployment must already be configured for Kerberos authentication and your application host must be able to obtain Kerberos credentials.\n\n### Code Placeholders\n\nThe code example on this page uses the following placeholders:\n\n- ``: Your Kerberos principal to authenticate.\n\n- ``: Fully qualified domain name (FQDN) of a `mongod` or `mongos` host in your deployment. Kerberos requires FQDNs rather than IP addresses or short hostnames for correct realm resolution.\n\n- ``: Port number of your MongoDB deployment. If you omit this parameter, MongoDB uses the default port number (`27017`).\n\nTo use the code example on this page, replace these placeholders with your own values.\n\nWhen you embed `` in a MongoDB connection URI, you must percent-encode the `@` character as `%40`.\n\n## Using GSSAPI Authentication in Your Application\n\nBefore you can use the Kerberos authentication mechanism with the C++ driver, you must configure your MongoDB deployment to use Kerberos. To configure your deployment, see the MongoDB Server MongoDB Server Kerberos documentation, and complete the steps described there.\n\nTo authenticate with GSSAPI, you must build the MongoDB C driver with SASL support. If you are building the driver from source, you can enable SASL support with the `ENABLE_SASL` `cmake` option.\n\nAfter you configure your deployment, complete the following steps to authenticate by using GSSAPI:\n\n### Obtain a Ticket-Granting Ticket\n\nOn Unix environments, you must first run the `kinit` command to obtain and cache an initial ticket-granting ticket. If you're running a Windows environment, you can skip ahead to the next step.\n\nThe following example uses the `kinit` command to obtain a ticket-granting ticket for the principal `mongodbuser@EXAMPLE.COM`. It then uses the `klist` command to display the principal and ticket in the credentials cache.\n\n```sh\n$ kinit mongodbuser@EXAMPLE.COM\nmongodbuser@EXAMPLE.COM's Password:\n$ klist\nCredentials cache: FILE:/tmp/krb5cc_1000\n Principal: mongodbuser@EXAMPLE.COM\n\nIssued Expires Principal\nFeb 9 13:48:51 2013 Feb 9 23:48:51 2013 krbtgt/mongodbuser@EXAMPLE.COM\n```\n\n### Set the Connection Options\n\nNext, set the following connection options:\n\n- `kerberos_principal`: The Kerberos principal to authenticate.\n\n- `authMechanism`: Set to `\"GSSAPI\"`.\n\n- `authMechanismProperties`: Optional. By default, MongoDB uses `mongodb` as the authentication service name. To specify a different service name, set this option to `\"SERVICE_NAME: \"`.\n\nYou can set these options through parameters in your connection URI, as shown in the following example:\n\n```cpp\nauto uri = mongocxx::uri(\"mongodb://@:/?\"\n \"authMechanism=GSSAPI\"\n \"&authMechanismProperties=SERVICE_NAME:\");\nauto client = mongocxx::client(uri);\n```\n\nYou must replace the `@` symbol in the principal with `%40`, as shown in the preceding example.\n\n## API Documentation\n\nTo learn more about creating a `mongocxx::client` object in C++ driver, see the following API documentation:\n\n- mongocxx::client"} -{"chunk_id": "6a1e766bcafdea84218660c2-0", "page_id": "6a1e766bcafdea84218660c2", "source_name": "cpp-driver", "product_name": "C++ Driver", "url": "https://mongodb.com/docs/languages/cpp/cpp-driver/current/connect/advanced-installation", "title": "Advanced Configuration and Installation Options", "text": "# Advanced Configuration and Installation Options\n\n## Additional Options for Integrators\n\nIn the event that you are building the BSON C++ library and/or the C++ driver to embed with other components and you wish to avoid the potential for collision with components installed from a standard build or from a distribution package manager, you can make use of the `BSONCXX_OUTPUT_BASENAME` and `MONGOCXX_OUTPUT_BASENAME` options to `cmake`.\n\n```bash\ncmake .. \\\n -DBSONCXX_OUTPUT_BASENAME=custom_bsoncxx \\\n -DMONGOCXX_OUTPUT_BASENAME=custom_mongocxx\n```\n\nThe above command would produce libraries named `libcustom_bsoncxx.so` and `libcustom_mongocxx.so` (or with the extension appropriate for the build platform). Those libraries could be placed in a standard system directory or in an alternate location and could be linked to by specifying something like `-lcustom_mongocxx -lcustom_bsoncxx` on the linker command line (possibly adjusting the specific flags to those required by your linker).\n\n## Install with Package Managers\n\nYou can use the following package managers to install the C++ driver:\n\n- vcpkg\n\n- Conan\n\n- Homebrew\n\n### Vcpkg Install Instructions\n\nIf you do not already have Vcpkg installed, install it with the following command:\n\n```bash\n$ git clone https://github.com/Microsoft/vcpkg.git\n$ cd vcpkg\n$ ./bootstrap-vcpkg.sh\n```\n\nOptionally, to install with Visual Studio integration:\n\n```bash\nvcpkg integrate install\n```\n\nInstall the driver. You may need to `git pull` to get the latest version of the driver.\n\n```bash\n$ ./vcpkg install mongo-cxx-driver\n```\n\nYou can use the toolchain file, `vcpkg.cmake`, to instruct CMake where to find the development files, for example:\n\n```bash\n-DCMAKE_TOOLCHAIN_FILE=//vcpkg/scripts/buildsystems/vcpkg.cmake\n```\n\nYou can find the header files in:\n\n```none\nvcpkg/installed/-/include/\n```\n\nThe library files are in:\n\n```none\nvcpkg/installed/-/lib/\n```\n\n### Conan Install Instructions\n\nPackage Specifier: `mongo-cxx-driver/3.8.0`\n\nIf you do not already have Conan installed, then install it and run the Conan initalization command below:\n\n```bash\n$ pip install conan\n$ conan profile detect --force\n```\n\nAdd the following to your `conanfile.txt`:\n\n```none\n[requires]\nmongo-cxx-driver/3.8.0\n[generators]\nCMakeDeps\nCMakeToolchain\n```\n\nInstall the driver via Conan, and build your project:\n\n```bash\n$ conan install conanfile.txt --output-folder=build --build=missing\n$ cmake \\\n -B build \\\n -DCMAKE_TOOLCHAIN_FILE=conan_toolchain.cmake \\\n -DCMAKE_BUILD_TYPE=Release\n$ cmake --build build\n```\n\n### Homebrew Install Instructions\n\nMacOS users can use Homebrew to install the C++ driver by running the following command:\n\n```bash\nbrew install mongo-cxx-driver\n```\n\n#### For an Apple Silicon Mac\n\nHeaders can be found in:\n\n```none\n/opt/homebrew/include/mongocxx/v_noabi/\n/opt/homebrew/include/bsoncxx/v_noabi/\n```\n\nLibrary files can be found in:\n\n```none\n/opt/homebrew/lib/\n```\n\n#### For an Intel Mac\n\nHeaders can be found in:\n\n```none\n/usr/local/include/mongocxx/v_noabi/\n/usr/local/include/bsoncxx/v_noabi/\n```\n\nLibrary files can be found in:\n\n```none\n/usr/local/lib/\n```\n\n## Install the MongoDB C Driver\n\nThe mongocxx driver builds on top of the MongoDB C driver.\n\nThe build of mongocxx-4.6.1 automatically downloads and installs the C driver if the C driver is not detected. To use an existing install of the C driver, set `CMAKE_PREFIX_PATH` to the directory containing the C driver install. For information about the minimum required `libmongoc` version for each version of the C++ driver, see Compatibility.\n\nUnless you know that your package manager offers a sufficiently recent version, you will need to download and build from the source code. Get a tarball from the C Driver release page.\n\nFollow the instructions for building from a tarball at Installing libmongoc.\n\nIndustry best practices and some regulations require the use of TLS 1.1 or newer. The MongoDB C Driver supports TLS 1.1 on Linux if OpenSSL is at least version 1.0.1. On macOS and Windows, the C Driver uses native TLS implementations that support TLS 1.1.\n\n## Advanced Configuration (Static Configurations)\n\nThe following sub-sections detail advanced options for configuring the C++ driver and/or its dependencies as static libraries rather than the typical shared libraries. These options will produce library artifacts that will behave differently. Ensure you have a complete understanding of the implications of the various linking approaches before utilizing these options.\n\n### Configuring with `mongocxx` 3.2.x or Newer\n\nUsers have the option to build `mongocxx` as a static library. **This is not recommended for novice users.** A user can enable this behavior with the `-DBUILD_SHARED_LIBS` option:\n\n```bash\ncmake .. \\\n -DCMAKE_BUILD_TYPE=Release \\\n -DBUILD_SHARED_LIBS=OFF\n```\n\n### Configuring with `mongocxx` 3.5.0 or Newer\n\nUsers have the option to build `mongocxx` as both static and shared libraries. A user can enable this behavior with the `-DBUILD_SHARED_AND_STATIC_LIBS` option:\n\n```bash\ncmake .. \\\n -DCMAKE_BUILD_TYPE=Release \\\n -DBUILD_SHARED_AND_STATIC_LIBS=ON\n```\n\nUsers have the option to build `mongocxx` as a shared library that has statically linked `libmongoc`. **This is not recommended for novice users.** A user can enable this behavior with the `-DBUILD_SHARED_LIBS_WITH_STATIC_MONGOC` option:\n\n```bash\ncmake .. \\\n -DCMAKE_BUILD_TYPE=Release \\\n -DBUILD_SHARED_LIBS_WITH_STATIC_MONGOC=ON\n```\n\n## Disabling Tests\n\nPass `-DENABLE_TESTS=OFF` as a cmake option to disable configuration of test targets.\n\n```bash\ncmake .. -DENABLE_TESTS=OFF\ncmake --build .. --target help\n# No test targets are configured.\n```\n\n## Installing to Non-Standard Directories\n\nTo install the C++ driver to a non-standard directory, specify `CMAKE_INSTALL_PREFIX` to the desired install path:\n\n```bash\ncmake .. \\\n -DCMAKE_BUILD_TYPE=Release \\\n -DCMAKE_INSTALL_PREFIX=$HOME/mongo-cxx-driver\n```\n\nConsider also specifying the `-DCMAKE_INSTALL_RPATH=` option to the `lib` directory of the install. This may enable libmongocxx.so to locate libbsoncxx.so:\n\n```bash\ncmake .. \\\n -DCMAKE_BUILD_TYPE=Release \\\n -DCMAKE_INSTALL_PREFIX=$HOME/mongo-cxx-driver \\\n -DCMAKE_INSTALL_RPATH=$HOME/mongo-cxx-driver/lib\n```\n\nIf the C driver is installed to a non-standard directory, specify `CMAKE_PREFIX_PATH` to the install path of the C driver:\n\n```bash\ncmake .. \\\n -DCMAKE_BUILD_TYPE=Release \\\n -DCMAKE_PREFIX_PATH=$HOME/mongo-c-driver \\\n -DCMAKE_INSTALL_PREFIX=$HOME/mongo-cxx-driver\n```\n\nIf you need multiple paths in a CMake PATH variable, separate them with a semicolon like this: `-DCMAKE_PREFIX_PATH=\"/your/cdriver/prefix;/some/other/path\"`\n\n### Configuring with `mongocxx` 3.1.x or 3.0.x\n\nInstead of the `-DCMAKE_PREFIX_PATH` option, users must specify the `libmongoc` installation directory by using the `-DLIBMONGOC_DIR` and `-DLIBBSON_DIR` options:\n\n```bash\ncmake .. \\\n -DCMAKE_BUILD_TYPE=Release \\\n -DLIBMONGOC_DIR=$HOME/mongo-c-driver \\\n -DLIBBSON_DIR=$HOME/mongo-c-driver \\\n -DCMAKE_INSTALL_PREFIX=$HOME/mongo-cxx-driver\n```\n\n## Troubleshooting"} -{"chunk_id": "6a1e766bcafdea84218660c2-1", "page_id": "6a1e766bcafdea84218660c2", "source_name": "cpp-driver", "product_name": "C++ Driver", "url": "https://mongodb.com/docs/languages/cpp/cpp-driver/current/connect/advanced-installation", "title": "Advanced Configuration and Installation Options", "text": "### Fixing the `Library not loaded` Error on macOS\n\nApplications linking to a non-standard directory installation may encounter an error loading the C++ driver at runtime. Example:\n\n```bash\n# Tell pkg-config where to find C++ driver installation.\nexport PKG_CONFIG_PATH=$HOME/mongo-cxx-driver/lib/pkgconfig\nclang++ app.cpp -std=c++11 $(pkg-config --cflags --libs libmongocxx) -o ./app.out\n./app.out\n# Prints the following error:\n# dyld[3217]: Library not loaded: '@rpath/libmongocxx._noabi.dylib'\n# Referenced from: '/Users/kevin.albertson/code/app.out'\n# Reason: tried: '/usr/local/lib/libmongocxx._noabi.dylib' (no such file), '/usr/lib/libmongocxx._noabi.dylib' (no such file)\n# zsh: abort ./app.out\n```\n\nThe default `install name` of the C++ driver on macOS includes `@rpath`:\n\n```bash\notool -D $HOME/mongo-cxx-driver/lib/libmongocxx.dylib\n# Prints:\n# /Users/kevin.albertson/mongo-cxx-driver/lib/libmongocxx.dylib:\n# @rpath/libmongocxx._noabi.dylib\n```\n\nIncluding `@rpath` in the install name allows linking applications to control the list of search paths for the library.\n\n`app.out` includes the load command for `@rpath/libmongocxx._noabi.dylib`. `app.out` does not have entries to substitute for `@rpath`.\n\nThere are several ways to consider solving this on macOS:\n\nPass `DYLD_FALLBACK_LIBRARY_PATH` to the directory containing the C++ driver libraries:\n\n```bash\nDYLD_FALLBACK_LIBRARY_PATH=$HOME/mongo-cxx-driver/lib ./app.out\n# Prints \"successfully connected with C++ driver\"\n```\n\nAlternatively, the linker option `-Wl,-rpath` can be passed to add entries to substitute for `@rpath`:\n\n```bash\n# Tell pkg-config where to find C++ driver installation.\nexport PKG_CONFIG_PATH=$HOME/mongo-cxx-driver/lib/pkgconfig\n# Pass the linker option -rpath to set an rpath in the final executable.\nclang++ app.cpp -std=c++11 -Wl,-rpath,$HOME/mongo-cxx-driver/lib $(pkg-config --cflags --libs libmongocxx) -o ./app.out\n./app.out\n# Prints \"successfully connected with C++ driver\"\n```\n\nIf building the application with cmake, the Default RPATH settings include the full RPATH to all used libraries in the build tree. However, when installing, cmake will clear the RPATH of these targets so they are installed with an empty RPATH. This may result in a `Library not loaded` error after install.\n\nExample:\n\n```bash\n# Build application ``app`` using the C++ driver from a non-standard install.\ncmake \\\n -DCMAKE_PREFIX_PATH=$HOME/mongo-cxx-driver \\\n -DCMAKE_INSTALL_PREFIX=$HOME/app \\\n -DCMAKE_CXX_STANDARD=11 \\\n -Bcmake-build -S.\ncmake --build cmake-build --target app.out\n# Running app.out from build tree includes rpath to C++ driver.\n./cmake-build ./cmake-build/app.out\n# Prints: \"successfully connected with C++ driver\"\n\ncmake --build cmake-build --target install\n# Running app.out from install tree does not include rpath to C++ driver.\n$HOME/app/bin/app.out\n# Prints \"Library not loaded\" error.\n```\n\nConsider setting `-DCMAKE_INSTALL_RPATH_USE_LINK_PATH=TRUE` so the rpath for the executable is kept in the install target.\n\n```bash\n# Build application ``app`` using the C++ driver from a non-standard install.\n# Use CMAKE_INSTALL_RPATH_USE_LINK_PATH=TRUE to keep rpath entry on installed app.\ncmake \\\n -DCMAKE_PREFIX_PATH=$HOME/mongo-cxx-driver \\\n -DCMAKE_INSTALL_PREFIX=$HOME/app \\\n -DCMAKE_INSTALL_RPATH_USE_LINK_PATH=TRUE \\\n -DCMAKE_CXX_STANDARD=11 \\\n -Bcmake-build -S.\n\ncmake --build cmake-build --target install\n$HOME/app/bin/app.out\n# Prints \"successfully connected with C++ driver\"\n```\n\nSee the cmake documentation for RPATH handling for more information.\n\n### Fixing the \"cannot open shared object file\" Error on Linux\n\nApplications linking to a non-standard directory installation may encounter an error loading the C++ driver at runtime. Example:\n\n```bash\n# Tell pkg-config where to find C++ driver installation.\nexport PKG_CONFIG_PATH=$HOME/mongo-cxx-driver/lib/pkgconfig\ng++ -std=c++11 app.cpp $(pkg-config --cflags --libs libmongocxx) -o ./app.out\n./app.out\n# Prints the following error:\n# ./app.out: error while loading shared libraries: libmongocxx.so._noabi: cannot open shared object file: No such file or directory\n```\n\nThere are several ways to consider solving this on Linux:\n\nPass `LD_LIBRARY_PATH` to the directory containing the C++ driver libraries:\n\n```bash\nLD_LIBRARY_PATH=$HOME/mongo-cxx-driver/lib ./app.out\n# Prints \"successfully connected with C++ driver\"\n```\n\nAlternatively, the linker option `-Wl,-rpath` can be passed to add `rpath` entries:\n\n```bash\n# Tell pkg-config where to find C++ driver installation.\nexport PKG_CONFIG_PATH=$HOME/mongo-cxx-driver/lib/pkgconfig\n# Pass the linker option -rpath to set an rpath in the final executable.\ng++ app.cpp -std=c++11 -Wl,-rpath,$HOME/mongo-cxx-driver/lib $(pkg-config --cflags --libs libmongocxx) -o ./app.out\n./app.out\n# Prints \"successfully connected with C++ driver\"\n```\n\nIf building the application with cmake, the Default RPATH settings include the full RPATH to all used libraries in the build tree. However, when installing, cmake will clear the RPATH of these targets so they are installed with an empty RPATH. This may result in a `Library not loaded` error after install.\n\nExample:\n\n```bash\n# Build application ``app`` using the C++ driver from a non-standard install.\ncmake \\\n -DCMAKE_PREFIX_PATH=$HOME/mongo-cxx-driver \\\n -DCMAKE_INSTALL_PREFIX=$HOME/app \\\n -DCMAKE_CXX_STANDARD=11 \\\n -Bcmake-build -S.\ncmake --build cmake-build --target app.out\n# Running app.out from build tree includes rpath to C++ driver.\n./cmake-build ./cmake-build/app.out\n# Prints: \"successfully connected with C++ driver\"\n\ncmake --build cmake-build --target install\n# Running app.out from install tree does not include rpath to C++ driver.\n$HOME/app/bin/app.out\n# Prints \"cannot open shared object file\" error.\n```\n\nConsider setting `-DCMAKE_INSTALL_RPATH_USE_LINK_PATH=TRUE` so the rpath for the executable is kept in the install target.\n\n```bash\n# Build application ``app`` using the C++ driver from a non-standard install.\n# Use CMAKE_INSTALL_RPATH_USE_LINK_PATH=TRUE to keep rpath entry on installed app.\ncmake \\\n -DCMAKE_PREFIX_PATH=$HOME/mongo-cxx-driver \\\n -DCMAKE_INSTALL_PREFIX=$HOME/app \\\n -DCMAKE_INSTALL_RPATH_USE_LINK_PATH=TRUE \\\n -DCMAKE_CXX_STANDARD=11 \\\n -Bcmake-build -S.\n\ncmake --build cmake-build --target install\n$HOME/app/bin/app.out\n# Prints \"successfully connected with C++ driver\"\n```\n\nSee the cmake documentation for RPATH handling for more information."} -{"chunk_id": "6a1e766bcafdea8421866170-0", "page_id": "6a1e766bcafdea8421866170", "source_name": "cpp-driver", "product_name": "C++ Driver", "url": "https://mongodb.com/docs/languages/cpp/cpp-driver/current/security/authentication/aws-iam", "title": "AWS Identity and Access Management", "text": "# AWS Identity and Access Management\n\n## Overview\n\nAWS authentication is available only in the MongoDB Enterprise Edition for MongoDB 4.4 and later.\n\nThe `MONGODB-AWS` authentication mechanism uses AWS Identity and Access Management (IAM) and AWS Security Token Service (STS) to prove the client's identity to a MongoDB deployment. The following steps describe the AWS authentication process:\n\n1. The client uses AWS IAM credentials to create a signature and sends it to the MongoDB deployment.\n\n2. The deployment uses the client's signature to send a request to AWS STS.\n\n3. If the request succeeds, STS returns the Amazon Resource Name (ARN) of the IAM user or role that corresponds to the client's credentials.\n\n4. The deployment uses the returned ARN to look up the user. The client authenticates as this user.\n\nThe client and server use different usernames. The client sends the AWS access key ID as the username. The server uses the ARN of the IAM user or role corresponding to the access key ID as the username.\n\nTo authenticate with this mechanism:\n\n- Create a user on the `$external` database whose name is the ARN of the IAM user or role you want to authenticate as.\n\n- Configure the client to use the `MONGODB-AWS` authentication mechanism.\n\n### AWS Credentials\n\nAWS credentials include the following components:\n\n- Access key ID\n\n- Secret access key\n\n- Optional session token\n\nAuthentication with AWS IAM credentials uses the access key ID and the secret access key. Authentication with temporary AWS IAM credentials uses all three components: access key ID, secret access key, and session token.\n\nThe driver never sends the secret access key or the session token over the network.\n\nTemporary credentials are used with:\n\n- STS Assume Role requests.\n\n- EC2 instance roles.\n\n- ECS task roles.\n\n- AWS Lambda environment.\n\n- IAM roles for service accounts.\n\n### Code Placeholders\n\nThe code examples on this page use the following placeholders:\n\n- ``: The network address of your MongoDB deployment.\n\n- ``: The port number of your MongoDB deployment.\n\n- ``: The AWS access key ID.\n\n- ``: The AWS secret access key.\n\n- ``: The AWS session token.\n\nTo use the code examples on this page, replace these placeholders with your own values.\n\n## Using AWS IAM Authentication in Your Application\n\nThe C++ driver can retrieve AWS IAM credentials from the environment, or you can provide them explicitly in your application code.\n\nWhen you use the `MONGODB-AWS` authentication mechanism, the C++ driver attempts to retrieve AWS credentials from the following sources, in this order:\n\n1. Credentials passed in the connection URI\n\n2. Environment variables\n\n3. AWS EKS AssumeRoleWithWebIdentity request\n\n4. ECS container metadata\n\n5. EC2 instance metadata\n\n### Providing Credentials Explicitly\n\nYou can provide long-term (non-temporary) IAM credentials in the connection URI. To do so, set the following URI parameters:\n\n- `username`: Set to your AWS access key ID.\n\n- `password`: Set to your AWS secret access key.\n\n- `authMechanism`: Set to `MONGODB-AWS`.\n\nYou can use the connection URI by itself or the connection URI with TLS options configured by using the `mongocxx::options::tls` and `mongocxx::options::client` classes. Select the Connection URI or Client Options with TLS tab to see the corresponding syntax:\n\n\n\n\n\n```cpp\nauto uri = mongocxx::uri(\"mongodb://:@:/?\"\n \"authMechanism=MONGODB-AWS\");\nauto client = mongocxx::client(uri);\n```\n\n\n\n\n\n```cpp\nmongocxx::options::client client_options;\nmongocxx::options::tls tls_options;\n\ntls_options.ca_file(\"/path/to/ca.pem\");\nclient_options.tls_opts(tls_options);\n\nauto uri = mongocxx::uri(\"mongodb://:@:/?\"\n \"authMechanism=MONGODB-AWS&tls=true\");\nauto client = mongocxx::client(uri, client_options);\n```\n\n\n\n\n\nIf you provide credentials in a URI, percent-encode any special characters in the access key ID or secret access key.\n\n### Providing Temporary Credentials\n\nYou can provide temporary IAM credentials in the connection URI by including the session token in the `authMechanismProperties` parameter of the connection URI.\n\nSelect the Connection URI or Client Options with TLS tab to see the corresponding syntax:\n\n\n\n\n\n```cpp\nauto uri = mongocxx::uri(\"mongodb://:@:/?\"\n \"authMechanism=MONGODB-AWS&authMechanismProperties=AWS_SESSION_TOKEN:\");\nauto client = mongocxx::client(uri);\n```\n\n\n\n\n\n```cpp\nmongocxx::options::client client_options;\nmongocxx::options::tls tls_options;\n\ntls_options.ca_file(\"/path/to/ca.pem\");\nclient_options.tls_opts(tls_options);\n\nauto uri = mongocxx::uri(\"mongodb://:@:/?\"\n \"authMechanism=MONGODB-AWS\"\n \"&authMechanismProperties=AWS_SESSION_TOKEN:&tls=true\");\nauto client = mongocxx::client(uri, client_options);\n```\n\n\n\n"} -{"chunk_id": "6a1e766bcafdea8421866170-1", "page_id": "6a1e766bcafdea8421866170", "source_name": "cpp-driver", "product_name": "C++ Driver", "url": "https://mongodb.com/docs/languages/cpp/cpp-driver/current/security/authentication/aws-iam", "title": "AWS Identity and Access Management", "text": "### Automatically Retrieving Credentials\n\nWhen you specify the `MONGODB-AWS` authentication mechanism and omit the `username` and `password`, the C++ driver automatically attempts to retrieve AWS credentials from environment variables, web identity roles, and AWS metadata endpoints.\n\n#### Environment Variables\n\nThe C++ driver first checks for the credentials from the following environment variables:\n\n- `AWS_ACCESS_KEY_ID`\n\n- `AWS_SECRET_ACCESS_KEY`\n\n- `AWS_SESSION_TOKEN` (optional)\n\nThese variables are recognized by many AWS tools and SDKs, such as the AWS CLI, and are also commonly set in AWS Lambda environments.\n\nExample of setting these variables:\n\n```shell\nexport AWS_ACCESS_KEY_ID=\nexport AWS_SECRET_ACCESS_KEY=\nexport AWS_SESSION_TOKEN=\n```\n\nAfter you set these environment variables, set the `authMechanism` parameter in your connection URI to `\"MONGODB-AWS\"`. Select the Connection URI or Client Options with TLS tab to see the corresponding syntax:\n\n\n\n\n\n```cpp\nauto uri = mongocxx::uri(\"mongodb://:/?\"\n \"authMechanism=MONGODB-AWS\");\nauto client = mongocxx::client(uri);\n```\n\n\n\n\n\n```cpp\nmongocxx::options::client client_options;\nmongocxx::options::tls tls_options;\n\ntls_options.ca_file(\"/path/to/ca.pem\");\nclient_options.tls_opts(tls_options);\n\nauto uri = mongocxx::uri(\"mongodb://:/?\"\n \"authMechanism=MONGODB-AWS&tls=true\");\nauto client = mongocxx::client(uri, client_options);\n```\n\n\n\n\n\n#### AssumeRoleWithWebIdentity\n\nIf your application runs in an Amazon EKS cluster and authenticates through an OpenID Connect (OIDC) identity provider, the C++ driver can use an AssumeRoleWithWebIdentity request. This request exchanges the OIDC token for temporary AWS credentials for your application.\n\nTo configure this mechanism:\n\n1. Create or update your AWS configuration file. To learn how to create this configuration file, see Globally configuring AWS SDKs and tools.\n\n2. Set the following environment variables:\n\n - `AWS_ROLE_ARN`: Set to the ARN of the IAM role to assume.\n\n - `AWS_WEB_IDENTITY_TOKEN_FILE`: Set to the path of the file that contains the OIDC token for your service account.\n\n - `AWS_ROLE_SESSION_NAME` (optional): Set to an identifier for the assumed role session. If you omit this variable, the driver generates a random identifier.\n\n3. Set the `authMechanism` parameter in your connection URI to `\"MONGODB-AWS\"`.\n\nSelect the Connection URI or Client Options with TLS tab to see the corresponding syntax:\n\n\n\n\n\n```cpp\nauto uri = mongocxx::uri(\"mongodb://:/?\"\n \"authMechanism=MONGODB-AWS\");\nauto client = mongocxx::client(uri);\n```\n\n\n\n\n\n```cpp\nmongocxx::options::client client_options;\nmongocxx::options::tls tls_options;\n\ntls_options.ca_file(\"/path/to/ca.pem\");\nclient_options.tls_opts(tls_options);\n\nauto uri = mongocxx::uri(\"mongodb://:/?\"\n \"authMechanism=MONGODB-AWS&tls=true\");\nauto client = mongocxx::client(uri, client_options);\n```\n\n\n\n\n\nTo learn more about authenticating with web identity roles, see AssumeRoleWithWebIdentity API\n\n#### ECS Task Metadata\n\nIf your application runs in an Amazon ECS container, the C++ driver can retrieve temporary AWS credentials from the ECS task metadata endpoint.\n\nTo enable this behavior, set the `AWS_CONTAINER_CREDENTIALS_RELATIVE_URI` environment variable to the relative URI of the ECS task metadata endpoint, as shown in the following example:\n\n```sh\nexport AWS_CONTAINER_CREDENTIALS_RELATIVE_URI=\n```\n\nThen construct the client with the `authMechanism` set to `\"MONGODB-AWS\"`. Select the Connection URI or Client Options with TLS tab to see the corresponding syntax:\n\n\n\n\n\n```cpp\nauto uri = mongocxx::uri(\"mongodb://:/?\"\n \"authMechanism=MONGODB-AWS\");\nauto client = mongocxx::client(uri);\n```\n\n\n\n\n\n```cpp\nmongocxx::options::client client_options;\nmongocxx::options::tls tls_options;\n\ntls_options.ca_file(\"/path/to/ca.pem\");\nclient_options.tls_opts(tls_options);\n\nauto uri = mongocxx::uri(\"mongodb://:/?\"\n \"authMechanism=MONGODB-AWS&tls=true\");\nauto client = mongocxx::client(uri, client_options);\n```\n\n\n\n\n\n#### EC2 Instance Metadata\n\nIf your application runs on an Amazon EC2 instance, the C++ driver can retrieve temporary AWS credentials from the EC2 instance metadata endpoint.\n\nTo enable this behavior, set the `authMechanism` parameter in your connection URI to `\"MONGODB-AWS\"`. Select the Connection URI or Client Options with TLS tab to see the corresponding syntax:\n\n\n\n\n\n```cpp\nauto uri = mongocxx::uri(\"mongodb://:/?\"\n \"authMechanism=MONGODB-AWS\");\nauto client = mongocxx::client(uri);\n```\n\n\n\n\n\n```cpp\nmongocxx::options::client client_options;\nmongocxx::options::tls tls_options;\n\ntls_options.ca_file(\"/path/to/ca.pem\");\nclient_options.tls_opts(tls_options);\n\nauto uri = mongocxx::uri(\"mongodb://:/?\"\n \"authMechanism=MONGODB-AWS&tls=true\");\nauto client = mongocxx::client(uri, client_options);\n```\n\n\n\n\n\nIf you set any of the environment variables from the preceding AWS authentication methods, the C++ driver attempts to retrieve credentials by using those methods before attempting to retrieve them from an EC2 instance. To attempt to retrieve credentials only from an EC2 instance, ensure that the environment variables are not set.\n\nIf an application runs in an ECS container on an EC2 instance and the container is allowed access to the instance metadata, the driver attempts to retrieve AWS credentials from the EC2 instance metadata endpoint. If the driver retrieves credentials in this way, your application can authenticate as the IAM role assigned to the EC2 instance.\n\nTo learn how to prevent containers from accessing EC2 instance metadata, see the AWS documentation.\n\n## API Documentation\n\nTo learn more about creating a `mongocxx::client` object in the C++ driver or configuring TLS, see the following API documentation:\n\n- mongocxx::client\n\n- mongocxx::options::client\n\n- mongocxx::options::tls"} -{"chunk_id": "6a1e766bcafdea842186610a-0", "page_id": "6a1e766bcafdea842186610a", "source_name": "cpp-driver", "product_name": "C++ Driver", "url": "https://mongodb.com/docs/languages/cpp/cpp-driver/current/crud/query/project", "title": "Specify Fields To Return", "text": "# Specify Fields To Return\n\n## Overview\n\nIn this guide, you can learn how to use the C++ driver to specify which fields to return from a read operation by using a **projection**. A projection is a document that specifies which fields MongoDB returns from a query.\n\n### Sample Data\n\nThe examples in this guide use the `restaurants` collection in the `sample_restaurants` database from the Atlas sample datasets. To access this collection from your C++ application, instantiate a `mongocxx::client` that connects to an Atlas cluster and assign the following values to your `db` and `collection` variables:\n\n```cpp\nauto db = client[\"sample_restaurants\"];\nauto collection = db[\"restaurants\"];\n```\n\nTo learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the MongoDB Get Started guide.\n\n## Projection Types\n\nYou can use a projection to specify which fields to include in a return document, or to specify which fields to exclude. You cannot combine inclusion and exclusion statements in a single projection, unless you are excluding the `_id` field.\n\n### Specify Fields to Include\n\nTo specify the fields to include in the result, create an instance of the `mongocxx::options::find` class and set its `projection` field. To set this field, use the following syntax:\n\n```cpp\n.projection(make_document(kvp(\"\", 1)));\n```\n\nThe following example sets the `projection` field of a `mongocxx::options::find` object to return only the `name`, `cuisine`, and `borough` fields of matching documents. It then calls the `find()` method to find all restaurants in which the `name` field value is `\"Emerald Pub\"`, passing the `mongocxx::options::find` object as a parameter to `find()`:\n\n```cpp\nmongocxx::options::find opts{};\nopts.projection(make_document(kvp(\"name\", 1), kvp(\"cuisine\", 1), kvp(\"borough\", 1)));\n\nauto cursor = collection.find(make_document(kvp(\"name\", \"Emerald Pub\")), opts);\nfor(auto&& doc : cursor) {\n std::cout << bsoncxx::to_json(doc) << std::endl;\n}\n```\n\n```\n{ \"_id\" : { \"$oid\" : \"...\" }, \"borough\" : \"Manhattan\", \"cuisine\" : \"American\", \"name\" : \"Emerald Pub\" }\n{ \"_id\" : { \"$oid\" : \"...\" }, \"borough\" : \"Queens\", \"cuisine\" : \"American\", \"name\" : \"Emerald Pub\" }\n```\n\nWhen you use a projection to specify fields to include in the return document, the `_id` field is also included by default. All other fields are implicitly excluded. To remove the `_id` field from the return document, you must explicitly exclude it.\n\n### Exclude the `_id` Field\n\nWhen specifying fields to include, you can also exclude the `_id` field from the returned document.\n\nThe following example performs the same query as the preceding example but excludes the `_id` field from the projection:\n\n```python\nmongocxx::options::find opts{};\nopts.projection(make_document(kvp(\"_id\", 0), kvp(\"name\", 1), kvp(\"cuisine\", 1), kvp(\"borough\", 1)));\n\nauto cursor = collection.find(make_document(kvp(\"name\", \"Emerald Pub\")), opts);\nfor(auto&& doc : cursor) {\n std::cout << bsoncxx::to_json(doc) << std::endl;\n}\n```\n\n```\n{ \"borough\" : \"Manhattan\", \"cuisine\" : \"American\", \"name\" : \"Emerald Pub\" }\n{ \"borough\" : \"Queens\", \"cuisine\" : \"American\", \"name\" : \"Emerald Pub\" }\n```\n\n### Specify Fields to Exclude\n\nTo specify the fields to exclude in the result, create an instance of the `mongocxx::options::find` class and set its `projection` field. To set this field, use the following syntax:\n\n```cpp\n.projection(make_document(kvp(\"\", 0)));\n```\n\nThe following example sets the `projection` field of a `mongocxx::options::find` object to exclude the `grades` and `address` fields of matching documents. It then calls the `find()` method to find all restaurants in which the `name` field value is `\"Emerald Pub\"`, passing the `mongocxx::options::find` object as a parameter to `find()`:\n\n```cpp\nmongocxx::options::find opts{};\nopts.projection(make_document(kvp(\"grades\", 0), kvp(\"address\", 0)));\n\nauto cursor = collection.find(make_document(kvp(\"name\", \"Emerald Pub\")), opts);\nfor(auto&& doc : cursor) {\n std::cout << bsoncxx::to_json(doc) << std::endl;\n}\n```\n\n```\n{ \"_id\" : { \"$oid\" : \"...\" }, \"borough\" : \"Manhattan\", \"cuisine\" : \"American\", \"name\" : \"Emerald Pub\", \"restaurant_id\" : \"40367329\" }\n{ \"_id\" : { \"$oid\" : \"...\" }, \"borough\" : \"Queens\", \"cuisine\" : \"American\", \"name\" : \"Emerald Pub\", \"restaurant_id\" : \"40668598\" }\n```\n\nWhen you use a projection to specify which fields to exclude, any unspecified fields are implicitly included in the return document.\n\n## Additional Information\n\nTo learn more about projections, see the Project Fields guide in the MongoDB Server manual.\n\n### API Documentation\n\nTo learn more about any of the methods or types discussed in this guide, see the following API documentation:\n\n- find()\n\n- mongocxx::options::find\n\n- projection"} -{"chunk_id": "6a1e766bcafdea8421866116-0", "page_id": "6a1e766bcafdea8421866116", "source_name": "cpp-driver", "product_name": "C++ Driver", "url": "https://mongodb.com/docs/languages/cpp/cpp-driver/current/crud/update", "title": "Update Documents", "text": "# Update Documents\n\n## Overview\n\nIn this guide, you can learn how to use the C++ driver to update documents in a MongoDB collection. You can call the `update_one()` method to update a single document or the `update_many()` method to update multiple documents.\n\n### Sample Data\n\nThe examples in this guide use the `restaurants` collection in the `sample_restaurants` database from the Atlas sample datasets. To access this collection from your C++ application, instantiate a `mongocxx::client` that connects to an Atlas cluster and assign the following values to your `db` and `collection` variables:\n\n```cpp\nauto db = client[\"sample_restaurants\"];\nauto collection = db[\"restaurants\"];\n```\n\nTo learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the MongoDB Get Started guide.\n\n## Update Operations\n\nYou can perform update operations in MongoDB by using the following methods:\n\n- `update_one()`, which updates *the first document* that matches the search criteria\n\n- `update_many()`, which updates *all documents* that match the search criteria\n\nEach update method requires the following parameters:\n\n- **Query filter** document: Specifies which documents to update. For more information about query filters, see the Query Filter Documents section in the MongoDB Server manual.\n\n- **Update** document: Specifies the **update operator**, or the kind of update to perform, and the fields and values to change. For a list of update operators and their usage, see the Field Update Operators guide in the MongoDB Server manual.\n\n### Update One Document\n\nThe following example uses the `update_one()` method to update the `name` value of a document in the `restaurants` collection from `\"Bagels N Buns\"` to `\"2 Bagels 2 Buns\"`:\n\n```cpp\nauto query_filter = make_document(kvp(\"name\", \"Bagels N Buns\"));\nauto update_doc = make_document(kvp(\"$set\", make_document(kvp(\"name\", \"2 Bagels 2 Buns\"))));\n\nauto result = collection.update_one(query_filter.view(), update_doc.view());\n```\n\n### Update Many Documents\n\nThe following example uses the `update_many()` method to update all documents that have a `cuisine` value of `\"Pizza\"`. After the update, the documents have a `cuisine` value of `\"Pasta\"`.\n\n```cpp\nauto query_filter = make_document(kvp(\"cuisine\", \"Pizza\"));\nauto update_doc = make_document(kvp(\"$set\", make_document(kvp(\"cuisine\", \"Pasta\"))));\n\nauto result = collection.update_many(query_filter.view(), update_doc.view());\n```\n\n### Upsert Option\n\nThe `upsert` parameter allows you to use the `update_one()` and `update_many()` operations to perform a conditional operation:\n\n- If the specified document exists, the command updates it.\n\n- If the specified document does not exist, the command creates a new document with the specified parameter.\n\nFor more information, see the Modify Update Example section or the options table on this page.\n\n### Customize the Update Operation\n\nYou can modify the behavior of the `update_one()` and `update_many()` methods by passing an instance of the `mongocxx::options::update` class as an optional parameter. The following table describes the fields you can set in a `mongocxx::options::update` instance:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nField\n\n\nDescription\n\n
\n`upsert`\n\n\nSpecifies whether the update operation performs an upsert operation if no documents match the query filter. For more information, see the upsert statement in the MongoDB Server manual.Defaults to `false`.\n\n
\n`bypass_document_validation`\n\n\nSpecifies whether the update operation bypasses document validation. This lets you update documents that don't meet the schema validation requirements, if any exist. For more information about schema validation, see Schema Validation in the MongoDB Server manual.Defaults to `false`.\n\n
\n`collation`\n\n\nSpecifies the kind of language collation to use when sorting results. For more information, see Collation in the MongoDB Server manual.\n\n
\n`array_filters`\n\n\nSpecifies which array elements an update applies to if the operation modifies array fields.\n\n
\n`hint`\n\n\nSets the index to scan for documents. For more information, see the hint statement in the MongoDB Server manual.\n\n
\n`write_concern`\n\n\nSets the write concern for the operation. For more information, see Write Concern in the MongoDB Server manual.\n\n
\n`let`\n\n\nSpecifies a document with a list of values to improve operation readability. Values must be constant or closed expressions that don't reference document fields. For more information, see the let statement in the MongoDB Server manual.\n\n
\n`comment`\n\n\nA comment to attach to the operation. For more information, see the insert command fields guide in the MongoDB Server manual for more information.\n\n
\n#### Modify Update Example\n\nThe following example uses the `update_many()` method to find all documents that have the `borough` value of `\"Manhattan\"`. It then updates the `borough` value in these documents to `\"Manhattan (north)\"`.\n\nBecause the `upsert` option is set to `true`, if the query filter doesn't match any existing documents, the C++ driver inserts a new document that contains the fields and values in the filter and update documents.\n\n```cpp\nmongocxx::options::update opts{};\nopts.upsert(true);\n\nauto query_filter = make_document(kvp(\"borough\", \"Manhattan\"));\nauto update_doc = make_document(kvp(\"$set\", make_document(kvp(\"borough\", \"Manhattan (north)\"))));\n\nauto result = collection.update_many(query_filter.view(), update_doc.view(), opts);\n```\n\n### Return Value\n\nThe `update_one()` and `update_many()` methods return an instance of the `mongocxx::result::update` class. This class contains the following member functions:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nFunction\n\n\nDescription\n\n
\n`matched_count()`\n\n\nReturns the number of documents that matched the query filter, regardless of how many were updated.\n\n
\n`modified_count()`\n\n\nReturns number of documents modified by the update operation. If an updated document is identical to the original, it is not included in this count.\n\n
\n`result()`\n\n\nReturns the raw result document for the operation.\n\n
\n`upserted_count()`\n\n\nReturns the number of document that were upserted into the database.\n\n
\n`upserted_id()`\n\n\nReturns the ID of the document that was upserted in the database, if the driver performed an upsert.\n\n
The following example uses the `update_many()` method to update the `name` field of matching documents from `\"Dunkin' Donuts\"` to `\"Dunkin'\"`. It calls the `modified_count()` member function to print the number of modified documents:\n\n```cpp\nauto query_filter = make_document(kvp(\"name\", \"Dunkin' Donuts\"));\nauto update_doc = make_document(kvp(\"$set\", make_document(kvp(\"name\", \"Dunkin'\"))));\n\nauto result = collection.update_many(query_filter.view(), update_doc.view());\nstd::cout << \"Modified documents: \" << result->modified_count() << std::endl;\n```\n\n```\nModified documents: 206\n```\n\n## Additional Information\n\nTo learn more about creating query filters, see the Specify a Query guide."} -{"chunk_id": "6a1e766bcafdea8421866116-1", "page_id": "6a1e766bcafdea8421866116", "source_name": "cpp-driver", "product_name": "C++ Driver", "url": "https://mongodb.com/docs/languages/cpp/cpp-driver/current/crud/update", "title": "Update Documents", "text": "### API Documentation\n\nTo learn more about any of the methods or types discussed in this guide, see the following API documentation:\n\n- update_one()\n\n- update_many()\n\n- mongocxx::options::update\n\n- mongocxx::result::update"} -{"chunk_id": "6a1e766bcafdea84218660f2-0", "page_id": "6a1e766bcafdea84218660f2", "source_name": "cpp-driver", "product_name": "C++ Driver", "url": "https://mongodb.com/docs/languages/cpp/cpp-driver/current/crud/query/cursor", "title": "Access Data From a Cursor", "text": "# Access Data From a Cursor\n\n## Overview\n\nIn this guide, you can learn how to access data from a **cursor** by using the C++ driver.\n\nA cursor is a mechanism that returns the results of a read operation in iterable batches. Cursors reduce both memory consumption and network bandwidth usage by holding only a subset of documents at any given time rather than returning all documents at once.\n\nWhenever the C++ driver performs a read operation by using the `find()` method, it returns the matching documents in a `mongocxx::cursor` instance.\n\n### Sample Data\n\nThe examples in this guide use the `restaurants` collection in the `sample_restaurants` database from the Atlas sample datasets. To access this collection from your C++ application, instantiate a `mongocxx::client` that connects to an Atlas cluster and assign the following values to your `db` and `collection` variables:\n\n```cpp\nauto db = client[\"sample_restaurants\"];\nauto collection = db[\"restaurants\"];\n```\n\nTo learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the MongoDB Get Started guide.\n\n## Retrieve All Cursor Documents\n\nTo iterate over the contents of a `mongocxx::cursor` instance, use a `for` loop.\n\nThe following example uses the `find()` method to retrieve all documents that have a `name` value of `\"Dunkin' Donuts\"`. It then prints each document from the cursor returned by the `find()` method:\n\n```cpp\nauto cursor = collection.find(make_document(kvp(\"name\", \"Dunkin' Donuts\")));\nfor(auto&& doc : cursor) {\n std::cout << bsoncxx::to_json(doc) << std::endl;\n}\n```\n\n```\n{ \"_id\" : { \"$oid\" : \"...\" }, ... \"name\" : \"Dunkin' Donuts\", \"restaurant_id\" : \"40379573\" }\n{ \"_id\" : { \"$oid\" : \"...\" }, ... \"name\" : \"Dunkin' Donuts\", \"restaurant_id\" : \"40363098\" }\n{ \"_id\" : { \"$oid\" : \"...\" }, ... \"name\" : \"Dunkin' Donuts\", \"restaurant_id\" : \"40395071\" }\n...\n```\n\n## Retrieve Documents Individually\n\nTo retrieve an individual document from a cursor, call the `begin()` method on a `mongocxx::cursor` instance. This method returns an instance of `mongocxx::cursor::iterator` that points to the first document in the cursor.\n\nThe following example finds all documents in a collection that have a `name` value of `\"Dunkin' Donuts\"`. It then prints the first document from the cursor by calling the `begin()` method:\n\n```cpp\nauto cursor = collection.find(make_document(kvp(\"name\", \"Dunkin' Donuts\")));\nauto doc = cursor.begin();\nstd::cout << bsoncxx::to_json(*doc) << std::endl;\n```\n\n```\n{ \"_id\" : { \"$oid\" : \"...\" }, ... \"name\" : \"Dunkin' Donuts\", \"restaurant_id\" : \"40379573\" }\n```\n\n## Tailable Cursors\n\nWhen querying on a capped collection, you can use a **tailable cursor** that remains open after the client exhausts the results in a cursor. To create a tailable cursor, instantiate a `mongocxx::options::find` object and set its `cursor_type` field to `mongocxx::cursor::type::k_tailable`. Then, pass your `mongocxx::options::find` instance as an argument to the `find()` method.\n\nFor example, you can create a capped collection called `vegetables` that stores documents representing vegetables, as shown in the following code:\n\n```cpp\nauto db = client[\"db\"];\nauto collection = db.create_collection(\"vegetables\", make_document(kvp(\"capped\", true), kvp(\"size\", 1024 * 1024)));\n\nstd::vector vegetables;\nvegetables.push_back(make_document(kvp(\"name\", \"cauliflower\")));\nvegetables.push_back(make_document(kvp(\"name\", \"zucchini\")));\n\nauto result = collection.insert_many(vegetables);\n```\n\nThe following code uses a tailable cursor to retrieve all documents in the `vegetables` collection. After the cursor is exhausted, it remains open until retrieving three documents:\n\n```cpp\nmongocxx::options::find opts{};\nopts.cursor_type(mongocxx::cursor::type::k_tailable);\nauto cursor = collection.find({}, opts);\n\nint docs_found = 0;\nwhile (docs_found < 3) {\n for (auto&& doc : cursor) {\n std::cout << bsoncxx::to_json(doc) << std::endl;\n docs_found++;\n }\n\n // Sleeps for 100 milliseconds before trying to access more documents\n std::this_thread::sleep_for(std::chrono::milliseconds(100));\n}\n```\n\n```\n{ \"_id\" : { \"$oid\" : \"...\" }, \"name\" : \"cauliflower\" }\n{ \"_id\" : { \"$oid\" : \"...\" }, \"name\" : \"zucchini\" }\n```\n\nIf you insert another document into the `vegetables` collection, the preceding code prints the new document and closes the `while` loop.\n\nTo learn more about tailable cursors, see the Tailable Cursors guide in the MongoDB Server manual.\n\n## Additional Information\n\nTo learn more about read operations, see the Find Documents guide.\n\n### API Documentation\n\nTo learn more about any of the methods or types discussed in this guide, see the following API documentation:\n\n- mongocxx::cursor\n\n- find()\n\n- begin()\n\n- mongocxx::options::find"} -{"chunk_id": "68a95beb5e79d242619d86cb-0", "page_id": "68a95beb5e79d242619d86cb", "source_name": "csharp", "product_name": "C# Driver", "url": "https://mongodb.com/docs/drivers/csharp/current/connect/connection-options/server-selection", "title": "Customize Server Selection", "text": "# Customize Server Selection\n\n## Overview\n\nAll MongoDB drivers follow a defined algorithm when selecting a server to read or write from. By using the `ClusterConfigurator` property of a `MongoClient` object, you can customize this algorithm to choose the server that works best for your application.\n\nCustomizing the server selection algorithm might have unintended consequences, such as degraded read or write performance.\n\n## Default Algorithm\n\nWhen the .NET/C# Driver executes a read operation, it performs the following steps, in order, to select a MongoDB deployment:\n\n1. Selects all servers that match the active read preference from the list of known servers.\n\n2. If at least one readable server exists, the driver calls the user-defined server-selector function and passes in the list from the previous step.\n\n3. Applies the `LocalThreshold` connection setting to the list of servers returned from the function.\n\n4. Selects a server at random from the servers still on the list and executes the operation against this server.\n\nWhen the .NET/C# Driver executes a write operation, it begins by selecting all writeable servers, not just those that match the active read preference. The remaining steps are identical.\n\nTo learn more about the default server selection algorithm, which the driver follows when you don't specify any custom server selection logic, see Server Selection Algorithm in the MongoDB Server manual.\n\n## Specifying Other Server Selection Algorithms\n\nYou can specify different server selection logic by passing an instance of a server selector class to the `PreServerSelector` or `PostServerSelector` property of the `ClusterConfigurator`. The `PreServerSelector` property specifies a server selector that runs before the standard server selection logic runs, while the `PostServerSelector` property specifies a server selector that runs after standard server selection logic runs. You can then pass your `ClusterConfigurator` instance to the `MongoClientSettings` object when you create a `MongoClient` instance to apply your custom server selection logic.\n\nThe following table lists the different types of server selectors you can pass to the `ClusterConfigurator` property:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nServer Selector\n\n\nDescription\n\n
\n`CompositeServerSelector`\n\n\nSelects servers based on multiple partial selectors\n\n
\n`DelegateServerSelector`\n\n\nWraps a delegate server selector\n\n
\n`EndPointServerSelector`\n\n\nSelects servers based on their endpoint\n\n
\n`LatencyLimitingServerSelector`\n\n\nSelects servers within an acceptable latency range\n\n
\n`PriorityServerSelector`\n\n\nSelects a server based on a collection of servers to deprioritize\n\n
\n`RandomServerSelector`\n\n\nSelects a random server\n\n
\n`ReadPreferenceServerSelector`\n\n\nSelects servers based on a specified read preference\n\n
The following example instructs a `MongoClient` to use the `RandomServerSelector` class to select a server at random before the standard server selection logic runs:\n\n```csharp\nvar settings = MongoClientSettings.FromConnectionString(\"\");\nvar clusterConfigurator = builder =>\n{\n builder.ConfigureCluster(c =>\n c.With(PreServerSelector: new RandomServerSelector()));\n};\n\nsettings.ClusterConfigurator = clusterConfigurator;\nvar client = new MongoClient(settings);\n```\n\nTo learn more about the different server selector classes, see the ServerSelectors API documentation.\n\n## Implementing Custom Server Selection Logic\n\nYou can implement your own custom server selection logic by creating a class that inherits from the `IServerSelector` interface and overrides the `SelectServers()` method. The following example shows a simple custom server selection class that selects servers with a `ServerType` of `ServerType.ReplicaSetSecondary`:\n\n```csharp\npublic class CustomServerSelector : IServerSelector\n{\n public IEnumerable SelectServers(ClusterDescription cluster,\n IEnumerable servers)\n {\n return servers.Where(server => server.Type == ServerType.ReplicaSetSecondary);\n }\n}\n```\n\nYou can then pass an instance of this class to the `PreServerSelector` or `PostServerSelector` property of a `ClusterConfigurator` instance, as shown in the Specifying Other Server Selection Algorithms section."} -{"chunk_id": "68a95beb5e79d242619d86cb-1", "page_id": "68a95beb5e79d242619d86cb", "source_name": "csharp", "product_name": "C# Driver", "url": "https://mongodb.com/docs/drivers/csharp/current/connect/connection-options/server-selection", "title": "Customize Server Selection", "text": "## Using Settings to Configure Server Selection\n\nYou can specify the following server selection settings in your `MongoClient` object or in your connection URI:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nSetting\n\n\nDescription\n\n
\n`LocalThreshold`\n\n\nThe latency window for server eligibility. If a server's round trip takes longerthan the fastest server's round-trip time plus this value, the server isn'teligible for selection.**Data Type**: `TimeSpan`**Default**: 15 milliseconds**Connection URI Example**: `localThresholdMS=0`\n\n
\n`ReadPreference`\n\n\nThe client's default read-preference settings. `MaxStaleness` represents thelongest replication lag (in real time) that a secondary can experience andstill be eligible for server selection. Specifying `-1` means no maximum.See read preference for more information.**Data Type**: ReadPreference**Default**: `ReadPreference.Primary`**Connection URI Example**:```none\nreadPreference=primaryPreferred\n&maxStalenessSeconds=90\n&readPreferenceTags=dc:ny,rack:1\n```\n\n
\n`ServerSelectionTimeout`\n\n\nThe length of time the driver tries to select a server before timing out.**Data Type**: `TimeSpan`**Default**: 30 seconds**Connection URI Example**: `serverSelectionTimeoutMS=15000`\n\n
\n\n## Troubleshooting\n\n### Driver Throws a Timeout During Server Selection\n\nEach driver operation requires that you choose a server that satisfies the server selection criteria. If you do not select an appropriate server within the server selection timeout, the driver throws a server selection timeout exception. The exception looks similar to the following:\n\n```none\nA timeout occurred after 30000ms selecting a server using CompositeServerSelector{ Selectors = MongoDB.Driver.MongoClient+AreSessionsSupportedServerSelector, LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000 }, OperationsCountServerSelector }.\nClient view of cluster state is\n{\n ClusterId : \"1\",\n Type : \"Unknown\",\n State : \"Disconnected\",\n Servers :\n [{\n ServerId: \"{ ClusterId : 1, EndPoint : \"Unspecified/localhost:27017\" }\",\n EndPoint: \"Unspecified/localhost:27017\",\n ReasonChanged: \"Heartbeat\",\n State: \"Disconnected\",\n ServerVersion: ,\n TopologyVersion: ,\n Type: \"Unknown\",\n HeartbeatException: \"\"\n }]\n}.\n```\n\nThe error message consists of multiple parts:\n\n1. The server selection timeout (30000 ms).\n\n2. The server selectors considered (`CompositeServerSelector` containing `AreSessionsSupportedServerSelector`, `LatencyLimitingServerSelector`, and `OperationsCountServerSelector`).\n\n3. The driver\u2019s current view of the cluster topology. The list of servers that the driver is aware of is a key part of this view. Each server description contains an exhaustive description of its current state including information about an endpoint, a server version, a server type, and its current health state. If the server encounters issues in reporting its health, `HeartbeatException` contains the exception from the last failed heartbeat. Analyzing the `HeartbeatException` on each cluster node can assist in diagnosing most server selection issues. The following heartbeat exceptions are common:\n\n - `No connection could be made because the target machine actively refused it`: The driver cannot see this cluster node. This might be because the cluster node has crashed, a firewall is preventing network traffic from reaching the cluster node or port, or some other network error is preventing traffic from being successfully routed to the cluster node.\n\n - `Attempted to read past the end of the stream`: This error happens when the driver cannot connect to the cluster nodes due to a network error, misconfigured firewall, or other network issue. To address this exception, ensure that all cluster nodes are reachable. This error commonly occurs when the client machine\u2019s IP address is not configured in the Atlas IPs Access List, which you can find under the Network Access tab for your Atlas Project.\n\n - `The remote certificate is invalid according to the validation procedure`: This error typically indicates a TLS/SSL-related problem such as an expired/invalid certificate or an untrusted root CA. You can use tools like `openssl s_client` to debug TLS/SSL-related certificate problems.\n\n## API Documentation\n\nTo learn more about the classes and methods used in this guide, see the following API documentation:\n\n- MongoClient\n\n- MongoClientSettings\n\n- ClusterConfigurator\n\n- ServerSelectors\n\n- IServerSelector\n\n- SelectServer()"} -{"chunk_id": "68a95beb5e79d242619d86f8-0", "page_id": "68a95beb5e79d242619d86f8", "source_name": "csharp", "product_name": "C# Driver", "url": "https://mongodb.com/docs/drivers/csharp/current/crud/restful-api-tutorial", "title": "Create a RESTful API", "text": "# Create a RESTful API\n\n## Overview\n\nIn this tutorial, you can learn how to create a RESTful API with endpoints that perform basic create, read, update, and delete (CRUD) operations across collections in a MongoDB Atlas cluster.\n\n## Prerequisites\n\nBefore you start this tutorial, perform the following actions:\n\n- Set up a MongoDB Atlas account and deploy and configure a cluster that is M0 or higher. To view instructions, see the MongoDB Get Started guide.\n\n- Install .NET 6.0 or later on your machine. To install .NET, visit the Microsoft .NET download page.\n\nThis tutorial uses .NET Core 8.0, but you can use any version later than .NET 6.0.\n\n## Set Up Your Project\n\nRun the following commands in your terminal to create a new .NET Core project that uses a web application template:\n\n```bash\ndotnet new webapi -o MongoExample\ncd MongoExample\n```\n\nTo add the .NET/C# Driver to your project as a dependency, run the following command:\n\n```bash\ndotnet add package MongoDB.Driver\n```\n\nThe preceding commands create a new web application project for .NET Core named `MongoExample` and install the latest .NET/C# Driver. The template project includes some boilerplate files that you modify to implement a RESTful API.\n\n## Design a Document Model and Database Service\n\nIn this section, you can create and configure your MongoDB service and define the data model for your RESTful API.\n\nCreate a MongoDB Service\n\n### Create the MongoDBSettings class\n\nYour MongoDB service is responsible for establishing a connection and directly working with documents within MongoDB. In your project, create a folder named `Models`. In the `Models` folder, create a new file named `MongoDBSettings.cs`. In this file, add the following code:\n\n```csharp\nnamespace MongoExample.Models;\n\npublic class MongoDBSettings {\n\n public string ConnectionURI { get; set; } = null!;\n public string DatabaseName { get; set; } = null!;\n public string CollectionName { get; set; } = null!;\n\n}\n```\n\nThe preceding code defines a class named `MongoDBSettings` that contains information about your connection, the database name, and the collection name.\n\n### Update the appsettings.json file\n\nYou can find the data that is stored in the class fields defined in the `MongoDBSettings` class in the projects' `appsettings.json` file. Open this file and add the following configuration:\n\n```json\n{\n \"Logging\": {\n \"LogLevel\": {\n \"Default\": \"Information\",\n \"Microsoft.AspNetCore\": \"Warning\"\n }\n },\n \"AllowedHosts\": \"*\",\n \"MongoDB\": {\n \"ConnectionURI\": \"\",\n \"DatabaseName\": \"sample_mflix\",\n \"CollectionName\": \"playlist\"\n }\n}\n```\n\nThis tutorial uses the `sample_mflix` database and the `playlist` collection. Replace the `` placeholder with your MongoDB Atlas connection string. For more information on how to find your connection string, see the Connect to Your Cluster tutorial in the Atlas documentation.\n\n### Create the service\n\nIn your project, create a folder named `Services`. In the `Services` folder, create a new file named `MongoDBService.cs` and add the following code:\n\n```csharp\nusing MongoExample.Models;\nusing Microsoft.Extensions.Options;\nusing MongoDB.Driver;\nusing MongoDB.Bson;\n\nnamespace MongoExample.Services;\n\npublic class MongoDBService {\n\n private readonly IMongoCollection _playlistCollection;\n\n public MongoDBService(IOptions mongoDBSettings) {\n MongoClient client = new MongoClient(mongoDBSettings.Value.ConnectionURI);\n IMongoDatabase database = client.GetDatabase(mongoDBSettings.Value.DatabaseName);\n _playlistCollection = database.GetCollection(mongoDBSettings.Value.CollectionName);\n }\n\n public async Task> GetAsync() { }\n public async Task CreateAsync(Playlist playlist) { }\n public async Task AddToPlaylistAsync(string id, string movieId) {}\n public async Task DeleteAsync(string id) { }\n\n}\n```\n\nThe preceding code defines a class named `MongoDBService` that includes empty asynchronous functions. Throughout this tutorial, you add code to these functions as you create your endpoints. The settings you configured in the `appsettings.json` file are set to variables.\n\n### Connect the service to the application\n\nOpen the `Program.cs` file and add the following code to the top of the file:\n\n```csharp\nusing MongoExample.Models;\nusing MongoExample.Services;\n\nvar builder = WebApplication.CreateBuilder(args);\n\nbuilder.Services.Configure(builder.Configuration.GetSection(\"MongoDB\"));\nbuilder.Services.AddSingleton();\n```\n\nIn the preceding code, the `GetSection()` function pulls your settings from the `MongoDB` field in the `appsettings.json` file.\n\nIf the template code already has the `builder` variable, don't add it twice.\n\n### Create the document model\n\nNow that the service is set up, you can create a data model for your collection.\n\nIn the `Models` folder, create a new file named `Playlist.cs` and add the following code:\n\n```csharp\nusing MongoDB.Bson;\nusing MongoDB.Bson.Serialization.Attributes;\nusing System.Text.Json.Serialization;\n\nnamespace MongoExample.Models;\n\npublic class Playlist {\n\n [BsonId]\n [BsonRepresentation(BsonType.ObjectId)]\n public string? Id { get; set; }\n\n public string username { get; set; } = null!;\n\n [BsonElement(\"items\")]\n [JsonPropertyName(\"items\")]\n public List movieIds { get; set; } = null!;\n\n}\n```\n\nIn the preceding code, the `Id` field is serialized as an `ObjectId` in the `_id` field. The field is represented as a string in your application.\n\nThe `movieIds` field is serialized as `items`. When you send or receive JSON values, the field is also named `items` instead of `movieIds`.\n\nIf you plan to have your local class field match the document field directly, it isn't necessary to define custom mappings. For example, the `username` field in the preceding code has no custom mappings. It is called be `username` in C#, in JSON, and in MongoDB.\n\nAfter this step, you have a MongoDB service and document model for your collection to work with .NET Core.\n\n## Build CRUD Endpoints\n\nTo create the CRUD endpoints for this application, you must update two different files within the project. In this section, you can learn how to define the endpoint within a controller and update the corresponding work within the service.\n\nIn this example project, there is no data validation for the HTTP requests.\n\nBuild endpoints to interact with MongoDB\n\n### Create a controller\n\nIn your project, create a folder named `Controllers`. In the `Controllers` folder, create a new file named `PlaylistController.cs` and add the following code:\n\n```csharp\nusing System;\nusing Microsoft.AspNetCore.Mvc;\nusing MongoExample.Services;\nusing MongoExample.Models;\n\nnamespace MongoExample.Controllers;\n\n[Controller]\n[Route(\"api/[controller]\")]\npublic class PlaylistController: Controller {\n\n private readonly MongoDBService _mongoDBService;\n\n public PlaylistController(MongoDBService mongoDBService) {\n _mongoDBService = mongoDBService;\n }\n\n [HttpGet]\n public async Task> Get() {}\n\n [HttpPost]\n public async Task Post([FromBody] Playlist playlist) {}\n\n [HttpPut(\"{id}\")]\n public async Task AddToPlaylist(string id, [FromBody] string movieId) {}\n\n [HttpDelete(\"{id}\")]\n public async Task Delete(string id) {}\n\n}\n```\n\nThe `PlaylistController` class contains a constructor method that gains access to your singleton service class. Then, there is a series of endpoints for this controller."} -{"chunk_id": "68a95beb5e79d242619d86f8-1", "page_id": "68a95beb5e79d242619d86f8", "source_name": "csharp", "product_name": "C# Driver", "url": "https://mongodb.com/docs/drivers/csharp/current/crud/restful-api-tutorial", "title": "Create a RESTful API", "text": "### Add data through the POST endpoint\n\nGo to `Services/MongoDBService.cs` and update the `CreateAsync` function to use the following code:\n\n```csharp\npublic async Task CreateAsync(Playlist playlist) {\n await _playlistCollection.InsertOneAsync(playlist);\n return;\n}\n```\n\nThe preceding code sets the `_playlistCollection` in the constructor method of the service. This lets your application use the `InsertOneAsync` method, which takes a passed `Playlist` variable and inserts it.\n\nTo complete the creation of the `POST` endpoint, go to the `Controllers/PlaylistController.cs` file and update the `Post` method to use the following code:\n\n```csharp\n[HttpPost]\npublic async Task Post([FromBody] Playlist playlist) {\n await _mongoDBService.CreateAsync(playlist);\n return CreatedAtAction(nameof(Get), new { id = playlist.Id }, playlist);\n}\n```\n\nWhen the `POST` endpoint executes, the application takes the `Playlist` object from the `request`, which .NET Core parses, and passes it to the `CreateAsync` function in the service. After the insert, the code returns information about the interaction.\n\n### Read data through the GET endpoint\n\nGo to `Services/MongoDBService.cs` and update the `GetAsync` function to use the following code:\n\n```csharp\npublic async Task> GetAsync() {\n return await _playlistCollection.Find(new BsonDocument()).ToListAsync();\n}\n```\n\nThe `Find` operation in the preceding code returns all documents that exist in the collection.\n\nTo complete the creation of the `GET` endpoint, go to the `Controllers/PlaylistController.cs` file and update the `Get` method to use the following code:\n\n```csharp\n[HttpGet]\npublic async Task> Get() {\n return await _mongoDBService.GetAsync();\n}\n```\n\n### Update data using the PUT endpoint\n\nGo to `Services/MongoDBService.cs` and update the `AddToPlaylistAsync` function to use the following code:\n\n```csharp\npublic async Task AddToPlaylistAsync(string id, string movieId) {\n FilterDefinition filter = Builders.Filter.Eq(\"Id\", id);\n UpdateDefinition update = Builders.Update.AddToSet(\"movieIds\", movieId);\n await _playlistCollection.UpdateOneAsync(filter, update);\n return;\n}\n```\n\nThe preceding code sets up a match filter to determine which document or documents receive an update, in this case adding an item to your playlist. The code matches based on the `Id` field, which is unique. Then, the code defines the update criteria, which is an `AddtoSet` operation that only adds an item to the array if it doesn't already exist in the array.\n\nThe `UpdateOneAsync` methods only updates on document even if the match filter returns more than one match.\n\nTo complete the creation of the PUT endpoint, go to the `Controllers/PlaylistController.cs` file and update the `AddToPlaylist` function to use the following code:\n\n```csharp\n[HttpPut(\"{id}\")]\npublic async Task AddToPlaylist(string id, [FromBody] string movieId) {\n await _mongoDBService.AddToPlaylistAsync(id, movieId);\n return NoContent();\n}\n```\n\n### Delete data by using the DELETE endpoint\n\nGo to `Services/MongoDBService.cs` and update the `DeleteAsync` function to use the following code:\n\n```csharp\npublic async Task DeleteAsync(string id) {\n FilterDefinition filter = Builders.Filter.Eq(\"Id\", id);\n await _playlistCollection.DeleteOneAsync(filter);\n return;\n}\n```\n\nThe preceding code deletes a single document based on the filter criteria, which matches the unique value of the `Id` field.\n\nTo complete the creation of the DELETE endpoint, go to the `Controllers/PlaylistController.cs` file and update the `Delete` function to use the following code:\n\n```csharp\n[HttpDelete(\"{id}\")]\npublic async Task Delete(string id) {\n await _mongoDBService.DeleteAsync(id);\n return NoContent();\n}\n```\n\nAfter this step, you have a complete set of CRUD endpoints for your RESTful API.\n\n## Test Your API Endpoints\n\nWith the endpoints created, you can test them using the Swagger UI that is included with the template .NET Core application. To do this, go to the `Program.cs` file and remove any code from the template project related to the `WeatherForecast` class. Update the file to include the following code:\n\n```csharp\n// Adds services to the container to configure Swagger/OpenAPI\nbuilder.Services.AddEndpointsApiExplorer();\nbuilder.Services.AddSwaggerGen();\n\nvar app = builder.Build();\n\n// Configures the HTTP request pipeline\nif (app.Environment.IsDevelopment())\n{\n app.UseSwagger();\n app.UseSwaggerUI();\n}\n\napp.UseHttpsRedirection();\n\n// Maps the endpoints for the API\napp.MapGet(\"/api/playlists\", async (MongoDBService mongoDBService) =>\n{\n var playlists = await mongoDBService.GetAsync();\n return playlists;\n})\n.WithName(\"GetPlaylists\")\n.WithOpenApi();\n\napp.MapPost(\"/api/playlists\", async (MongoDBService mongoDBService, Playlist newPlaylist) =>\n{\n await mongoDBService.CreateAsync(newPlaylist);\n return Results.Created($\"/playlists/{newPlaylist.Id}\", newPlaylist);\n})\n.WithName(\"CreatePlaylist\")\n.WithOpenApi();\n\napp.MapPut(\"/api/playlists/{id}\", async (MongoDBService mongoDBService, string id, string movieId) =>\n{\n await mongoDBService.AddToPlaylistAsync(id, movieId);\n return Results.NoContent();\n})\n.WithName(\"AddMovieToPlaylist\")\n.WithOpenApi();\n\napp.MapDelete(\"/playlists/{id}\", async (MongoDBService mongoDBService, string id) =>\n{\n await mongoDBService.DeleteAsync(id);\n return Results.NoContent();\n})\n.WithName(\"DeletePlaylist\")\n.WithOpenApi();\n\napp.Run();\n```\n\nYou can replace any repetitive code from the project template with the preceding code.\n\nExecute the following command to run your application:\n\n```bash\ndotnet run\n```\n\nAfter the application starts, open your browser and go to your configured localhost URL to access the Swagger UI, for example `http://localhost:5000/swagger`. The following image shows how the Swagger UI appears:\n\nThe Swagger UI for the RESTful API.\n\nYou can test the application by clicking the Try it out button on each endpoint. To get started, go to the `/api/playlists` `POST` endpoint to add some data to the database. Add the following sample data:\n\n```json\n{\n \"username\": \"testuser\",\n \"items\": [\n \"1234\",\n \"5678\"\n ]\n}\n```\n\nRun this request to insert data into the database. You can then go to the `GET` endpoint to see the data you just inserted. You can also test the `PUT` and `DELETE` endpoints to update and delete data.\n\n## Next Steps\n\nTo learn more about the operations discussed in this tutorial, see the following guides:\n\n- Insert Documents\n\n- Retrieve Data\n\n- Update One\n\n- Delete Documents"} -{"chunk_id": "68a95beb5e79d242619d8735-0", "page_id": "68a95beb5e79d242619d8735", "source_name": "csharp", "product_name": "C# Driver", "url": "https://mongodb.com/docs/drivers/csharp/current/integrations/odata", "title": "Use OData with MongoDB", "text": "# Use OData with MongoDB\n\n## Overview\n\nOData (Open Data Protocol) is a standardized protocol for building and consuming RESTful APIs that allows for the querying and manipulation of data by using HTTP requests. It provides a uniform way to expose and interact with data from multiple sources.\n\nIn this tutorial, you will learn how to integrate OData with your MongoDB application.\n\n### Sample Data\n\nThis tutorial uses the `sample_restaurants.restaurants` collection from the Atlas sample datasets. To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the Get Started with the .NET/C# Driver.\n\n## Tutorial\n\n### Install Dependencies\n\nCreate a new ASP.Net application named `ODataExample` and install the .NET/C# Driver. You can install the driver by using the NuGet package manager in your IDE, or by running the following command in the .NET CLI:\n\n```shell\ndotnet add package MongoDB.Driver\n```\n\nThen, install the `MongoDB.AspNetCore.OData` NuGet package through the NuGet Package Manager or through the .NET CLI by running the following command:\n\n```shell\ndotnet add package MongoDB.AspNetCore.OData\n```\n\n### Define your Models\n\nCreate a new folder in your solution called `Models` and copy the following `Restaurant.cs`, `Address.cs`, and `GradeEntry.cs` files into the folder:\n\n```csharp\npublic class Restaurant\n{\n [BsonRepresentation(BsonType.ObjectId)]\n public string Id { get; set; }\n\n public string Name { get; set; }\n\n [BsonElement(\"restaurant_id\")]\n public string RestaurantId { get; set; }\n\n public string Cuisine { get; set; }\n\n public Address Address { get; set; }\n\n public string Borough { get; set; }\n\n public List Grades { get; set; }\n}\n```\n\n```csharp\npublic class Address\n{\n public string Building { get; set; }\n\n [BsonElement(\"coord\")]\n public double[] Coordinates { get; set; }\n\n public string Street { get; set; }\n\n [BsonElement(\"zipcode\")]\n public string ZipCode { get; set; }\n}\n```\n\n```csharp\npublic class GradeEntry\n{\n public DateTime Date { get; set; }\n\n public string Grade { get; set; }\n\n public float? Score { get; set; }\n}\n```\n\nThe documents in the `restaurants` collection use the snake-case naming convention. The examples in this guide use a `ConventionPack` to deserialize the fields in the collection into Pascal case and map them to the properties in the `Restaurant` class.\n\nTo learn more about custom serialization, see Custom Serialization.\n\n### Create an OData Controller\n\nCreate a new folder in your solution called `Controllers` and add a new controller file called `RestaurantsController.cs`. Copy the following code into the file:\n\n```csharp\nusing Microsoft.AspNetCore.Mvc;\nusing Microsoft.AspNetCore.OData.Routing.Controllers;\nusing MongoDB.AspNetCore.OData;\nusing MongoDB.Driver;\nusing ODataTest.Models;\n\nnamespace ODataTest.Controllers;\n\npublic class RestaurantsController : ODataController\n{\n private readonly IQueryable _restaurants;\n\n public RestaurantsController(IMongoClient client)\n {\n var database = client.GetDatabase(\"sample_restaurants\");\n _restaurants = database.GetCollection(\"restaurants\")\n .AsQueryable();\n }\n\n // Registers Get endpoint and sets max documents to 5\n [MongoEnableQuery(PageSize = 5)]\n public ActionResult> Get()\n {\n return Ok(_restaurants);\n }\n}\n```\n\nThis code performs the following actions:\n\n- Creates a constructor that connects to MongoDB, and gets the `restaurants` collection.\n\n- Creates a `Get` endpoint that returns all restaurants in the collection.\n\n- Specifies the `MongoEnableQuery` attribute to enable querying on the `Get` endpoint.\n\n- Specifies the `PageSize` attribute on `MongoEnableQuery` to limit the number of documents returned to `5`.\n\n### Configure the OData Service\n\nPaste the following code into your `Program.cs` file to configure the OData service and map your controller endpoints.\n\n```csharp\nusing Microsoft.AspNetCore.OData;\nusing Microsoft.OData.ModelBuilder;\nusing MongoDB.Bson.Serialization.Conventions;\nusing MongoDB.Driver;\nusing ODataTest.Models;\n\nvar builder = WebApplication.CreateBuilder(args);\n\n// Registers a convention pack to convert fields to camel case\nvar camelCaseConvention = new ConventionPack {\n new CamelCaseElementNameConvention()\n };\nConventionRegistry.Register(\n \"CamelCase\", camelCaseConvention, type => true);\n\nbuilder.Services.AddSingleton(\n new MongoClient(\"\"));\n\n// Registers the Restaurants entity and sets the Id field as the key\nvar modelBuilder = new ODataConventionModelBuilder();\nmodelBuilder.EntitySet(\"Restaurants\");\nmodelBuilder.EntityType().HasKey(r => r.Id);\n\n// Adds OData and specify query capabilities\nbuilder.Services.AddControllers().AddOData(\n options => options.Select()\n .AddRouteComponents(\"odata\", modelBuilder.GetEdmModel())\n);\n\nvar app = builder.Build();\napp.UseRouting();\napp.MapControllers();\n\napp.Run();\n```\n\nReplace the `<\"Your connection URI\">` placeholder with your MongoDB connection string.\n\nThis code performs the following actions:\n\n- Instantiates a new `MongoClient` and registers it as a singleton in the dependency injection container.\n\n- Defines the Entity Data Model (EDM) and registers `Restaurants` as an entity set with the key `Id`.\n\n- Adds the OData service and enables the `Select()` query operation.\n\n- Registers the route by using the `AddRouteComponents()` method.\n\n- Calls the `UseRouting()` and `MapControllers()` methods to match incoming HTTP requests and route them to the appropriate endpoint.\n\nThe .NET/C# Driver does not support OData-Aggregation with the `$apply` query operation.\n\n### Run the Application\n\nRun the application by using your IDE, or by running the following command in your shell at the root directory of your project:\n\n```shell\ndotnet run ODataExample.csproj\n```\n\nAfter running the application, your terminal displays output similar to the following:\n\n```none\ninfo: Microsoft.Hosting.Lifetime[14]\n Now listening on: http://localhost:5183\ninfo: Microsoft.Hosting.Lifetime[0]\n Application started. Press Ctrl+C to shut down.\ninfo: Microsoft.Hosting.Lifetime[0]\n Hosting environment: Development\ninfo: Microsoft.Hosting.Lifetime[0]\n Content root path: \n```\n\nAfter running your application, your IDE might automatically open a browser window to the URL where the application is running, which displays a `\"page can't be found\"` error. This is expected because the application only has a single `Get` endpoint configured.\n\n### Query the Data\n\nTo query the data, navigate to the `Get` endpoint specified in the application. To do so, open a browser and navigate to the `localhost` URL specified in the terminal output from the preceding step. Then, append the route for the `Get` endpoint: `/odata/Restaurants`. For example, if an application is running at `localhost:5183`, navigate to `http://localhost:5183/odata/Restaurants`.\n\nIf successful, the browser displays 5 restaurants in the collection, in JSON format. The output is similar to the following:\n\n```json\n{\n \"@odata.context\": \"http://localhost:5183/odata/$metadata#Restaurants\",\n \"value\": [\n {\n \"Name\": \"Glorious Food\",\n \"RestaurantId\": \"40361521\",\n \"Cuisine\": \"American\",\n \"Borough\": \"Manhattan\",\n \"Id\": \"...\",\n \"Address\": {\n \"Building\": \"522\",\n \"Coordinates\": [-73.95171, 40.767461],\n \"Street\": \"East 74 Street\",\n \"ZipCode\": \"10021\"\n },\n \"Grades\": [\n ...\n ]\n },\n\n ...\n\n ]\n}\n```\n\n## Additional Information\n\nTo learn more about ASP.NET Core OData, see the Microsoft OData documentation.\n\nTo learn more about OData, see the OData documentation."} -{"chunk_id": "68a95beb5e79d242619d8774-0", "page_id": "68a95beb5e79d242619d8774", "source_name": "csharp", "product_name": "C# Driver", "url": "https://mongodb.com/docs/drivers/csharp/current/serialization/polymorphic-objects", "title": "Polymorphic Objects", "text": "# Polymorphic Objects\n\n## Overview\n\n**Polymorphic** objects inherit properties and methods from one or more parent classes. These objects require special mapping to ensure that the .NET/C# Driver correctly serializes them to and from BSON documents.\n\nThis guide explains the following:\n\n- How to deserialize polymorphic types\n\n- The discriminator conventions included with the .NET/C# Driver\n\n- How to create custom discriminator conventions\n\nThe examples on this page use the following inheritance hierarchy:\n\n```csharp\npublic class Animal\n{\n}\n\npublic class Cat : Animal\n{\n}\n\npublic class Dog : Animal\n{\n}\n\npublic class Lion : Cat\n{\n}\n\npublic class Tiger : Cat\n{\n}\n```\n\n## Deserialize Polymorphic Objects\n\nBefore the serializer can deserialize any polymorphic objects, you must document the relationship of all classes in the inheritance hierarchy.\n\nIf you're using the automapper to map your classes, apply the `[BsonKnownTypes]` attribute to each base class in the hierarchy. Pass each class that directly inherits from the base class as an argument.\n\nThe following example shows how to apply the `[BsonKnownTypes]` attribute to classes in the example `Animal` hierarchy:\n\n```csharp\n[BsonKnownTypes(typeof(Cat), typeof(Dog))]\npublic class Animal\n{\n}\n\n[BsonKnownTypes(typeof(Lion), typeof(Tiger))]\npublic class Cat : Animal\n{\n}\n\npublic class Dog : Animal\n{\n}\n\npublic class Lion : Cat\n{\n}\n\npublic class Tiger : Cat\n{\n}\n```\n\nApply the `[BsonKnownTypes]` attribute only to parent classes. Pass as arguments only the types that *directly* inherit from the class, not all child classes in the hierarchy.\n\nIf you're creating a class map manually, call the `BsonClassMap.RegisterClassMap()` method for every class in the hierarchy, as shown in the following example:\n\n```csharp\nBsonClassMap.RegisterClassMap();\nBsonClassMap.RegisterClassMap();\nBsonClassMap.RegisterClassMap();\nBsonClassMap.RegisterClassMap();\nBsonClassMap.RegisterClassMap();\n```\n\nTo learn more about mapping classes, see the Customize Class Mapping documentation.\n\n## Use Discriminators\n\nIn MongoDB, a **discriminator** is a field added to a document to identify the class to which the document deserializes. When a collection contains more than one type from a single inheritance hierarchy, discriminators ensure that each document deserializes to the right class. The .NET/C# Driver stores the discriminator value in a field named `_t` in the BSON document. Generally, `_t` is the second field in the BSON document after `_id`.\n\n**Discriminator conventions** define the value stored in the discriminator field. In this section, you can learn about the discriminator conventions included with the .NET/C# Driver and how to create custom discriminator conventions.\n\n### ScalarDiscriminatorConvention\n\nBy default, the .NET/C# Driver uses the `ScalarDiscriminatorConvention`. According to this convention, the .NET/C# Driver sets the value of the `_t` field to the name of the class from which the document was serialized.\n\nSuppose you create an instance of the example `Animal` class and each of its subclasses. If you serialize these objects to a single collection, the .NET/C# Driver applies the `ScalarDiscriminatorConvention` and the corresponding BSON documents appear as follows:\n\n```json\n{ _id: ..., _t: \"Animal\", ... }\n{ _id: ..., _t: \"Cat\", ... }\n{ _id: ..., _t: \"Dog\", ... }\n{ _id: ..., _t: \"Lion\", ... }\n{ _id: ..., _t: \"Tiger\", ... }\n```\n\nThe `ScalarDiscriminatorConvention` uses concise discriminator values, but can be difficult to run a query on. For example, to find all documents of type or subtype `Cat`, you must explicitly list each class you're looking for:\n\n```csharp\nvar query = coll.AsQueryable().Where(\n item => item.GetType() == typeof(Cat) ||\n item.GetType() == typeof(Lion) ||\n item.GetType() == typeof(Tiger));\n```\n\n### HierarchicalDiscriminatorConvention\n\nTo simplify queries against your collection of polymorphic types, you can use the `HierarchicalDiscriminatorConvention`. According to this convention, the value of `_t` is an array of all classes in the inheritance hierarchy of the document's type.\n\nTo use the `HierarchicalDiscriminatorConvention`, label the base class of your inheritance hierarchy as the root class. If you're using the automapper, label the root class by applying the `[BsonDiscriminatorAttribute]` attribute to the class and passing `RootClass = true` as an argument.\n\nYou must specify hierarchical discriminators in root-to-leaf order. If the order is inverted, the .NET/C# Driver cannot resolve the correct concrete type.\n\nThe following code example labels the `Animal` class as the root of the example inheritance hierarchy:\n\n```csharp\n[BsonDiscriminator(RootClass = true)]\n[BsonKnownTypes(typeof(Cat), typeof(Dog)]\npublic class Animal\n{\n}\n```\n\nIf you're creating a class map manually, call the `SetIsRootClass()` method and pass `true` as an argument when you register the class map for the root class. The following code example registers class maps for all five example classes but labels only the `Animal` class as the root of the inheritance hierarchy:\n\n```csharp\nBsonClassMap.RegisterClassMap(classMap => {\n classMap.AutoMap();\n classMap.SetIsRootClass(true);\n});\nBsonClassMap.RegisterClassMap();\nBsonClassMap.RegisterClassMap();\nBsonClassMap.RegisterClassMap();\nBsonClassMap.RegisterClassMap();\n```\n\nSuppose you label the example `Animal` class as the root of the inheritance hierarchy, and then create an instance of the `Animal` class and each of its subclasses. If you serialize these objects to a single collection, the .NET/C# Driver applies the `HierarchicalDiscriminatorConvention` and the corresponding BSON documents appear as follows:\n\n```javascript\n{ _id: ..., _t: \"Animal\", ... }\n{ _id: ..., _t: [\"Animal\", \"Cat\"], ... }\n{ _id: ..., _t: [\"Animal\", \"Dog\"], ... }\n{ _id: ..., _t: [\"Animal\", \"Cat\", \"Lion\"], ... }\n{ _id: ..., _t: [\"Animal\", \"Cat\", \"Tiger\"], ... }\n```\n\nAny document mapped to the root class still uses a string value for the discriminator field.\n\nWhen using the `HierarchicalDiscriminatorConvention`, you can search for all documents of type or subtype `Cat` by using a single boolean condition, as shown in the following example:\n\n```csharp\nvar query = coll.Aggregate().Match(a => a is Cat);\n```\n\n### Custom Discriminator Conventions\n\nIf you're working with data that doesn't follow the conventions used by the .NET/C# Driver--for example, data inserted into MongoDB by another driver or object mapper--you might need to use a different value for your discriminator field to ensure your classes align with those conventions.\n\nIf you're using the automapper, you can specify a custom value for a class's discriminator field by applying the `[BsonDiscriminator]` attribute to the class and passing the custom discriminator value as a string argument. The following code example sets the value of the discriminator field for the `Animal` class to \"myAnimalClass\":\n\n```csharp\n[BsonDiscriminator(\"myAnimalClass\")]\npublic class Animal\n{\n}\n```\n\nIf you're creating a class map manually, call the `SetDiscriminator()` method and pass the custom discriminator value as an argument when you register the class map. The following code example sets the value of the discriminator field for the `Animal` class to \"myAnimalClass\":\n\n```csharp\nBsonClassMap.RegisterClassMap(classMap =>\n{\n classMap.AutoMap();\n classMap.SetDiscriminator(\"myAnimalClass\");\n});\n```\n\nAn instance of the previous `Animal` class appears as follows after serialization:\n\n```json\n{ \"_id\": \"...\", \"_t\": \"myAnimalClass\"}\n```"} -{"chunk_id": "68a95beb5e79d242619d8767-0", "page_id": "68a95beb5e79d242619d8767", "source_name": "csharp", "product_name": "C# Driver", "url": "https://mongodb.com/docs/drivers/csharp/current/serialization/class-mapping", "title": "Customize Class Mapping", "text": "# Customize Class Mapping\n\n## Overview\n\nIn this guide, you can learn how to customize the way the MongoDB .NET/C# Driver maps BSON documents to and from C# classes. Read this page to learn more about the default class mapping behavior, or if you must customize the way the driver serializes or deserializes your data.\n\nYou can also use POCO attributes to set serialization behavior. To learn more, see the POCOs guide.\n\n## Automatic Class Mapping\n\nWhen you use a class, rather than a `BsonDocument`, to represent data in a MongoDB collection, the .NET/C# Driver automatically creates a **class map** that it uses to serialize or deserialize your data. It does this mapping by matching the name of the field in the document to the name of the property in the class.\n\nMatch the type of the property in your class to the type of the field in the document. The .NET/C# Driver instantiates a serializer based on the type of the property in your class. If the types don't match when the driver attempts to deserialize the data, the serializer throws an exception.\n\n## Manually Creating A Class Map\n\nYou can bypass the driver's automatic class mapping functionality, and manually define the class map by using the `RegisterClassMap()` method.\n\nThe following example defines a `Person` class:\n\n```csharp\npublic class Person\n{\n public string Name { get; set; }\n public int Age { get; set; }\n public List Hobbies {get; set;}\n}\n```\n\nThe following code demonstrates how to register the class map for the `Person` class:\n\n```csharp\nBsonClassMap.RegisterClassMap(classMap =>\n{\n classMap.MapMember(p => p.Name);\n classMap.MapMember(p => p.Age);\n classMap.MapMember(p => p.Hobbies);\n});\n```\n\nYou must register a class map *before* it's needed in your code. We recommend registering class maps before initializing a connection with MongoDB.\n\nYou can also manually map a subset of class properties, while still allowing the driver to automatically map the remaining properties. To do this, register a class map and call the `AutoMap()` method before manually specifying your properties.\n\nIn the following code example, the `AutoMap()` method maps all properties of the `Person` class, then manually adjusts the mapping for the `Hobbies` field:\n\n```csharp\nBsonClassMap.RegisterClassMap(classMap =>\n{\n classMap.AutoMap();\n classMap.MapMember(p => p.Hobbies).SetElementName(\"favorite_hobbies\");\n});\n```\n\n## Customize Class Serialization\n\nYou can customize how the driver serializes and deserializes documents at the class level by applying attributes to the class or by calling methods while registering a class map.\n\n### Omit Fields\n\nYou can prevent specified fields from being serialized by using the `UnmapMember()` method when registering a class map.\n\nThe following example shows how to create a class map to prevent the `Age` property from being serialized:\n\n```csharp\nBsonClassMap.RegisterClassMap(classMap =>\n{\n classMap.AutoMap();\n classMap.UnmapMember(p => p.Age);\n});\n```\n\nTo learn about how to set this behavior by using a field attribute, see the Omit Fields section of the POCOs guide.\n\n### Ignore Extra Elements\n\nWhen a BSON document is deserialized to a C# class, the .NET/C# Driver looks at the name of each field in the document and tries to find a matching property name in the class. By default, if a field in the document doesn't have a match in the class, the driver throws an exception.\n\nYou can choose to ignore any elements that do not have a matching class property by using the `BsonIgnoreExtraElements` attribute. This prevents the driver from throwing an exception, and maps any other fields that have matching class properties.\n\nThe following example shows how to add a `BsonIgnoreExtraElements` attribute to a class.\n\n```csharp\n[BsonIgnoreExtraElements]\npublic class Person\n{\n public string Name { get; set; }\n public int Age { get; set; }\n public List Hobbies {get; set;}\n}\n```\n\nYou can also ignore any extra elements when registering a class map:\n\n```csharp\nBsonClassMap.RegisterClassMap(classMap =>\n{\n classMap.AutoMap();\n classMap.SetIgnoreExtraElements(true);\n});\n```\n\n### Identify Id Field\n\nBy default, the driver maps any public property named `Id`, `id`, or `_id` to the BSON `_id` field. To explicitly select the property to map to the `_id` field, use the `MapIdMember()` class map method.\n\nThe following code sample maps the `Identifier` property to the `_id` field:\n\n```csharp\nBsonClassMap.RegisterClassMap(classMap =>\n{\n classMap.AutoMap();\n classMap.MapIdMember(p => p.Identifier);\n});\n```\n\n#### String IDs\n\nIf you are using strings to represent your documement IDs, you can use the `IdMemberMap.SetSerializer()` class map method to serialize these values to `ObjectId` instances in MongoDB. This way, you can customize how your ID values are represented in your application while adhering to MongoDB best practices for ID management in the database.\n\nThe following example directs the driver to serialize string ID values as `ObjectId` values:\n\n```csharp\nBsonClassMap.RegisterClassMap(classMap =>\n{\n classMap.AutoMap();\n classMap.IdMemberMap.SetSerializer(new StringSerializer(BsonType.ObjectId));\n});\n```\n\nIf you want the driver to generate valid 24-digit hex strings to use as your ID values, you can chain the `SetIdGenerator()` method to the `MapIdMember()` method and pass an instance of `StringObjectIdGenerator`:\n\n```csharp\nBsonClassMap.RegisterClassMap(classMap =>\n{\n classMap.AutoMap();\n classMap.MapIdMember(p => p.Identifier).SetIdGenerator(StringObjectIdGenerator.Instance);\n});\n```\n\nTo learn more about ID generators, see the Specify an ID Generator section of the POCOs guide.\n\n#### GUID IDs\n\nIf your application uses GUIDs as unique identifiers in your documents, you can register a class map to specify how `Guid` values are serialized. By default, the driver uses the `GuidGenerator` type to generate a unique value for the ID property. You must specify the GUID representation by initializing a `GuidSerializer`.\n\nThe following code specifies the `Standard` GUID representation when registering the class map:\n\n```csharp\nBsonClassMap.RegisterClassMap(classMap =>\n{\n classMap.AutoMap();\n classMap.IdMemberMap.SetSerializer(new GuidSerializer(GuidRepresentation.Standard));\n});\n```\n\nTo learn more about serializing GUIDs, see the GUIDs guide."} -{"chunk_id": "68a95beb5e79d242619d8767-1", "page_id": "68a95beb5e79d242619d8767", "source_name": "csharp", "product_name": "C# Driver", "url": "https://mongodb.com/docs/drivers/csharp/current/serialization/class-mapping", "title": "Customize Class Mapping", "text": "## Mapping with Constructors\n\nBy default, the .NET/C# Driver automatically maps a class if the class has a no-argument constructor. This constructor can have any access modifier, including `private`. To have the driver use a constructor that accepts arguments, add the `BsonConstructor` attribute to the constructor. The driver then examines the type and maps the constructor arguments to the corresponding class properties or fields.\n\nFor the following `Person` class, the driver uses the constructor marked with the `BsonConstructor` attribute to create a class map. The `name` argument maps to the `Name` property and the `age` argument maps to the `Age` property.\n\n```csharp\npublic class Person\n{\n public string Name { get; set; }\n public int Age { get; set; }\n public List Hobbies {get; set;}\n\n [BsonConstructor]\n public Person(string name, string age)\n {\n Name = name;\n Age = age;\n }\n}\n```\n\nIf there is more than one constructor with the `BsonConstructor` attribute, the driver uses the constructor that has the most parameters with matching fields in the document.\n\nYou can also specify the constructor to use when registering your class map:\n\n```csharp\npublic class Person\n{\n public string Name { get; set; }\n public int Age { get; set; }\n public List Hobbies {get; set;}\n\n public Person(string name, string age)\n {\n Name = name;\n Age = age;\n }\n}\n\nBsonClassMap.RegisterClassMap(classMap =>\n{\n classMap.AutoMap();\n classMap.MapCreator(p => new Person(p.Name, p.Age));\n});\n```\n\n## Customize Property Serialization\n\nYou can customize how the driver serializes a class property by adding attributes to the property. For more information about custom property serialization, see Custom Serialization.\n\n### Support Extra Elements\n\nYou can design your C# class to store any extra elements in your document that don't have matching class properties. To do this your class must have a `BsonDocument` type property to hold the extra elements.\n\nThe following code uses the `BsonExtraElements` attribute with the `ExtraElements` property to direct the driver to store extra elements:\n\n```csharp\npublic class Person\n{\n public string Name { get; set;\n public int Age { get; set; }\n public List Hobbies {get; set;}\n [BsonExtraElements]\n public BsonDocument ExtraElements {get; set;}\n}\n```\n\nYou can also support extra elements when initializing a class map as follows:\n\n```csharp\nBsonClassMap.RegisterClassMap(classMap =>\n{\n classMap.AutoMap();\n classMap.MapExtraElementsMember(p => p.ExtraElements);\n});\n```\n\nAfter the driver serializes a class with extra elements back to BSON, the extra elements may not be in the same order as they were in the original document.\n\n### Dynamically Serialize Properties\n\nYou can use a method to determine whether to serialize a property. For the driver to automatically use the method when serializing, you must prefix the method name with `ShouldSerialize` followed by the name of the property that the method applies to. When the driver sees a method with this naming convention, it uses that method to determine whether to serialize properties that have the provided property name.\n\nThe following example creates a method that only serializes the `Age` property if its value is not equal to `0`. The driver does not serialize any properties whose values don't meet this requirement:\n\n```csharp\npublic class Person\n{\n public string Name { get; set; }\n public int Age { get; set; }\n public List Hobbies {get; set;}\n\n public bool ShouldSerializeAge()\n {\n return Age != 0;\n }\n}\n```\n\nYou can also specify the method while registering a class map:\n\n```csharp\nBsonClassMap.RegisterClassMap(classMap =>\n{\n classMap.AutoMap();\n classMap.MapMember(p => c.Age).SetShouldSerializeMethod(\n obj => ((Person) obj).Age != 0\n );\n});\n```\n\n## Additional Information\n\nFor more information on using C# classes, see POCOs.\n\n## API Documentation\n\n- BsonClassMap\n\n- RegisterClassMap\n\n- AutoMap"} -{"chunk_id": "68a95beb5e79d242619d86f7-0", "page_id": "68a95beb5e79d242619d86f7", "source_name": "csharp", "product_name": "C# Driver", "url": "https://mongodb.com/docs/drivers/csharp/current/crud/query/specify-documents", "title": "Specify Documents to Return", "text": "# Specify Documents to Return\n\n## Overview\n\nIn this guide, you can learn how to specify which documents to return from a read operation by chaining the following methods to the `Find()` method:\n\n- Limit(): Specifies the maximum number of documents to return from a query\n\n- Sort(): Specifies the sort order for the returned documents\n\n- Skip(): Specifies the number of documents to skip before returning query results\n\n### Sample Data\n\nThe examples in this guide use the `restaurants` collection in the `sample_restaurants` database from the Atlas sample datasets. To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the MongoDB Get Started guide.\n\nThe examples on this page use the following `Restaurant` class as a model for the documents in the collection:\n\n```csharp\n[BsonIgnoreExtraElements]\npublic class Restaurant {\n public ObjectId Id { get; set; }\n\n [BsonElement(\"name\")]\n public string Name { get; set; }\n\n [BsonElement(\"cuisine\")]\n public string Cuisine { get; set; }\n}\n```\n\n## Limit\n\nTo specify the maximum number of documents returned from a read operation, use the `Limit()` method provided by the `IFindFluent` interface. After calling the `Find()` method, chain the `Limit()` method to modify the behavior of the operation.\n\nThe following example finds all restaurants that have a `cuisine` field value of `\"Italian\"` and limits the results to `5` documents:\n\n```csharp\nvar filter = Builders.Filter.Eq(\"cuisine\", \"Italian\");\nvar results = collection.Find(filter).Limit(5).ToList();\n\nforeach (var result in results)\n{\n Console.WriteLine(result.Name);\n}\n```\n\n```\nV & T Restaurant\nMimis Restaurant & Bar\nVenice Restaurant\nAreo Restaurant\nTre Giovani Pizza & Pasta\n```\n\nThe preceding example returns the first five documents matched by the query according to their natural order in the database. The following section describes how to return the documents in a specified order.\n\n## Sort\n\nTo return documents in a specified order, use the `Sort()` method provided by the `IFindFluent` interface. After calling the `Find()` method, chain the `Sort()` method to modify the behavior of the operation.\n\nWhen calling `Sort()`, you must pass in the sort definition as a parameter. You can construct a sort definition by using the `Builders.Sort.Ascending()` method to sort values from lowest to highest, or the `Builders.Sort.Ascending()` method to sort them from highest to lowest. Both of these methods take the field name to sort by as a parameter. These methods can be chained to sort returned documents by multiple fields.\n\nThe following example returns all documents that have a `cuisine` field value of `\"Italian\"`, sorted in ascending order of `name` field values:\n\n```csharp\nvar filter = Builders.Filter.Eq(\"cuisine\", \"Italian\");\nvar sort = Builders.Sort.Ascending(\"name\");\nvar results = collection.Find(filter).Sort(sort).ToList();\n\nforeach (var result in results)\n{\n Console.WriteLine(result.Name);\n}\n```\n\n```\n(Lewis Drug Store) Locanda Vini E Olii\n101 Restaurant And Bar\n44 Sw Ristorante & Bar\n900 Park\nA Voce\n...\n```\n\n## Skip\n\nTo skip a specified number of documents before returning your query results, use the `Skip()` method provided by the `IFindFluent` interface. After calling the `Find()` method, chain the `Skip()` method to modify the behavior of the operation.\n\nThe following example returns all documents that have a `cuisine` field value of `\"Italian\"` and skips the first `10` documents:\n\n```csharp\nvar filter = Builders.Filter.Eq(\"cuisine\", \"Italian\");\nvar results = collection.Find(filter).Skip(10).ToList();\n\nforeach (var result in results)\n{\n Console.WriteLine(result.Name);\n}\n```\n\n```\nTrattoria Alba\nDa Umberto Restaurant\nLa Strada Restaurant\nPasta Lovers Trattoria\nNanni Restaurant\nVilla Mosconi Restaurant\nVilla Berulia\nMarco Polo Ristorante\nCafe Luna\nBaraonda\n```\n\n## Combine Limit, Sort, and Skip\n\nYou can chain the `Limit()`, `Sort()`, and `Skip()` methods to a single `Find()` method call. This allows you to set a maximum number of sorted documents to return from the read operation, skipping a specified number of documents before returning.\n\nThe following example returns `5` documents that have a `cuisine` value of `\"Italian\"`. The results are sorted in ascending order by the `name` field value, skipping the first `10` documents:\n\n```csharp\nvar filter = Builders.Filter.Eq(\"cuisine\", \"Italian\");\nvar sort = Builders.Sort.Ascending(\"name\");\n\nvar results = collection.Find(filter).Limit(10).Sort(sort).Skip(10).ToList();\n\nforeach (var result in results)\n{\n Console.WriteLine(result.Name);\n}\n```\n\n```\nAcqua\nAcqua Restaurant\nAcqua Santa\nAcquista Trattoria\nAcquolina Catering\nAdriatic Restaurant Pizzeria Bar\nAdrienne'S Pizza Bar\nAi Fiori\nAita Restaurant\nAl Di La\n```\n\nThe order in which you call these methods doesn't change the documents that are returned. The .NET/C# Driver automatically reorders the calls to perform the sort operation first, the skip operation next, and then the limit operation.\n\n## Additional Information\n\nFor more information about retrieving documents, see the Retrieve Data guide.\n\nFor more information about specifying a query, see the Create a Query Filter guide.\n\n### API Documentation\n\nTo learn more about any of the methods or types discussed in this guide, see the following API documentation:\n\n- Find()\n\n- IFindFluent\n\n- Limit()\n\n- Sort()\n\n- Skip()"} -{"chunk_id": "68a95beb5e79d242619d875d-0", "page_id": "68a95beb5e79d242619d875d", "source_name": "csharp", "product_name": "C# Driver", "url": "https://mongodb.com/docs/drivers/csharp/current/security/authentication/oidc", "title": "OIDC (Workload Identity Federation) Authentication", "text": "# OIDC (Workload Identity Federation) Authentication\n\n## Overview\n\nThe OpenID Connect (OIDC) authentication mechanism allows you to authenticate to MongoDB by using a third-party identity provider, such as Azure or Google Cloud Platform (GCP).\n\nYou can use this mechanism only when authenticating to MongoDB Atlas or MongoDB Enterprise Advanced, and only when authenticating to MongoDB v7.0 or later.\n\nTo learn more about configuring MongoDB Atlas for OIDC authentication, see Set up Workforce Identity Federation with OIDC in the Atlas documentation.\n\nFor more information about using OIDC authentication with MongoDB, see OpenID Connect Authentication and MongoDB Server Parameters in the MongoDB Server manual.\n\n### Code Placeholders\n\nThe code examples on this page use the following placeholders:\n\n- `+srv`: Include this option in your connection string prefix only if you are connecting to a MongoDB Atlas cluster. To learn more about the `+srv` option, see Connection String Formats in the MongoDB Server manual.\n\n- ``: The client ID or application ID of the Azure managed identity or enterprise application, if authenticating against Azure IMDS.\n\n- ``: The network address of your MongoDB deployment.\n\n- ``: The port number of your MongoDB deployment. If you omit this parameter, the driver uses the default port number (`27017`). You don't need to specify a port when connecting to a MongoDB Atlas cluster.\n\n- ``: The audience parameter configured on your MongoDB deployment.\n\nTo use the code examples on this page, replace these placeholders with your own values.\n\n## Using OIDC Authentication in Your Application\n\nThe following sections describe how to use OIDC authentication to authenticate from various platforms.\n\n### Azure IMDS\n\nIf your application runs on an Azure VM, or otherwise uses the Azure Instance Metadata Service (IMDS), you can authenticate to MongoDB by using the .NET/C# Driver's built-in Azure support.\n\nYou can specify Azure IMDS OIDC authentication on a `MongoClientSettings` object either by using a `MongoCredential` object or as part of the connection string. Select the Connection String or MongoCredential tab to see the corresponding syntax.\n\n\n\n\n\nThe following code example shows how to specify Azure IMDS OIDC authentication. Replace the `` placeholder with the percent-encoded value of the `audience` parameter configured on your MongoDB deployment.\n\n```csharp\nvar connectionString = \"mongodb://@[:]/?\" +\n \"authMechanism=MONGODB-OIDC\" +\n \"&authMechanismProperties=ENVIRONMENT:azure,TOKEN_RESOURCE:\");\nvar mongoClientSettings = MongoClientSettings.FromConnectionString(connectionString);\nvar client = new MongoClient(mongoClientSettings);\n```\n\n\n\n\n\nThe following code example shows how to specify Azure IMDS OIDC authentication:\n\n```csharp\nvar mongoClientSettings = MongoClientSettings.FromConnectionString(\n \"mongodb://[:]\");\nmongoClientSettings.Credential = MongoCredential\n .CreateOidcCredential(\"azure\", \"\")\n .WithMechanismProperty(\"TOKEN_RESOURCE\", \"\");\nvar client = new MongoClient(mongoClientSettings);\n```\n\n\n\n\n\n### GCP IMDS\n\nIf your application runs on a Google Compute Engine VM, or otherwise uses the GCP Instance Metadata Service, you can authenticate to MongoDB by using the .NET/C# Driver's built-in GCP support.\n\nYou can specify GCP IMDS OIDC authentication on a `MongoClientSettings` object either by using a `MongoCredential` object or as part of the connection string. Select the Connection String or MongoCredential tab to see the corresponding syntax.\n\n\n\n\n\nThe following code example shows how to specify GCP IMDS OIDC authentication as part of the authentication string:\n\n```csharp\nvar connectionString = \"mongodb://[:]/?authMechanism=MONGODB-OIDC\" +\n \"&authMechanismProperties=ENVIRONMENT:gcp,TOKEN_RESOURCE:\");\nvar mongoClientSettings = MongoClientSettings.FromConnectionString(connectionString);\nvar client = new MongoClient(mongoClientSettings);\n```\n\n\n\n\n\nThe following code example shows how to specify GCP IMDS OIDC authentication by using a `MongoCredential` object:\n\n```csharp\nvar mongoClientSettings = MongoClientSettings.FromConnectionString(\n \"mongodb://[:]\");\nmongoClientSettings.Credential = MongoCredential\n .CreateOidcCredential(\"gcp\")\n .WithMechanismProperty(\"TOKEN_RESOURCE\", \"\");\nvar client = new MongoClient(mongoClientSettings);\n```\n\n\n\n\n\n### Kubernetes\n\nIf your application runs on a Kubernetes cluster, you can authenticate to MongoDB by using the .NET/C# Driver's built-in Kubernetes support.\n\nYou can specify Kubernetes OIDC authentication on a `MongoClientSettings` object either by using a `MongoCredential` object or as part of the connection string. Select the Connection String or MongoCredential tab to see the corresponding syntax.\n\n\n\n\n\nThe following code example shows how to specify Kubernetes OIDC authentication as part of the connection string:\n\n```csharp\nvar connectionString = \"mongodb://[:]/?authMechanism=MONGODB-OIDC\" +\n \"&authMechanismProperties=ENVIRONMENT:k8s\";\nvar mongoClientSettings = MongoClientSettings.FromConnectionString(connectionString);\nvar client = new MongoClient(mongoClientSettings);\n```\n\n\n\n\n\nThe following code example shows how to specify Kubernetes OIDC authentication by using a `MongoCredential` object:\n\n```csharp\nvar mongoClientSettings = MongoClientSettings.FromConnectionString(\n \"mongodb://[:]\");\nmongoClientSettings.Credential = MongoCredential\n .CreateOidcCredential(\"k8s\")\nvar client = new MongoClient(mongoClientSettings);\n```\n\n\n\n\n\nIf you specify Kubernetes OIDC as the authentication mechanism, the driver reads the contents of the OIDC token from one of the following locations:\n\n- `AZURE_FEDERATED_TOKEN_FILE` environment variable for applications running on Azure Kubernetes Service (AKS)\n\n- `AWS_WEB_IDENTITY_TOKEN_FILE` environment variable for applications running on Elastic Kubernetes Service (EKS)\n\n- `/var/run/secrets/kubernetes.io/serviceaccount/token` file, the default location for all other applications, including ones that run on Google Kubernetes Engine (GKE)\n\nYou must store your OIDC token in the location that corresponds to the service you use to run your application."} -{"chunk_id": "68a95beb5e79d242619d875d-1", "page_id": "68a95beb5e79d242619d875d", "source_name": "csharp", "product_name": "C# Driver", "url": "https://mongodb.com/docs/drivers/csharp/current/security/authentication/oidc", "title": "OIDC (Workload Identity Federation) Authentication", "text": "### Custom Callback\n\nThe .NET/C# Driver doesn't offer built-in support for all platforms, including Azure Functions. Instead, you must define a custom callback to use OIDC to authenticate from these platforms.\n\nFirst, define a class that implements the `IOidcCallback` interface. This interface contains two methods:\n\n- `GetOidcAccessToken()`: This method accepts the parameters to the callback method and returns the callback response.\n\n- `GetOidcAccessTokenAsync()`: This method is an asynchronous version of the previous method.\n\nThe following code is an example implementation of the `IOidcCallback` interface. In this example, the methods retrieve an OIDC token from a file named `\"access-token.dat\"` in the local file system.\n\n```csharp\npublic class MyCallback : IOidcCallback\n{\n public OidcAccessToken GetOidcAccessToken(\n OidcCallbackParameters parameters,\n CancellationToken cancellationToken)\n {\n var accessToken = File.ReadAllText(\"access-token.dat\");\n return new(accessToken, expiresIn: null);\n }\n\n public async Task GetOidcAccessTokenAsync(\n OidcCallbackParameters parameters,\n CancellationToken cancellationToken)\n {\n var accessToken = await File.ReadAllTextAsync(\n \"access-token.dat\",\n cancellationToken)\n .ConfigureAwait(false);\n return new(accessToken, expiresIn: null);\n }\n}\n```\n\nAfter you define a class that contains your custom callback methods, call the `MongoCredential.CreateOidcCredential()` method and pass in a new instance of your class. Store the result of this method call in the `Credential` property of your `MongoClientSettings` object, as shown in the following code example:\n\n```csharp\nvar mongoClientSettings = MongoClientSettings\n .FromConnectionString(\"mongodb://[:]\");\nmongoClientSettings.Credential = MongoCredential.CreateOidcCredential(new MyCallback());\nvar client = new MongoClient(mongoClientSettings);\n```\n\n## API Documentation\n\nTo learn more about any of the methods or types discussed on this page, see the following API documentation:\n\n- MongoClient()\n\n- MongoClientSettings()\n\n- MongoCredential()\n\n- MongoClientSettings.Extensions.AddAWSAuthentication()\n\n- CreateOidcCredential()\n\n- WithMechanismProperty()\n\n- IOidcCallback\n\n- OidcAccessToken\n\n- OidcCallbackParameters"} -{"chunk_id": "68a95beb5e79d242619d875f-0", "page_id": "68a95beb5e79d242619d875f", "source_name": "csharp", "product_name": "C# Driver", "url": "https://mongodb.com/docs/drivers/csharp/current/security/authentication/x509", "title": "X.509 Authentication with TLS", "text": "# X.509 Authentication with TLS\n\n## Overview\n\nIn the **X.509** authentication mechanism, the server and client use the TLS protocol to exchange X.509 public-key certificates. You can use this mechanism to authenticate to MongoDB Atlas, MongoDB Enterprise Advanced, and MongoDB Community Edition.\n\nTo learn how to use TLS/SSL with the .NET/C# Driver, see TLS/SSL.\n\nFor more information about X.509 certificates, see X.509 in the MongoDB Server manual.\n\n### Code Placeholders\n\nThe code examples on this page use the following placeholders:\n\n- `+srv`: Include this option in your connection string prefix only if you are connecting to a MongoDB Atlas cluster. If you're using a `MongoClientSettings` object, you can specify the `srv` format by setting the `Scheme` property to `ConnectionStringScheme.MongoDBPlusSrv`. To learn more about the `+srv` option, see Connection String Formats in the MongoDB Server manual.\n\n- ``: The network address of your MongoDB deployment.\n\n- ``: The port number of the MongoDB deployment. If you omit this parameter, the driver uses the default port number (`27017`). You don't need a port number when connecting to a MongoDB Atlas cluster.\n\n- ``: The username of the user associated with the X.509 certificate. The username must match the distinguished subject name of the certificate. If you omit this parameter, the MongoDB deployment infers the username from the X.509 certificate.\n\n- ``: The path to the X.509 certificate file.\n\n- ``: The password for the X.509 certificate.\n\nTo use the code examples on this page, replace these placeholders with your own values.\n\n## Using X.509 Authentication in Your Application\n\nTo use an X.509 certificate for authentication, you must use a `MongoClientSettings` object to specify the path to your X.509 certificate and the password for the certificate. The certificate must use the PKCS #12 (`.p12`) format.\n\nIf your certificate uses the PEM (`.pem`) format, you can convert it to the `.p12` format by using the `openssl` command-line tool, as shown in the following code example:\n\n```bash\nopenssl pkcs12 -export -out <.p12 file> -inkey -in <.pem file>\n```\n\nYou can provide a `.pem` format certificate directly by using the `X509Certificate2.CreateFromPem()` method, as shown in the following code example:\n\n```csharp\nvar certPem = File.ReadAllText(\"client.crt\");\nvar keyPem = File.ReadAllText(\"client.key\");\nvar rsa = RSA.Create();\nrsa.ImportFromEncryptedPem(keyPem, \"\");\nvar cert = X509Certificate2.CreateFromPem(certPem);\nvar clientCertificate = cert.CopyWithPrivateKey(rsa);\n```\n\nFor more information about `openssl-pkcs12`, see the OpenSSL documentation.\n\nYou must also specify `MONGODB-X509` as the authentication mechanism and `$external` as the authentication source. You can specify these options either in your connection string or by using a `MongoCredential` object. Select the Connection String or MongoCredential tab to see the corresponding syntax:\n\n\n\n\n\n```csharp\nvar connectionString = \"mongodb[+srv]://[:]/?authSource=$external&authMechanism=MONGODB-X509\";\nvar settings = MongoClientSettings.FromConnectionString(connectionString);\n\nsettings.UseTls = true;\nsettings.SslSettings = new SslSettings\n{\n ClientCertificates = new List()\n {\n new X509Certificate2(\"\", \"\")\n }\n};\n```\n\n\n\n\n\n```csharp\nvar credential = MongoCredential.CreateMongoX509Credential(\"\");\nvar settings = new MongoClientSettings\n{\n Credential = credential,\n SslSettings = new SslSettings\n {\n ClientCertificates = new List()\n {\n new X509Certificate2(\"\", \"\")\n },\n },\n UseTls = true,\n Server = new MongoServerAddress(\"\"[, \"\"]),\n Scheme = ConnectionStringScheme.MongoDBPlusSrv // Needed when connecting to MongoDB Atlas\n};\n```\n\n\n\n\n\n## Troubleshooting\n\nIf you are using Windows as your operating system, you might encounter an issue in which the .NET/C# Driver is unable to locate an `X.509` authentication certificate in memory. This error displays the following error message:\n\n```none\nNo credentials are available in the security package\n```\n\nTo resolve this issue, add the following code to your application. This code generates any `X.509` certificates required by your application and stores them to disk:\n\n```csharp\nusing (X509Certificate2 certWithKey = certOnly.CopyWithPrivateKey(key))\n{\n return new X509Certificate2(certWithKey.Export(X509ContentType.Pkcs12));\n}\n```\n\n## API Documentation\n\nTo learn more about any of the MongoDB methods and types used on this page, see the following API documentation:\n\n- MongoClient\n\n- MongoClientSettings\n\n- MongoCredential\n\n- SslSettings\n\n- MongoServerAddress\n\n- CreateMongoX509Credential()\n\nFor more information about the .NET types used on this page, see the following MSDN documentation:\n\n- X509Certificate\n\n- X509Certificate2"} -{"chunk_id": "68a95beb5e79d242619d872b-0", "page_id": "68a95beb5e79d242619d872b", "source_name": "csharp", "product_name": "C# Driver", "url": "https://mongodb.com/docs/drivers/csharp/current/issues-and-help", "title": "Issues & Help", "text": "# Issues & Help\n\nIn this guide, you can learn how to report issues, suggest new features, and contribute to the .NET/C# Driver.\n\nYou can find support for general questions by using the MongoDB Stack Overflow tag or the MongoDB Reddit community.\n\n## Bugs / Feature Requests\n\nTo report a bug or to request a new feature in the .NET/C# Driver, please open an issue in JIRA, our issue management tool, using the following steps:\n\n1. Create a JIRA account.\n\n2. Navigate to the CSHARP Driver project.\n\n3. Click Create Issue. Please provide as much information as possible about the issue and the steps to reproduce it.\n\nBug reports in JIRA for the CSHARP Driver project can be viewed by everyone.\n\nIf you identify a security vulnerability in the driver or in any other MongoDB project, please report it according to the instructions found in Create a Vulnerability Report.\n\n## Pull Requests\n\nWe are happy to accept contributions to help improve the driver. To contribute to the official driver, follow the development and testing guidelines. We will guide user contributions to ensure they meet the standards of the codebase."} -{"chunk_id": "68a95beb5e79d242619d8704-0", "page_id": "68a95beb5e79d242619d8704", "source_name": "csharp", "product_name": "C# Driver", "url": "https://mongodb.com/docs/drivers/csharp/current/crud/update-many", "title": "Update Many", "text": "# Update Many\n\n`UpdateMany()`\n\n`UpdateManyAsync()`\n\ndocuments\n\nConfiguration Options\n\nUpdate Fields in Many Documents\n\nUpdate Arrays in Many Documents\n\nmultiple documents\n\n- UpdateMany()\n\n- UpdateManyAsync()\n\nUpdateMany()\n\nUpdateManyAsync()\n\nThis page includes a short interactive lab that demonstrates how to modify data by using the `UpdateManyAsync()` method. You can complete this lab directly in your browser window without installing MongoDB or a code editor.\n\nTo start the lab, click the Open Interactive Tutorial button at the top of the page. To expand the lab to a full-screen format, click the full-screen button (\u26f6) in the top-right corner of the lab pane.\n\n\n\n\n\n```csharp\nvar filter = Builders.Filter\n .Eq(\"cuisine\", \"Pizza\");\n\nvar combinedUpdate = Builders.Update.Combine(\n Builders.Update.Set(\"cuisine\", \"French\"),\n Builders.Update.Unset(\"borough\")\n);\n\n_restaurantsCollection.UpdateMany(filter, combinedUpdate);\n```\n\n\n\n\n\n```csharp\nvar filter = Builders.Filter\n .Eq(\"cuisine\", \"Pizza\");\n\nvar combinedUpdate = Builders.Update.Combine(\n Builders.Update.Set(\"cuisine\", \"French\"),\n Builders.Update.Unset(\"borough\")\n);\n\nawait _restaurantsCollection.UpdateManyAsync(filter, combinedUpdate);\n```\n\n\n\n\n\n\n\n\n\n```csharp\nvar filter = Builders.Filter\n .Eq(\"cuisine\", \"Pizza\");\n\nvar updatePipeline = Builders.Update.Pipeline(\n PipelineDefinition.Create(\n new BsonDocument(\"$set\", new BsonDocument(\"cuisine\", \"French\")),\n new BsonDocument(\"$unset\", \"borough\")\n )\n);\n\n_restaurantsCollection.UpdateMany(filter, updatePipeline);\n```\n\n\n\n\n\n```csharp\nvar filter = Builders.Filter\n .Eq(\"cuisine\", \"Pizza\");\n\nvar updatePipeline = Builders.Update.Pipeline(\n PipelineDefinition.Create(\n new BsonDocument(\"$set\", new BsonDocument(\"cuisine\", \"French\")),\n new BsonDocument(\"$unset\", \"borough\")\n )\n);\n\nawait _restaurantsCollection.UpdateManyAsync(filter, updatePipeline);\n```\n\n\n\n\n\n## Overview\n\nIn this guide, you can learn how to use the MongoDB .NET/C# Driver to update values in multiple documents.\n\nThe .NET/C# Driver provides the following methods to update values:\n\n- `UpdateMany()`: Updates one or more fields in multiple documents.\n\n- `UpdateManyAsync()`: The asynchronous version of `UpdateMany()`.\n\nThe following sections describe these methods in more detail.\n\nMany of the methods on this page have multiple overloads. The examples in this guide show only one definition of each method. For more information about the available overloads, see the API documentation.\n\nBuilder classes and LINQ queries pass values to the underlying MongoDB operation. By design, these APIs are not a security sanitization layer. Validate and sanitize untrusted input in your application before you pass it to a builder or a LINQ query.\n\n### Sample Data\n\nThe examples in this guide use the `restaurants` collection from the `sample_restaurants` database. The documents in this collection use the following `Restaurant`, `Address`, and `GradeEntry` classes as models:\n\n```csharp\npublic class Restaurant\n{\n public ObjectId Id { get; set; }\n\n public string Name { get; set; }\n\n [BsonElement(\"restaurant_id\")]\n public string RestaurantId { get; set; }\n\n public string Cuisine { get; set; }\n\n public Address Address { get; set; }\n\n public string Borough { get; set; }\n\n public List Grades { get; set; }\n}\n```\n\n```csharp\npublic class Address\n{\n public string Building { get; set; }\n\n [BsonElement(\"coord\")]\n public double[] Coordinates { get; set; }\n\n public string Street { get; set; }\n\n [BsonElement(\"zipcode\")]\n public string ZipCode { get; set; }\n}\n```\n\n```csharp\npublic class GradeEntry\n{\n public DateTime Date { get; set; }\n\n public string Grade { get; set; }\n\n public float? Score { get; set; }\n}\n```\n\nThe documents in the `restaurants` collection use the snake-case naming convention. The examples in this guide use a `ConventionPack` to deserialize the fields in the collection into Pascal case and map them to the properties in the `Restaurant` class.\n\nTo learn more about custom serialization, see Custom Serialization.\n\nThis collection is from the sample datasets provided by Atlas. See the Get Started with the .NET/C# Driver to learn how to create a free MongoDB cluster and load this sample data.\n\n## Methods and Parameters\n\nThe `UpdateMany()` and `UpdateManyAsync()` methods accept the following parameters:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nParameter\n\n\nDescription\n\n
\n`filter`\n\n\nAn instance of the `FilterDefinition` class that specifies the documents to update. To learn how to create a query filter, see Create a Query Filter.\n\n**Data Type:** FilterDefinition\n\n
\n`update`\n\n\nAn instance of the `UpdateDefinition` class. This object specifies the kind of update operation, the fields to update, and the new value for each field. To learn how to create an `UpdateDefinition` object, see Update Fields in Many Documents and Update Arrays in Many Documents.\n\n**Data Type:** UpdateDefinition\n\n
\n`options`\n\n\n*Optional.* An instance of the `UpdateOptions` class that specifies the configuration for the update operation. The default value is `null`. For a list of available options, see Configuration Options.\n\n**Data Type:** UpdateOptions\n\n
\n`cancellationToken`\n\n\n*Optional.* A token that you can use to cancel the operation.\n\n**Data type**: `CancellationToken`\n\n
\n\n## Update Multiple Values\n\nThe `UpdateMany()` and `UpdateManyAsync()` methods each accept only one `UpdateDefinition` object. The following sections describe how to update multiple values in a single method call.\n\n### Combined Update Definitions\n\nThe `Builders.Update.Combine()` method lets you combine multiple `UpdateDefinition` objects. This method accepts the following parameter:\n\n\n\n\n\n\n\n\n\n\n
\nParameter\n\n\nDescription\n\n
\n`updates`\n\n\nAn array of update definitions to combine.\n\n**Data Type:** `UpdateDefinition[]`\n\n
The `Combine()` method returns a single `UpdateDefinition` object that defines multiple update operations.\n\nThe following code example uses the `Combine()` method to combine a $set operation and an $unset operation:\n\n\n\n\n\n```csharp\nvar filter = Builders.Filter\n .Eq(\"cuisine\", \"Pizza\");\n\nvar combinedUpdate = Builders.Update.Combine(\n Builders.Update.Set(\"cuisine\", \"French\"),\n Builders.Update.Unset(\"borough\")\n);\n\n_restaurantsCollection.UpdateMany(filter, combinedUpdate);\n```\n\n\n\n\n\n```csharp\nvar filter = Builders.Filter\n .Eq(\"cuisine\", \"Pizza\");\n\nvar combinedUpdate = Builders.Update.Combine(\n Builders.Update.Set(\"cuisine\", \"French\"),\n Builders.Update.Unset(\"borough\")\n);\n\nawait _restaurantsCollection.UpdateManyAsync(filter, combinedUpdate);\n```\n\n\n\n"} -{"chunk_id": "68a95beb5e79d242619d8704-1", "page_id": "68a95beb5e79d242619d8704", "source_name": "csharp", "product_name": "C# Driver", "url": "https://mongodb.com/docs/drivers/csharp/current/crud/update-many", "title": "Update Many", "text": "### Update Pipelines\n\nYou can join a sequence of update operations into a single aggregation pipeline.\n\nTo create an update pipeline, call the `Builders.Update.Pipeline()` method. This method accepts the following parameter:\n\n\n\n\n\n\n\n\n\n\n
\nParameter\n\n\nDescription\n\n
\n`pipeline`\n\n\nA `PipelineDefinition` instance that represents the update pipeline. To create a `PipelineDefinition` object, create a BSON document for each update operation you want to perform, then pass these documents to the `PipelineDefinition.Create()` method.\n\n**Data Type:** `PipelineDefinition`\n\n
The `Pipeline()` method returns a single `UpdateDefinition` object that defines multiple aggregation stages.\n\nThe following code example uses the `Pipeline()` method to combine a $set operation and an $unset operation:\n\n\n\n\n\n```csharp\nvar filter = Builders.Filter\n .Eq(\"cuisine\", \"Pizza\");\n\nvar updatePipeline = Builders.Update.Pipeline(\n PipelineDefinition.Create(\n new BsonDocument(\"$set\", new BsonDocument(\"cuisine\", \"French\")),\n new BsonDocument(\"$unset\", \"borough\")\n )\n);\n\n_restaurantsCollection.UpdateMany(filter, updatePipeline);\n```\n\n\n\n\n\n```csharp\nvar filter = Builders.Filter\n .Eq(\"cuisine\", \"Pizza\");\n\nvar updatePipeline = Builders.Update.Pipeline(\n PipelineDefinition.Create(\n new BsonDocument(\"$set\", new BsonDocument(\"cuisine\", \"French\")),\n new BsonDocument(\"$unset\", \"borough\")\n )\n);\n\nawait _restaurantsCollection.UpdateManyAsync(filter, updatePipeline);\n```\n\n\n\n\n\nUpdate pipelines don't support all update operations, but they do support certain aggregation stages not found in other update definitions. For a list of update operations supported by pipelines, see Updates with Aggregation Pipeline in the MongoDB Server manual.\n\n## Configuration Options\n\nThe `UpdateMany()` and `UpdateManyAsync()` methods optionally accept an `UpdateOptions` object as a parameter. You can use this argument to configure the update operation.\n\nThe `UpdateOptions` class contains the following properties:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nProperty\n\n\nDescription\n\n
\n`ArrayFilters`\n\n\nSpecifies which array elements to modify for an update operation on an array field. See the MongoDB Server manual for more information.\n\n**Data Type:** IEnumerable\n\n
\n`BypassDocumentValidation`\n\n\nSpecifies whether the update operation bypasses document validation. This lets you update documents that don't meet the schema validation requirements, if any exist. See the MongoDB Server manual for more information on schema validation.\n\n**Data Type:** `bool?`\n\n
\n`Collation`\n\n\nSpecifies the kind of language collation to use when sorting results. See the Collation section of this page for more information.\n\n**Data Type:** Collation\n\n
\n`Comment`\n\n\nGets or sets the user-provided comment for the operation. See the MongoDB Server manual for more information.\n\n**Data Type:** BsonValue\n\n
\n`Hint`\n\n\nGets or sets the index to use to scan for documents. See the MongoDB Server manual for more information.\n\n**Data Type:** BsonValue\n\n
\n`IsUpsert`\n\n\nSpecifies whether the update operation performs an upsert operation if no documents match the query filter. See the MongoDB Server manual for more information.\n\n**Data Type:** `bool`\n\n
\n`Sort`\n\n\nDetermines which document the operation updates if the query selects multiple documents, because the update operation updates the first document in the sort order specified. To set this option, you must instantiate an `UpdateOptions` instance that uses a generic type that models your data, as shown in the following code:\n\n```csharp\nvar options = new UpdateOptions\n{\n Sort = Builders.Sort.Ascending(r => r.Name)\n};\n```\n\n**Data Type:** `SortDefinition`\n\n
\n`Let`\n\n\nGets or sets the let document. See the MongoDB Server manual for more information.\n\n**Data Type:** BsonDocument\n\n
"} -{"chunk_id": "68a95beb5e79d242619d8704-2", "page_id": "68a95beb5e79d242619d8704", "source_name": "csharp", "product_name": "C# Driver", "url": "https://mongodb.com/docs/drivers/csharp/current/crud/update-many", "title": "Update Many", "text": "### Collation\n\nTo configure collation for your operation, create an instance of the Collation class.\n\nThe following table describes the parameters that the `Collation` constructor accepts. It also lists the corresponding class property that you can use to read each setting's value.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nParameter\n\n\nDescription\n\n\nClass Property\n\n
\n`locale`\n\n\nSpecifies the International Components for Unicode (ICU) locale. For a list of supported locales, see Collation Locales and Default Parameters in the MongoDB Server Manual.If you want to use simple binary comparison, use the `Collation.Simple` static property to return a `Collation` object with the `locale` set to `\"simple\"`.**Data Type**: `string`\n\n\n`Locale`\n\n
\n`caseLevel`\n\n\n*(Optional)* Specifies whether to include case comparison.When this argument is `true`, the driver's behavior depends on the value of the `strength` argument:- If `strength` is `CollationStrength.Primary`, the driver compares base characters and case.- If `strength` is `CollationStrength.Secondary`, the driver compares base characters, diacritics, other secondary differences, and case.- If `strength` is any other value, this argument is ignored.When this argument is `false`, the driver doesn't include case comparison at strength level `Primary` or `Secondary`.**Data Type**: `boolean`**Default**: `false`\n\n\n`CaseLevel`\n\n
\n`caseFirst`\n\n\n*(Optional)* Specifies the sort order of case differences during tertiary level comparisons.**Data Type**: CollationCaseFirst**Default**: `CollationCaseFirst.Off`\n\n\n`CaseFirst`\n\n
\n`strength`\n\n\n*(Optional)* Specifies the level of comparison to perform, as defined in the ICU documentation.**Data Type**: CollationStrength**Default**: `CollationStrength.Tertiary`\n\n\n`Strength`\n\n
\n`numericOrdering`\n\n\n*(Optional)* Specifies whether the driver compares numeric strings as numbers.If this argument is `true`, the driver compares numeric strings as numbers. For example, when comparing the strings \"10\" and \"2\", the driver treats the values as 10 and 2, and finds 10 to be greater.If this argument is `false` or excluded, the driver compares numeric strings as strings. For example, when comparing the strings \"10\" and \"2\", the driver compares one character at a time. Because \"1\" is less than \"2\", the driver finds \"10\" to be less than \"2\".For more information, see Collation Restrictions in the MongoDB Server manual.**Data Type**: `boolean`**Default**: `false`\n\n\n`NumericOrdering`\n\n
\n`alternate`\n\n\n*(Optional)* Specifies whether the driver considers whitespace and punctuation as base characters for purposes of comparison.**Data Type**: CollationAlternate**Default**: `CollationAlternate.NonIgnorable` (spaces and punctuation are considered base characters)\n\n\n`Alternate`\n\n
\n`maxVariable`\n\n\n*(Optional)* Specifies which characters the driver considers ignorable when the `alternate` argument is `CollationAlternate.Shifted`.**Data Type**: CollationMaxVariable**Default**: `CollationMaxVariable.Punctuation` (the driver ignores punctuation and spaces)\n\n\n`MaxVariable`\n\n
\n`normalization`\n\n\n*(Optional)* Specifies whether the driver normalizes text as needed.Most text doesn't require normalization. For more information about normalization, see the ICU documentation.**Data Type**: `boolean`**Default**: `false`\n\n\n`Normalization`\n\n
\n`backwards`\n\n\n*(Optional)* Specifies whether strings containing diacritics sort from the back of the string to the front.**Data Type**: `boolean`**Default**: `false`\n\n\n`Backwards`\n\n
For more information about collation, see the Collation page in the MongoDB Server manual.\n\n## Return Value\n\nThe `UpdateMany()` method returns an `UpdateResult`, and the `UpdateManyAsync()` method returns a `Task` object. The `UpdateResult` class contains the following properties:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nProperty\n\n\nDescription\n\n
\n`IsAcknowledged`\n\n\nIndicates whether the update operation was acknowledged by MongoDB.\n\n**Data Type:** `bool`\n\n
\n`IsModifiedCountAvailable`\n\n\nIndicates whether you can read the count of update records on the `UpdateResult`.\n\n**Data Type:** `bool`\n\n
\n`MatchedCount`\n\n\nThe number of documents that matched the query filter, regardless of whether one was updated.\n\n**Data Type:** `long`\n\n
\n`ModifiedCount`\n\n\nThe number of documents updated by the update operation.\n\n**Data Type:** `long`\n\n
\n`UpsertedId`\n\n\nThe ID of the document that was upserted in the database, if the driver performed an upsert.\n\n**Data Type:** BsonValue\n\n
\n\n## Additional Information\n\nThis page includes a short interactive lab that demonstrates how to modify data by using the `UpdateManyAsync()` method. You can complete this lab directly in your browser window without installing MongoDB or a code editor.\n\nTo start the lab, click the Open Interactive Tutorial button at the top of the page. To expand the lab to a full-screen format, click the full-screen button (\u26f6) in the top-right corner of the lab pane.\n\nFor runnable examples of the update operations, see the following usage examples:\n\n- UpdateMany()\n\n- UpdateManyAsync()\n\nTo learn more about creating query filters, see the Create a Query Filter guide.\n\n### API Documentation\n\nFor more information about any of the methods or types discussed in this guide, see the following API documentation:\n\n- UpdateMany()\n\n- UpdateManyAsync()\n\n- UpdateOptions\n\n- UpdateResult"} -{"chunk_id": "68a95be15e79d242619d8030-0", "page_id": "68a95be15e79d242619d8030", "source_name": "database-tools", "product_name": "MongoDB Database Tools", "url": "https://mongodb.com/docs/database-tools/mongodump/mongodump-compatibility-and-installation", "title": "mongodump Compatibility and Installation", "text": "# mongodump Compatibility and Installation\n\n\u27a4`mongodump`Connect to a MongoDB Atlas Cluster using AWS IAM CredentialsThis page describes software compatibility and installation for version `100.19.1` of `mongodump`.\n\nStarting in MongoDB 4.4, the MongoDB Database Tools are released separately from the MongoDB Server. The MongoDB Database Tools use their own versioning, with an initial version of `100.0.0`.\n\n## Compatibility\n\n### MongoDB Server Compatibility\n\n`mongodump` version `100.19.1` supports the following versions of the MongoDB Server:\n\n- MongoDB 9.0\n\n- MongoDB 8.3\n\n- MongoDB 8.2\n\n- MongoDB 8.1\n\n- MongoDB 8.0\n\n- MongoDB 7.0\n\n- MongoDB 6.0\n\n- MongoDB 5.0\n\n- MongoDB 4.4\n\n- MongoDB 4.2\n\n`mongodump` does not support MongoDB Server versions earlier than 4.2. Attempts to connect to an earlier Server version fail.\n\n`mongodump` also works with Atlas Infinite Database clusters. For details, see mongodump Behavior, Access, and Usage.\n\n### Platform Support\n\n`mongodump` version `100.19.1` is supported on these platforms:\n\n\u2713\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n\n\nx86_64\n\n\nARM64\n\n\nPPC64LE\n\n\ns390x\n\n
\nAmazon Linux 2023\n\n\n\u2713\n\n\n\u2713\n\n\n\n\n\n
\nAmazon 2\n\n\n\u2713\n\n\n\u2713\n\n\n\n\n\n
\nDebian 12\n\n\n\u2713\n\n\n\n\n\n\n\n
\nDebian 11\n\n\n\u2713\n\n\n\n\n\n\n\n
\nDebian 10\n\n\n\u2713\n\n\n\n\n\n\n\n
\nDebian 9\n\n\n\u2713\n\n\n\n\n\n\n\n
\nRHEL (Red Hat Enterprise Linux) / CentOS 9\n\n\n\u2713\n\n\n\u2713\n\n\n\u2713\n\n\n\u2713\n\n
\nRHEL (Red Hat Enterprise Linux) / CentOS 8\n\n\n\u2713\n\n\n\n\n\u2713\n\n\n\u2713\n\n
\nRHEL (Red Hat Enterprise Linux) / CentOS 7\n\n\n\u2713\n\n\n\n\n\u2713\n\n\n\u2713\n\n
\nRHEL (Red Hat Enterprise Linux) / CentOS 6\n\n\n\u2713\n\n\n\n\n\n\n\n
\nSUSE 15\n\n\n\u2713\n\n\n\n\n\n\n\n
\nSUSE 12\n\n\n\u2713\n\n\n\n\n\n\n\n
\nUbuntu 24.04\n\n\n\u2713\n\n\n\u2713\n\n\n\n\n\n
\nUbuntu 22.04\n\n\n\u2713\n\n\n\u2713\n\n\n\n\n\n
\nUbuntu 20.04\n\n\n\u2713\n\n\n\u2713\n\n\n\n\n\n
\nUbuntu 18.04\n\n\n\u2713\n\n\n\u2713\n\n\n\n\n\n
\nUbuntu 16.04\n\n\n\u2713\n\n\n\u2713\n\n\n\u2713\n\n\n\n
\nWindows 11 and later\n\n\n\u2713\n\n\n\n\n\n\n\n
\nWindows Server 2016 and later\n\n\n\u2713\n\n\n\n\n\n\n\n
\nmacOS 11 and later\n\n\n\u2713\n\n\n\u2713\n\n\n\n\n\n
\nmacOS 10.12 - 10.15\n\n\n\u2713\n\n\n\n\n\n\n\n
\n\n### Additional Considerations for Ubuntu 18.04\n\n`mongodump`Ubuntu 18.04 may use a non-standard DNS resolver. When you use a non-standard DNS resolver, `mongodump` returns an error message like:\n\n```shell\nerror parsing uri: lookup on 127.0.0.53:53: cannot unmarshal DNS message\n```\n\nTo resolve the problem, edit `/etc/resolv.conf` to point to a different DNS resolver.\n\n## Installation\n\nThe `mongodump` tool is part of the *MongoDB Database Tools* package:\n\n\u27a4 Follow the Database Tools Installation Guide to install `mongodump`.\n\n## Learn More\n\n- `mongodump`\n\n- mongodump Behavior, Access, and Usage\n\n- mongodump Examples"} -{"chunk_id": "68a95be15e79d242619d802b-0", "page_id": "68a95be15e79d242619d802b", "source_name": "database-tools", "product_name": "MongoDB Database Tools", "url": "https://mongodb.com/docs/database-tools/mongoimport", "title": "`mongoimport`", "text": "# `mongoimport`\n\nMongoDB Command Line Database Tool binaries are not supported or tested for use with non-genuine MongoDB deployments. While the tools may work on these deployments, compatibility is not guaranteed.`mongoimport`\n`mongoimport`\n\u27a4`mongoimport`Connect to a MongoDB Atlas Cluster using AWS IAM CredentialsThis documentation is for version `100.19.1` of `mongoimport`.\n\n## Synopsis\n\n`mongoimport` imports content from an Extended JSON, CSV, or TSV export created by `mongoexport`, or potentially, another third-party export tool.\n\nRun `mongoimport` from the system command line, not the `mongo` shell.\n\n`mongoexport` provides data export capabilities.\n\nYou can use the MongoDB Database Tools to migrate from a self-hosted deployment to MongoDB Atlas. MongoDB Atlas is the fully managed service for MongoDB deployments in the cloud. To learn more, see Seed with mongorestore.\n\nTo learn all the ways you can migrate to MongoDB Atlas, see Migrate or Import Data.\n\nYou can also import and export data using the graphical user interface tool MongoDB Compass. For details, see MongoDB Compass Import and Export.\n\n## Syntax\n\n`mongoimport` syntax:\n\n```sh\nmongoimport \n```"} -{"chunk_id": "68a95be15e79d242619d802b-1", "page_id": "68a95be15e79d242619d802b", "source_name": "database-tools", "product_name": "MongoDB Database Tools", "url": "https://mongodb.com/docs/database-tools/mongoimport", "title": "`mongoimport`", "text": "## Options\n\n`--help`\nReturns information on the options and use of `mongoimport`.\n\n`--verbose, -v`\n\nIncreases the amount of internal reporting returned on standard output or in log files. Increase the verbosity with the `-v` form by including the option multiple times, (e.g. `-vvvvv`.)\n\n`--quiet`\nRuns `mongoimport` in a quiet mode that attempts to limit the amount of output.\n\nThis option suppresses:\n\n- output from database commands\n\n- replication activity\n\n- connection accepted events\n\n- connection closed events\n\n`--version`\nReturns the `mongoimport` release number.\n\n`--config=`\nSpecifies the full path to a YAML configuration file that contains sensitive values for the following `mongoimport` options:\n\n- `--password`\n\n- `--uri`\n\n- `--sslPEMKeyPassword`\n\nThis is the recommended way to specify a password to `mongoimport`, aside from specifying it through a password prompt. You can use any combination of the arguments in the file.\n\nThe configuration file takes the following form:\n\n```sh\npassword: \nuri: mongodb://mongodb0.example.com:27017\nsslPEMKeyPassword: \n```\n\nIf you specify the `password` option without specifying `uri`, you can specify the other components of the connection string by using `mongoimport` command line options, such as `--username` and `--host`.\n\nBe sure to secure this file with appropriate filesystem permissions.\n\nWhen using the `--config` option, keep the following limitations and behaviors in mind:\n\n- If you provide the `password` field and provide a connection string in the `uri` field with a conflicting password, `mongorestore` throws an error.\n\n- If you specify a configuration file with `--config` and also use the `--password`, `--uri`, or `--sslPEMKeyPassword`\n `mongoimport` command line options, the command line option overrides the corresponding configuration file option.\n\n`--uri=`\nSpecifies the resolvable URI connection string of the MongoDB deployment, enclosed in quotes:\n\n```none\n--uri \"mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]\"\n```\n\nIf you don't specify a database with the `--db` or `--uri` option, `mongoimport` uses the `test` database by default. If the `test` database doesn't exist, `mongoimport` creates the database.\n\nStarting with version `100.0` of `mongoimport`, the connection string may alternatively be provided as a positional parameter, without using the `--uri` option:\n\n```none\nmongoimport mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]\n```\n\nAs a positional parameter, the connection string may be specified at any point on the command line, as long as it begins with either `mongodb://` or `mongodb+srv://`. For example:\n\n```none\nmongoimport --username joe --password secret1 mongodb://mongodb0.example.com:27017 --ssl\n```\n\nOnly one connection string can be provided. Attempting to include more than one, whether using the `--uri` option or as a positional argument, will result in an error.\n\nFor information on the components of the connection string, see the Connection String URI Format documentation.\n\nSome components in the `connection string` may alternatively be specified using their own explicit command-line options, such as `--username` and `--password`. Providing a connection string while also using an explicit option and specifying conflicting information will result in an error.\n\nIf using `mongoimport` on Ubuntu 18.04, you may experience a `cannot unmarshal DNS` error message when using SRV connection strings (in the form `mongodb+srv://`) with the `--uri` option. If so, use one of the following options instead:\n\n- the `--uri` option with a non-SRV connection string (in the form `mongodb://`)\n\n- the `--host` option to specify the host to connect to directly\n\nOn some systems, a password provided in a connection string with the `--uri` option may be visible to system status programs such as `ps` that may be invoked by other users. Consider instead:\n\n- omitting the password in the connection string to receive an interactive password prompt, or\n\n- using the `--config` option to specify a configuration file containing the password.\n\n`--host=<:port>, -h=<:port>`\n\n*Default*: localhost:27017\n\nSpecifies the resolvable hostname of the MongoDB deployment. By default, `mongoimport` attempts to connect to a MongoDB instance running on the localhost on port number `27017`.\n\nTo connect to a replica set, specify the `replSetName` and a seed list of set members, as in the following:\n\n```none\n--host=/<:port>,<:port>,<...>\n```\n\nWhen specifying the replica set list format, `mongoimport` always connects to the primary.\n\nYou can also connect to any single member of the replica set by specifying the host and port of only that member:\n\n```none\n--host=<:port>\n```\n\nIf you use IPv6 and use the `
:` format, you must enclose the portion of an address and port combination in brackets (e.g. `[
]`).\n\nAlternatively, you can also specify the hostname directly in the `URI connection string`. Providing a connection string while also using `--host` and specifying conflicting information will result in an error.\n\n`--port=`\n*Default*: 27017\n\nSpecifies the TCP port on which the MongoDB instance listens for client connections.\n\nAlternatively, you can also specify the port directly in the `URI connection string`. Providing a connection string while also using `--port` and specifying conflicting information will result in an error.\n\n`--ssl`\nEnables connection to a `mongod` or `mongos` that has TLS/SSL support enabled.\n\nAlternatively, you can also configure TLS/SSL support directly in the `URI connection string`. Providing a connection string while also using `--ssl` and specifying conflicting information will result in an error.\n\nFor more information about TLS/SSL and MongoDB, see Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients.\n\n`--sslCAFile=`\nSpecifies the .pem file that contains the root certificate chain from the Certificate Authority. Specify the file name of the .pem file using relative or absolute paths.\n\nAlternatively, you can also specify the `.pem` file directly in the `URI connection string`. Providing a connection string while also using `--sslCAFile` and specifying conflicting information will result in an error.\n\nFor more information about TLS/SSL and MongoDB, see Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients.\n\n`--sslPEMKeyFile=`\nSpecifies the .pem file that contains both the TLS/SSL certificate and key. Specify the file name of the .pem file using relative or absolute paths.\n\nThis option is required when using the `--ssl` option to connect to a `mongod` or `mongos` that has `CAFile` enabled *without*\n`allowConnectionsWithoutCertificates`.\n\nAlternatively, you can also specify the `.pem` file directly in the `URI connection string`. Providing a connection string while also using `--sslPEMKeyFile` and specifying conflicting information will result in an error.\n\nFor more information about TLS/SSL and MongoDB, see Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients.\n\n`--sslPEMKeyPassword=`\nSpecifies the password to de-crypt the certificate-key file (i.e. `--sslPEMKeyFile`). Use the `--sslPEMKeyPassword` option only if the certificate-key file is encrypted. In all cases, the `mongoimport` redacts the password from all logging and reporting output.\n\nIf the private key in the PEM file is encrypted and you do not specify the `--sslPEMKeyPassword` option, the `mongoimport` prompts for a passphrase. See TLS/SSL Certificate Passphrase.\n\nAlternatively, you can also specify the password directly in the `URI connection string`. Providing a connection string while also using `--sslPEMKeyPassword` and specifying conflicting information will result in an error."} -{"chunk_id": "68a95be15e79d242619d802b-2", "page_id": "68a95be15e79d242619d802b", "source_name": "database-tools", "product_name": "MongoDB Database Tools", "url": "https://mongodb.com/docs/database-tools/mongoimport", "title": "`mongoimport`", "text": "For more information about TLS/SSL and MongoDB, see Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients.\n\nOn some systems, a password provided directly using the `--sslPEMKeyPassword` option may be visible to system status programs such as `ps` that may be invoked by other users. Consider using the `--config` option to specify a configuration file containing the password instead.\n\n`--sslCRLFile=`\nSpecifies the .pem file that contains the Certificate Revocation List. Specify the file name of the .pem file using relative or absolute paths.\n\nFor more information about TLS/SSL and MongoDB, see Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients.\n\n`--sslAllowInvalidCertificates`\nBypasses the validation checks for server certificates and allows the use of invalid certificates. When using the `allowInvalidCertificates` setting, MongoDB logs a warning for invalid certificates.\n\nAlthough available, avoid using the `--sslAllowInvalidCertificates` option if possible. If the use of `--sslAllowInvalidCertificates` is necessary, only use the option on systems where intrusion is not possible.\n\nConnecting to a `mongod` or `mongos` instance without validating server certificates is a potential security risk. If you only need to disable the validation of the hostname in the TLS/SSL certificates, see `--sslAllowInvalidHostnames`.\n\nAlternatively, you can also disable certificate validation directly in the `URI connection string`. Providing a connection string while also using `--sslAllowInvalidCertificates` and specifying conflicting information will result in an error.\n\nFor more information about TLS/SSL and MongoDB, see Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients.\n\n`--sslAllowInvalidHostnames`\nDisables the validation of the hostnames in TLS/SSL certificates. Allows `mongoimport` to connect to MongoDB instances even if the hostname in their certificates do not match the specified hostname.\n\nAlternatively, you can also disable hostname validation directly in the `URI connection string`. Providing a connection string while also using `--sslAllowInvalidHostnames` and specifying conflicting information will result in an error.\n\nFor more information about TLS/SSL and MongoDB, see Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients.\n\n`--username=, -u=`\n\nSpecifies a username with which to authenticate to a MongoDB database that uses authentication. Use in conjunction with the `--password` and `--authenticationDatabase` options.\n\nAlternatively, you can also specify the username directly in the `URI connection string`. Providing a connection string while also using `--username` and specifying conflicting information will result in an error.\n\nIf connecting to a MongoDB Atlas cluster using the `MONGODB-AWS` `authentication mechanism`, you can specify your AWS access key ID in:\n\n- this field,\n\n- the `connection string`, or\n\n- the `AWS_ACCESS_KEY_ID` environment variable.\n\nSee Connect to a MongoDB Atlas Cluster using AWS IAM Credentials for an example of each.\n\n`--password=, -p=`\n\nSpecifies a password with which to authenticate to a MongoDB database that uses authentication. Use in conjunction with the `--username` and `--authenticationDatabase` options.\n\nTo prompt the user for the password, pass the `--username` option without `--password` or specify an empty string as the `--password` value, as in `--password \"\"` .\n\nAlternatively, you can also specify the password directly in the `URI connection string`. Providing a connection string while also using `--password` and specifying conflicting information will result in an error.\n\nIf connecting to a MongoDB Atlas cluster using the `MONGODB-AWS` `authentication mechanism`, you can specify your AWS secret access key in:\n\n- this field,\n\n- the `connection string`, or\n\n- the `AWS_SECRET_ACCESS_KEY` environment variable.\n\nSee Connect to a MongoDB Atlas Cluster using AWS IAM Credentials for an example of each.\n\nOn some systems, a password provided directly using the `--password` option may be visible to system status programs such as `ps` that may be invoked by other users. Consider instead:\n\n- omitting the `--password` option to receive an interactive password prompt, or\n\n- using the `--config` option to specify a configuration file containing the password.\n\n`--awsSessionToken=`\nIf connecting to a MongoDB Atlas cluster using the `MONGODB-AWS` `authentication mechanism`, and using session tokens in addition to your AWS access key ID and secret access key, you can specify your AWS session token in:\n\n- this field,\n\n- the `AWS_SESSION_TOKEN` `authMechanismProperties` parameter to the `connection string`, or\n\n- the `AWS_SESSION_TOKEN` environment variable.\n\nSee Connect to a MongoDB Atlas Cluster using AWS IAM Credentials for an example of each.\n\nOnly valid when using the `MONGODB-AWS`\n`authentication mechanism`.\n\n`--authenticationDatabase=`\nSpecifies the authentication database where the specified `--username` has been created. See Authentication Database.\n\nIf you use the GSSAPI (Kerberos), PLAIN (LDAP SASL), or `MONGODB-AWS`\n`authentication mechanisms`, you must set `--authenticationDatabase` to `$external`.\n\nAlternatively, you can also specify the authentication database directly in the `URI connection string`. Providing a connection string while also using `--authenticationDatabase` and specifying conflicting information will result in an error.\n\n`--authenticationMechanism=`\n*Default*: SCRAM-SHA-1\n\nSpecifies the authentication mechanism the `mongoimport` instance uses to authenticate to the `mongod` or `mongos`.\n\nStarting in version `100.1.0`, `mongoimport` adds support for the `MONGODB-AWS` authentication mechanism when connecting to a MongoDB Atlas cluster.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nValue\n\n\nDescription\n\n
\nSCRAM-SHA-1\n\n\nRFC 5802 standard Salted Challenge Response Authentication Mechanism using the SHA-1 hash function.\n\n
\nSCRAM-SHA-256\n\n\nRFC 7677 standard Salted Challenge Response Authentication Mechanism using the SHA-256 hash function.\n\nRequires featureCompatibilityVersion set to `4.0`.\n\n
\nMONGODB-X.509\n\n\nMongoDB TLS/SSL certificate authentication.\n\n
\n`MONGODB-AWS`\n\n\nExternal authentication using AWS IAM credentials for use in connecting to a MongoDB Atlas cluster. See Connect to a MongoDB Atlas Cluster using AWS IAM Credentials.\n\n
\nGSSAPI (Kerberos)\n\n\nExternal authentication using Kerberos. This mechanism is available only in MongoDB Enterprise.\n\n
\nPLAIN (LDAP SASL)\n\n\nExternal authentication using LDAP. You can also use `PLAIN` for authenticating in-database users. `PLAIN` transmits passwords in plain text. This mechanism is available only in MongoDB Enterprise.\n\n
Alternatively, you can also specify the authentication mechanism directly in the `URI connection string`. Providing a connection string while also using `--authenticationMechanism` and specifying conflicting information will result in an error.\n\n`--gssapiServiceName=`\nSpecify the name of the service using GSSAPI/Kerberos. Only required if the service does not use the default name of `mongodb`.\n\nThis option is available only in MongoDB Enterprise.\n\n`--gssapiHostName=`\nSpecify the hostname of a service using GSSAPI/Kerberos. *Only* required if the hostname of a machine does not match the hostname resolved by DNS.\n\nThis option is available only in MongoDB Enterprise.\n\n`--db=, -d=`"} -{"chunk_id": "68a95be15e79d242619d802b-3", "page_id": "68a95be15e79d242619d802b", "source_name": "database-tools", "product_name": "MongoDB Database Tools", "url": "https://mongodb.com/docs/database-tools/mongoimport", "title": "`mongoimport`", "text": "Specifies the name of the database on which to run the `mongoimport`.\n\nAlternatively, you can also specify the database directly in the `URI connection string`. Providing a connection string while also using `--db` and specifying conflicting information will result in an error.\n\nIf you don't specify a database with the `--db` or `--uri` option, `mongoimport` uses the `test` database by default. If the `test` database doesn't exist, `mongoimport` creates the database.\n\n`--collection=, -c=`\n\nSpecifies the collection to import. If you do not specify `--collection`, `mongoimport` reads the collection name from the input filename, omitting the file's extension if it has one.\n\n`--fields=, -f=`\n\nSpecify a comma separated list of field names when importing CSV or TSV files that do not have field names in the first (i.e. header) line of the file.\n\nTo also specify the field type as well as the field name, use `--fields` with `--columnsHaveTypes`.\n\nIf you attempt to include `--fields` when importing JSON data, `mongoimport` returns an error. `--fields` is only for CSV or TSV imports.\n\n`--fieldFile=`\nAs an alternative to `--fields`, the `--fieldFile` option allows you to specify a file that holds a list of field names if your CSV or TSV file does not include field names in the first line of the file (i.e. header). Place one field per line.\n\nTo also specify the field type as well as the field name, use `--fieldFile` with `--columnsHaveTypes`.\n\nIf you attempt to include `--fieldFile` when importing JSON data, `mongoimport` returns an error. `--fieldFile` is only for CSV or TSV imports.\n\n`--ignoreBlanks`\nIgnores empty fields in CSV and TSV exports. If not specified, `mongoimport` creates fields without values in imported documents.\n\nIf you attempt to include `--ignoreBlanks` when importing JSON data, `mongoimport` returns an error. `--ignoreBlanks` is only for CSV or TSV imports.\n\n`--type=`\nSpecifies the file type to import. The default format is JSON, but it's possible to import CSV and TSV files.\n\nThe `csv` parser accepts that data that complies with RFC-4180. As a result, backslashes are *not* a valid escape character. If you use double-quotes to enclose fields in the CSV data, you must escape internal double-quote marks by prepending another double-quote.\n\n`--file=`\nSpecifies the location and name of a file containing the data to import. If you do not specify a file, `mongoimport` reads data from standard input (e.g. \"stdin\").\n\n`--drop`\nModifies the import process so that the target instance drops the collection and any associated indexes before importing data from the input.\n\n`--headerline`\nIf using `--type csv` or `--type tsv`, uses the first line as field names. Otherwise, `mongoimport` imports the first line as a distinct document.\n\nIf you attempt to include `--headerline` when importing JSON data, `mongoimport` returns an error. `--headerline` is only for CSV or TSV imports.\n\n`--useArrayIndexFields`\nInterpret natural numbers in fields as array indexes when importing CSV or TSV files.\n\nField names must be in the form `.` where `arrayIndex` is a natural number beginning with `0` and increasing sequentially by `1` for each member of the array.\n\nFor example, with the following CSV file:\n\n```javascript\na.0,a.1,a.2,a.3\nred,yellow,green,blue\n```\n\nAn import with the `--useArrayIndexFields` option would result in the following document:\n\n```javascript\n\"a\" : [ \"red\", \"yellow\", \"green\", \"blue\" ]\n```\n\nIf using the `--columnsHaveTypes` option as well, use the form `..()` to specify both the array index and type for each field. See `--columnsHaveTypes` for more information.\n\nNumerical keys with leading zeros (e.g. `a.000,a.001`) are not interpreted as array indexes.\n\nIf the first part of a key is a natural number (e.g. `0.a,1.a`), it is interpreted as a document key, and not an array index.\n\nIf using the `--ignoreBlanks` option with `--useArrayIndexFields`, `mongoimport` returns an error if you attempt to import a document that contains a blank value (e.g. `\"\"`) for an array index field.\n\nThe `--useArrayIndexFields` option has no effect when importing JSON data, as arrays are already encoded in JSON format.\n\n`--mode=`\n*Default*: insert\n\nSpecifies how the import process should handle existing documents in the database that match documents in the import file.\n\nBy default, `mongoimport` uses the `_id` field to match documents in the collection with documents in the import file. To specify the fields against which to match existing documents for the `upsert`, `merge`, and `delete` modes, use `--upsertFields`.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nValue\n\n\nDescription\n\n
\n`insert`\n\n\nInsert the documents in the import file. `mongoimport` returns an error if you attempt to import a document that contains a duplicate value for a field with a unique index, such as `_id`.\n\n
\n`upsert`\n\n\nReplace existing documents in the database with matching documents from the import file. `mongoimport` inserts all other documents. Replace Matching Documents during Import describes how to use `--mode` `upsert`.\n\n
\n`merge`\n\n\nMerge existing documents that match a document in the import file with the new document. `mongoimport` inserts all other documents. Merge Matching Documents during Import describes how to use `--mode`\n`merge`.\n\n
\n`delete`\n\n\nDelete existing documents in the database that match a document in the import file. `mongoimport` takes *no action* on non-matching documents. Delete Matching Documents describes how to use `--mode` `delete`.\n\n
`--upsertFields=`\nSpecifies a list of fields for the query portion of the import process. `--upsertFields` can be used with `--mode` `upsert`, `merge`, and `delete`.\n\nUse this option if the `_id` fields in the existing documents don't match the field in the document, but another field or field combination can uniquely identify documents as a basis for performing upsert operations.\n\nIf you do not specify a field, `--upsertFields` upserts on the basis of the `_id` field.\n\nTo ensure adequate performance, indexes should exist for the field or fields you specify with `--upsertFields`.\n\n`--stopOnError`\nForces `mongoimport` to halt the insert operation at the first error rather than continuing the operation despite errors.\n\nBy default, `mongoimport` continues an operation when it encounters duplicate key and document validation errors. To ensure that the program stops on these errors, specify `--stopOnError`.\n\n`--jsonArray`\nAccepts the import of data expressed with multiple MongoDB documents within a single JSON array. Limited to imports of 16 MB or smaller.\n\nUse `--jsonArray` in conjunction with `mongoexport --jsonArray`.\n\n`--legacy`\nIndicates that the import data is in Extended JSON v1 format instead of the default Extended JSON v2 format.\n\nIn general, the versions of `mongoexport` and `mongoimport` should match. That is, to import data created from `mongoexport`, you should use the corresponding version of `mongoimport`.\n\nFor example, if the import data is in v1 format:\n\n```javascript\n{\"_id\":1.0,\"myregfield\":{\"$regex\":\"foo\",\"$options\":\"i\"}}\n```\n\nImport without the `--legacy` option results in the following document in the collection:\n\n```javascript\n{ \"_id\" : 1, \"myregfield\" : { \"$regex\" : \"foo\", \"$options\" : \"i\" } }\n```\n\nImport with the `--legacy` results in the following document in the collection:\n\n```javascript\n{ \"_id\" : 1, \"myregfield\" : { \"$regularExpression\" : { \"pattern\" : \"foo\", \"options\" : \"i\" } } }\n```\n\n`--maintainInsertionOrder`\n*Default*: false"} -{"chunk_id": "68a95be15e79d242619d802b-4", "page_id": "68a95be15e79d242619d802b", "source_name": "database-tools", "product_name": "MongoDB Database Tools", "url": "https://mongodb.com/docs/database-tools/mongoimport", "title": "`mongoimport`", "text": "If specified, `mongoimport` inserts the documents in the order of their appearance in the input source. That is, both the bulk write batch order and document order within the batches are maintained.\n\nSpecifying `--maintainInsertionOrder` also enables `--stopOnError` and sets `numInsertionWorkers` to 1.\n\nIf unspecified, `mongoimport` may perform the insertions in an arbitrary order.\n\n`--numInsertionWorkers=`\n*Default*: 1\n\nSpecifies the number of insertion workers to run concurrently.\n\nFor large imports, increasing the number of insertion workers may increase the speed of the import.\n\n`--writeConcern=`\n*Default*: majority\n\nSpecifies the write concern for each write operation that `mongoimport` performs.\n\nSpecify the write concern as a document with w options:\n\n```sh\n--writeConcern \"{w:'majority'}\"\n```\n\nIf the write concern is also included in the `--uri connection string`, the command-line `--writeConcern` overrides the write concern specified in the URI string.\n\n`--bypassDocumentValidation`\nEnables `mongoimport` to bypass document validation during the operation. This lets you insert documents that do not meet the validation requirements.\n\n`--columnsHaveTypes`\nInstructs `mongoimport` that the field list specified in `--fields`, `--fieldFile`, or `--headerline` specifies the types of each field.\n\nField names must be in the form of `.()`. You must backslash-escape the following characters if you wish to include them in an argument: `(`, `)`, and `\\`.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n`type`\n\n\nSupported Arguments\n\n\nExample Header Field\n\n
\n`auto()`\n\n\nNone.\n\n\n`misc.auto()`\n\n
\n`binary()`\n\n\n- `base32` (RFC4648 encoding schema)\n\n- `base64` (RFC4648 encoding schema)\n\n- `hex`\n\n\n`user thumbnail.binary(base64)`\n\n
\n`boolean()`\n\n\nNone.\n\n\n`verified.boolean()`\n\n
\n`date()`\n\n\nAlias for `date_go()`. Go Language time.Parse format.\n\n\n`created.date(2006-01-02 15:04:05)`\n\n
\n`date_go()`\n\n\nGo Language time.Parse format\n\n\n`created.date_go(2006-01-02T15:04:05Z)`\n\n
\n`date_ms()`\n\n\nMicrosoft SQL Server FORMAT format\n\n\n`created.date_ms(yyyy-MM-dd H:mm:ss)`\n\n
\n`date_oracle()`\n\n\nOracle Database TO_DATE format.\n\n\n`created.date_oracle(YYYY-MM-DD HH24:MI:SS)`\n\n
\n`decimal()`\n\n\nNone\n\n\n`price.decimal()`\n\n
\n`double()`\n\n\nNone.\n\n\n`revenue.double()`\n\n
\n`int32()`\n\n\nNone.\n\n\n`followerCount.int32()`\n\n
\n`int64()`\n\n\nNone.\n\n\n`bigNumber.int64()`\n\n
\n`string()`\n\n\nNone.\n\n\n`zipcode.string()`\n\n
See Import CSV with Specified Field Types for sample usage.\n\nIf you attempt to include `--columnsHaveTypes` when importing JSON data, `mongoimport` returns an error. `--columnsHaveTypes` is only for CSV or TSV imports.\n\n`--parseGrace=`\n*Default*: stop\n\nSpecifies how `mongoimport` handles type coercion failures when importing CSV or TSV files with `--columnsHaveTypes`.\n\n`--parseGrace` has no effect when importing JSON documents.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nValue\n\n\nDescription\n\n
\n`autoCast`\n\n\nAssigns a type based on the value of the field. For example, if a field is defined as a `double` and the value for that field was `\"foo\"`, `mongoimport` would make that field value a string type.\n\n
\n`skipField`\n\n\nFor the row being imported, `mongoimport` does not include the field whose type does not match the expected type.\n\n
\n`skipRow`\n\n\n`mongoimport` does not import rows containing a value whose type does not match the expected type.\n\n
\n`stop`\n\n\n`mongoimport` returns an error that ends the import.\n\n
\n\n## Learn More\n\n- mongoimport Compatibility and Installation\n\n- mongoimport Behavior\n\n- mongoimport Examples\n\n- MongoDB Compass Import and Export"} -{"chunk_id": "68a95be15e79d242619d8013-0", "page_id": "68a95be15e79d242619d8013", "source_name": "database-tools", "product_name": "MongoDB Database Tools", "url": "https://mongodb.com/docs/database-tools/mongodump/mongodump-behavior", "title": "mongodump Behavior, Access, and Usage", "text": "# mongodump Behavior, Access, and Usage\n\n\u27a4`mongodump`Connect to a MongoDB Atlas Cluster using AWS IAM CredentialsWhen dumping to a case-insensitive file system such as Windows or macOS, collections with names that differ only by capitalization will be overwritten. For case-insensitive file systems, always use the --archive option.\n\nStarting in MongoDB 5.0, document field names can be prefixed with a dollar character (`$`). However, `mongodump` and `mongorestore` won't work with field names that are prefixed with a dollar character in a collection's options.\n\nMongoDB Extended JSON (v2) cannot differentiate between type wrappers and fields that have the same name as type wrappers. Don't use extended JSON formats if the corresponding BSON representation might include `$` prefixed keys. The DBRefs mechanism is an exception to this general rule.\n\n## Behavior\n\n### Using `mongodump` Without an `authSource`\n\nWhen `authSource` is not specified in the MongoDB URI, the database name specified in `--db` is used both to authenticate your `mongodump` session and to indicate the database being dumped. For an example of using a different database for authentication when using `mongodump`, see Authenticating with a Specific Database.\n\n### Restore to Matching Server Version\n\nWhen using `mongorestore` to load data files created by `mongodump`, the MongoDB versions of your source and destination deployments must be either:\n\n- The same major version.\n\n- The same feature compatibility version.\n\nFor example, if your dump was created from a MongoDB deployment running version `4.4`, the MongoDB deployment you restore to must also run version `4.4` or have its FCV set to `4.4`.\n\nTo change your feature compatibility version, see `setFeatureCompatibilityVersion`.\n\nYou can restore the BSON files generated from `mongodump` into MongoDB deployments running the same or newer version as the source deployment. However, restoring files into a newer version deployment is not the recommended way to upgrade your deployment. To learn how to upgrade your deployment, see the upgrade documentation.\n\nThis guarantee does not apply to metadata, archive, or oplog replay files. If you try to restore these files using different source and destination deployment versions, the `mongorestore` process could result in failure, silent failure, or corrupted metadata.\n\nIn addition, ensure that you are using the same version of `mongorestore` to load the data files as the version of `mongodump` that you used to create them. In practice, using a different version of `mongorestore` often works, but if the dump format changes between versions, the restore can fail or restore data incorrectly. For example, if you use `mongodump` version `100.19.1` to create the dump, use `mongorestore` version `100.19.1` to restore it.\n\n### Time Series Collections\n\nTo dump time series collections from a MongoDB 9.0 deployment, use Database Tools 100.16.0 or later. Earlier Database Tools versions read time series bucket namespaces directly, which MongoDB 9.0 doesn't allow. If you use an earlier Database Tools version, `mongodump` aborts with a `CommandNotSupportedOnLegacyTimeseriesBucketsNamespace` error. To resolve the error, upgrade to the latest Database Tools version.\n\nIf a time series format conversion starts while `mongodump` reads a time series collection, the operation fails with an `InterruptedDueToTimeseriesUpgradeDowngrade` error. The dump isn't truncated or corrupted. To resolve the error, wait for the feature compatibility version (FCV) change to finish, then run `mongodump` again. To learn more about the conversion, see Oplog Replay Across a Time Series Format Conversion.\n\n### Read Preference\n\nBy default, `mongodump` uses read preference `primary`. To override the default, you can specify the read preference in the `--readPreference` command-line option or in the `--uri connection string`.\n\nIf read preference is specified in both the URI string and the `--readPreference` option, the `--readPreference` value overrides the read preference specified in the URI string.\n\n### Data Exclusion\n\nIf you specify both the `--db` and the `--collection` options, `mongodump` dumps the specified collection.\n\nIf you only specify the `--db` option, `mongodump` dumps that database with the following exclusions:\n\n- If the value of `--db` is `admin`:\n\n - If you aren't connected to an Atlas Proxy, `mongodump` dumps the database but excludes the `system.keys` collection.\n\n - If you're connected to an Atlas Proxy, `mongodump` attempts to dump the database but errors out.\n\n- If the value of `--db` is `config`, `mongodump` dumps all collections in that database.\n\n- If the value of `--db` is `local`, `mongodump` dumps all collections in that database.\n\n- For all other databases, `mongodump` excludes all collections that start with `system.`, except for `system.js`.\n\nIf you omit the `--db` option, the following exclusions apply:\n\n- `mongodump` excludes the `local` database.\n\n- `mongodump` only includes the following collections in the output for the `config` database:\n\n - `chunks`\n\n - `collections`\n\n - `databases`\n\n - `settings`\n\n - `shards`\n\n - `tags`\n\n - `version`\n\n- If you're connected to an Atlas Proxy, `mongodump` excludes the `admin` database.\n\n`mongodump` output:\n\n- Contains the documents in the database and the index definitions.\n\n- Does not contain the index data.\n\n`mongorestore` or `mongod` must rebuild the indexes after restoring data.\n\nIf you're using views:\n\n- By default, `mongodump` only exports a view's metadata. `mongodump` doesn't create a binary export of the documents included in the view.\n\n- To export the documents in a view, use `--viewsAsCollections`.\n\n### Metadata Output\n\nIf `mongodump` outputs to a directory, the output contains collection metadata which includes the following properties:\n\n- Collection names\n\n- Collection types\n\n- Collection configuration options\n\n- UUIDs\n\n- Indexes\n\nIf `mongodump` outputs to standard output (`stdout`), the output does not include metadata. For more information, see the `--out` option.\n\n### Metadata Format\n\n`mongodump` uses Extended JSON v2.0 (Canonical) format for the metadata files. To parse these files for restore, use `mongorestore`, which supports Extended JSON v2.0 (Canonical or Relaxed mode) format.\n\n### Overwrite Files\n\n`mongodump` overwrites output files if they exist in the backup data folder. Before running the `mongodump` command multiple times, either ensure that you no longer need the files in the output folder (the default is the `dump/` folder) or rename the folders or files.\n\n### `mongodump` During Resharding\n\n`mongodump` fails if:\n\n- `mongodump` is initiated when a resharding operation is in progress.\n\n- The `reshardCollection` command is run during a `mongodump` operation.\n\n### Data Compression Handling\n\nWhen run on a `mongod` instance that uses the WiredTiger storage engine, `mongodump` outputs uncompressed data.\n\n### Working Set\n\n`mongodump` can adversely affect performance of the `mongod`. If your data is larger than system memory, `mongodump` will push the working set out of memory.\n\n### FIPS\n\n`mongodump` automatically creates FIPS-compliant connections to a `mongod` or `mongos` that are configured to use FIPS mode.\n\n### Using `mongodump` on Atlas Free and Shared Tier Clusters\n\nOn free (`M0`) and shared (`M2` and `M5`) tier Atlas clusters, the following limitations apply:\n\n- You can't run `mongodump` on the `admin` database. By default, `mongodump` skips this database. If you use the `--db` option to set the destination database to `admin`, the program returns an error.\n\n- You can't use the following options with the `mongodump` program:\n\n - `--dumpDbUsersAndRoles`\n\n - `--oplog`"} -{"chunk_id": "68a95be15e79d242619d8013-1", "page_id": "68a95be15e79d242619d8013", "source_name": "database-tools", "product_name": "MongoDB Database Tools", "url": "https://mongodb.com/docs/database-tools/mongodump/mongodump-behavior", "title": "mongodump Behavior, Access, and Usage", "text": "### Using mongodump on Atlas Infinite Database Clusters\n\n`mongodump` supports the `--oplog` option when you dump data from an Atlas Infinite Database cluster. Oplog replay is not supported with Atlas Infinite Database clusters. For details, see mongorestore Behavior, Access, and Usage.\n\nIf the cluster undergoes a rollback during the restore process, delete all restored or imported data and redo the process from the beginning. See the rollback documentation for more details.\n\n## Required Access\n\nTo run `mongodump` against a MongoDB deployment that has access control enabled, you must have privileges that grant `find` action for each database to back up. The built-in `backup` role provides the required privileges to perform backup of any and all databases.\n\n## Usage in Backup Strategy\n\n### Standalone Deployments and Replica Sets\n\nFor standalone or a replica set, `mongodump` can be a part of a backup strategy with `mongorestore` for partial backups based on a query, syncing from production to staging or development environments, or changing the storage engine of a standalone.\n\nFor details on using `mongodump` with `mongorestore` as part of a backup and recovery strategy, see:\n\n- Back Up and Restore with MongoDB Tools\n\n- MongoDB Backup Methods\n\n### Sharded Clusters\n\nTo use `mongodump` and `mongorestore` as a backup strategy for sharded clusters, see Back Up a Self-Managed Sharded Cluster with a Database Dump.\n\nSharded clusters can also use one of the following coordinated backup and restore processes, which guarantee atomicity across shards while still accepting writes:\n\n- MongoDB Atlas\n\n- MongoDB Cloud Manager\n\n- MongoDB Ops Manager\n\n## Learn More\n\n- `mongodump`\n\n- mongodump Compatibility and Installation\n\n- mongodump Examples"} -{"chunk_id": "68a95be15e79d242619d8032-0", "page_id": "68a95be15e79d242619d8032", "source_name": "database-tools", "product_name": "MongoDB Database Tools", "url": "https://mongodb.com/docs/database-tools/mongofiles", "title": "`mongofiles`", "text": "`mongofiles`\n`mongofiles`\n\n# `mongofiles`\n\nMongoDB Command Line Database Tool binaries are not supported or tested for use with non-genuine MongoDB deployments. While the tools may work on these deployments, compatibility is not guaranteed.\u27a4`mongofiles`Connect to a MongoDB Atlas Cluster using AWS IAM Credentials## Synopsis\n\nThe `mongofiles` utility makes it possible to manipulate files stored in your MongoDB instance in GridFS objects from the command line. It is particularly useful as it provides an interface between objects stored in your file system and GridFS.\n\nRun `mongofiles` from the system command line, not the `mongo` shell.\n\n### Versioning\n\n`mongofiles` is now released separately from the MongoDB Server and uses its own versioning, with an initial version of `100.0.0`. Previously, `mongofiles` was released alongside the MongoDB Server and used matching versioning.\n\n- MongoDB 4.2 mongofiles\n\n- MongoDB 4.0 mongofiles\n\nThis documentation is for version `100.19.1` of `mongofiles`.\n\n## Compatibility\n\n### MongoDB Server Compatibility\n\n`mongofiles` version `100.19.1` supports the following versions of the MongoDB Server:\n\n- MongoDB 9.0\n\n- MongoDB 8.3\n\n- MongoDB 8.2\n\n- MongoDB 8.1\n\n- MongoDB 8.0\n\n- MongoDB 7.0\n\n- MongoDB 6.0\n\n- MongoDB 5.0\n\n- MongoDB 4.4\n\n- MongoDB 4.2\n\n`mongofiles` does not support MongoDB Server versions earlier than 4.2. Attempts to connect to an earlier Server version fail.\n\n### Platform Support\n\n`mongofiles` version `100.19.1` is supported on the following platforms:\n\n\u2713\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n\n\nx86_64\n\n\nARM64\n\n\nPPC64LE\n\n\ns390x\n\n
\nAmazon Linux 2023\n\n\n\u2713\n\n\n\u2713\n\n\n\n\n\n
\nAmazon 2\n\n\n\u2713\n\n\n\u2713\n\n\n\n\n\n
\nDebian 12\n\n\n\u2713\n\n\n\n\n\n\n\n
\nDebian 11\n\n\n\u2713\n\n\n\n\n\n\n\n
\nDebian 10\n\n\n\u2713\n\n\n\n\n\n\n\n
\nDebian 9\n\n\n\u2713\n\n\n\n\n\n\n\n
\nRHEL (Red Hat Enterprise Linux) / CentOS 9\n\n\n\u2713\n\n\n\u2713\n\n\n\u2713\n\n\n\u2713\n\n
\nRHEL (Red Hat Enterprise Linux) / CentOS 8\n\n\n\u2713\n\n\n\n\n\u2713\n\n\n\u2713\n\n
\nRHEL (Red Hat Enterprise Linux) / CentOS 7\n\n\n\u2713\n\n\n\n\n\u2713\n\n\n\u2713\n\n
\nRHEL (Red Hat Enterprise Linux) / CentOS 6\n\n\n\u2713\n\n\n\n\n\n\n\n
\nSUSE 15\n\n\n\u2713\n\n\n\n\n\n\n\n
\nSUSE 12\n\n\n\u2713\n\n\n\n\n\n\n\n
\nUbuntu 24.04\n\n\n\u2713\n\n\n\u2713\n\n\n\n\n\n
\nUbuntu 22.04\n\n\n\u2713\n\n\n\u2713\n\n\n\n\n\n
\nUbuntu 20.04\n\n\n\u2713\n\n\n\u2713\n\n\n\n\n\n
\nUbuntu 18.04\n\n\n\u2713\n\n\n\u2713\n\n\n\n\n\n
\nUbuntu 16.04\n\n\n\u2713\n\n\n\u2713\n\n\n\u2713\n\n\n\n
\nWindows 11 and later\n\n\n\u2713\n\n\n\n\n\n\n\n
\nWindows Server 2016 and later\n\n\n\u2713\n\n\n\n\n\n\n\n
\nmacOS 11 and later\n\n\n\u2713\n\n\n\u2713\n\n\n\n\n\n
\nmacOS 10.12 - 10.15\n\n\n\u2713\n\n\n\n\n\n\n\n
\n\n## Installation\n\nThe `mongofiles` tool is part of the *MongoDB Database Tools* package:\n\n\u27a4 Follow the Database Tools Installation Guide to install `mongofiles`.\n\n## Syntax\n\nThe `mongofiles` command has the following form:\n\n```sh\nmongofiles \n```\n\nRun `mongofiles` from the system command line, not the `mongo` shell.\n\nThe components of the `mongofiles` command are:\n\n1. Options. You may use one or more of these options to control the behavior of `mongofiles`.\n\n2. `Connection String`. The connection string of the `mongod` / `mongos` to connect to with `mongofiles`.\n\n3. Command. Use one of these commands to determine the action of `mongofiles`.\n\n4. An identifier which is either: the name of a file on your local file system, or a GridFS object.\n\nFor replica sets, `mongofiles` can only read from the set's primary.\n\n## Required Access\n\nIn order to connect to a `mongod` that enforces authorization with the `--auth` option, you must use the `--username` and `--password` options. The connecting user must possess, at a minimum:\n\n- the `read` role for the accessed database when using the `list`, `search` or `get` commands,\n\n- the `readWrite` role for the accessed database when using the `put` or `delete` commands.\n\n## Behavior\n\n### FIPS\n\n`mongofiles` automatically creates FIPS-compliant connections to a `mongod`/`mongos` that is configured to use FIPS mode.\n\n### Read Preference\n\nBy default, `mongofiles` uses read preference `primary`. To override the default, you can specify the read preference in the `--readPreference` command line option or in the `--uri connection string`.\n\nIf you specify read preference in the URI string and the `--readPreference`, the `--readPreference` value overrides the read preference specified in the URI string.\n\n### Write Concern\n\nYou can specify both the `--writeConcern` and the `--uri connection string` option. If write concern is specified using both options, the `--writeConcern` value overrides the write concern specified in the URI string."} -{"chunk_id": "68a95be15e79d242619d8032-1", "page_id": "68a95be15e79d242619d8032", "source_name": "database-tools", "product_name": "MongoDB Database Tools", "url": "https://mongodb.com/docs/database-tools/mongofiles", "title": "`mongofiles`", "text": "## Options\n\n`--help`\nReturns information on the options and use of `mongofiles`.\n\n`--verbose, -v`\n\nIncreases the amount of internal reporting returned on standard output or in log files. Increase the verbosity with the `-v` form by including the option multiple times, (e.g. `-vvvvv`.)\n\n`--quiet`\nRuns `mongofiles` in a quiet mode that attempts to limit the amount of output.\n\nThis option suppresses:\n\n- output from database commands\n\n- replication activity\n\n- connection accepted events\n\n- connection closed events\n\n`--version`\nReturns the `mongofiles` release number.\n\n`--config=`\nSpecifies the full path to a YAML configuration file that contains sensitive values for the following `mongofiles` options:\n\n- `--password`\n\n- `--uri`\n\n- `--sslPEMKeyPassword`\n\nThis is the recommended way to specify a password to `mongofiles`, aside from specifying it through a password prompt. You can use any combination of the arguments in the file.\n\nThe configuration file takes the following form:\n\n```sh\npassword: \nuri: mongodb://mongodb0.example.com:27017\nsslPEMKeyPassword: \n```\n\nIf you specify the `password` option without specifying `uri`, you can specify the other components of the connection string by using `mongofiles` command line options, such as `--username` and `--host`.\n\nBe sure to secure this file with appropriate filesystem permissions.\n\nWhen using the `--config` option, keep the following limitations and behaviors in mind:\n\n- If you provide the `password` field and provide a connection string in the `uri` field with a conflicting password, `mongorestore` throws an error.\n\n- If you specify a configuration file with `--config` and also use the `--password`, `--uri`, or `--sslPEMKeyPassword`\n `mongofiles` command line options, the command line option overrides the corresponding configuration file option.\n\n`--uri=`\nSpecifies the resolvable URI connection string of the MongoDB deployment, enclosed in quotes:\n\n```none\n--uri=\"mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]\"\n```\n\nStarting with version `100.0` of `mongofiles`, the connection string may alternatively be provided as a positional parameter, without using the `--uri` option:\n\n```none\nmongofiles mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]\n```\n\nAs a positional parameter, the connection string may be specified at any point on the command line, as long as it begins with either `mongodb://` or `mongodb+srv://`. For example:\n\n```none\nmongofiles --username joe --password secret1 mongodb://mongodb0.example.com:27017 --ssl\n```\n\nOnly one connection string can be provided. Attempting to include more than one, whether using the `--uri` option or as a positional argument, will result in an error.\n\nFor information on the components of the connection string, see the Connection String URI Format documentation.\n\nSome components in the `connection string` may alternatively be specified using their own explicit command-line options, such as `--username` and `--password`. Providing a connection string while also using an explicit option and specifying conflicting information will result in an error.\n\nIf using `mongofiles` on Ubuntu 18.04, you may experience a `cannot unmarshal DNS` error message when using SRV connection strings (in the form `mongodb+srv://`) with the `--uri` option. If so, use one of the following options instead:\n\n- the `--uri` option with a non-SRV connection string (in the form `mongodb://`)\n\n- the `--host` option to specify the host to connect to directly\n\nOn some systems, a password provided in a connection string with the `--uri` option may be visible to system status programs such as `ps` that may be invoked by other users. Consider instead:\n\n- omitting the password in the connection string to receive an interactive password prompt, or\n\n- using the `--config` option to specify a configuration file containing the password.\n\n`--host=<:port>`\nSpecifies a resolvable hostname for the `mongod` that holds your GridFS system. By default `mongofiles` attempts to connect to a MongoDB process running on the localhost port number `27017`.\n\nOptionally, specify a port number to connect a MongoDB instance running on a port other than 27017.\n\nAlternatively, you can also specify the hostname directly in the `URI connection string`. Providing a connection string while also using `--host` and specifying conflicting information will result in an error.\n\n`--port=`\n*Default*: 27017\n\nSpecifies the TCP port on which the MongoDB instance listens for client connections.\n\nAlternatively, you can also specify the port directly in the `URI connection string`. Providing a connection string while also using `--port` and specifying conflicting information will result in an error.\n\n`--ssl`\nEnables connection to a `mongod` or `mongos` that has TLS/SSL support enabled.\n\nAlternatively, you can also configure TLS/SSL support directly in the `URI connection string`. Providing a connection string while also using `--ssl` and specifying conflicting information will result in an error.\n\nFor more information about TLS/SSL and MongoDB, see Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients.\n\n`--sslCAFile=`\nSpecifies the .pem file that contains the root certificate chain from the Certificate Authority. Specify the file name of the .pem file using relative or absolute paths.\n\nAlternatively, you can also specify the `.pem` file directly in the `URI connection string`. Providing a connection string while also using `--sslCAFile` and specifying conflicting information will result in an error.\n\nFor more information about TLS/SSL and MongoDB, see Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients.\n\n`--sslPEMKeyFile=`\nSpecifies the .pem file that contains both the TLS/SSL certificate and key. Specify the file name of the .pem file using relative or absolute paths.\n\nThis option is required when using the `--ssl` option to connect to a `mongod` or `mongos` that has `CAFile` enabled *without*\n`allowConnectionsWithoutCertificates`.\n\nAlternatively, you can also specify the `.pem` file directly in the `URI connection string`. Providing a connection string while also using `--sslPEMKeyFile` and specifying conflicting information will result in an error.\n\nFor more information about TLS/SSL and MongoDB, see Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients.\n\n`--sslPEMKeyPassword=`\nSpecifies the password to de-crypt the certificate-key file (i.e. `--sslPEMKeyFile`). Use the `--sslPEMKeyPassword` option only if the certificate-key file is encrypted. In all cases, the `mongofiles` will redact the password from all logging and reporting output.\n\nIf the private key in the PEM file is encrypted and you do not specify the `--sslPEMKeyPassword` option, the `mongofiles` will prompt for a passphrase. See TLS/SSL Certificate Passphrase.\n\nAlternatively, you can also specify the password directly in the `URI connection string`. Providing a connection string while also using `--sslPEMKeyPassword` and specifying conflicting information will result in an error.\n\nFor more information about TLS/SSL and MongoDB, see Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients.\n\nOn some systems, a password provided directly using the `--sslPEMKeyPassword` option may be visible to system status programs such as `ps` that may be invoked by other users. Consider using the `--config` option to specify a configuration file containing the password instead.\n\n`--sslCRLFile=`\nSpecifies the .pem file that contains the Certificate Revocation List. Specify the file name of the .pem file using relative or absolute paths.\n\nFor more information about TLS/SSL and MongoDB, see Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients."} -{"chunk_id": "68a95be15e79d242619d8032-2", "page_id": "68a95be15e79d242619d8032", "source_name": "database-tools", "product_name": "MongoDB Database Tools", "url": "https://mongodb.com/docs/database-tools/mongofiles", "title": "`mongofiles`", "text": "`--sslAllowInvalidCertificates`\nBypasses the validation checks for server certificates and allows the use of invalid certificates. When using the `allowInvalidCertificates` setting, MongoDB logs as a warning the use of the invalid certificate.\n\nAlthough available, avoid using the `--sslAllowInvalidCertificates` option if possible. If the use of `--sslAllowInvalidCertificates` is necessary, only use the option on systems where intrusion is not possible.\n\nConnecting to a `mongod` or `mongos` instance without validating server certificates is a potential security risk. If you only need to disable the validation of the hostname in the TLS/SSL certificates, see `--sslAllowInvalidHostnames`.\n\nAlternatively, you can also disable certificate validation directly in the `URI connection string`. Providing a connection string while also using `--sslAllowInvalidCertificates` and specifying conflicting information will result in an error.\n\nFor more information about TLS/SSL and MongoDB, see Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients.\n\n`--sslAllowInvalidHostnames`\nDisables the validation of the hostnames in TLS/SSL certificates. Allows `mongofiles` to connect to MongoDB instances even if the hostname in their certificates do not match the specified hostname.\n\nAlternatively, you can also disable hostname validation directly in the `URI connection string`. Providing a connection string while also using `--sslAllowInvalidHostnames` and specifying conflicting information will result in an error.\n\nFor more information about TLS/SSL and MongoDB, see Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients.\n\n`--username=, -u=`\n\nSpecifies a username with which to authenticate to a MongoDB database that uses authentication. Use in conjunction with the `--password` and `--authenticationDatabase` options.\n\nAlternatively, you can also specify the username directly in the `URI connection string`. Providing a connection string while also using `--username` and specifying conflicting information will result in an error.\n\nIf connecting to a MongoDB Atlas cluster using the `MONGODB-AWS` `authentication mechanism`, you can specify your AWS access key ID in:\n\n- this field,\n\n- the `connection string`, or\n\n- the `AWS_ACCESS_KEY_ID` environment variable.\n\nSee Connect to a MongoDB Atlas Cluster using AWS IAM Credentials for an example of each.\n\n`--password=, -p=`\n\nSpecifies a password with which to authenticate to a MongoDB database that uses authentication. Use in conjunction with the `--username` and `--authenticationDatabase` options.\n\nTo prompt the user for the password, pass the `--username` option without `--password` or specify an empty string as the `--password` value, as in `--password \"\"` .\n\nAlternatively, you can also specify the password directly in the `URI connection string`. Providing a connection string while also using `--password` and specifying conflicting information will result in an error.\n\nIf connecting to a MongoDB Atlas cluster using the `MONGODB-AWS` `authentication mechanism`, you can specify your AWS secret access key in:\n\n- this field,\n\n- the `connection string`, or\n\n- the `AWS_SECRET_ACCESS_KEY` environment variable.\n\nSee Connect to a MongoDB Atlas Cluster using AWS IAM Credentials for an example of each.\n\nOn some systems, a password provided directly using the `--password` option may be visible to system status programs such as `ps` that may be invoked by other users. Consider instead:\n\n- omitting the `--password` option to receive an interactive password prompt, or\n\n- using the `--config` option to specify a configuration file containing the password.\n\n`--awsSessionToken=`\nIf connecting to a MongoDB Atlas cluster using the `MONGODB-AWS` `authentication mechanism`, and using session tokens in addition to your AWS access key ID and secret access key, you can specify your AWS session token in:\n\n- this field,\n\n- the `AWS_SESSION_TOKEN` `authMechanismProperties` parameter to the `connection string`, or\n\n- the `AWS_SESSION_TOKEN` environment variable.\n\nSee Connect to a MongoDB Atlas Cluster using AWS IAM Credentials for an example of each.\n\nOnly valid when using the `MONGODB-AWS`\n`authentication mechanism`.\n\n`--authenticationDatabase=`\nSpecifies the authentication database where the specified `--username` has been created. See Authentication Database.\n\nIf you use the GSSAPI (Kerberos), PLAIN (LDAP SASL), or `MONGODB-AWS`\n`authentication mechanisms`, you must set `--authenticationDatabase` to `$external`.\n\nAlternatively, you can also specify the authentication database directly in the `URI connection string`. Providing a connection string while also using `--authenticationDatabase` and specifying conflicting information will result in an error.\n\n`--authenticationMechanism=`\n*Default*: SCRAM-SHA-1\n\nSpecifies the authentication mechanism the `mongofiles` instance uses to authenticate to the `mongod` or `mongos`.\n\nStarting in version `100.1.0`, `mongofiles` adds support for the `MONGODB-AWS` authentication mechanism when connecting to a MongoDB Atlas cluster.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nValue\n\n\nDescription\n\n
\nSCRAM-SHA-1\n\n\nRFC 5802 standard Salted Challenge Response Authentication Mechanism using the SHA-1 hash function.\n\n
\nSCRAM-SHA-256\n\n\nRFC 7677 standard Salted Challenge Response Authentication Mechanism using the SHA-256 hash function.\n\nRequires featureCompatibilityVersion set to `4.0`.\n\n
\nMONGODB-X.509\n\n\nMongoDB TLS/SSL certificate authentication.\n\n
\n`MONGODB-AWS`\n\n\nExternal authentication using AWS IAM credentials for use in connecting to a MongoDB Atlas cluster. See Connect to a MongoDB Atlas Cluster using AWS IAM Credentials.\n\n
\nGSSAPI (Kerberos)\n\n\nExternal authentication using Kerberos. This mechanism is available only in MongoDB Enterprise.\n\n
\nPLAIN (LDAP SASL)\n\n\nExternal authentication using LDAP. You can also use `PLAIN` for authenticating in-database users. `PLAIN` transmits passwords in plain text. This mechanism is available only in MongoDB Enterprise.\n\n
Alternatively, you can also specify the authentication mechanism directly in the `URI connection string`. Providing a connection string while also using `--authenticationMechanism` and specifying conflicting information will result in an error.\n\n`--gssapiServiceName=`\nSpecify the name of the service using GSSAPI/Kerberos. Only required if the service does not use the default name of `mongodb`.\n\nThis option is available only in MongoDB Enterprise.\n\n`--gssapiHostName=`\nSpecify the hostname of a service using GSSAPI/Kerberos. *Only* required if the hostname of a machine does not match the hostname resolved by DNS.\n\nThis option is available only in MongoDB Enterprise.\n\n`--db=, -d=`\n\nSpecifies the name of the database on which to run the `mongofiles`.\n\nAlternatively, you can also specify the database directly in the `URI connection string`. Providing a connection string while also using `--db` and specifying conflicting information will result in an error.\n\n`--local=, -l=`\n\nSpecifies the local filesystem name of a file for get and put operations.\n\nIn the mongofiles put and mongofiles get commands, the required `` modifier refers to the name the object will have in GridFS. `mongofiles` assumes that this reflects the file's name on the local file system. This setting overrides this default."} -{"chunk_id": "68a95be15e79d242619d8032-3", "page_id": "68a95be15e79d242619d8032", "source_name": "database-tools", "product_name": "MongoDB Database Tools", "url": "https://mongodb.com/docs/database-tools/mongofiles", "title": "`mongofiles`", "text": "`--type=`\nProvides the ability to specify a MIME type to describe the file inserted into GridFS storage. `mongofiles` omits this option in the default operation.\n\nUse only with mongofiles put operations.\n\n`--replace, -r`\n\nAlters the behavior of mongofiles put to replace existing GridFS objects with the specified local file, rather than adding an additional object with the same name.\n\nIn the default operation, files will not be overwritten by a mongofiles put option.\n\n`--prefix=`\n*Default*: fs\n\nGridFS prefix to use.\n\n`--writeConcern=`\n*Default*: majority\n\nSpecifies the write concern for each write operation that `mongofiles` performs.\n\nSpecify the write concern as a document with w options:\n\n```sh\n--writeConcern=\"{w:'majority'}\"\n```\n\nIf the write concern is also included in the `--uri connection string`, the command-line `--writeConcern` overrides the write concern specified in the URI string.\n\n`--readPreference=`\n*Default*: `primary`\n\nSpecifies the read preference for `mongofiles`. The `--readPreference` option can take:\n\n- A string if specifying only the read preference mode:\n\n ```sh\n --readPreference=secondary\n ```\n\n- A quote-enclosed document to specify the mode, the optional read preference tag sets, and the optional maxStalenessSeconds:\n\n ```sh\n --readPreference='{mode: \"secondary\", tagSets: [ { \"region\": \"east\" } ], maxStalenessSeconds: 120}'\n ```\n\n If specifying the maxStalenessSeconds, the value must be greater than or equal to 90.\n\n`mongofiles` defaults to `primary`\nread preference.\n\nIf the read preference is also included in the `--uri connection string`, the command-line `--readPreference` overrides the read preference specified in the URI string.\n\n## Commands\n\nLists the files in the GridFS store. The characters specified after `list` (e.g. ``) optionally limit the list of returned items to files that begin with that string of characters.\n\nLists the files in the GridFS store with names that match any portion of ``.\n\nCopy the specified file or files from the local file system into GridFS storage. Multiple files can be specified as a space-separated list.\n\nEach specified filename refers to the name the object will have in GridFS, and `mongofiles` assumes that this reflects the name the file has on the local file system. If the local filename is different, use the `mongofiles --local` option.\n\nCopy the specified file or files from GridFS storage to the local file system.\n\nEach specified filename refers to the name the object has in GridFS, and `mongofiles` will use this filename when writing to the local file system.\n\nIf specifying *only one* `filename` to the `get` command, you can use the `--local` option to specify a different local filename to write to, if desired. The `--local` option **cannot** be used if specifying *more than one* `filename` to the `get` command.\n\nTo copy files from GridFS storage that match a regular expression, use the `get_regex` command instead.\n\nCopy the file, specified by its `<_id>`, from GridFS storage to the local file system. `<_id>` refers to the extended JSON `_id` of the object in GridFS. `get_id` can accept either ObjectId values or non-ObjectId values for `<_id>`.\n\n`mongofiles` writes the file to the local file system using the file's filename in GridFS. To choose a different location for the file on the local file system, use the `--local` option.\n\nCopy the file or files, matched by the specified `` expression, from GridFS storage to the local file system. The `get_regex` command uses Perl compatible regular expressions (\"PCRE\") version 8.42 with UTF-8 support.\n\nYou may optionally specify one or more `` using the `--regexOptions` flag. These can be any of the options supported by the $regex operator, which include settings such as case-insensitivity. Multiple options should be provided together without separators, e.g. `--regexOptions si`\n\n`mongofiles` writes the file or files to the local file system using each file's matched filename in GridFS. You **cannot** use the `--local` option with the `get_regex` command.\n\nDelete the specified file from GridFS storage.\n\nDelete the file, specified by its `<_id>`, from GridFS storage. `delete_id` can accept either ObjectId values or non-ObjectId values for `<_id>`.\n\n## Examples\n\nRun `mongofiles` from the system command line, not the `mongo` shell.\n\nTo return a list of all files in a GridFS collection in the `records` database, use the following invocation at the system shell:\n\n```sh\nmongofiles -d=records list\n```\n\nThis `mongofiles` instance will connect to the `mongod` instance running on the `27017` localhost interface to specify the same operation on a different port or hostname, and issue a command that resembles one of the following:\n\n```sh\nmongofiles --port=37017 -d=records list\nmongofiles --host=db1.example.net -d=records list\nmongofiles --host=db1.example.net --port=37017 -d=records list\n```\n\nModify any of the following commands as needed if you're connecting the `mongod` instances on different ports or hosts.\n\nTo upload a file named `32-corinth.lp` to the GridFS collection in the `records` database, you can use the following command:\n\n```sh\nmongofiles -d=records put 32-corinth.lp\n```\n\nTo delete the `32-corinth.lp` file from this GridFS collection in the `records` database, you can use the following command:\n\n```sh\nmongofiles -d=records delete 32-corinth.lp\n```\n\nTo search for files in the GridFS collection in the `records` database that have the string `corinth` in their names, you can use following command:\n\n```sh\nmongofiles -d=records search corinth\n```\n\nTo list all files in the GridFS collection in the `records` database with names that begin with the string `32`, you can use the following command:\n\n```sh\nmongofiles -d=records list 32\n```\n\nTo fetch the file from the GridFS collection in the `records` database named `32-corinth.lp`, you can use the following command:\n\n```sh\nmongofiles -d=records get 32-corinth.lp\n```\n\nTo fetch all files from the GridFS collection in the `records` database with names beginning with the string `32` and ending with the string `.lp`, you can use the following command:\n\n```sh\nmongofiles -d=records get_regex 32*.lp\n```\n\nTo fetch the file from the GridFS collection in the `records` database with `_id: ObjectId(\"56feac751f417d0357e7140f\")`, you can use the following command:\n\n```sh\nmongofiles -d=records get_id '{\"$oid\": \"56feac751f417d0357e7140f\"}'\n```\n\nYou must include quotation marks around the `_id`."} -{"chunk_id": "68a95be15e79d242619d8032-4", "page_id": "68a95be15e79d242619d8032", "source_name": "database-tools", "product_name": "MongoDB Database Tools", "url": "https://mongodb.com/docs/database-tools/mongofiles", "title": "`mongofiles`", "text": "### Connect to a MongoDB Atlas Cluster using AWS IAM Credentials\n\nTo connect to a MongoDB Atlas cluster which has been configured to support authentication via AWS IAM credentials, provide a `connection string` to `mongofiles` similar to the following:\n\n```none\nmongofiles 'mongodb+srv://:@cluster0.example.com/testdb?authSource=$external&authMechanism=MONGODB-AWS' \n```\n\nConnecting to Atlas using AWS IAM credentials in this manner uses the `MONGODB-AWS` `authentication mechanism` and the `$external` `authSource`, as shown in this example.\n\nIf using an AWS session token, as well, provide it with the `AWS_SESSION_TOKEN`\n`authMechanismProperties` value, as follows:\n\n```none\nmongofiles 'mongodb+srv://:@cluster0.example.com/testdb?authSource=$external&authMechanism=MONGODB-AWS&authMechanismProperties=AWS_SESSION_TOKEN:' \n```\n\nIf the AWS access key ID, secret access key, or session token include the following characters:\n\n```none\n: / ? # [ ] @\n```\n\nthose characters must be converted using percent encoding.\n\nAlternatively, the AWS access key ID, secret access key, and optionally session token can each be provided outside of the connection string using the `--username`, `--password`, and `--awsSessionToken` options instead, like so:\n\n```none\nmongofiles 'mongodb+srv://cluster0.example.com/testdb?authSource=$external&authMechanism=MONGODB-AWS' --username --password --awsSessionToken \n```\n\nWhen provided as command line parameters, these three options do not require percent encoding.\n\nYou may also set these credentials on your platform using standard AWS IAM environment variables. `mongofiles` checks for the following environment variables when you use the `MONGODB-AWS`\n`authentication mechanism`:\n\n- `AWS_ACCESS_KEY_ID`\n\n- `AWS_SECRET_ACCESS_KEY`\n\n- `AWS_SESSION_TOKEN`\n\nIf set, these credentials do not need to be specified in the connection string or via their explicit options.\n\nIf you chose to use the AWS environment variables to specify these values, you cannot mix and match with the corresponding explicit or connection string options for these credentials. Either use the environment variables for access key ID *and* secret access key (*and* session token if used), **or** specify each of these using the explicit or connection string options instead.\n\nThe following example sets these environment variables in the `bash` shell:\n\n```none\nexport AWS_ACCESS_KEY_ID=''\nexport AWS_SECRET_ACCESS_KEY=''\nexport AWS_SESSION_TOKEN=''\n```\n\nSyntax for setting environment variables in other shells will be different. Consult the documentation for your platform for more information.\n\nYou can verify that these environment variables have been set with the following command:\n\n```none\nenv | grep AWS\n```\n\nOnce set, the following example connects to a MongoDB Atlas cluster using these environment variables:\n\n```none\nmongofiles 'mongodb+srv://cluster0.example.com/testdb?authSource=$external&authMechanism=MONGODB-AWS' \n```"} -{"chunk_id": "68a95be15e79d242619d8017-0", "page_id": "68a95be15e79d242619d8017", "source_name": "database-tools", "product_name": "MongoDB Database Tools", "url": "https://mongodb.com/docs/database-tools/release-notes/dbtools-100.3.0-changelog", "title": "Database Tools 100.3.0 Changelogs", "text": "# Database Tools 100.3.0 Changelogs\n\n## 100.3.1 Changelog\n\n*Released 2021-03-17*\n\nThis release includes various bug fixes. Particularly notable is TOOLS-2783, where we reverted a change from 100.2.1 (TOOLS-1856: use a memory pool in `mongorestore`) after discovering that it was causing memory usage issues.\n\n### Build Failure\n\n- TOOLS-2796 mongotop_sharded.js failing on all versions of the qa-tests\n\n- TOOLS-2815 Development build artifacts accidentally uploaded for versioned release\n\n### Release\n\n- TOOLS-2791 Release Database Tools 100.3.1\n\n### Bug\n\n- TOOLS-2584 Restoring single BSON file should use db set in URI\n\n- TOOLS-2783 Mongorestore uses huge amount of RAM\n\n### Task\n\n- TOOLS-704 Remove system.indexes collection dumping from mongodump\n\n- TOOLS-2801 Migrate from dep to Go modules and update README\n\n- TOOLS-2802 Make mongo-tools-common a subpackage of mongo-tools\n\n- TOOLS-2805 Add mod tidy static analysis check for Go modules\n\n- TOOLS-2806 Migrate mongo-tools-common unit tests to mongo-tools\n\n- TOOLS-2807 Migrate mongo-tools-common integration tests to mongo-tools\n\n- TOOLS-2808 Migrate mongo-tools-common IAM auth tests to mongo-tools\n\n## 100.3.0 Changelog\n\n*Released 2021-02-04*\n\nThis release includes support for PKCS8-encrypted client private keys, support for providing secrets in a config file instead of on the command line, and a few small bug fixes.\n\n### Build Failure\n\n- TOOLS-2795 Tools failing to build on SUSE15-sp2\n\n- TOOLS-2800 RPM creation failing on amazon linux 1\n\n### Release\n\n- TOOLS-2790 Release Database Tools 100.3.0\n\n### Investigation\n\n- TOOLS-2771 SSL connection problems mongodump\n\n### Bug\n\n- TOOLS-2751 Deferred query EstimatedDocumentCount helper incorrect with filter\n\n- TOOLS-2760 rpm package should not obsolete itself\n\n- TOOLS-2775 --local does not work with multi-file get or get_regex\n\n### New Feature\n\n- TOOLS-2779 Add --config option for password values\n\n### Task\n\n- TOOLS-2013 Support PKCS8 encrypted client private keys\n\n- TOOLS-2707 Build mongo-tools and mongo-tools-common with go 1.15\n\n- TOOLS-2780 Add warning when password value appears on command line\n\n- TOOLS-2798 Add Amazon Linux 2 Arm64 to Tools"} -{"chunk_id": "68a95be15e79d242619d800b-0", "page_id": "68a95be15e79d242619d800b", "source_name": "database-tools", "product_name": "MongoDB Database Tools", "url": "https://mongodb.com/docs/database-tools/release-notes/dbtools-100.1.0-changelog", "title": "Database Tools 100.1.0 Changelogs", "text": "# Database Tools 100.1.0 Changelogs\n\n## 100.1.1 Changelog\n\n*Released 2020-07-31*\n\nThis release contains a fix for a linux packaging bug and a `mongorestore` bug related to the `--convertLegacyIndexes` flag.\n\n### Release\n\n- TOOLS-2685 Release Database Tools 100.1.1\n\n### Bug\n\n- TOOLS-2645 Check for duplicate index keys after converting legacy index definitions\n\n- TOOLS-2683 Ubuntu 16.04 DB Tools 100.1.0 DEB depends on `libcom-err2`, should be `libcomerr2`\n\n## 100.1.0 Changelog\n\n*Released 2020-07-24*\n\nThis release officially adds support for MongoDB 4.4. In addition to various bug fixes, it adds support for MongoDB 4.4's new `MONGODB-AWS` authentication mechanism.\n\nThe full list of changes is below:\n\n### Build Failure\n\n- TOOLS-2604 integration-4.4-cluster is failing on master\n\n- TOOLS-2638 Test-case failure for mongorestore\n\n- TOOLS-2643 New linux distros missing from repo-config.yaml\n\n### Release\n\n- TOOLS-2630 Release Database Tools 100.1.0\n\n### Bug\n\n- TOOLS-2287 URI parser incorrectly prints unsupported parameter warnings\n\n- TOOLS-2337 nsInclude does not work with percent encoded namespaces\n\n- TOOLS-2366 ^C isn't handled by mongodump\n\n- TOOLS-2494 mongorestore thorw error \"panic: close of closed channel\"\n\n- TOOLS-2531 mongorestore hung if restoring views with --preserveUUID --drop options\n\n- TOOLS-2596 Database Tools --help links to old Manual doc pages\n\n- TOOLS-2597 swallows errors from URI parsing\n\n- TOOLS-2609 Detached signatures incorrectly appearing in download JSON\n\n- TOOLS-2622 Tools do not build following README instructions\n\n- TOOLS-2669 macOS zip archive structure incorrect\n\n- TOOLS-2670 Troubleshoot IAM auth options errors\n\n### New Feature\n\n- TOOLS-2369 IAM Role-based authentication\n\n### Task\n\n- TOOLS-2363 Update warning message for \"mongorestore\"\n\n- TOOLS-2476 Notarize builds for macOS catalina\n\n- TOOLS-2505 Add missing 4.4 Platforms\n\n- TOOLS-2534 Ignore startIndexBuild and abortIndexBuild oplog entries in oplog replay\n\n- TOOLS-2535 commitIndexBuild and createIndexes oplog entries should build indexes with the createIndexes command during oplog replay\n\n- TOOLS-2554 Remove ReplSetTest file dependencies from repo\n\n- TOOLS-2569 Update tools to go driver 1.4.0\n\n- TOOLS-2618 Refactor AWS IAM auth testing code\n\n- TOOLS-2628 Add 3.4 tests to evg\n\n- TOOLS-2644 Update barque authentication\n\n- TOOLS-2650 Create changelog for tools releases"} -{"chunk_id": "68a95be15e79d242619d8019-0", "page_id": "68a95be15e79d242619d8019", "source_name": "database-tools", "product_name": "MongoDB Database Tools", "url": "https://mongodb.com/docs/database-tools/release-notes/dbtools-100.0.0-changelog", "title": "Database Tools 100.0.0 Changelogs", "text": "# Database Tools 100.0.0 Changelogs\n\n## 100.0.2 Changelog\n\nThis release contains several bugfixes. It also adds support for dumping and restoring collections with long names since the 120 byte name limit will be raised to 255 bytes in MongoDB version 4.4.\n\nThe full list of changes is below:\n\n### Bug\n\n- TOOLS-1785 Typo in mongodump help\n\n- TOOLS-2495 Oplog replay can't handle entries > 16 MB\n\n- TOOLS-2498 Nil pointer error mongodump\n\n- TOOLS-2559 Error on uninstalling database-tools 99.0.1-1 RPM\n\n- TOOLS-2575 mongorestore panic during convertLegacyIndexes from 4.4 mongodump\n\n- TOOLS-2593 Fix special handling of $admin filenames\n\n### Task\n\n- TOOLS-2446 Add MMAPV1 testing to Tools tests\n\n- TOOLS-2469 Accept multiple certs in CA\n\n- TOOLS-2530 Mongorestore can restore from new mongodump format\n\n- TOOLS-2537 Ignore config.system.indexBuilds namespace\n\n- TOOLS-2544 Add 4.4 tests to Evergreen\n\n- TOOLS-2551 Split release uploading into per-distro tasks\n\n- TOOLS-2555 Support directConnection option\n\n- TOOLS-2561 Sign mongodb-tools tarballs\n\n- TOOLS-2605 Cut 100.0.2 release\n\n## 100.0.1 Changelog\n\nThis release was a test of our new release infrastructure and contains no changes from 100.0.0.\n\n### Task\n\n- TOOLS-2493 Cut tools 100.0.0 and 100.0.1 GA releases\n\n## 100.0.0 Changelog\n\nThis is the first separate release of the Database Tools from the Server. We decided to move to a separate release so we can ship new features and bugfixes more frequently. The new separate release version starts from `100.0.0` to make it clear the versioning is separate from the Server. You can read more about this on the MongoDB blog.\n\nThis release contains bugfixes, some new command-line options, and quality of life improvements. A full list can be found below, but here are some highlights:\n\n- There are no longer restrictions on using `--uri` with other connection options such as `--port` and `--password` as long as the URI and the explicit option don't provide conflicting information. Connection strings can now be specified as a positional argument without the `--uri` option.\n\n- The new `--useArrayIndexFields` flag for `mongoimport` interprets natural numbers in fields as array indexes when importing csv or tsv files.\n\n- The new `--convertLegacyIndexes` flag for `mongorestore` removes any invalid index options specified in the corresponding `mongodump` output, and rewrites any legacy index key values to use valid values.\n\n- A new `delete` `mode` for `mongoimport`. With `--mode`\n `delete`, `mongoimport` deletes existing documents in the database that match a document in the import file.\n\n### Build Failure\n\n- TOOLS-2489 format-go task failing on master\n\n### Bug\n\n- TOOLS-1493 Tools crash running help when terminal width is low\n\n- TOOLS-1786 mongodump does not create metadata.json file for views dumped as collections\n\n- TOOLS-1826 mongorestore panic in archive mode when replay oplog failed\n\n- TOOLS-1909 mongoimport does not report that it supports the decimal type\n\n- TOOLS-2275 autoIndexId:false is not supported in 4.0\n\n- TOOLS-2334 Skip system collections during oplog replay\n\n- TOOLS-2336 Wrong deprecation error message printed when restoring from stdin\n\n- TOOLS-2346 mongodump --archive to stdout corrupts archive when prompting for password\n\n- TOOLS-2379 mongodump/mongorestore error if source database has an invalid index option\n\n- TOOLS-2380 mongodump fails against hidden node with authentication enabled\n\n- TOOLS-2381 Restore no socket timeout behavior\n\n- TOOLS-2395 Incorrect message for oplog overflow\n\n- TOOLS-2403 mongorestore hang while replaying last oplog failed in archive mode\n\n- TOOLS-2422 admin.tempusers is not dropped by mongorestore\n\n- TOOLS-2423 mongorestore does not drop admin.tempusers if it exists in the dump\n\n- TOOLS-2455 mongorestore hangs on invalid archive\n\n- TOOLS-2462 Password prompt does not work on windows\n\n- TOOLS-2497 mongorestore may incorrectly validate index name length before calling createIndexes\n\n- TOOLS-2513 Creating client options results in connection string validation error\n\n- TOOLS-2520 Fix options parsing for SSL options\n\n- TOOLS-2547 Installing database tools fails on rhel 7.0\n\n- TOOLS-2548 Installing database tools fails on SLES 15\n\n### New Feature\n\n- TOOLS-1954 Support roundtrip of mongoexport array notation in mongoimport\n\n- TOOLS-2268 Add remove mode to mongoimport\n\n- TOOLS-2412 Strip unsupported legacy index options\n\n- TOOLS-2430 mongorestore: in dotted index keys, replace \"hashed\" with \"1\"\n\n- TOOLS-2459 Allow --uri to be used with other connection string options\n\n- TOOLS-2460 A connection string can be set as a positional argument\n\n- TOOLS-2521 Add support for the tlsDisableOCSPEndpointCheck URI option\n\n- TOOLS-2529 Mongodump outputs new file format for long collection names\n\n### Task\n\n- TOOLS-2418 Remove mongoreplay from mongo-tools\n\n- TOOLS-2421 Maintain test coverage after moving tools tests from server\n\n- TOOLS-2438 Create MSI installer in dist task\n\n- TOOLS-2439 Tools formula included in homebrew tap\n\n- TOOLS-2440 Sign MSI installer\n\n- TOOLS-2441 Update release process documentation\n\n- TOOLS-2442 Automate release uploads\n\n- TOOLS-2443 Generate tarball archive in dist task\n\n- TOOLS-2444 Generate deb packages in dist task\n\n- TOOLS-2449 Create sign task\n\n- TOOLS-2464 Update platform support\n\n- TOOLS-2470 Sign linux packages\n\n- TOOLS-2471 Automate JSON download feed generation\n\n- TOOLS-2472 Automate linux package publishing\n\n- TOOLS-2473 Consolidate community and enterprise buildvariants\n\n- TOOLS-2475 Manually verify tools release\n\n- TOOLS-2480 Generate rpm packages in dist task\n\n- TOOLS-2488 Update package naming and versioning\n\n- TOOLS-2493 Cut tools 100.0.0 and 100.0.1 GA releases\n\n- TOOLS-2506 Update maintainer in linux packages\n\n- TOOLS-2523 Remove Ubuntu 12.04 and Debian 7.1 variants\n\n- TOOLS-2536 ignoreUnknownIndexOptions option in the createIndexes command for servers >4.1.9\n\n- TOOLS-2538 Move convertLegacyIndexKeys() from mongorestore to mongo-tools-common\n\n- TOOLS-2539 Publish linux packages to curator with correct names\n\n- TOOLS-2549 Push GA releases to server testing repo\n\n- TOOLS-2550 Push GA releases to the 4.4 repo\n\n- TOOLS-2551 Split release uploading into per-distro tasks"} -{"chunk_id": "68d62ff87a7e4b3c5a4f1d78-0", "page_id": "68d62ff87a7e4b3c5a4f1d78", "source_name": "database-tools", "product_name": "MongoDB Database Tools", "url": "https://mongodb.com/docs/database-tools/verify/rpm", "title": "Verify RPM Packages (RHEL)", "text": "# Verify RPM Packages (RHEL)\n\nThe MongoDB release team digitally signs Database Tools packages to certify that packages are a valid and unaltered MongoDB release. Before you install the Database Tools, you can use the digital signature to validate the package.\n\nThis page describes how to verify `.rpm` packages on RHEL operating systems.\n\n## Before you Begin\n\nIf you don't have the MongoDB Database Tools installed, download the Database Tools binaries from the Download Center.\n\n## Steps\n\n### Import the MongoDB Database Tools public key in gpg and rpm\n\n```sh\ncurl https://pgp.mongodb.com/server-Tools.asc | gpg --import\n\nrpm --import https://pgp.mongodb.com/server-Tools.asc\n```\n\nIf the key imports successfully, the command returns:\n\n```sh\ngpg: key 3132835C1D925D5B: public key \"MongoDB CLI Tools Release Signing Key \" imported\ngpg: Total number processed: 1\ngpg: imported: 1\n```\n\nIf you have previously imported the key, the command returns:\n\n```sh\ngpg: key 3132835C1D925D5B: \"MongoDB CLI Tools Release Signing Key \" not changed\ngpg: Total number processed: 1\ngpg: unchanged: 1\n```\n\n### Verify the rpm file\n\n```sh\nrpm --checksig \n```\n\nIf the file is signed, the command returns:\n\n```sh\n digests signatures OK\n```"} -{"chunk_id": "68d62ff87a7e4b3c5a4f1d79-0", "page_id": "68d62ff87a7e4b3c5a4f1d79", "source_name": "database-tools", "product_name": "MongoDB Database Tools", "url": "https://mongodb.com/docs/database-tools/verify", "title": "Verify Integrity of Database Tools Packages", "text": "# Verify Integrity of Database Tools Packages\n\nThe MongoDB release team digitally signs Database Tools packages to certify that packages are a valid and unaltered MongoDB release. Before you install the Database Tools, you can use the digital signature to validate the package.\n\nTo learn how to verify Database Tools packages, see the corresponding page for your verification method:\n\n- Verify macOS Binaries\n\n- Verify Packages with GPG (Linux)\n\n- Verify RPM Packages (RHEL)\n\n- Verify Windows Packages"} -{"chunk_id": "68a95be15e79d242619d8014-0", "page_id": "68a95be15e79d242619d8014", "source_name": "database-tools", "product_name": "MongoDB Database Tools", "url": "https://mongodb.com/docs/database-tools/release-notes/dbtools-100.11.0-changelog", "title": "Database Tools 100.11.0 Changelogs", "text": "# Database Tools 100.11.0 Changelogs\n\n## 100.11.0 Changelog\n\n*Released 2025-02-02*\n\nThis version adds support for OIDC for programmatic workloads. It also updates a few dependency libraries to fix vulnerabilities, adds a check of metadata consistency to accommodate `$`-prefixed fields, and fixes a small race condition in logging.\n\nBug:\n\n- TOOLS-3618 - Race condition in the `mongorestore.ParseOptions` and `log.Logvf`\n\n- TOOLS-3637 - `mongodump` should check collection metadata consistency\n\nTask:\n\n- TOOLS-3537 - Create the SSDLC report template\n\n- TOOLS-3736 - Add OIDC Support for Programmatic workloads\n\n- TOOLS-3741 - Update `x/crypto` to address CVE-2024-45337\n\n- TOOLS-3743 - Release new mongo-tools version."} -{"chunk_id": "68a95c3c5e79d242619e1a6e-0", "page_id": "68a95c3c5e79d242619e1a6e", "source_name": "django", "product_name": "Django MongoDB Backend", "url": "https://mongodb.com/docs/languages/python/django-mongodb/current/issues-and-help", "title": "Report Issues and Request Help", "text": "# Report Issues and Request Help\n\nWe're lucky to have such a vibrant community of Django MongoDB Backend users. We recommend seeking support for general questions through the MongoDB communities on Reddit or Stack Overflow.\n\nTo learn more about Django MongoDB Backend's feature availability and limitations, see the Django and MongoDB Feature Compatibility guide.\n\n## Bugs / Feature Requests\n\nTo report a bug or to request a new feature in Django MongoDB Backend, please open an issue in JIRA, our issue-management tool, using the following steps:\n\n1. Create a JIRA account.\n\n2. Navigate to the Python Integrations project.\n\n3. Click Create Issue. Please provide as much information as possible about the issue and the steps to reproduce it.\n\nBug reports in JIRA for the Django MongoDB Backend project can be viewed by everyone.\n\nIf you identify a security vulnerability in the driver or in any other MongoDB project, please report it according to the instructions found in Create a Vulnerability Report."} -{"chunk_id": "68a95c3c5e79d242619e1a81-0", "page_id": "68a95c3c5e79d242619e1a81", "source_name": "django", "product_name": "Django MongoDB Backend", "url": "https://mongodb.com/docs/languages/python/django-mongodb/current/model-data/models", "title": "Create Models to Represent Collections", "text": "# Create Models to Represent Collections\n\n## Overview\n\nIn this guide, you can learn how to create Django **models** that represent MongoDB collections. Models are Python classes that define the structure of your data. When using Django MongoDB Backend, you can map each model to a MongoDB collection and interact with the collection's documents by using model objects.\n\nTo learn more about Django models, see `Model` in the Django documentation.\n\n## Supported Fields\n\nThis section describes Django MongoDB Backend's support for the following fields, which you can include in your models:\n\n- Django Fields\n\n- MongoDB BSON Fields\n\n### Django Fields\n\nThe following table describes the Django model fields that Django MongoDB Backend supports:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nField Type\n\n\nDescription\n\n
\n`BinaryField`\n\n\nStores raw binary data.\n\n
\n`BooleanField`\n\n\nStores boolean (`True` or `False`) values.\n\n
\n`CharField`\n\n\nStores string values. To store longer text values, use `TextField`.\n\n
\n`DateField`\n\n\nStores date values in Python `datetime.date` instances.\n\n
\n`DateTimeField`\n\n\nStores date and time values in Python `datetime.datetime` instances.\n\n
\n`DecimalField`\n\n\nStores decimal values.\n\n
\n`DurationField`\n\n\nStores values representing periods of time in Python `timedelta` instances.\n\n
\n`EmailField`\n\n\nStores `CharField` values and uses an `EmailValidator` to verify that the value is an email address.\n\n
\n`FileField`\n\n\nStores file values.\n\n
\n`FilePathField`\n\n\nStores `CharField` values that represent filenames on your filesystem.\n\n
\n`FloatField`\n\n\nStores float values.\n\n
\n`GenericIPAddressField`\n\n\nStores an IPv4 or IPv6 address in string format.\n\n
\n`ImageField`\n\n\nStores a `FileField` value and verifies that the uploaded object is a valid image.\n\n
\n`IntegerField` and `BigIntegerField`\n\n\nStores integer values up to 64 bits in size.\n\n
\n`JSONField`\n\n\nStores JSON data. To learn more about this field, see the Store JSON Data section in this guide.\n\n
\n`PositiveIntegerField` and `PositiveBigIntegerField`\n\n\nStores positive integer values up to 64 bits in size.\n\n
\n`PositiveSmallIntegerField`\n\n\nStores positive integer values up to 32 bits in size.\n\n
\n`SlugField`\n\n\nStores a short text label, often for URL values.\n\n
\n`SmallIntegerField`\n\n\nStores integer values up to 32 bits in size.\n\n
\n`TextField`\n\n\nStores large text values.\n\n
\n`URLField`\n\n\nStores a `CharField` value representing a URL.\n\n
\n`UUIDField`\n\n\nStores instances of Python's `UUID` class.\n\n
\n\n### MongoDB BSON Fields\n\nMongoDB organizes and stores documents in a binary representation called BSON that allows for flexible data processing.\n\nTo learn more about how MongoDB stores BSON data, see BSON Types in the MongoDB Server manual.\n\nThe following table describes supported BSON field types and their Django MongoDB Backend equivalents that you can use in your Django models:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nBSON Field Type\n\n\nDjango MongoDB Backend Field Type\n\n\nBSON Description\n\n
\n`Array`\n\n\n`ArrayField`\n\n\nStores array values. To learn more about using this field with Django MongoDB Backend, see the Store Array Data section in this guide.\n\n
\n`Object`\n\n\n`EmbeddedModelField` or `EmbeddedModelArrayField`\n\n\nStores one or multiple embedded documents. To learn more about using these fields with Django MongoDB Backend, see the Store Embedded Model Data and Store Embedded Model Array Data sections.\n\n
\n`ObjectId`\n\n\n`ObjectIdField`\n\n\nStores unique 12-byte identifiers that MongoDB uses as primary keys.\n\n
\n`Binary`\n\n\n`BinaryField`\n\n\nStores binary data.\n\n
\n`Boolean`\n\n\n`BooleanField`\n\n\nStores `true` or `false` values.\n\n
\n`Date`\n\n\n`DatetimeField`\n\n\nStores dates and times in milliseconds since the Unix epoch, or January 1, 1970.\n\n
\n`Decimal128`\n\n\n`DecimalField`\n\n\nStores 28-bit decimal values.\n\n
\n`Double`\n\n\n`FloatField`\n\n\nStores floating-point values.\n\n
\n`Int32`\n\n\n`SmallIntegerField`\n\n\nStores 32-bit signed integers.\n\n
\n`Int64`\n\n\n`IntegerField` or `BigIntegerField`\n\n\nStores 64-bit signed integers.\n\n
\n`String`\n\n\n`CharField` or `TextField`\n\n\nStores UTF-8 encoded string values.\n\n
"} -{"chunk_id": "68a95c3c5e79d242619e1a81-1", "page_id": "68a95c3c5e79d242619e1a81", "source_name": "django", "product_name": "Django MongoDB Backend", "url": "https://mongodb.com/docs/languages/python/django-mongodb/current/model-data/models", "title": "Create Models to Represent Collections", "text": "## Define a Model\n\nTo create a model that represents a MongoDB collection, add your model class definitions to your application's `models.py` file. In your model class, specify the fields you want to store and include any model metadata in an inner `Meta` class. You can also use the `__str__()` method to define the string representation of your model. Use the following syntax to define a model:\n\n```python\n class (models.Model):\n = \n # Include additional fields here\n\n class Meta:\n # Include metadata here\n\n def __str__(self):\n # Include logic for displaying your model as a string here\n```\n\nTo learn more about the metadata options you can specify in the `Meta` class, see Model Meta options in the Django documentation.\n\nTo use your models, you must add them to your project's `settings.py` file. Edit the `INSTALLED_APPS` value to include the name of the module that stores your `models.py` file, as shown in the following code:\n\n```python\n INSTALLED_APPS = [\n '',\n # Include other app modules here\n ]\n```\n\nFinally, run the following database migration commands from your project's root directory to create MongoDB collections for your models or use existing collections to store model data:\n\n```bash\npython manage.py makemigrations \npython manage.py migrate\n```\n\n### Example\n\nThis sample `models.py` file defines a `Movie` model class that includes the following information:\n\n- List of fields that represent movie data.\n\n- `Meta` class that sets the `db_table` option to `movies`. This instructs Django MongoDB Backend to use this model to represent the `sample_mflix.movies` collection from the Atlas sample datasets.\n\n The `Meta` class also sets the `managed` option to `False`, instructing Django MongoDB Backend not to create a new collection for the model.\n\n- `__str__()` method that defines the model's string representation as its `title` field value.\n\n```python\nfrom django.db import models\n\nclass Movie(models.Model):\n title = models.CharField(max_length=200)\n plot = models.TextField(blank=True)\n runtime = models.IntegerField(default=0)\n released = models.DateTimeField(\"release date\", null=True, blank=True)\n\n class Meta:\n db_table = \"movies\"\n managed = False\n\n def __str__(self):\n return self.title\n```\n\nTo learn more about the fields used in the model class definition, see the Supported Fields section of this guide.\n\n## Use Advanced Fields\n\nThis section shows how to use the following fields in your Django models:\n\n- JSONField\n\n- ArrayField\n\n- EmbeddedModelField\n\n- EmbeddedModelArrayField\n\n- PolymorphicEmbeddedModelField\n\n- PolymorphicEmbeddedModelArrayField\n\n### Store JSON Data\n\nYou can use a `JSONField` in your model to store JSON objects. JSON is a human-readable format for data exchange, and JSON objects are data containers that map string keys to values. MongoDB provides the `Object` field type to store JSON data in documents and internally stores this data in BSON, or Binary JSON, format.\n\nYou can also use embedded models and polymorphic embedded models to represent a MongoDB `Object`.\n\n#### Example\n\nThe following example adds a `JSONField` value to the model created in the Define a Model example in this guide. The new field, called `imdb`, stores JSON data that represents user ratings for each `Movie` object:\n\n```python\nfrom django.db import models\n\nclass Movie(models.Model):\n title = models.CharField(max_length=200)\n plot = models.TextField(blank=True)\n runtime = models.IntegerField(default=0)\n released = models.DateTimeField(\"release date\", null=True, blank=True)\n imdb = models.JSONField(null=True, blank=True)\n\n class Meta:\n db_table = \"movies\"\n managed = False\n\n def __str__(self):\n return self.title\n```\n\nTo learn how to query data stored in a `JSONField`, see Query JSON Values in the Specify a Query guide.\n\n#### Limitations\n\nDjango MongoDB Backend's support for `JSONField` has the following limitations:\n\n- If you set the field's value to `None`, Django MongoDB Backend stores its value as a SQL `NULL` value. Alternatively, you can set the `JSONField` value to `Value(None, JSONField())`, which represents the JSON scalar `null`. However, there is no way to distinguish between the SQL `NULL` and the JSON `null` when querying.\n\n- Some queries that use `Q` objects might not return the expected results, particularly when using the `QuerySet.exclude()` method.\n\n- When querying for fields that have a `None` value, Django MongoDB Backend incorrectly returns documents in which the field doesn't exist.\n\n### Store Array Data\n\nYou can use an `ArrayField` in your model to store a list of data. To create an `ArrayField`, use the `ArrayField()` class constructor and pass the following arguments:\n\n- `base_field`: Specifies the underlying data type of each value stored in the array. You cannot specify `EmbeddedModelField` or `FileField` as the base field type.\n\n- `size`: *(Optional)* Specifies the maximum size of the array.\n\n- `options`: *(Optional)* Specifies Django field options. To view a list of available options, see Field options in the Django documentation.\n\nYou can store an array of array values in an `ArrayField` by using the following syntax:\n\n```python\nmy_array = ArrayField(\n ArrayField(\n base_field,\n # ... Additional arguments\n ),\n)\n```\n\n#### Example\n\nThe following example adds an `ArrayField` value to the model created in the Define a Model example in this guide. The new field, called `genres`, stores a list of `CharField` values that represent movie genres and can store a maximum of `5` values:\n\n```python\nfrom django.db import models\nfrom django_mongodb_backend.fields import ArrayField\n\nclass Movie(models.Model):\n title = models.CharField(max_length=200)\n plot = models.TextField(blank=True)\n runtime = models.IntegerField(default=0)\n released = models.DateTimeField(\"release date\", null=True, blank=True)\n genres = ArrayField(\n models.CharField(max_length=100),\n size=5,\n null=True,\n blank=True)\n\n class Meta:\n db_table = \"movies\"\n managed = False\n\n def __str__(self):\n return self.title\n```\n\nTo learn how to query data stored in an `ArrayField`, see Query Array Values in the Specify a Query guide."} -{"chunk_id": "68a95c3c5e79d242619e1a81-2", "page_id": "68a95c3c5e79d242619e1a81", "source_name": "django", "product_name": "Django MongoDB Backend", "url": "https://mongodb.com/docs/languages/python/django-mongodb/current/model-data/models", "title": "Create Models to Represent Collections", "text": "### Store Embedded Model Data\n\nYou can use an `EmbeddedModelField` to represent a MongoDB `Object`, which stores a nested document value. This type allows one model to store a separate model in one of its fields. To create an `EmbeddedModelField`, define an embedded model class as a subclass of the `EmbeddedModel` abstract model. Then, create a field in your base model class by using the `EmbeddedModelField()` constructor and pass the following arguments:\n\n- `embedded_model`: Specifies the model class to store.\n\n- `options`: *(Optional)* Specifies Django field options. To view a list of available options, see Field options in the Django documentation.\n\nThe `makemigrations` Django command does not detect changes to embedded models. If you make changes to the embedded model's class, the model stored in the `EmbeddedModelField` does not reflect the changes.\n\n#### Example\n\nThis example adds an `EmbeddedModelField` value to the model created in the Define a Model example in this guide. The new field, called `awards`, stores an embedded `Award` model as its value. The following code defines the `Award` model and modifies the `Movie` model to include the `EmbeddedModelField`:\n\n```python\nfrom django.db import models\nfrom django_mongodb_backend.models import EmbeddedModel\nfrom django_mongodb_backend.fields import EmbeddedModelField\n\nclass Award(EmbeddedModel):\n wins = models.IntegerField(default=0)\n nominations = models.IntegerField(default=0)\n text = models.CharField(max_length=100)\n\nclass Movie(models.Model):\n title = models.CharField(max_length=200)\n plot = models.TextField(blank=True)\n runtime = models.IntegerField(default=0)\n released = models.DateTimeField(\"release date\", null=True, blank=True)\n awards = EmbeddedModelField(Award, null=True, blank=True)\n\n class Meta:\n db_table = \"movies\"\n managed = False\n\n def __str__(self):\n return self.title\n```\n\nTo learn how to query data stored in an `EmbeddedModelField`, see Query Embedded Model Values in the Specify a Query guide.\n\n### Store Embedded Model Array Data\n\nYou can use an `EmbeddedModelArrayField` to represent a MongoDB document field that stores an array of documents in a one-to-many relationship. Each document in the array corresponds to a Django MongoDB Backend `EmbeddedModelField` value. To create an `EmbeddedModelArrayField`, use the `EmbeddedModelArrayField()` class constructor and pass the following arguments:\n\n- `embedded_model`: Specifies the model stored in each array item.\n\n- `max_size`: *(Optional)* Specifies the maximum size of the array.\n\n#### Example\n\nThis example adds an `EmbeddedModelArrayField` value to the model created in the Define a Model example in this guide. This `cast` field stores an array of embedded `Actor` models. The following code defines the `Actor` model and modifies the `Movie` model to include the `EmbeddedModelArrayField`:\n\n```python\nfrom django.db import models\nfrom django_mongodb_backend.models import EmbeddedModel\nfrom django_mongodb_backend.fields import EmbeddedModelArrayField\n\nclass Actor(EmbeddedModel):\n first_name = models.CharField(max_length=100)\n last_name = models.CharField(max_length=100)\n role = models.CharField(max_length=100)\n\nclass Movie(models.Model):\n title = models.CharField(max_length=200)\n plot = models.TextField(blank=True)\n runtime = models.IntegerField(default=0)\n released = models.DateTimeField(\"release date\", null=True, blank=True)\n cast = EmbeddedModelArrayField(Actor, null=True, blank=True)\n\n class Meta:\n db_table = \"movies\"\n managed = False\n\n def __str__(self):\n return self.title\n```\n\n### Store Polymorphic Embedded Model Data\n\nYou can use a `PolymorphicEmbeddedModelField` to represent a MongoDB document field that can store multiple types of embedded documents. Each embedded document is represented by a Django MongoDB Backend model class.\n\nTo create a `PolymorphicEmbeddedModelField`, pass the `embedded_models` argument to the `PolymorphicEmbeddedModelField()` class constructor. This argument specifies a list of model classes that the field can store.\n\n#### Example\n\nThis example adds a `PolymorphicEmbeddedModelField` value to the model created in the Define a Model example in this guide. This `awards` field can store an embedded model of type `Oscars` or `GoldenGlobes`. Each embedded model contains information about all the Oscar or Golden Globe awards a movie has won.\n\nThe following code defines the `Oscars` and `GoldenGlobes` embedded models, and then modifies the `Movie` model to include the `PolymorphicEmbeddedModelField`:\n\n```python\nfrom django.db import models\nfrom django_mongodb_backend.models import EmbeddedModel\nfrom django_mongodb_backend.fields import PolymorphicEmbeddedModelField\n\nclass Oscars(EmbeddedModel):\n wins = models.IntegerField(default=0)\n nominations = models.IntegerField(default=0)\n best_picture = models.BooleanField(default=False)\n\nclass GoldenGlobes(EmbeddedModel):\n wins = models.IntegerField(default=0)\n nominations = models.IntegerField(default=0)\n\nclass Movie(models.Model):\n title = models.CharField(max_length=200)\n plot = models.TextField(blank=True)\n runtime = models.IntegerField(default=0)\n released = models.DateTimeField(\"release date\", null=True, blank=True)\n awards = PolymorphicEmbeddedModelField([\"Oscars\", \"GoldenGlobes\"], null=True, blank=True)\n\n class Meta:\n db_table = \"movies\"\n managed = False\n\n def __str__(self):\n return self.title\n```\n\nTo learn how to query data stored in a `PolymorphicEmbeddedModelField`, see Query Polymorphic Embedded Model Values in the Specify a Query guide.\n\n### Store Polymorphic Embedded Model Array Data\n\nYou can use a `PolymorphicEmbeddedModelArrayField` to represent a MongoDB document field that can store multiple types of embedded documents. This field is similar to the `PolymorphicEmbeddedModelField`, but it stores an array of embedded documents instead of a single document. Each embedded document in the array is represented by a Django MongoDB Backend model class.\n\nTo create a `PolymorphicEmbeddedModelArrayField`, pass the following arguments to the `PolymorphicEmbeddedModelArrayField()` class constructor:\n\n- `embedded_models`: Specifies the model classes that the field can store\n\n- `max_size`: *(Optional)* Specifies the maximum size of the array\n\n#### Example\n\nThis example adds a `PolymorphicEmbeddedModelArrayField` value to the model created in the Define a Model example in this guide. This `awards` field can store a list of embedded models of type `Oscar` or `GoldenGlobe`. Each embedded model contains information about one Oscar or Golden Globe award that a movie has won.\n\nThe following code defines the `Oscar` and `GoldenGlobe` embedded models, and then modifies the `Movie` model to include the `PolymorphicEmbeddedModelArrayField`:\n\n```python\nfrom django.db import models\nfrom django_mongodb_backend.models import EmbeddedModel\nfrom django_mongodb_backend.fields import PolymorphicEmbeddedModelArrayField\n\nclass Oscar(EmbeddedModel):\n category = models.CharField(max_length=200)\n year = models.IntegerField(default=0)\n\nclass GoldenGlobe(EmbeddedModel):\n category = models.CharField(max_length=200)\n year = models.IntegerField(default=0)\n\nclass Movie(models.Model):\n title = models.CharField(max_length=200)\n plot = models.TextField(blank=True)\n runtime = models.IntegerField(default=0)\n released = models.DateTimeField(\"release date\", null=True, blank=True)\n awards = PolymorphicEmbeddedModelArrayField([\"Oscar\", \"GoldenGlobe\"], null=True, blank=True)\n\n class Meta:\n db_table = \"movies\"\n managed = False\n\n def __str__(self):\n return self.title\n```\n\nTo learn how to query data stored in a `PolymorphicEmbeddedModelArrayField`, see Query Polymorphic Embedded Model Array Values in the Specify a Query guide."} -{"chunk_id": "68a95c3c5e79d242619e1a81-3", "page_id": "68a95c3c5e79d242619e1a81", "source_name": "django", "product_name": "Django MongoDB Backend", "url": "https://mongodb.com/docs/languages/python/django-mongodb/current/model-data/models", "title": "Create Models to Represent Collections", "text": "## Specify Unique Constraints\n\nTo ensure that a field does not store the same value in multiple documents, specify a unique constraint.\n\nTo create a unique constraint, assign the `constraints` option in your model's `Meta` class to a `UniqueConstraint` object. Pass the following arguments to the `UniqueConstraint()` constructor in any order:\n\n- `name`: The name of your constraint.\n\n- `fields`: One or more fields that must store unique values.\n\n- `nulls_distinct`: *(Optional)* A boolean that specifies whether Django considers fields that have `NULL` values as distinct from each other. To allow only one `NULL` value, set this option to `False`.\n\nThe `nulls_distinct` option is available only in Django MongoDB Backend v6.0.2 and later.\n\nThe following example sets a unique constraint on the `Movie` model's `plot` field, defined in the Define a Model example, by modifying the model's `Meta` class:\n\n```python\nclass Meta:\n db_table = \"movies\"\n managed = False\n constraints = [\n models.UniqueConstraint(name=\"unique_plot\", fields=[\"plot\"])\n ]\n```\n\n### Embedded Field Constraints\n\nYou can specify unique constraints on `EmbeddedModelField` and `EmbeddedModelArrayField` subfields only in Django MongoDB Backend v6.0.2 and later.\n\nDjango MongoDB Backend v6.0.3 adds support for unique constraints on `PolymorphicEmbeddedModelField` and `PolymorphicEmbeddedModelArrayField` subfields.\n\nTo set a unique constraint on subfields of embedded model fields, assign the `Meta.constraints` option to an `EmbeddedFieldUniqueConstraint` object. Pass the following arguments to the `EmbeddedFieldUniqueConstraint()` constructor in any order:\n\n- `name`: The name of your constraint.\n\n- `fields`: One or more subfields that must store unique values. Use dot notation to reference the subfield names.\n\nThe following example sets a unique constraint on the embedded `Award` model's `text` field, defined in the Store Embedded Model Data example, by modifying the `Movie` model's `Meta` class:\n\n```python\nclass Meta:\n db_table = \"movies\"\n managed = False\n constraints = [\n EmbeddedFieldUniqueConstraint(\n name=\"unique_award_details\",\n fields=[\"awards.text\"],\n )\n ]\n```\n\n## Additional Information\n\nTo learn how to use your models to run database operations, see the Interact with Data guides.\n\nTo learn more about Django fields, see the Model field reference in the Django documentation."} -{"chunk_id": "6a76cb256b218fc00ba0b664-0", "page_id": "6a76cb256b218fc00ba0b664", "source_name": "django", "product_name": "Django MongoDB Backend", "url": "https://mongodb.com/docs/languages/python/django-mongodb/current/interact-data/transactions", "title": "Transactions and Sessions", "text": "# Transactions and Sessions\n\n## Overview\n\nIn this guide, you can learn how to use Django MongoDB Backend to perform **transactions**. Transactions allow you to run a series of operations that change data only if the entire transaction is committed. If any operation in the transaction does not succeed, Django MongoDB Backend stops the transaction and discards all changes to the data before they ever become visible. This feature is called **atomicity**.\n\nIn MongoDB, transactions run within logical sessions. A session is a grouping of related read or write operations that you want to run sequentially. Sessions enable causal consistency for a group of operations and allow you to run operations in an **ACID-compliant** transaction, which is a transaction that meets an expectation of atomicity, consistency, isolation, and durability.\n\nDjango's native transaction API is not supported, but Django MongoDB Backend provides a custom transaction API that enables the same functionality. To run operations within a transaction, define them inside an atomic block of code. Django MongoDB Backend manages session logic internally, so you do not need to manually start a session before running a transaction.\n\nDjango MongoDB Backend's transaction API has several limitations. To view a list of limitations, see Database and Collection Support in the Django and MongoDB Feature Compatibility guide.\n\n### Sample Data\n\nThe examples in this guide use the `Movie` model, which represents the `sample_mflix.movies` collection from the Atlas sample datasets. The `Movie` model class has the following definition:\n\n```python\nfrom django.db import models\nfrom django_mongodb_backend.fields import ArrayField\n\nclass Movie(models.Model):\n title = models.CharField(max_length=200)\n plot = models.TextField(blank=True)\n runtime = models.IntegerField(default=0)\n released = models.DateTimeField(\"release date\", null=True, blank=True)\n genres = ArrayField(models.CharField(max_length=100), null=True, blank=True)\n\n class Meta:\n db_table = \"movies\"\n managed = False\n\n def __str__(self):\n return self.title\n```\n\n`Movie` model includes\n\n```python\nfrom .models import Movie\nfrom django.utils import timezone\nfrom datetime import datetime\n```\n\nThe `Movie` model includes an inner `Meta` class, which specifies model metadata, and a `__str__()` method, which defines the model's string representation. To learn about these model features, see Define a Model in the Create Models guide.\n\n#### Run Code Examples\n\nYou can use the Python interactive shell to run the code examples. To enter the shell, run the following command from your project's root directory:\n\n```bash\npython manage.py shell\n```\n\nAfter entering the Python shell, ensure that you import the following models and modules:\n\n```python\nfrom .models import Movie\nfrom django.utils import timezone\nfrom datetime import datetime\n```\n\nTo learn how to create a Django application that uses the `Movie` model and the Python interactive shell to interact with MongoDB documents, visit the Get Started with Django MongoDB Backend tutorial.\n\n## Start a Transaction\n\nTo start a database transaction, call the `django_mongodb_backend.transaction.atomic()` function. You can use this function as a decorator or a context manager.\n\nEnsure that you import the `transaction` module by using the following import statement:\n\n```python\nfrom django_mongodb_backend import transaction\n```\n\n### Use a Decorator\n\nYou can start a database transaction by adding the `@transaction.atomic` decorator above your function. This decorator guarantees the atomicity of any database operations within the function. If the function successfully completes, the changes are committed to MongoDB.\n\nThe following example calls the `create()` method within a transaction, which inserts a document into the `sample_mflix.movies` collection if the transaction succeeds:\n\n```python\n@transaction.atomic\ndef insert_movie_transaction():\n Movie.objects.create(\n title=\"Poor Things\",\n runtime=141,\n genres=[\"Comedy\", \"Romance\"]\n )\n```\n\n### Use a Context Manager\n\nAlternatively, you can use the `transaction.atomic()` context manager to create an atomic block of code. This example runs the same operation as the preceding example but uses a context manager to start a transaction:\n\n```python\ndef insert_movie_transaction():\n with transaction.atomic():\n Movie.objects.create(\n title=\"Poor Things\",\n runtime=141,\n genres=[\"Comedy\", \"Romance\"]\n )\n```\n\n## Run Callbacks After a Transaction\n\nTo perform certain actions only if a transaction successfully completes, you can use the `transaction.on_commit()` function. This function allows you to register callbacks that run after a transaction is committed to the database. Pass a function, or any callable object, as an argument to `on_commit()`.\n\nThe following example queries for movies that have a `genre` value of `[\"Horror\", \"Comedy\"]` only after a related database transaction completes:\n\n```python\ndef get_horror_comedies():\n movies = Movie.objects.filter(genres=[\"Horror\", \"Comedy\"])\n for m in movies:\n print(f\"Title: {m.title}, runtime: {m.runtime}\")\n\ndef insert_movie_with_callback():\n with transaction.atomic():\n Movie.objects.create(\n title=\"The Substance\",\n runtime=140,\n genres=[\"Horror\", \"Comedy\"]\n )\n transaction.on_commit(get_horror_comedies)\n```\n\n## Handle Transaction Errors\n\nTo handle exceptions that occur during a transaction, add error handling logic around your atomic code block. If you handle errors inside the atomic block, you might obscure these errors from Django. Since Django uses errors to determine whether to commit or roll back a transaction, this can cause unexpected behavior.\n\nIf a transaction does not succeed, Django does not revert any changes made to a model's fields. To avoid inconsistencies between your models and database documents, you might need to manually restore the original field values.\n\n### Example\n\nThe following example includes error handling logic that reverts the modified `title` value of the retrieved document if the database transaction fails:\n\n```python\nmovie = Movie.objects.get(title=\"Jurassic Park\")\nmovie.title = \"Jurassic Park I\"\ntry:\n with transaction.atomic():\n movie.save()\nexcept DatabaseError:\n movie.title = \"Jurassic Park\"\n\nif movie.title == \"Jurassic Park I\":\n movie.plot = \"An industrialist invites experts to visit his theme park of cloned dinosaurs. After a power failure,\" \\\n \" the creatures run loose, putting everyone's lives, including his grandchildren's, in danger.\"\n movie.save()\n\n```\n\nSince the code performs a second database operation based on the model's `title` value, reverting the change if the transaction errors prevents further data inconsistencies.\n\n## Additional Information\n\nTo learn more about the Django transaction API, see Database Transactions in the Django documentation."} -{"chunk_id": "68a95c3c5e79d242619e1a76-0", "page_id": "68a95c3c5e79d242619e1a76", "source_name": "django", "product_name": "Django MongoDB Backend", "url": "https://mongodb.com/docs/languages/python/django-mongodb/current/interact-data/specify-a-query", "title": "Specify a Query", "text": "# Specify a Query\n\n## Overview\n\nIn this guide, you can learn how to use Django MongoDB Backend to specify a database query.\n\nYou can refine the set of documents that a query returns by creating a **query filter**. A query filter is an expression that specifies the search criteria MongoDB uses to match documents in a read or write operation. In a query filter, you can prompt Django MongoDB Backend to search for documents with an exact match to your query, or you can compose query filters to express more complex matching criteria.\n\n### Query API\n\nThe Django `QuerySet` API provides methods that allow you to retrieve model objects. To run a MongoDB database query, call `QuerySet` methods on your model's manager. The `Manager` class handles database operations and allows you to interact with your MongoDB data by referencing Django models. By default, Django adds a `Manager` named `objects` to every model class.\n\nWhen you assign a `QuerySet` to a variable, Django MongoDB Backend does not perform the operation until you evaluate the variable. After evaluating the `QuerySet`, Django saves the query results in the `QuerySet` cache. Future evaluations of the `QuerySet` use the cached results.\n\nTo learn more about the Django `QuerySet` API, see `QuerySet` in the Django documentation.\n\n### Sample Data\n\nThe examples in this guide use the `Movie` model, which represents the `sample_mflix.movies` collection from the Atlas sample datasets. The `Movie` model contains an embedded `Award` model as the value of its `awards` field. These model classes have the following definitions:\n\n```python\nfrom django.db import models\nfrom django_mongodb_backend.models import EmbeddedModel\nfrom django_mongodb_backend.fields import EmbeddedModelField, ArrayField\n\nclass Award(EmbeddedModel):\n wins = models.IntegerField(default=0)\n nominations = models.IntegerField(default=0)\n text = models.CharField(max_length=100)\n\nclass Movie(models.Model):\n title = models.CharField(max_length=200)\n plot = models.TextField(blank=True)\n runtime = models.IntegerField(default=0)\n released = models.DateTimeField(\"release date\", null=True, blank=True)\n awards = EmbeddedModelField(Award)\n genres = ArrayField(models.CharField(max_length=100), null=True, blank=True)\n imdb = models.JSONField(null=True)\n\n class Meta:\n db_table = \"movies\"\n managed = False\n\n def __str__(self):\n return self.title\n```\n\n`Movie` model includes\n\n```python\nfrom .models import Movie, Award\nfrom django.utils import timezone\nfrom datetime import datetime\n```\n\nThe `Movie` model includes an inner `Meta` class, which specifies model metadata, and a `__str__()` method, which defines the model's string representation. To learn about these model features, see Define a Model in the Create Models guide.\n\n#### Run Code Examples\n\nYou can use the Python interactive shell to run the code examples. To enter the shell, run the following command from your project's root directory:\n\n```bash\npython manage.py shell\n```\n\nAfter entering the Python shell, ensure that you import the following models and modules:\n\n```python\nfrom .models import Movie, Award\nfrom django.utils import timezone\nfrom datetime import datetime\n```\n\nTo learn how to create a Django application that uses the `Movie` model and the Python interactive shell to interact with MongoDB documents, visit the Get Started with Django MongoDB Backend tutorial.\n\n## Run a Query\n\nTo query your MongoDB data, call a `QuerySet` method on your model's manager and specify your matching criteria in a query filter.\n\nThis section describes how to use the following methods from the `QuerySet` API:\n\n- all()\n\n- filter()\n\n- get()\n\n- exclude()\n\n- raw_aggregate()\n\n### Retrieve All Documents\n\nTo retrieve all documents from a collection, call the `all()` method on your model's manager.\n\nThe following example calls the `all()` method to retrieve all documents in the `sample_mflix.movies` collection:\n\n```python\nMovie.objects.all()\n```\n\n```\n, ,\n,\n, ,\n, ,\n, , ,\n'...(remaining elements truncated)...']>\n```\n\n### Retrieve Matching Documents\n\nTo query a collection for documents that match a set of criteria, call the `filter()` method on your model's manager. Pass a query filter to the `filter()` method that specifies your query criteria.\n\nThe following example calls the `filter()` method to query the `sample_mflix.movies` collection for documents that have a `runtime` value of `300`:\n\n```python\nMovie.objects.filter(runtime=300)\n```\n\n```\n, ,\n]>\n```\n\n### Retrieve One Document\n\nTo retrieve one document from a collection, call the `get()` method on your model's manager. Pass a query filter to the `get()` method that specifies your query criteria.\n\nIf your query matches no documents or multiple documents, the `get()` method generates an error. To retrieve one document from a query that might match multiple, use the first() method.\n\nThe following example calls the `get()` method to retrieve one document that has a `title` value of `\"Finding Nemo\"`:\n\n```python\nMovie.objects.get(title=\"Finding Nemo\")\n```\n\n```\n\n```\n\n### Exclude Matching Documents\n\nTo query a collection for documents that do not meet your search criteria, call the `exclude()` method on your model's manager. Pass the exclusion criteria as an argument to the `exclude()` method.\n\nThe following example calls the `exclude()` method to exclude documents released before `datetime(1980, 1, 1)` (January 1, 1980) from the results:\n\n```python\nMovie.objects.exclude(released__lt=timezone.make_aware(datetime(1980, 1, 1)))\n```\n\n```\n, ,\n, ,\n, , ,\n, ,\n, '...(remaining elements truncated)...']>\n```\n\nThe preceding example uses the `lt` field lookup to query the collection. To learn more about comparison lookups, see the Use Comparison Lookups section in this guide.\n\n### Run Raw Database Queries\n\nIf you want to run complex queries that Django's query API does not support, you can use the `raw_aggregate()` method. This method allows you to specify your query criteria in a MongoDB aggregation pipeline, which you pass as an argument to `raw_aggregate()`.\n\nTo learn how to run raw database queries, see the Perform Raw Database Queries guide.\n\n## Customize Your Query Filter\n\nYou can further refine your query criteria by using a **field lookup** in your query filter. Field lookups allow you to clarify the relationship between the field you're querying and the value you want to query for. Use the following syntax to specify a field lookup:\n\n```python\nModel.objects.filter(__=)\n```\n\nYou can use different lookup types to perform advanced queries, such as partial text matching, array element queries, regular expression matching, and year value matching for datetime fields.\n\nTo view a full list of lookup types, see Field lookups in the `QuerySet` Django API reference.\n\nThis section describes how to refine your query filters in the following ways:\n\n- Use Text Match Lookups\n\n- Use Comparison Lookups\n\n- Combine Lookups"} -{"chunk_id": "68a95c3c5e79d242619e1a76-1", "page_id": "68a95c3c5e79d242619e1a76", "source_name": "django", "product_name": "Django MongoDB Backend", "url": "https://mongodb.com/docs/languages/python/django-mongodb/current/interact-data/specify-a-query", "title": "Specify a Query", "text": "### Use Text Match Lookups\n\nThe following table describes some of the lookup types that you can use to run queries that include specific matching criteria for text values:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nLookup Type\n\n\nDescription\n\n
\n`exact`\n\n\nSpecifies an exact text match. If you do not provide a lookup type in your query filter, Django MongoDB Backend uses this type by default.You can specify a case-insensitive exact text match by using `iexact`.\n\n
\n`contains`\n\n\nSpecifies a partial text match.You can specify a case-insensitive partial text match by using `icontains`.\n\n
\n`startswith`\n\n\nMatches field values that begin with the specified text.You can specify a case-insensitive partial text match by using `istartswith`.\n\n
\n`endswith`\n\n\nMatches field values that end with the specified text.You can specify a case-insensitive partial text match by using `iendswith`.\n\n
#### Example\n\nThe following example uses the `contains` lookup to query for documents in which the `plot` value includes the text `\"coming-of-age\"`:\n\n```python\nMovie.objects.filter(plot__contains=\"coming-of-age\")\n```\n\n```\n, ,\n, , ,\n, , ,\n, , ,\n'...(remaining elements truncated)...']>\n```\n\n### Use Comparison Lookups\n\nThe following table describes some of the lookup types that you can use to run queries that evaluate a field value against a specified value:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nLookup Type\n\n\nDescription\n\n
\n`gt`\n\n\nMatches field values that are greater than the specified value.\n\n
\n`gte`\n\n\nMatches field values that are greater than or equal to the specified value.\n\n
\n`lt`\n\n\nMatches field values that are less than the specified value.\n\n
\n`lte`\n\n\nMatches field values that are less or equal to than the specified value.\n\n
#### Example\n\nThe following example uses the `lte` lookup to query for documents in which the `runtime` value is less than or equal to `50`:\n\n```python\nMovie.objects.filter(runtime__lte=50)\n```\n\n```\n, ,\n,\n, ,\n, , ,\n'...(remaining elements truncated)...']>\n```\n\n### Combine Lookups\n\nYou can run queries that use multiple sets of matching criteria in the following ways:\n\n- Pass multiple query filters to your query method, separated by commas. To view an example, see Retrieving objects in the Django documentation.\n\n- Chain query methods together. To learn more, see Chaining filters in the Django documentation.\n\n- Use `Q` objects and separate each object with a logical operator. To learn more, see Complex lookups with Q objects in the Django documentation.\n\n#### Q Object Example\n\nYou can use `Q` objects to run queries with multiple sets of matching criteria. To create a `Q` object, pass your query filter to the `Q()` method. You can pass multiple `Q` objects as arguments to your query method and separate each `Q` object by an OR (`|`), AND (`&`), or XOR (`^`) operator. You can also negate `Q` objects by prefixing them with the `~` symbol.\n\nThis example uses `Q` objects to query for documents that meet the following query conditions:\n\n- `title` field value begins either with the text `\"Funny\"` or `\"Laugh\"`\n\n- `genres` array field does not contain the value `\"Comedy\"`\n\n```python\nMovie.objects.filter(\n (Q(title__startswith=\"Funny\") | Q(title__startswith=\"Laugh\"))\n & ~Q(genres__contains=[\"Comedy\"])\n)\n```\n\n```\n, ]>\n```\n\nThe preceding example uses a field lookup on an `ArrayField` value. For more information about querying an `ArrayField`, see the Query Array Values section in this guide.\n\n## Modify Query Results\n\nThis section describes how to modify your query results in the following ways:\n\n- Sort Results\n\n- Skip and Limit Results\n\n- Retrieve the First Result\n\n### Sort Results\n\nYou can provide a sort order for your query results by using the `order_by()` method. To specify an ascending sort based on values of a given field, pass the field name as an argument. To specify a descending sort, pass the field name prefixed with a minus symbol (`-`) as an argument.\n\nYou can pass multiple field names, separated by commas, to the `order_by()` method. Django MongoDB Backend sorts results by each field in the order provided.\n\n#### Example\n\nThis example performs the following actions:\n\n- Calls the `filter()` method on the `Movie` model's manager to query the `sample_mflix.movies` collection\n\n- Queries documents that have a `title` value starting with the text `\"Rocky\"`\n\n- Sorts the results in ascending order of their `released` field values\n\n```python\nMovie.objects.filter(title__startswith=\"Rocky\").order_by(\"released\")\n```\n\n```\n, , ,\n, , ,\n]>\n```\n\n### Skip and Limit Results\n\nYou can specify the number of results that a query returns by using Python's array-slicing syntax, as shown in the following code:\n\n```python\nModel.objects.filter()[:]\n```\n\nReplace the `` and `` placeholders with integer values representing the subset of results you want to return. The start value is exclusive and the end value is inclusive.\n\nIf you omit the `` value, the query returns each result, beginning with the first match, until it returns the number specified by the `` value.\n\nIf you omit the `` value, the query returns each result but skips the number of initial results specified by ``.\n\n#### Example\n\nThis example performs the following actions:\n\n- Calls the `filter()` method on the `Movie` model's manager to query the `sample_mflix.movies` collection\n\n- Queries documents that have a `released` value of `datetime(2010, 7, 16)` (July 16, 2010)\n\n- Returns the third and fourth results\n\n```python\nMovie.objects.filter(released=timezone.make_aware(datetime(2010, 7, 16)))[2:4]\n```\n\n```\n, ]>\n```\n\n### Retrieve the First Result\n\nTo retrieve the first result from a query that might match multiple results, chain the `first()` method to the `filter()` method. Pass a query filter to the `filter()` method that specifies your query criteria.\n\nThe following example calls the `filter()` and `first()` methods to query the `sample_mflix.movies` collection for the first document in which the `genres` value is `[\"Crime\", \"Comedy\"]`:\n\n```python\nMovie.objects.filter(genres=[\"Crime\", \"Comedy\"]).first()\n```\n\n```\n\n```\n\n## Advanced Field Queries\n\nThis section describes how to run queries on the following fields:\n\n- EmbeddedModelField\n\n- ArrayField\n\n- EmbeddedModelArrayField\n\n- PolymorphicEmbeddedModelField\n\n- PolymorphicEmbeddedModelArrayField\n\n- JSONField\n\n- Primary Key"} -{"chunk_id": "68a95c3c5e79d242619e1a76-2", "page_id": "68a95c3c5e79d242619e1a76", "source_name": "django", "product_name": "Django MongoDB Backend", "url": "https://mongodb.com/docs/languages/python/django-mongodb/current/interact-data/specify-a-query", "title": "Specify a Query", "text": "### Query Embedded Model Values\n\nYou can run operations on your model that query fields of embedded models. To query these fields, specify your model field and each embedded field name separated by double underscores (`__`) until you reach the field you want to query, as shown in the following code:\n\n```python\nModel.objects.filter(__=)\n```\n\nYou can also use field lookups to refine your embedded model query. Add your lookup type after the embedded model field you're querying, prefixed by double underscores.\n\n#### Example\n\nThis example uses a lookup to query the `Award` model, which is embedded in the `Movie` model. This embedded model represents the `awards` field in the `sample_mflix.movies` collection and its nested `wins`, `nominations`, and `text` fields. The following code queries for documents in which the `awards.wins` nested field value is greater than `150`:\n\n```python\nMovie.objects.filter(awards__wins__gt=150)\n```\n\n```\n,\n, ,\n, , ,\n, , ,\n, ]>\n```\n\n### Query Array Values\n\nYou can query data stored in an `ArrayField` value by using the standard query syntax. Django MongoDB Backend provides additional field lookup types for querying `ArrayField` values, which are described in the following table:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nLookup Type\n\n\nDescription\n\n
\n`contains`\n\n\nMatches fields that store the provided value as a subset of their data. This `ArrayField` lookup overrides the `contains` lookup described in the Use Text Match Lookups section of this guide.\n\n
\n`contained_by`\n\n\nMatches fields that store a subset of the provided values. This lookup type is the inverse of `contains`.\n\n
\n`overlap`\n\n\nMatches field that store any of the provided values.\n\n
\n`len`\n\n\nMatches fields that store the number of values provided.\n\n
#### Example\n\nThe following example uses the `overlap` lookup to query for documents whose `genres` field contains any values in the `[\"Adventure\", \"Family\"]` array:\n\n```python\nMovie.objects.filter(genres__overlap=[\"Adventure\", \"Family\"])\n```\n\n```\n, ,\n, , ,\n, , ,\n, , ,\n'...(remaining elements truncated)...']>\n```\n\n### Query Embedded Model Array Values\n\nThe examples in this section use the model classes defined in the Store Embedded Model Array Data section of the Create Models guide.\n\nYou can run operations on your model that query fields of an array of embedded models. These queries use the same syntax as described in the Query Embedded Model Values section:\n\n```python\nModel.objects.filter(__=)\n```\n\nYou can also use field lookups to refine your embedded model query. Add your lookup type after the embedded model field you're querying, prefixed by double underscores. However, you can only use the following lookup types to query an embedded field:\n\n- `exact`\n\n- `iexact`\n\n- `in`\n\n- `gt`\n\n- `gte`\n\n- `lt`\n\n- `lte`\n\nIf the model instances embedded in your `EmbeddedModelArrayField` have their own embedded array fields, you cannot query those nested field values.\n\n#### Length Transform Example\n\nYou can use the `len` lookup type to filter by the number of embedded model instances in an `EmbeddedModelArrayField` value. To further refine your query, you can combine the `len` lookup with other comparison lookups.\n\nThis example uses the `len` lookup to query the `cast` field, which stores an array of embedded `Actor` models. The following code queries for documents in which the length of the `cast` array is greater than `5`:\n\n```python\nMovie.objects.filter(cast__len__gt=5)\n```\n\n#### Index and Slice Transforms Example\n\nYou can use index and slice transforms to query specific array elements of your `EmbeddedModelArrayField`.\n\nThe following example specifies an array index to query for documents in which the first element of the `cast` array has a `last_name` value of `\"Winslet\"`:\n\n```python\nMovie.objects.filter(cast__0__last_name=\"Winslet\")\n```\n\nSimilarly, the following example uses a slice transform to query for documents in which one of the first three elements of the `cast` array has a `last_name` value of `\"Winslet\"`:\n\n```python\nMovie.objects.filter(cast__0_2__last_name=\"Winslet\")\n```\n\n### Query Polymorphic Embedded Model Values\n\nTo query data stored in a `PolymorphicEmbeddedModelField` value, use the same syntax described in the preceding Query Embedded Model Values section. You can query fields that are shared among the embedded models or fields that are unique to a specific model.\n\nIf you query a field that is shared among multiple embedded models but has different data types, you might see inaccurate results. Django cannot correctly determine which data type to assign to the lookup value. In this case, Django MongoDB Backend iterates through the embedded models and uses the first field, and corresponding data type, that it finds.\n\nSimilarly, if you query a nested embedded model field that has the same name and data type in multiple models, Django MongoDB Backend queries only the first model listed in your `PolymorphicEmbeddedModelField` definition.\n\n#### Examples\n\nThe following examples use the model classes defined in the Store Polymorphic Embedded Model Data section of the Create Models guide.\n\nThis example uses a lookup to query the `awards` field, which can store embedded models of type `Oscar` or `GoldenGlobe`. The code queries for documents that have an `awards.wins` value of `10`, which can match documents represented by either embedded model type:\n\n```python\nMovie.objects.filter(awards__wins=10)\n```\n\nYou can also query fields that are not shared among the embedded models. The following example queries the `awards.best_picture` field, which is unique to the `Oscar` embedded model:\n\n```python\nMovie.objects.filter(awards__best_picture=True)\n```"} -{"chunk_id": "68a95c3c5e79d242619e1a76-3", "page_id": "68a95c3c5e79d242619e1a76", "source_name": "django", "product_name": "Django MongoDB Backend", "url": "https://mongodb.com/docs/languages/python/django-mongodb/current/interact-data/specify-a-query", "title": "Specify a Query", "text": "### Query Polymorphic Embedded Model Array Values\n\nTo query data stored in a `PolymorphicEmbeddedModelArrayField` value, use the same syntax and operators described in the Query Embedded Model Array Values section. You can query fields that are shared among the embedded models or fields that are unique to a specific model.\n\n`PolymorphicEmbeddedModelArrayField`\n\nIf you query a field that is shared among multiple embedded models but has different data types, you might see inaccurate results. Django cannot correctly determine which data type to assign to the lookup value. In this case, Django MongoDB Backend iterates through the embedded models and uses the first field and corresponding data type that it finds.\n\nSimilarly, if you query a nested embedded model field that has the same name and data type in multiple models, Django MongoDB Backend queries only the first model listed in your `PolymorphicEmbeddedModelArrayField` definition.\n\n#### Example\n\nThe following example uses the model classes defined in the Store Polymorphic Embedded Model Array Data section of the Create Models guide.\n\nThis example uses a lookup to query the `awards` field, which stores an array of embedded models of type `Oscar` or `GoldenGlobe`. The code queries for documents that have an `awards.year` value less than `2000`, which can match documents represented by either embedded model type.\n\n```python\nMovie.objects.filter(awards__year__lt=2000)\n```\n\n### Query Geospatial Values\n\nYou can use spatial lookups only in Django MongoDB Backend v6.0.1 and later.\n\nBefore running a geospatial query, you must create a model that has GeoDjango fields. To learn how to specify these fields, see the Model Geospatial Data guide.\n\nYou can use spatial lookups to query GeoDjango fields, which store geospatial data. Django MongoDB Backend supports the following spatial lookups:\n\n- `contains`: Queries for values that contain the specified lookup geometry, which you must specify in a `Point` object\n\n- `disjoint`: Queries for values that are spatially disjoint from, or do not intersect with, the lookup geometry\n\n- `distance_gt`: Queries for values where the distance from the lookup geometry is greater than the specified distance value\n\n- `distance_lte`: Queries for values where the distance from the lookup geometry is less than or equal to the specified distance value\n\n- `dwithin`: Queries for values where the distance from the lookup geometry is within the specified distance value\n\n- `intersects`: Queries for values that spatially intersect the lookup geometry\n\n- `within`: Queries for values that are spatially within the bounds of the lookup geometry\n\nTo learn more about these lookups, see Spatial Lookups in the Django documentation.\n\n#### Example\n\nTo view the sample models used in this example, see the Model Example in the Model Geospatial Data guide.\n\nThis example uses the `within` spatial lookup to query the `Theater` model, which contains an embedded `Location` model storing geospatial data. The code queries for documents that have `location.geo` field values within the boundaries of Manhattan:\n\n```python\nfrom django.contrib.gis.geos import Polygon\n\nmanhattan_coords = [\n [-73.925492, 40.877410],\n [-73.910372, 40.872366],\n [-73.935127, 40.834020],\n [-73.929049, 40.798569],\n [-73.976485, 40.711432],\n [-74.015747, 40.701229],\n [-74.018859, 40.708367],\n [-74.008007, 40.754307],\n [-73.925492, 40.877410]\n]\n\n# Creates a polygon from the coordinates\nsearch_area = Polygon(manhattan_coords)\nTheater.objects.filter(location__geo__within=search_area)\n```\n\n```\n, , ,\n, , , ,\n]>\n```\n\n### Query JSON Values\n\nYou can query data stored in a `JSONField` value by using the same syntax as show in the Query Embedded Model Values section. Chain each field and nested field name together, separated by double underscores (`__`), until you reach the field you want to query.\n\nThe following example queries the `JSONField`-valued `imdb` field for values of its nested `votes` field that exceed `900000`:\n\n```python\nMovie.objects.filter(imdb__votes__gt=900000)\n```\n\n```\n, ,\n, , ,\n, ,\n,\n, ,\n,\n, ,\n, ,\n, , ,\n, ,\n'...(remaining elements truncated)...']>\n```\n\n#### Annotate and Filter JSON Data\n\nYou can use `KT()` expressions to annotate and filter data stored in a `JSONField` value. `KT()` expressions allow you to work with the text value of keys, indexes, or path transforms within a `JSONField`. Pass your `KT()` expression to the `annotate()` method, which annotates each object in the `QuerySet` with the provided `KT()` expressions.\n\nTo learn more about `KT()` expressions and the `annotate()` method, see the following resources in the Django documentation:\n\n- `KT`\n\n- `annotate`\n\nThe following example uses `annotate()` and `KT()` to create a new `score` key, which stores `imdb.rating` nested field values. Then, the code sorts each document in the `sample_mflix.movies` collection by their descending `score` values:\n\n```python\nfrom django.db.models.fields.json import KT\n\nMovie.objects.annotate(score=KT(\"imdb__rating\")).all().order_by(\"-score\")\n```\n\n```\n, , ,\n, ,\n, , ,\n, ,\n, , ,\n, , ,\n, ,\n, ,\n'...(remaining elements truncated)...']>\n```\n\n### Query Primary Key Values\n\nYou can use the `pk` lookup shortcut to query primary key values, which MongoDB stores as `ObjectId` values.\n\nThe following example queries the `sample_mflix.movies` collection for a document whose primary key is `ObjectId(\"573a1394f29313caabce0d37\")`:\n\n```python\nfrom bson import ObjectId\n\nMovie.objects.get(pk=ObjectId(\"573a1394f29313caabce0d37\"))\n```\n\n```\n// Your ObjectId values might differ\n\n\n```\n\nThe `Movie` model, which represents the `sample_mflix.movies` collection, uses the `id` field as its primary key. The following example constructs the same query as the preceding code by using the `id` field:\n\n```python\nfrom bson import ObjectId\n\nMovie.objects.get(id=ObjectId(\"573a1394f29313caabce0d37\"))\n```\n\n## Additional Information\n\nTo learn how to run raw database queries by using MongoDB's aggregation pipeline syntax, see the Perform Raw Database Queries guide.\n\nTo learn how to perform other `QuerySet` operations, see the Perform CRUD Operations guide.\n\nTo learn more about Django queries, see Making queries in the Django documentation."} -{"chunk_id": "68a95c3c5e79d242619e1a67-0", "page_id": "68a95c3c5e79d242619e1a67", "source_name": "django", "product_name": "Django MongoDB Backend", "url": "https://mongodb.com/docs/languages/python/django-mongodb/current/interact-data/crud", "title": "Perform CRUD Operations", "text": "# Perform CRUD Operations\n\n## Overview\n\nIn this guide, you can learn how to use Django MongoDB Backend to run create, read, update, and delete (CRUD) operations on your MongoDB collection.\n\nYou can also use the Django admin site to edit your models and their corresponding collections on a web interface. For more information, see the Django Admin Site entry in the Django documentation.\n\n### Query API\n\nYou can use methods provided by the Django `QuerySet` API to run CRUD operations. To run these operations, you can call `QuerySet` methods on your model's manager. The `Manager` class handles database operations and allows you to interact with your MongoDB data by referencing Django models. By default, Django adds a `Manager` named `objects` to every model class.\n\nTo learn more about Django's `QuerySet` API, see `QuerySet` in the Django documentation.\n\nThis guide shows how to use the following `QuerySet` methods:\n\n- create(): Inserts documents into the collection\n\n- filter() and get(): Retrieves one or multiple collection documents\n\n- update(): Modifies collection documents\n\n- delete(): Deletes collection documents\n\n### Sample Data\n\nThe examples in this guide use the `Movie` model, which represents the `sample_mflix.movies` collection from the Atlas sample datasets. The `Movie` model class has the following definition:\n\n```python\nfrom django.db import models\nfrom django_mongodb_backend.fields import ArrayField\n\nclass Movie(models.Model):\n title = models.CharField(max_length=200)\n plot = models.TextField(blank=True)\n runtime = models.IntegerField(default=0)\n released = models.DateTimeField(\"release date\", null=True, blank=True)\n genres = ArrayField(models.CharField(max_length=100), null=True, blank=True)\n\n class Meta:\n db_table = \"movies\"\n managed = False\n\n def __str__(self):\n return self.title\n```\n\n`Movie` model includes\n\n```python\nfrom .models import Movie\nfrom django.utils import timezone\nfrom datetime import datetime\n```\n\nThe `Movie` model includes an inner `Meta` class, which specifies model metadata, and a `__str__()` method, which defines the model's string representation. To learn about these model features, see Define a Model in the Create Models guide.\n\n#### Run Code Examples\n\nYou can use the Python interactive shell to run the code examples. To enter the shell, run the following command from your project's root directory:\n\n```bash\npython manage.py shell\n```\n\nAfter entering the Python shell, ensure that you import the following models and modules:\n\n```python\nfrom .models import Movie\nfrom django.utils import timezone\nfrom datetime import datetime\n```\n\nTo learn how to create a Django application that uses the `Movie` model and the Python interactive shell to interact with MongoDB documents, visit the Get Started with Django MongoDB Backend tutorial.\n\n## Insert Documents\n\nTo insert a document into a collection, call the `create()` method on your model's manager. Pass the new document's field names and field values as arguments to the `create()` method.\n\n### Example\n\nThe following example calls the `create()` method to insert a document into the `sample_mflix.movies` collection. The new document has a `title` value of `\"Poor Things\"` and a `runtime` value of `141`:\n\n```python\nMovie.objects.create(title=\"Poor Things\", runtime=141)\n```\n\nThe `create()` method allows you to create a new `Movie` object and save the object to MongoDB in one method call. Alternatively, you can create a `Movie` object and call `save()`, as shown in the following code:\n\n```python\nmovie = Movie(title=\"Poor Things\", runtime=141)\nmovie.save()\n```\n\nTo learn more about the `create()` method, see `create` in the Django documentation.\n\n## Read Documents\n\nTo retrieve documents from your collection, call the `filter()` method on your model's manager. Pass a query filter, or criteria that specifies which documents to retrieve, as an argument to the `filter()` method.\n\nAlternatively, you can call the `get()` method to retrieve a single document that matches your query.\n\n### Return Multiple Documents Example\n\nThe following example calls the `filter()` method to retrieve documents from the `sample_mflix.movies` collection. The query returns `Movie` objects that represent movies released on January 1, 2000:\n\n```python\nMovie.objects.filter(released=timezone.make_aware(datetime(2000, 1, 1)))\n```\n\n```\n , ,\n , , ,\n ]>\n```\n\nTo learn more about the `filter()` method, see `filter` in the Django documentation.\n\n### Return One Document Example\n\nTo retrieve only one document that matches your query criteria, call the `get()` method and pass a query filter as an argument. The following example retrieves a document in which the `title` value is `\"Boyhood\"`:\n\n```python\nMovie.objects.get(title=\"Boyhood\")\n```\n\n```\n \n```\n\nIf your query matches no documents or multiple documents, the `get()` method generates an error. To retrieve one document from a query that might match multiple, chain the `first()` method to `filter()`, as shown in the following code:\n\n```python\nMovie.objects.filter(title=\"Boyhood\").first()\n```\n\nTo learn more about the `get()` method, see `get` in the Django documentation.\n\n## Modify Documents\n\nTo modify documents in a collection, call the `filter()` and `update()` methods on your model's manager. Pass a query filter, or criteria that specifies which documents to update, as an argument to the `filter()` method. Then, pass the fields and values you want to update as arguments to the `update()` method.\n\n### Example\n\nThe following example calls the `update()` method to modify documents in the `sample_mflix.movies` collection. The code matches a document that has a `title` value of `\"High Fidelity\"` and adds a `plot` field:\n\n```python\nMovie.objects.filter(\n title=\"High Fidelity\").update(\n plot=\"Rob, a record store owner, recounts his top five breakups,including the one in progress.\")\n```\n\n```\n // Outputs the number of modified documents\n 1\n```\n\nTo learn more about the `update()` method, see `update` in the Django documentation.\n\n## Delete Documents\n\nTo delete documents in a collection, call the `filter()` and `delete()` methods on your model's manager, Pass a query filter, or criteria that specifies which documents to delete, as an argument to the `filter()` method.\n\n### Example\n\nThe following example calls the `delete()` method to delete documents in the `sample_mflix.movies` collection. The code matches and deletes documents that have a `runtime` value of `5`:\n\n```python\nMovie.objects.filter(runtime=5).delete()\n```\n\n```\n // Outputs the number of deleted documents and objects\n (16, {'sample_mflix.Movie': 16})\n```\n\nTo learn more about the `delete()` method, see `delete` in the Django documentation.\n\n## Additional Information\n\nTo learn more about performing read operations, see the Specify a Query guide.\n\nTo view more create, read, update, and delete examples, see the following steps of the Get Started with Django MongoDB Backend tutorial:\n\n- Write Data to MongoDB\n\n- Query MongoDB Data"} -{"chunk_id": "6a76cb256b218fc00ba0b65e-0", "page_id": "6a76cb256b218fc00ba0b65e", "source_name": "django", "product_name": "Django MongoDB Backend", "url": "https://mongodb.com/docs/languages/python/django-mongodb/current/integrations/djongo-migration", "title": "Migrate Your Djongo Application", "text": "# Migrate Your Djongo Application\n\n## Overview\n\nIn this guide, you can learn how to modify your Djongo project to use Django MongoDB Backend. Djongo is a third-party library that translates SQL queries into MongoDB Query Language (MQL) queries, allowing you to use MongoDB as your Django backend for Django versions 4.0 and earlier. However, Django MongoDB Backend is the officially supported integration and offers more comprehensive Django support, expanded access to MongoDB features, and compatibility with newer Django versions.\n\nThis guide shows how to migrate a Djongo application to Django MongoDB Backend by updating the following application components:\n\n- Database Settings\n\n- Installed Apps\n\n- Model Definitions\n\n- Indexes\n\n- Queries\n\n- Migrations\n\n## Database Settings\n\nTo connect to MongoDB by using Django MongoDB Backend instead of Djongo, modify the `DATABASES` setting in your application's `settings.py` file. Update the value of this setting's nested `ENGINE` key from `\"djongo\"` to `\"django_mongodb_backend\"`. Then, specify your connection string in the nested `HOST` key instead of the `CLIENT` key.\n\nTo learn more about the `DATABASES` setting, see the Connect to MongoDB guide.\n\n### Example\n\nThe following example shows how to modify your `DATABASES` setting to use Django MongoDB Backend. Select the Djongo tab to see the initial setting configuration, and select the Django MongoDB Backend tab to see the updated setting:\n\n\n\n\n\n```python\nDATABASES = {\n 'default': {\n 'ENGINE': 'djongo',\n 'CLIENT': {\n 'host': 'mongodb+srv://cluster0.example.mongodb.net',\n },\n 'NAME': 'my_database'\n }\n}\n```\n\n\n\n\n\n```python\nDATABASES = {\n 'default': {\n 'ENGINE': 'django_mongodb_backend',\n 'HOST': 'mongodb+srv://cluster0.example.mongodb.net',\n 'NAME': 'my_database'\n },\n}\n```\n\n\n\n\n\n## Installed Apps\n\nDjongo does not require any additional configuration of Django's built-in `contrib` apps. However, Django MongoDB Backend requires each `contrib` app that includes models to use `ObjectIdAutoField` as its default primary key field type. This affects the following apps:\n\n- `django.contrib.admin`\n\n- `django.contrib.auth`\n\n- `django.contrib.contenttypes`\n\nThe django-mongodb-project template includes the required `AppConfig` subclasses and `MIGRATION_MODULES` setting for the preceding apps. To learn how to create a project by using this template, see the Get Started with Django MongoDB Backend tutorial.\n\nTo configure these apps, create or update the `apps.py` file in your project directory to define a custom `AppConfig` subclass for each of the preceding apps. The following example shows a sample `apps.py` file that defines these `AppConfig` subclasses:\n\n```python\nfrom django.contrib.admin.apps import AdminConfig\nfrom django.contrib.auth.apps import AuthConfig\nfrom django.contrib.contenttypes.apps import ContentTypesConfig\n\nclass MongoAdminConfig(AdminConfig):\n default_auto_field = \"django_mongodb_backend.fields.ObjectIdAutoField\"\n\nclass MongoAuthConfig(AuthConfig):\n default_auto_field = \"django_mongodb_backend.fields.ObjectIdAutoField\"\n\nclass MongoContentTypesConfig(ContentTypesConfig):\n default_auto_field = \"django_mongodb_backend.fields.ObjectIdAutoField\"\n```\n\nThen, update the `INSTALLED_APPS` setting in your `settings.py` file to use your custom `AppConfig` classes instead of the default classes. The following example updates the settings of a project named `myproject` to use the custom `AppConfig` classes. Select the Djongo tab to see the initial settings, and select the Django MongoDB Backend tab to see the updated settings:\n\n\n\n\n\n```python\nINSTALLED_APPS = [\n 'myapp.apps.MyAppConfig',\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n]\n```\n\n\n\n\n\n```python\nINSTALLED_APPS = [\n 'myapp.apps.MyAppConfig',\n 'myproject.apps.MongoAdminConfig',\n 'myproject.apps.MongoAuthConfig',\n 'myproject.apps.MongoContentTypesConfig',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'django_mongodb_backend',\n]\n```\n\n\n\n\n\nFinally, add the `MIGRATION_MODULES` setting to your `settings.py` file to instruct Django MongoDB Backend to use MongoDB-compatible migration modules for the affected `contrib` apps:\n\n```python\nMIGRATION_MODULES = {\n 'admin': 'mongo_migrations.admin',\n 'auth': 'mongo_migrations.auth',\n 'contenttypes': 'mongo_migrations.contenttypes',\n}\n```\n\nAfter you complete the preceding steps, run the following commands to apply the migrations for the `contrib` apps:\n\n```bash\npython manage.py makemigrations\npython manage.py migrate\n```\n\n## Model Definitions\n\nTo update your models to use Django MongoDB Backend, make the following changes to your model definitions:\n\n1. Import the `models` module from `django.db` instead of from `djongo`.\n\n2. Remove explicit `ObjectIdField` definitions, because Django MongoDB Backend automatically creates an `_id` field of type `ObjectIdField`.\n\n3. Modify the syntax of MongoDB-specific array and embedded fields.\n\nDjongo and Django MongoDB Backend likely store Django fields in the same format. However, you might experience incompatibilities due to differences in the integrations' field converters. If you encounter any issues, you can submit feedback by using the Rate this page tab on the right side of this page.\n\nTo learn more Django MongoDB Backend models, see the Create Models to Represent Collections guide.\n\n### Single Model Example\n\nThe following example shows how to update a model class named `Recipe` for compatibility with Django MongoDB Backend. Select the Djongo tab to see the initial model, and select the Django MongoDB Backend tab to see the updated model:\n\n\n\n\n\n```python\nfrom djongo import models\n\nclass Tag(models.Model):\n data = models.CharField(max_length=100)\n\n class Meta:\n abstract = True\n\nclass Recipe(models.Model):\n _id = models.ObjectIdField()\n title = models.CharField(max_length=100)\n cuisine = models.CharField(max_length=100)\n cook_time = models.IntegerField(default=0)\n tags = models.ArrayField(model_container=Tag)\n```\n\n\n\n\n\n```python\nfrom django.db import models\nfrom django_mongodb_backend.fields import ArrayField\n\nclass Recipe(models.Model):\n title = models.CharField(max_length=100)\n cuisine = models.CharField(max_length=100)\n cook_time = models.IntegerField(default=0)\n tags = ArrayField(\n models.CharField(max_length=100),\n size=4,\n null=True,\n blank=True)\n```\n\n\n\n\n\nTo create a `Recipe` object that stores the preceding fields, use the following code:\n\n\n\n\n\n```python\nRecipe.objects.create(\n title=\"Tiramisu\",\n cuisine=\"Italian\",\n cook_time=20,\n tags=[\n {\"data\": \"dessert\"},\n {\"data\": \"classic\"},\n {\"data\": \"espresso\"},\n {\"data\": \"chocolate\"}\n ]\n)\n```\n\n\n\n\n\n```python\nRecipe.objects.create(\n title=\"Tiramisu\",\n cuisine=\"Italian\",\n cook_time=20,\n tags=[\"dessert\", \"classic\", \"espresso\", \"chocolate\"]\n)\n```\n\n\n\n"} -{"chunk_id": "6a76cb256b218fc00ba0b65e-1", "page_id": "6a76cb256b218fc00ba0b65e", "source_name": "django", "product_name": "Django MongoDB Backend", "url": "https://mongodb.com/docs/languages/python/django-mongodb/current/integrations/djongo-migration", "title": "Migrate Your Djongo Application", "text": "### Embedded Model Example\n\nWhen using Djongo, you can use an `EmbeddedField` to represent an embedded MongoDB document. To define a field that stores multiple embedded documents, you can use an `ArrayField`.\n\nDjango MongoDB Backend provides the following fields that represent embedded documents:\n\n- `EmbeddedModelField`: Stores a nested model\n\n- `EmbeddedModelArrayField`: Stores an array of nested models\n\nYou cannot use Djongo fields to store an array of multiple model types. However, Django MongoDB Backend provides the `PolymorphicEmbeddedModelField` and `PolymorphicEmbeddedModelArrayField` fields to support polymorphism. To learn more, see Use Advanced Fields in the Create Models guide.\n\nThe following example shows how to update a `models.py` file that defines a `Recipe` model containing the following embedded model fields:\n\n- `nutrition`: Stores one embedded `Nutrition` model that represents nutrition information\n\n- `reviews`: Stores multiple embedded `Review` models that represent individual recipe reviews\n\nSelect the Djongo tab to see the initial models, and select the Django MongoDB Backend tab to see the updated models:\n\n\n\n\n\n```python\nfrom djongo import models\n\nclass Nutrition(models.Model):\n calories = models.IntegerField(default=0)\n carb_grams = models.IntegerField(default=0)\n protein_grams = models.IntegerField(default=0)\n\n class Meta:\n abstract = True\n\nclass Review(models.Model):\n author = models.CharField(max_length=100)\n rating = models.IntegerField(default=0)\n\n class Meta:\n abstract = True\n\nclass Recipe(models.Model):\n _id = models.ObjectIdField()\n title = models.CharField(max_length=100)\n cuisine = models.CharField(max_length=100)\n cook_time = models.IntegerField(default=0)\n nutrition = models.EmbeddedField(model_container=Nutrition)\n reviews = models.ArrayField(model_container=Review)\n```\n\n\n\n\n\n```python\nfrom django.db import models\nfrom django_mongodb_backend.models import EmbeddedModel\nfrom django_mongodb_backend.fields import EmbeddedModelField, EmbeddedModelArrayField\n\nclass Nutrition(EmbeddedModel):\n calories = models.IntegerField(default=0)\n carb_grams = models.IntegerField(default=0)\n protein_grams = models.IntegerField(default=0)\n\nclass Review(EmbeddedModel):\n author = models.CharField(max_length=100)\n rating = models.IntegerField(default=0)\n\nclass Recipe(models.Model):\n title = models.CharField(max_length=100)\n cuisine = models.CharField(max_length=100)\n cook_time = models.IntegerField(default=0)\n nutrition = EmbeddedModelField(Nutrition, null=True, blank=True)\n reviews = EmbeddedModelArrayField(Review, null=True, blank=True)\n```\n\n\n\n\n\n## Indexes\n\nTo update the indexes in your Djongo app for Django MongoDB Backend compatibility, you must use the index classes provided by Django MongoDB Backend.\n\nDjongo provides separate classes to represent each MongoDB index, including classes for single field indexes, compound indexes, multikey indexes, and more.\n\nDjango MongoDB Backend provides the following three classes to represent all index types:\n\n- `Index` class: Django's index class, which represents all non-Search index types\n\n- `SearchIndex` class: A Django MongoDB Backend-specific class to represent MongoDB Search indexes\n\n- `VectorSearchIndex` class: A Django MongoDB Backend-specific class to represent MongoDB Vector Search indexes\n\nTo learn more about how to use Django MongoDB Backend to create indexes, see the Indexes for Query Optimization guide.\n\n### Example\n\nThe following example shows how to update a compound index on a `Recipe` model. The Django MongoDB Backend implementation also adds a MongoDB Search index, which Djongo does not support. Select the Djongo tab to see the initial index, and select the Django MongoDB Backend tab to see the updated indexes:\n\n\n\n\n\n```python\nfrom djongo import models\nfrom djongo.models.indexes import CompoundIndex\n\nclass Recipe(models.Model):\n _id = models.ObjectIdField()\n title = models.CharField(max_length=100)\n cuisine = models.CharField(max_length=100)\n cook_time = models.IntegerField(default=0)\n\n class Meta:\n indexes = [\n CompoundIndex(fields=[\"title\", \"cook_time\"])\n ]\n```\n\n\n\n\n\n```python\nfrom django.db import models\nfrom django_mongodb_backend.indexes import SearchIndex\n\nclass Recipe(models.Model):\n title = models.CharField(max_length=100)\n cuisine = models.CharField(max_length=100)\n cook_time = models.IntegerField(default=0)\n\n class Meta:\n indexes = [\n models.Index(fields=[\"title\", \"cook_time\"]),\n SearchIndex(fields=[\"cuisine\"], name=\"cuisine_search_idx\")\n ]\n```\n\n\n\n\n\n## Queries\n\nYou can use Django's `QuerySet` API to query both Djongo and Django MongoDB Backend models. However, the syntax differs for embedded model queries.\n\nDjongo treats embedded models as Python dictionaries, and you must use Python dictionary syntax to access or modify their fields. Django MongoDB Backend treats embedded models as Django models, so you use the same syntax for interacting with their fields as with all other models.\n\nDjongo and Django MongoDB Backend queries generate different underlying MQL queries, which might have performance implications. When migrating from Djongo to Django MongoDB Backend, we recommend that you monitor performance changes to identify potential regressions and file a JIRA ticket if you discover any.\n\nTo learn more about how to use Django MongoDB Backend to query your models, see the Specify a Query guide.\n\n### Example\n\nThe following example shows the difference between a Djongo and a Django MongoDB Backend query on the `Recipe` model and its `nutrition` embedded model field, defined in the Embedded Model Example section. The code queries the `Nutrition` embedded model's `calories` field. Select the Djongo tab to see the initial query, and select the Django MongoDB Backend tab to see the updated query:\n\n\n\n\n\n```python\nRecipe.objects.filter(nutrition__lt={'calories': 500})\n```\n\n\n\n\n\n```python\nRecipe.objects.filter(nutrition__calories__lt=500)\n```\n\n\n\n\n\n## Transactions\n\nBoth Djongo and Django MongoDB Backend support Django's atomic transaction API functionality. However, they each provide a custom API to implement this functionality. You can update your transactions for Django MongoDB Backend compatibility by modifying your code's import statement.\n\nTo learn more about how to use Django MongoDB Backend to perform transactions, see the Transactions and Sessions guide.\n\n### Example\n\nThe following example shows how to update your code to import Django MongoDB Backend's transaction API. Select the Djongo tab to see the initial statement, and select the Django MongoDB Backend tab to see the updated statement:\n\n\n\n\n\n```python\nfrom djongo import transaction\n```\n\n\n\n\n\n```python\nfrom django_mongodb_backend import transaction\n```\n\n\n\n\n\n## Migrations\n\nDjongo does not support database migrations and does not enforce schema validation by default. If you set the `ENFORCE_SCHEMA` setting to `True` in your `settings.py` file, Djongo enforces `MigrationErrors` when retrieved documents have missing field values.\n\nDjango MongoDB Backend supports database migrations with some limitations. To learn more about these limitations, see Migration Support in the Feature Compatibility guide.\n\nDjango MongoDB Backend does not enforce schema validation. As a result, updating model fields without running migrations to update the database schema does not generate errors."} -{"chunk_id": "6a76cb256b218fc00ba0b65e-2", "page_id": "6a76cb256b218fc00ba0b65e", "source_name": "django", "product_name": "Django MongoDB Backend", "url": "https://mongodb.com/docs/languages/python/django-mongodb/current/integrations/djongo-migration", "title": "Migrate Your Djongo Application", "text": "## Additional Information\n\nTo learn how to set up a new application that uses Django MongoDB Backend, see the Get Started with Django MongoDB Backend tutorial.\n\nTo learn more about running database operations by using Django MongoDB Backend, see the Perform CRUD Operations guide.\n\nTo learn more about creating Django MongoDB Backend models, see the Create Models to Represent Collections guide."} -{"chunk_id": "68a95c3c5e79d242619e1a6d-0", "page_id": "68a95c3c5e79d242619e1a6d", "source_name": "django", "product_name": "Django MongoDB Backend", "url": "https://mongodb.com/docs/languages/python/django-mongodb/current/model-data", "title": "Model Your Data", "text": "# Model Your Data\n\nIn this section, you can learn how to create and customize your Django models for use with MongoDB.\n\n- Create Models to Represent Collections: Learn how to create models by using supported field types and Django's model configuration features.\n\n- Indexes for Query Optimization: Learn how to create indexes by modifying your model classes.\n\n- Model Relationships and Denormalization: Learn how to choose between embedding and referencing related data, and how to use relational fields across collections.\n\n- Model Geospatial Data: Learn how to model geospatial data by using GeoDjango."} -{"chunk_id": "68a95c3c5e79d242619e1a51-0", "page_id": "68a95c3c5e79d242619e1a51", "source_name": "django", "product_name": "Django MongoDB Backend", "url": "https://mongodb.com/docs/languages/python/django-mongodb/current/connect", "title": "Connect to MongoDB", "text": "# Connect to MongoDB\n\n## Overview\n\nIn this guide, you can learn how to configure your Django project's connection to MongoDB.\n\n## Connection Configuration\n\nAfter installing Django MongoDB Backend and creating a project, you can configure your connection to MongoDB by modifying the `DATABASES` setting in your project's `settings.py` file.\n\nTo learn how to install Django MongoDB Backend and create a Django project, visit the Get Started with Django MongoDB Backend tutorial.\n\nSet `DATABASES` to a dictionary containing the `default` key, as shown in the following code:\n\n```python\nDATABASES = {\n \"default\": {\n # Specify nested dictionary keys here\n },\n}\n```\n\nTo configure the `default` key, assign a nested dictionary as its value. This nested dictionary has the following keys:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nKey\n\n\nDescription\n\n
\n**ENGINE**\n\n\nThe backend driver to use for the connection. Set this key to `\"django_mongodb_backend\"`.\n\n
\n**HOST**\n\n\nThe hostname. For localhost connections, this key is optional.For SRV connections, you must include a scheme prefix (`mongodb+srv://`).You can also specify a connection URI in this key. For more information, see Automatically Configure Database Settings.To specify more than one host, include all hostnames in one string. Use a comma to separate each hostname.**Example:** `\"HOST\": \"mongodb://mongos0.example.com:27017,mongos1.example.com:27017\"`\n\n
\n**NAME**\n\n\nThe database you want to use.\n\n
\n**USER**\n\n\nThe username for authenticating to the database, if your connection requires authentication.\n\n
\n**PASSWORD**\n\n\nThe password for your database user, if your connection requires authentication.\n\n
\n**PORT**\n\n\nThe port number on which the database server is listening. The default port is `27017`.For MongoDB Atlas connections, this key is optional.\n\n
\n**OPTIONS**\n\n\nA dictionary of additional connection options for the database. This key is optional.To see a full list of connection options that you can set in the `OPTIONS` key, see the optional parameters for MongoClient in the PyMongo API documentation.\n\n
This section shows how to use the `DATABASES` setting to configure your connection in the following ways:\n\n- Automatically Configure Database Settings: Use the nested `HOST` key to specify your connection URI and configure connection settings automatically.\n\n- Manually Configure Database Settings: Specify connection settings across multiple dictionary keys.\n\n### Automatically Configure Database Settings\n\nDjango MongoDB Backend v5.2.1 adds support for specifying a connection URI in the nested `HOST` key. If you use a previous version, you can still manually configure your connection.\n\nTo specify connection settings in your connection URI, set the following nested `default` keys:\n\n- `ENGINE`: Set to `\"django_mongodb_backend\"`.\n\n- `HOST`: Set to your connection URI.\n\n- `NAME`: Set to the name of the database you want to use.\n\nAll other keys described in the previous section are optional.\n\n#### Example\n\nThis example uses only the `ENGINE`, `HOST`, and `NAME` keys to configure a connection to MongoDB. The `DATABASES` setting performs the following actions:\n\n- Provides authentication information for a database user whose username is `my_user` and password is `my_password`\n\n- Sets the `retryWrites` connection option to `true`, which configures the driver to automatically retry certain write operations if they fail\n\n- Sets the `w` connection option to `majority`, which configures the driver to wait for acknowledgement from a majority of replica set members before performing write operations\n\n- Sets the database to `my_database`\n\n```python\nDATABASES = {\n \"default\": {\n \"ENGINE\": \"django_mongodb_backend\",\n \"HOST\": \"mongodb+srv://my_user:my_password@cluster0.example.mongodb.net/?retryWrites=true&w=majority\",\n \"NAME\": \"my_database\",\n }\n}\n```\n\nIf you specify additional keys in the `DATABASES` setting, the values in those keys override any conflicting values parsed from the connection URI.\n\n### Manually Configure Database Settings\n\nYou can manually configure your connection settings by specifying connection information across the `default` keys.\n\n#### Example\n\nThis example uses dictionary keys to configure the same database connection as the previous example:\n\n```python\nDATABASES = {\n \"default\": {\n \"ENGINE\": \"django_mongodb_backend\",\n \"HOST\": \"mongodb+srv://cluster0.example.mongodb.net\",\n \"NAME\": \"my_database\",\n \"USER\": \"my_user\",\n \"PASSWORD\": \"my_password\",\n \"PORT\": 27017,\n \"OPTIONS\": {\n \"retryWrites\": \"true\",\n \"w\": \"majority\",\n },\n },\n}\n```\n\n## Additional Information\n\nTo view a sample project that configures a MongoDB database connection, see the Configure your MongoDB Connection step in the Getting Started tutorial.\n\nTo learn more about Django settings, see Settings in the Django documentation."} -{"chunk_id": "6a76cb256b218fc00ba0b661-0", "page_id": "6a76cb256b218fc00ba0b661", "source_name": "django", "product_name": "Django MongoDB Backend", "url": "https://mongodb.com/docs/languages/python/django-mongodb/current/model-data/relationships", "title": "Model Relationships and Denormalization", "text": "# Model Relationships and Denormalization\n\n## Overview\n\nIn this guide, you can learn how to model relationships between collections in Django MongoDB Backend. Because MongoDB is a document database, Django MongoDB Backend provides embedded model fields that store related data in a single document instead of across multiple collections. Django MongoDB Backend also provides an array field, which allows you to store a list of related scalar values in the parent document.\n\nThis guide explains when to use each approach and provides examples to demonstrate the strategies.\n\n### Sample Data\n\nThe examples in this guide define models that represent the following collections in the `sample_mflix` database:\n\n- `movies`: Stores information about movies\n\n- `embedded_movies`: Extends `movies` with vector plot embeddings\n\n- `users`: Stores information about movie viewers\n\n- `comments`: Stores information about movie comments\n\nTo learn more about the `sample_mflix` database, see Sample Mflix Dataset in the MongoDB Atlas documentation.\n\n## Denormalization Strategies\n\nRelational databases normalize data into separate tables and use joins to combine related data at query time. MongoDB's document model allows you to embed related data directly inside a parent document instead, which is called **denormalization**. Django MongoDB Backend supports both approaches, but we recommend that you denormalize your data for better performance.\n\nTo denormalize, choose one of the following strategies:\n\n- Embed Related Models: Store related data inside the parent document by using an `EmbeddedModelField` or `EmbeddedModelArrayField`. Embedded data is stored in the same MongoDB document as the parent and retrieved in a single read operation.\n\n- Store Array Data: Store a list of related scalar values directly in the parent document by using an `ArrayField`. Array data is retrieved in a single read operation without `$lookup` operations.\n\n### Embed Related Models\n\nUse an embedded model when all of the following conditions apply:\n\n- The related data is always read together with the parent document.\n\n- The related data belongs to a single parent and is not shared across multiple documents.\n\n- The number of related items is bounded and predictable.\n\nTo embed related data, define an embedded model class as a subclass of `EmbeddedModel`, then use an EmbeddedModelField to store it in the parent model.\n\nThe following example defines a `Director` embedded model, and then defines a `Movie` model that stores an instance of the `Director` model:\n\n```python\nfrom django.db import models\nfrom django_mongodb_backend.models import EmbeddedModel\nfrom django_mongodb_backend.fields import EmbeddedModelField\n\nclass Director(EmbeddedModel):\n first_name = models.CharField(max_length=100)\n last_name = models.CharField(max_length=100)\n\nclass Movie(models.Model):\n title = models.CharField(max_length=200)\n director = EmbeddedModelField(Director, null=True, blank=True)\n```\n\nTo learn more about embedded models, see Store Embedded Model Data in the Create Models guide.\n\n### Store Array Data\n\nUse an ArrayField to store a list of related scalar values directly on the parent document. Array data is stored in the same MongoDB document and retrieved in a single read operation without performing `$lookup` operations. Use this strategy when the following conditions apply:\n\n- The related values are simple scalars, such as strings or integers.\n\n- The array size is bounded and predictable.\n\nThe following example defines a `Movie` model that stores a list of strings in the `cast` field:\n\n```python\nfrom django.db import models\nfrom django_mongodb_backend.fields import ArrayField\n\nclass Movie(models.Model):\n title = models.CharField(max_length=200)\n cast = ArrayField(models.CharField(max_length=100), blank=True)\n```\n\nTo store arrays of structured documents instead of scalar values, use an EmbeddedModelArrayField instead. To learn more, see Store Embedded Model Array Data in the Create Models guide.\n\n## Relational Fields\n\nQueries across relational fields use MongoDB's `$lookup` operator, which can be slow for large collections. When possible, use embedded models instead. To learn more about performance considerations, see Performance Limitations.\n\nIf your data is structured similarly to a relational database and you need to model large hierarchical datasets, you can use the following relational Django fields that link documents across separate collections:\n\n- ForeignKey\n\n- OneToOneField\n\n- ManyToManyField\n\nYou cannot use relational fields inside embedded model classes or as the `base_field` of an `ArrayField`.\n\n### ForeignKey\n\nUse a `ForeignKey` field to create a many-to-one relationship between two models. Each document in the referencing model links to one document in the referenced model. Pass the following arguments to the `ForeignKey()` constructor:\n\n- `to`: The model class to link to\n\n- `on_delete`: The deletion behavior when you delete the referenced document\n\nThe following example links a `Comment` model to a `Movie` model by using a `ForeignKey` field. When you delete a `sample_mflix.movies` document, all related `sample_mflix.comments` documents are also deleted:\n\n```python\nfrom django.db import models\n\nclass Movie(models.Model):\n title = models.CharField(max_length=200)\n\nclass Comment(models.Model):\n movie = models.ForeignKey(\n Movie,\n on_delete=models.CASCADE,\n )\n text = models.TextField()\n```\n\nTo learn more about `on_delete` options, see `ForeignKey.on_delete` in the Django documentation.\n\n### OneToOneField\n\nUse a `OneToOneField` field to create a one-to-one relationship between two models. Each document in the referencing model links to exactly one document in the referenced model. Pass the following arguments to the `OneToOneField()` constructor:\n\n- `to`: The model class to link to\n\n- `on_delete`: The deletion behavior when the referenced document is deleted\n\nThe following example defines an `EmbeddedMovie` model that links to a `Movie` model by using a `OneToOneField` field. When you delete a `sample_mflix.movies` document, its linked `sample_mflix.embedded_movies` document is also deleted:\n\n```python\nfrom django.db import models\nfrom django_mongodb_backend.fields import ArrayField\n\nclass Movie(models.Model):\n title = models.CharField(max_length=200)\n\nclass EmbeddedMovie(models.Model):\n movie = models.OneToOneField(\n Movie,\n on_delete=models.CASCADE,\n )\n plot_embedding = ArrayField(models.FloatField(), blank=True)\n```\n\n### ManyToManyField\n\nUse a `ManyToManyField` field to create a many-to-many relationship between two models. Each document in either model can link to multiple documents in the other model. Pass the model class to link to as the first argument to the `ManyToManyField()` constructor.\n\nThe following example links a `Viewer` model to a `Movie` model. Each viewer can watch multiple movies, and each movie can be watched by multiple viewers:\n\n```python\nfrom django.db import models\n\nclass Movie(models.Model):\n title = models.CharField(max_length=200)\n\nclass Viewer(models.Model):\n name = models.CharField(max_length=100)\n email = models.CharField(max_length=200)\n watched = models.ManyToManyField(Movie, blank=True)\n```"} -{"chunk_id": "6a76cb256b218fc00ba0b661-1", "page_id": "6a76cb256b218fc00ba0b661", "source_name": "django", "product_name": "Django MongoDB Backend", "url": "https://mongodb.com/docs/languages/python/django-mongodb/current/model-data/relationships", "title": "Model Relationships and Denormalization", "text": "## Convert Relational to Embedded Data\n\nIf you have existing models that use relational fields and want to improve read performance, you can convert them to use embedded models instead. This eliminates `$lookup` operations and stores all related data in a single MongoDB document.\n\nThis example defines a `Movie` model that has the following relational fields:\n\n- `ForeignKey`, which links to `Director`\n\n- `OneToOneField`, which links to `Award`\n\n- `ManyToManyField`, which links to `Writer`\n\n```python\nfrom django.db import models\n\nclass Director(models.Model):\n first_name = models.CharField(max_length=100)\n last_name = models.CharField(max_length=100)\n\nclass Award(models.Model):\n wins = models.IntegerField(default=0)\n nominations = models.IntegerField(default=0)\n text = models.CharField(max_length=100)\n\nclass Writer(models.Model):\n first_name = models.CharField(max_length=100)\n last_name = models.CharField(max_length=100)\n\nclass Movie(models.Model):\n title = models.CharField(max_length=200)\n director = models.ForeignKey(\n Director,\n null=True,\n on_delete=models.SET_NULL,\n )\n awards = models.OneToOneField(\n Award,\n null=True,\n on_delete=models.SET_NULL,\n )\n writers = models.ManyToManyField(Writer, blank=True)\n```\n\nTo convert these relational fields to embedded fields, change each related model to extend `EmbeddedModel` instead of `models.Model`, then replace the `Movie` model's relational fields with the corresponding embedded fields:\n\n- Replace the `ForeignKey` with an `EmbeddedModelField`\n\n- Replace the `OneToOneField` with an `EmbeddedModelField`\n\n- Replace the `ManyToManyField` with an `EmbeddedModelArrayField`\n\nThe following example shows the converted `Movie` model:\n\n```python\nfrom django.db import models\nfrom django_mongodb_backend.models import EmbeddedModel\nfrom django_mongodb_backend.fields import (\n EmbeddedModelField,\n EmbeddedModelArrayField,\n)\n\nclass Director(EmbeddedModel):\n first_name = models.CharField(max_length=100)\n last_name = models.CharField(max_length=100)\n\nclass Award(EmbeddedModel):\n wins = models.IntegerField(default=0)\n nominations = models.IntegerField(default=0)\n\nclass Writer(EmbeddedModel):\n first_name = models.CharField(max_length=100)\n last_name = models.CharField(max_length=100)\n\nclass Movie(models.Model):\n title = models.CharField(max_length=200)\n director = EmbeddedModelField(Director, null=True, blank=True)\n awards = EmbeddedModelField(Award, null=True, blank=True)\n writers = EmbeddedModelArrayField(Writer, blank=True)\n```\n\n## Additional Information\n\nTo learn how to query data across related models, see Advanced Field Queries in the Specify a Query guide.\n\nTo learn more about Django relational fields, see the `Model field reference` in the Django documentation.\n\nTo learn more about embedded models, see Store Embedded Model Data in the Create Models guide."} -{"chunk_id": "68a95c3c5e79d242619e1a66-0", "page_id": "68a95c3c5e79d242619e1a66", "source_name": "django", "product_name": "Django MongoDB Backend", "url": "https://mongodb.com/docs/languages/python/django-mongodb/current", "title": "Django MongoDB Backend", "text": "# Django MongoDB Backend\n\n## Introduction\n\nWelcome to the documentation site for the official Django MongoDB Backend, a Django database backend that uses PyMongo to connect to MongoDB.\n\n## Get Started\n\nLearn how to install Django MongoDB Backend, establish a connection to MongoDB, and begin working with data in the Get Started with Django MongoDB Backend tutorial.\n\n## Connection Configuration\n\nLearn how to configure a connection to a MongoDB deployment in the Connect to MongoDB section.\n\n## Model Your Data\n\nLearn how to create Django models that represent MongoDB collections in the Model Your Data section.\n\n## Interact with Data\n\nLearn how to use Django MongoDB Backend to perform operations on MongoDB data in the Interact with Data section.\n\n## Django and MongoDB Feature Compatibility\n\nLearn about Django MongoDB Backend's support for Django and MongoDB features in the Django and MongoDB Feature Compatibility section.\n\n## Compatibility\n\nLearn about the versions of MongoDB Server, PyMongo, Python, and Django that are compatible with Django MongoDB Backend on the Compatibility page.\n\n## Issues & Help\n\nLearn how to report bugs, contribute to Django MongoDB Backend, and find more resources for receiving help in the Issues & Help section."} -{"chunk_id": "68a95b585e79d242619cc97a-0", "page_id": "68a95b585e79d242619cc97a", "source_name": "docs", "product_name": "MongoDB Server", "url": "https://mongodb.com/docs/manual/core/replica-set-primary", "title": "Replica Set Primary", "text": "# Replica Set Primary\n\nThe primary is the only member in the replica set that receives write operations. MongoDB applies write operations on the primary and then records the operations on the primary's oplog. Secondary members replicate this log and apply the operations to their data sets.\n\nIn the following three-member replica set, the primary accepts all write operations. Then the secondaries replicate the oplog to apply to their data sets.\n\nAll members of the replica set can accept read operations. However, by default, an application directs its read operations to the primary member. See Read Preference for details on changing the default read behavior.\n\nThe replica set can have at most one primary. If the current primary becomes unavailable, an election determines the new primary. See Replica Set Elections for more details.\n\nIn the following 3-member replica set, the primary becomes unavailable. This triggers an election which selects one of the remaining secondaries as the new primary.\n\nIn some circumstances, two nodes in a replica set may *transiently* believe that they are the primary, but at most, one of them will be able to complete writes with `{ w: \"majority\" }` write concern. The node that can complete `{ w: \"majority\" }` writes is the current primary, and the other node is a former primary that has not yet recognized its demotion, typically due to a network partition. When this occurs, clients that connect to the former primary may observe stale data despite having requested read preference `primary`, and new writes to the former primary will eventually roll back."} -{"chunk_id": "68a95b585e79d242619cca66-0", "page_id": "68a95b585e79d242619cca66", "source_name": "docs", "product_name": "MongoDB Server", "url": "https://mongodb.com/docs/manual/core/unsharded-collections", "title": "Unsharded Collections", "text": "# Unsharded Collections\n\nStarting in MongoDB 8.0, you can unshard a sharded collection by using the `unshardCollection` command. When you unshard a collection, MongoDB moves the collection data onto a single shard and updates the metadata to reflect the unsharded state.\n\n## Command Syntax\n\nTo unshard a collection, use the `unshardCollection` command:\n\n```javascript\ndb.adminCommand({\n unshardCollection : \".\",\n toShard : \"\"\n})\n```\n\n## Use Cases\n\nA user can unshard a collection if:\n\n- You can store the collection entirely on a single shard.\n\n- The collection requires resource isolation, and access patterns are better supported if the collection lives on a single shard. To meet the same requirements on a sharded collection, see Zone Sharding.\n\n- The collection was previously sharded but no longer needs to be sharded.\n\n## Get Started\n\n- Unshard a Collection\n\n## Access Control\n\nIf your deployment has access control enabled, the `enableSharding` role grants you access to run the `unshardCollection` command.\n\n## Details\n\nAn unsharded collection's data only lives on one shard and the shard key is removed. Collections that you manually unshard behave the same as newly created collections that were never sharded.\n\nYou can specify the destination shard with the optional `toShard` field. If you don't specify a destination shard, MongoDB automatically selects the shard with the least amount of data.\n\n## Learn More\n\n- Moveable Collections\n\n- `unshardCollection`"} -{"chunk_id": "68a95b585e79d242619cd2a4-0", "page_id": "68a95b585e79d242619cd2a4", "source_name": "docs", "product_name": "MongoDB Server", "url": "https://mongodb.com/docs/manual/reference/operator/update-field", "title": "Field Update Operators", "text": "# Field Update Operators\n\nFor details on a specific command, including syntax and examples, click on the link to the command's reference page.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nDescription\n\n
\n`$currentDate`\n\n\nSets the value of a field to current date, either as a Date or a Timestamp.\n\n
\n`$inc`\n\n\nIncrements the value of the field by the specified amount.\n\n
\n`$min`\n\n\nOnly updates the field if the specified value is less than the existing field value.\n\n
\n`$max`\n\n\nOnly updates the field if the specified value is greater than the existing field value.\n\n
\n`$mul`\n\n\nMultiplies the value of the field by the specified amount.\n\n
\n`$rename`\n\n\nRenames a field.\n\n
\n`$set`\n\n\nSets the value of a field in a document.\n\n
\n`$setOnInsert`\n\n\nSets the value of a field if an update results in an insert of a document. Has no effect on update operations that modify existing documents.\n\n
\n`$unset`\n\n\nRemoves the specified field from a document.\n\n
"} -{"chunk_id": "68a95b585e79d242619cca82-0", "page_id": "68a95b585e79d242619cca82", "source_name": "docs", "product_name": "MongoDB Server", "url": "https://mongodb.com/docs/manual/data-modeling", "title": "Data Modeling in MongoDB", "text": "# Data Modeling in MongoDB\n\nData modeling refers to the organization of data within a database and the links between related entities.\n\nMongoDB has a **flexible data model** that allows you to store polymorphic data, meaning:\n\n- Documents within a single collection are not required to have the same set of fields.\n\n- A field's data type can differ between documents within a collection.\n\nA core principle of data modeling in MongoDB is that data that's accessed together should be stored together. You should structure your data model based on your application's data access patterns to optimize performance.\n\nTo learn more, see Best Practices for Data Modeling in MongoDB.\n\n## Use Cases\n\nConsider the following examples that take advantage of the document model's flexibility:\n\n- Your company tracks which department each employee works in. You can embed department information in the `employee` collection to return relevant information in a single query.\n\n- Your e-commerce application shows the five most recent reviews on a product page. You can store all reviews, including older ones, in a separate collection because they are not accessed as frequently.\n\n- Your clothing store needs to create a single-page application for a product catalog. Different products have different attributes and might have different document fields and field types. Despite these differences, you can store all of the products in the same collection.\n\n## Get Started\n\nTo ensure that your data model has a logical structure and achieves optimal performance, plan your schema prior to using your database at a production scale. To determine and implement your data model, follow the schema design process.\n\n## Details\n\n### Developing with a Flexible Data Model\n\nMongoDB's flexible schema lets you iteratively improve your data model as you develop your application.\n\nBy developing with MongoDB's flexible schema, you can:\n\n- Map your data model directly to objects that exist in code.\n\n- Add schema validation only to the sections and aspects of the documents that need stricter control.\n\nFor an example of how you can iteratively modify your data model, see Modify Your Data Model.\n\n### Document Relationships\n\nThe value of a document field can include any of the BSON data types, including other documents, arrays, and arrays of documents. These objects can be used to represent different types of relationships in your data model, including:\n\n- **One-to-one relationships**: Each document is associated with exactly one other document. For example, a patient has exactly one medical record.\n\n- **One-to-many relationships**: Each document is associated with multiple other documents. For example, a web application user can have many posts or comments.\n\n- **Many-to-many relationships**: Each document can be associated with multiple other documents, and vice versa. For example, a student can be enrolled in multiple courses, and each course can have multiple students.\n\nIn MongoDB, you can model relationships by either embedding or referencing your data. By choosing the best data-linking method, you can optimize your data model for your application's specific access patterns.\n\nTo learn more about modeling relationships in MongoDB, see:\n\n- Document Relationships.\n\n- Link Related Data.\n\n### Schema Design: Differences Between Relational and Document Databases\n\nWhen you design a schema for a document database like MongoDB, consider the following important differences from relational databases:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nRelational Database Behavior\n\n\nDocument Database Behavior\n\n
\nYou must determine a table's schema before you insert data. While you can change your data model in a relational database, a fixed schema requires more planning upfront, including consideration of how changes affect dependent references.\n\n\nYou can easily change your data model over time as the needs of your application evolve.\n\n
\nYou often need to join data from several different tables to return the data needed by your application.\n\n\nThe flexible data model lets you store data according to your application's data access patterns. For example, embedding data allows you to avoid complex joins across multiple collections, while improving performance and reducing your deployment's workload.\n\n
\n\n## Learn More\n\n- Best Practices for Data Modeling in MongoDB\n\n- Data Modeling in MongoDB Compass"} -{"chunk_id": "68a95b595e79d242619cd369-0", "page_id": "68a95b595e79d242619cd369", "source_name": "docs", "product_name": "MongoDB Server", "url": "https://mongodb.com/docs/manual/replication", "title": "Replication", "text": "# Replication\n\nA *replica set* in MongoDB is a group of `mongod` processes that maintain the same data set. Replica sets provide redundancy and high availability, and are the basis for all production deployments. This section introduces replication in MongoDB and the components and architecture of replica sets. The section also provides tutorials for common tasks related to replica sets.\n\ndeploy a replica set in the UIYou can deploy a replica set in the UI for deployments hosted in MongoDB Atlas.\n\nThis section describes the replica set architecture used by Atlas Core and self-managed deployments. On Atlas Infinite clusters, the storage layer handles replication and durability independently of the compute nodes. To learn more, see MongoDB Atlas Infinite: Architecture.\n\n## Redundancy and Data Availability\n\nReplication provides redundancy and data availability, maintaining multiple copies of data across database servers to tolerate the loss of any single server.\n\nIn some cases, replication can provide increased read capacity as clients can send read operations to different servers. Maintaining copies of data in different data centers can increase data locality and availability for distributed applications. You can also maintain additional copies for dedicated purposes, such as disaster recovery, reporting, or backup.\n\n## Replication in MongoDB\n\nA replica set is a group of `mongod` instances that maintain the same data set. A replica set contains several data bearing nodes and optionally one arbiter node. Of the data bearing nodes, one and only one member is deemed the primary node, while the other nodes are deemed secondary nodes.\n\nEach replica set node must belong to one, and only one, replica set. Replica set nodes cannot belong to more than one replica set.\n\nThe primary node receives all write operations. A replica set can have only one primary capable of confirming writes with `{ w: \"majority\" }` write concern, although in some circumstances, another mongod instance may transiently believe itself to also be primary. The primary records all changes to its data sets in its operation log, that is, the oplog. For more information on primary node operation, see Replica Set Primary.\n\nThe secondaries replicate the primary's oplog and apply the operations to their data sets such that the secondaries' data sets reflect the primary's data set. If the primary is unavailable, an eligible secondary holds an election to select a new primary. For more information on secondary members, see Replica Set Secondary Members.\n\nIf cost constraints prevent adding another secondary, you may add a `mongod` instance to a replica set as an arbiter. An arbiter participates in elections but does not hold data (that is, does not provide data redundancy). For more information on arbiters, see Replica Set Arbiter.\n\nAn arbiter is always an arbiter whereas a primary may step down and become a secondary and a secondary may become the primary during an election.\n\n## Asynchronous Replication\n\nSecondaries replicate the primary's oplog and apply the operations to their data sets asynchronously. By having the secondaries' data sets reflect the primary's data set, the replica set can continue to function despite the failure of one or more members.\n\nFor more information on replication mechanics, see Replica Set Oplog and Replica Set Data Synchronization.\n\n### Slow Operations\n\nSecondary members of a replica set now log oplog entries that take longer than the slow operation threshold to apply. These slow oplog messages:\n\n- Are logged for the secondaries in the `diagnostic log`.\n\n- Are logged under the `REPL` component with the text `applied op: took ms`.\n\n- Do not depend on the log levels (either at the system or component level)\n\n- Do not depend on the profiling level.\n\n- Are affected by `slowOpSampleRate`.\n\nThe profiler does not capture slow oplog entries.\n\n### Replication Lag and Flow Control\n\nReplication lag is a delay between an operation on the primary and the application of that operation from the oplog to the secondary. Some small delay period may be acceptable, but significant problems emerge as replication lag grows, including building cache pressure on the primary.\n\nAdministrators can limit the rate at which the primary applies its writes with the goal of keeping the `majority committed` lag under a configurable maximum value `flowControlTargetLagSeconds`.\n\nBy default, flow control is `enabled`.\n\nWith flow control enabled, as the lag grows close to the `flowControlTargetLagSeconds`, writes on the primary must obtain tickets before taking locks to apply writes. By limiting the number of tickets issued per second, the flow control mechanism attempts to keep the lag under the target.\n\nFor more information, see Check the Replication Lag and Flow Control.\n\n## Automatic Failover\n\nWhen a primary does not communicate with the other members of the set for more than the configured `electionTimeoutMillis` period (10 seconds by default), an eligible secondary calls for an election to nominate itself as the new primary.\n\nThe median time before a cluster elects a new primary should not typically exceed 12 seconds, assuming default `replica configuration settings`. This includes time required to mark the primary as unavailable and call and complete an election. You can tune this time period by modifying the `settings.electionTimeoutMillis` replication configuration option. Factors such as network latency may extend the time required for replica set elections to complete, which in turn affects the amount of time your cluster may operate without a primary. These factors are dependent on your particular cluster architecture.\n\nLowering the `electionTimeoutMillis` replication configuration option from the default `10000` (10 seconds) can result in faster detection of primary failure. However, the cluster may call elections more frequently due to factors such as temporary network latency even if the primary is otherwise healthy. This can result in increased rollbacks for w : 1 write operations.\n\nYour application connection logic should include tolerance for automatic failovers and the subsequent elections. MongoDB drivers can detect the loss of the primary and automatically retry certain write operations a single time, providing additional built-in handling of automatic failovers and elections:\n\nCompatible drivers enable retryable writes by default\n\nMongoDB provides mirrored reads to pre-warm electable secondary members' cache with the most recently accessed data. Pre-warming the cache of a secondary can help restore performance more quickly after an election.\n\nTo learn more about MongoDB's failover process, see:\n\n- Replica Set Elections\n\n- Retryable Writes\n\n- Rollbacks During Replica Set Failover\n\n## Read Operations\n\n### Read Preference\n\nBy default, clients read from the primary ; however, clients can specify a read preference to send read operations to secondaries.\n\nAsynchronous replication to secondaries means that reads from secondaries may return data that does not reflect the state of the data on the primary.\n\nTransactions that contain read operations must use read preference `primary`. All operations in a given transaction must route to the same member.\n\nFor information on reading from replica sets, see Read Preference."} -{"chunk_id": "68a95b595e79d242619cd369-1", "page_id": "68a95b595e79d242619cd369", "source_name": "docs", "product_name": "MongoDB Server", "url": "https://mongodb.com/docs/manual/replication", "title": "Replication", "text": "### Data Visibility\n\nDepending on the read concern, clients can see the results of writes before the writes are durable:\n\n- Regardless of a write's write concern, other clients using `\"local\"` or `\"available\"` read concern can see the result of a write operation before the write operation is acknowledged to the issuing client.\n\n- Clients using `\"local\"` or `\"available\"` read concern can read data which may be subsequently rolled back during replica set failovers.\n\nFor operations in a multi-document transaction, when a transaction commits, all data changes made in the transaction are saved and visible outside the transaction. That is, a transaction will not commit some of its changes while rolling back others.\n\nUntil a transaction commits, the data changes made in the transaction are not visible outside the transaction.\n\nHowever, when a transaction writes to multiple shards, not all outside read operations need to wait for the result of the committed transaction to be visible across the shards. For example, if a transaction is committed and write 1 is visible on shard A but write 2 is not yet visible on shard B, an outside read at read concern `\"local\"` can read the results of write 1 without seeing write 2.\n\nFor more information on read isolations, consistency and recency for MongoDB, see Read Isolation, Consistency, and Recency.\n\n### Mirrored Reads\n\nMirrored reads reduce the impact of primary elections by pre-warming the caches of `electable` secondary replica set members before a failover occurs. The primary mirrors a sample of the supported operations it receives to electable secondaries.\n\nThe size of the subset of `electable` secondary replica set members that receive mirrored reads can be configured with the `mirrorReads` parameter. See Enable/Disable Support for Mirrored Reads for further details.\n\nMirrored reads do not affect the primary's response to the client. The reads that the primary mirrors to secondaries are \"fire-and-forget\" operations. The primary doesn't await responses.\n\n#### Targeted Mirrored Reads\n\nStarting in MongoDB 8.2, you can selectively mirror read operations to specific servers that need their caches warmed up by tagging the nodes for read mirroring. Unlike general mirrored reads, targeted read mirroring allows you to target hidden nodes and mirror from both primary and secondary nodes.\n\nYou can configure targeted mirrored reads using the `targetedMirroring` field in the `mirrorReads` parameter.\n\n#### Supported Operations\n\nMirrored reads support the following operations:\n\n- `count`\n\n- `distinct`\n\n- `find`\n\n- `findAndModify` (Specifically, the filter is sent as a mirrored read)\n\n- `update` (Specifically, the filter is sent as a mirrored read)\n\n#### Enable/Disable Support for Mirrored Reads\n\nMirrored reads are enabled by default and use a default `sampling rate` of `0.01`. To disable mirrored reads, set the `mirrorReads` parameter to `{ samplingRate: 0.0 }`:\n\n```javascript\ndb.adminCommand( {\n setParameter: 1,\n mirrorReads: { samplingRate: 0.0 }\n} )\n```\n\nWith a sampling rate greater than `0.0`, the primary mirrors supported reads to a subset of `electable` secondaries. With a sampling rate of `0.01`, the primary mirrors one percent of the supported reads it receives to a selection of electable secondaries.\n\nFor example, consider a replica set that consists of one primary and two electable secondaries. If the primary receives `1000` operations that can be mirrored and the sampling rate is `0.01`, the primary mirrors about `10` supported reads to a randomly chosen selection of electable secondaries.\n\n#### Change the Sampling Rate for Mirrored Reads\n\nTo change the sampling rate for mirrored reads, set the `mirrorReads` parameter to a number between `0.0` and `1.0`:\n\n- A sampling rate of `0.0` disables mirrored reads.\n\n- A sampling rate of a number between `0.0` and `1.0` results in the primary forwarding a random sample of the supported reads at the specified sample rate to electable secondaries.\n\n- A sampling rate of `1.0` results in the primary forwarding all supported reads to electable secondaries.\n\nFor details, see `mirrorReads`.\n\n#### Mirrored Reads Metrics\n\nThe `serverStatus` command and the `db.serverStatus()` shell method return `mirroredReads` metrics if you specify the field in the operation:\n\n```javascript\ndb.serverStatus( { mirroredReads: 1 } )\n```\n\n## Transactions\n\nMulti-document transactions are available for replica sets.\n\nTransactions that contain read operations must use read preference `primary`. All operations in a given transaction must route to the same member.\n\nUntil a transaction commits, the data changes made in the transaction are not visible outside the transaction.\n\nHowever, when a transaction writes to multiple shards, not all outside read operations need to wait for the result of the committed transaction to be visible across the shards. For example, if a transaction is committed and write 1 is visible on shard A but write 2 is not yet visible on shard B, an outside read at read concern `\"local\"` can read the results of write 1 without seeing write 2.\n\n## Change Streams\n\nChange streams are available for replica sets and sharded clusters. Change streams allow applications to access real-time data changes without the complexity and risk of tailing the oplog. Applications can use change streams to subscribe to all data changes on a collection or collections.\n\n## Additional Features\n\nReplica sets provide a number of options to support application needs. For example, you may deploy a replica set with members in multiple data centers, or control the outcome of elections by adjusting the `members[n].priority` of some members. Replica sets also support dedicated members for reporting, disaster recovery, or backup functions.\n\nSee Priority 0 Replica Set Members, Hidden Replica Set Members and Delayed Replica Set Members for more information.\n\nIn some circumstances, two nodes in a replica set may *transiently* believe that they are the primary, but at most, one of them will be able to complete writes with `{ w: \"majority\" }` write concern. The node that can complete `{ w: \"majority\" }` writes is the current primary, and the other node is a former primary that has not yet recognized its demotion, typically due to a network partition. When this occurs, clients that connect to the former primary may observe stale data despite having requested read preference `primary`, and new writes to the former primary will eventually roll back."} -{"chunk_id": "68a95b585e79d242619ccf2d-0", "page_id": "68a95b585e79d242619ccf2d", "source_name": "docs", "product_name": "MongoDB Server", "url": "https://mongodb.com/docs/manual/reference/method/db.serverBuildInfo", "title": "db.serverBuildInfo() (mongosh method)", "text": "# db.serverBuildInfo() (mongosh method)\n\n`db.serverBuildInfo()`\nProvides a wrapper around the `buildInfo` database command. `buildInfo` returns a document that contains an overview of parameters used to compile this `mongod` instance.\n\n## Compatibility\n\nThis method is available in deployments hosted in the following environments:\n\n- MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud\n\nThis command is supported in all MongoDB Atlas clusters. For information on Atlas support for all commands, see Unsupported Commands.\n\n- MongoDB Enterprise: The subscription-based, self-managed version of MongoDB\n\n- MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB"} -{"chunk_id": "68a95b585e79d242619cd251-0", "page_id": "68a95b585e79d242619cd251", "source_name": "docs", "product_name": "MongoDB Server", "url": "https://mongodb.com/docs/manual/reference/operator/aggregation/toString", "title": "$toString (expression operator)", "text": "# $toString (expression operator)\n\n## Definition\n\n`$toString`\nConverts a value to a string. If the value cannot be converted to a string, `$toString` errors. If the value is null or missing, `$toString` returns null.\n\n`$toString` has the following syntax:\n\n```javascript\n{\n $toString: \n}\n```\n\nThe `$toString` takes any valid expression.\n\nThe `$toString` is a shorthand for the following `$convert` expression:\n\n```javascript\n{ $convert: { input: , to: \"string\" } }\n```\n\n- `$convert`\n\n- `$dateToString`\n\n## Behavior\n\nThe following table lists the input types that can be converted to a string:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nInput Type\n\n\nBehavior\n\n
\nArray\n\n\nReturns the `Array` as a string.\n\n
\nBinData\n\n\nIf the `BinData` is a UUID, returns the UUID as a string. Otherwise, returns the base64 encoded string value.\n\n
\nBoolean\n\n\nReturns the Boolean value as a string.\n\n
\nDate\n\n\nReturns the `Date` as a string.\n\n
\nDecimal\n\n\nReturns the `Decimal` value as a string.\n\n
\nDouble\n\n\nReturns the `Double` value as a string.\n\n
\nInteger\n\n\nReturns the `Integer` value as a string.\n\n
\nLong\n\n\nReturns the `Long` value as a string.\n\n
\nMaxKey\n\n\nReturns the `MaxKey` as a string.\n\n
\nMinKey\n\n\nReturns the `MinKey` as a string.\n\n
\nObject\n\n\nReturns the object as a string.\n\n
\nObjectId\n\n\nReturns the `ObjectId` value as a hexadecimal string.\n\n
\nRegular Expression\n\n\nReturns the `Regular Expression` as a string.\n\n
\nString\n\n\nNo operation. Returns the string value.\n\n
\nTimestamp\n\n\nReturns the `Timestamp` as a string.\n\n
To convert strings in bases other than `10`, use `$convert` with the `base` option.\n\nThe following table lists some conversion to string examples:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nExample\n\n\nResults\n\n
\n`{ $toString: true }`\n\n\n`\"true\"`\n\n
\n`{ $toString: false }`\n\n\n`\"false\"`\n\n
\n`{ $toString: 2.5 }`\n\n\n`\"2.5\"`\n\n
\n`{ $toString: Int32(2) }`\n\n\n`\"2\"`\n\n
\n`{ $toString: Long(1000) }`\n\n\n`\"1000\"`\n\n
\n`{ $toString: ObjectId(\"5ab9c3da31c2ab715d421285\") }`\n\n\n`\"5ab9c3da31c2ab715d421285\"`\n\n
\n`{ $toString: ISODate(\"2018-03-27T16:58:51.538Z\") }`\n\n\n`\"2018-03-27T16:58:51.538Z\"`\n\n
\n`{ $toString: BinData(4, \"hn3f\") }`\n\n\n`\"hn3f\"`\n\n
\n`{ $toString: /^ABC/i }`\n\n\n`\"/^ABC/i\"`\n\n
\n`{ $toString: new Timestamp(1565545664, 1) }`\n\n\n`\"Timestamp(1565545664, 1)\"`\n\n
\n`{ $toString: [[\"pizza\", {type: \"cheese\"}]] }`\n\n\n`\"[\\\"pizza\\\",{\\\"type\\\":\\\"cheese\\\"}]\"`\n\n
\n`{ $toString: {pizza: {type: \"cheese\"}} }`\n\n\n`\"{\\\"pizza\\\":{\\\"type\\\":\\\"cheese\\\"}}\"`\n\n
\n`{ $toString: MinKey }`\n\n\n`\"MinKey\"`\n\n
\n`{ $toString: MaxKey }`\n\n\n`\"MaxKey\"`\n\n
\n\n## Example\n\nCreate a collection `orders` with the following documents:\n\n```javascript\ndb.orders.insertMany( [\n { _id: 1, item: \"apple\", qty: 5, zipcode: 93445 },\n { _id: 2, item: \"almonds\", qty: 2, zipcode: \"12345-0030\" },\n { _id: 3, item: \"peaches\", qty: 5, zipcode: 12345 },\n] )\n```\n\nThe following aggregation operation on the `orders` collection converts the `zipcode` to string before sorting by the string value:\n\n```javascript\n// Define stage to add convertedZipCode field with the converted zipcode value\n\nzipConversionStage = {\n $addFields: {\n convertedZipCode: { $toString: \"$zipcode\" }\n }\n};\n\n// Define stage to sort documents by the converted zipcode\n\nsortStage = {\n $sort: { \"convertedZipCode\": 1 }\n};\n\ndb.orders.aggregate( [\n zipConversionStage,\n sortStage\n] )\n```\n\nThe operation returns the following documents:\n\n```javascript\n{\n _id: 3,\n item: 'peaches',\n qty: 5,\n zipcode: 12345,\n convertedZipCode: '12345'\n},\n{\n _id: 2,\n item: 'almonds',\n qty: 2,\n zipcode: '12345-0030',\n convertedZipCode: '12345-0030'\n},\n{\n _id: 1,\n item: 'apple',\n qty: 5,\n zipcode: 93445,\n convertedZipCode: '93445'\n}\n```\n\nIf the conversion operation encounters an error, the aggregation operation stops and throws an error. To override this behavior, use `$convert` instead."} -{"chunk_id": "68a95b585e79d242619cc897-0", "page_id": "68a95b585e79d242619cc897", "source_name": "docs", "product_name": "MongoDB Server", "url": "https://mongodb.com/docs/manual/core/indexes/index-types/geospatial/restrictions", "title": "Geospatial Index Restrictions", "text": "# Geospatial Index Restrictions\n\n2d and 2dsphere indexes are geospatial indexes. Geospatial indexes have these restrictions:\n\n## Collation Option\n\n2d indexes do not support the collation option, only binary comparison. Binary comparison compares the numeric Unicode value of each character in each string, and does not account for letter case or accent marks.\n\nTo create a 2d index on a collection that has a non-simple collation, you must explicitly specify `{ collation: { locale: \"simple\" } }` when you create the index.\n\nFor example, consider a collection named `collationTest` with a collation of `{ locale: \"en\" }`:\n\n```js\ndb.createCollection(\n \"collationTest\",\n {\n collation: { locale: \"en\" }\n }\n)\n```\n\nTo create a 2d index on the `collationTest` collection, you must specify `{ collation: { locale: \"simple\" } }`. This command creates a 2d index on the `loc` field:\n\n```js\ndb.collationTest.createIndex(\n {\n loc: \"2d\"\n },\n {\n collation: { locale: \"simple\" }\n }\n)\n```\n\n## Covered Queries\n\nGeospatial indexes cannot cover a query.\n\n## Shard Key\n\nYou cannot use a geospatial index as a shard key. However, you can create a geospatial index on a sharded collection by using a different field as the shard key.\n\n## Multiple Geospatial Indexes with `$geoNear`\n\nIf your collection has multiple geospatial indexes, when you run the `$geoNear` pipeline stage, you must specify the `$geoNear`\n`key` option. The `key` option specifies which index to use to support the query.\n\n## Supported Data Types\n\nA field indexed with a 2dsphere index must contain geometry data. Geometry data can either be:\n\n- GeoJSON data\n\n- Legacy coordinate pairs\n\nYou cannot:\n\n- Insert a document with non-geometry data into a field that is indexed with a 2dsphere index.\n\n- Build a 2dsphere index on a field that contains non-geometry data.\n\n## Number of Index Keys\n\nWhen you create a 2dsphere index, `mongod` maps GeoJSON shapes to an internal representation. The resulting internal representation may be a large array of values.\n\nThe `indexMaxNumGeneratedKeysPerDocument` setting limits the maximum number of keys generated for a single document to prevent out of memory errors. If an operation requires more keys than the `indexMaxNumGeneratedKeysPerDocument` parameter specifies, the operation fails.\n\nBy default, the server allows up to `100,000` index keys per document. To allow more index keys, raise the `indexMaxNumGeneratedKeysPerDocument` value.\n\n## Exact Matches on a Flat Surface\n\nA 2d index cannot improve performance for exact matches on a coordinate pair.\n\nFor example, consider a `contacts` collection with these documents:\n\n```javascript\ndb.contacts.insertMany( [\n {\n name: \"Evander Otylia\",\n phone: \"202-555-0193\",\n address: [ 55.5, 42.3 ]\n },\n {\n name: \"Georgine Lestaw\",\n phone: \"714-555-0107\",\n address: [ -74, 44.74 ]\n }\n] )\n```\n\nA 2d index on the `address` field **does not** improve performance for the following query:\n\n```javascript\ndb.contacts.find( { address: [ 55.5, 42.3 ] } )\n```\n\nTo improve performance for this query, create either an ascending or descending index on the `address` field:\n\n```javascript\ndb.contacts.createIndex( { address: 1 } )\n```\n\n## Learn More\n\n- 2d Index Internals\n\n- Index Properties"} -{"chunk_id": "68a95b585e79d242619cce87-0", "page_id": "68a95b585e79d242619cce87", "source_name": "docs", "product_name": "MongoDB Server", "url": "https://mongodb.com/docs/manual/reference/method/db.collection.getSearchIndexes", "title": "db.collection.getSearchIndexes() (mongosh method)", "text": "# db.collection.getSearchIndexes() (mongosh method)\n\n## Definition\n\n`db.collection.getSearchIndexes()`\nMongoDB Search indexes or MongoDB Vector Search indexesReturns information about existing MongoDB Search indexes or MongoDB Vector Search indexes on a specified collection or view.\n\nThis page documents a `mongosh` method. This is *not* the documentation for a language-specific driver, such as Node.js.\n\nFor MongoDB API drivers, refer to the language-specific MongoDB driver documentation.\n\n## Compatibility\n\nThis method is available in deployments hosted in the following environments:\n\n- MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud\n\n- MongoDB Enterprise deployments running version 8.2 or later with the Kubernetes Operator\n\n- MongoDB Community deployments running version 8.2 or later\n\nTo learn more about self-managed deployments, see MongoDB Search on Self-Managed Deployments.\n\n## Syntax\n\nCommand syntax:\n\n```javascript\ndb..getSearchIndexes()\n```\n\n## Command Fields\n\n`getSearchIndexes()` takes this field:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nField\n\n\nType\n\n\nNecessity\n\n\nDescription\n\n
\n`indexName`\n\n\nstring\n\n\nOptional\n\n\nName of the index to return information about. If you omit the `indexName` field, `getSearchIndexes()` returns information about all MongoDB Search indexes on the collection.\n\n
\n\n## Access Control\n\n`getSearchIndexes()`If your deployment enforces access control, the user running `getSearchIndexes()` must have the `listSearchIndexes` privilege action on the database or collection:\n\n```javascript\n{\n resource: {\n db : ,\n collection: \n },\n actions: [ \"listSearchIndexes\" ]\n}\n```\n\nThe built-in `read` role provides the the `listSearchIndexes` privilege. The following example grants the `read` role on the `qa` database:\n\n```javascript\ndb.grantRolesToUser(\n \"\",\n [ { role: \"read\", db: \"qa\" } ]\n)\n```\n\n## Output\n\nMongoDB Search Index StatusesIndex Status DetailsSynonym Mapping Details`getSearchIndexes()` returns an array of documents. Each document in the array contains the following fields:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nField\n\n\nType\n\n\nDescription\n\n
\n`id`\n\n\nstring\n\n\nUnique identifier for the index.\n\n
\n`name`\n\n\nstring\n\n\nName of the index.\n\n
\n`status`\n\n\nstring\n\n\nStatus of the index. For more information, see MongoDB Search Index Statuses.\n\n
\n`queryable`\n\n\nboolean\n\n\nIndicates whether the index is ready to be queried.\n\n
\n`latestDefinitionVersion`\n\n\ndocument\n\n\nDescribes the version of the index.\n\n
\n`latestDefinitionVersion.version`\n\n\ninteger\n\n\nVersion number associated with the index definition. When you update an index definition, the version number increments automatically.\n\n
\n`latestDefinitionVersion.createdAt`\n\n\ndate\n\n\nTime when the current index definition was created.\n\n
\n`latestDefinition`\n\n\ndocument\n\n\nThe most recent definition for the index. For more information, see Search Index Definition Syntax.\n\n
\n`statusDetail`\n\n\narray of documents\n\n\nContains the status of the index on each search host (`mongot`).\n\n
\n`statusDetail.[n].hostname`\n\n\nstring\n\n\nHostname of the corresponding `mongot`. MongoDB represents this field as `..`.\n\nYou can specify the `server.name` for an on-prem deployment in your configuration file.\n\n
\n`statusDetail.[n].status`\n\n\nstring\n\n\nStatus of the index on the corresponding `mongot`.\n\n
\n`statusDetail.[n].queryable`\n\n\nboolean\n\n\nIndicates whether the index is ready to be queried on the corresponding `mongot`.\n\n
\n`statusDetail.[n].mainIndex`\n\n\ndocument\n\n\nContains status information about the active index on the corresponding `mongot`.\n\nFor details, see Index Status Details.\n\n
\n`statusDetail.[n].stagedIndex`\n\n\ndocument\n\n\nContains status information about an index being built in the background on the corresponding `mongot`. This field only appears if you are building a new index to update an existing active index.\n\nFor details, see Index Status Details.\n\n
\n`synonymMappingStatus`\n\n\nstring\n\n\nStatus of the index's synonym mappings. This field only appears if the index has synonyms defined. Can be one of the following values:\n\n- `BUILDING`\n\n- `FAILED`\n\n- `READY`\n\nThe returned status is a summary of the synonym mappings on each individual `mongot`.\n\n
\n`synonymMappingStatusDetail`\n\n\narray of documents\n\n\nContains the status of the index's synonym mappings on each search host (`mongot`). This field (and its subfields) only appear if the index has synonyms defined.\n\n
\n`synonymMappingStatusDetail.[n].status`\n\n\nstring\n\n\nStatus for the corresponding synonym mapping across all `mongot` processes.\n\n
\n`synonymMappingStatusDetail.[n].queryable`\n\n\nboolean\n\n\nIndicates whether the corresponding synonym mapping can support queries across all `mongot` processes.\n\n
\n`message`\n\n\nstring\n\n\nDescribes an error for the synonym mapping, if applicable. Only appears if the `status` for this synonym mapping is `FAILED`.\n\n
"} -{"chunk_id": "68a95b585e79d242619cce87-1", "page_id": "68a95b585e79d242619cce87", "source_name": "docs", "product_name": "MongoDB Server", "url": "https://mongodb.com/docs/manual/reference/method/db.collection.getSearchIndexes", "title": "db.collection.getSearchIndexes() (mongosh method)", "text": "### Index Status Details\n\nThe following table describes the embedded fields of the following documents: - `statusDetail.[mongot].mainIndex` - `statusDetail.[mongot].stagedIndex`\n\nThe fields describe the index status on a specific `mongot`.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nField\n\n\nType\n\n\nDescription\n\n
\n`status`\n\n\nstring\n\n\nThe state of the index generation on the corresponding `mongot`.\n\n
\n`queryable`\n\n\nboolean\n\n\nIndicates whether the index generation is ready to be queried on the corresponding `mongot`.\n\n
\n`synonymMappingStatus`\n\n\nstring\n\n\nThe state of the index generation's synonym mappings on the corresponding `mongot`. Only present if the index has synonyms defined.\n\n
\n`synonymMappingStatusDetails`\n\n\ndocument\n\n\nContains the status of the index's synonym mappings on the corresponding `mongot`. This field (and its subfields) only appear if the index has synonyms defined.\n\nFor more information, see Synonym Mapping Details.\n\n
\n`definitionVersion`\n\n\ndocument\n\n\nDescribes the index definition version that this index generation is being built with.\n\n
\n`definitionVersion.version`\n\n\ninteger\n\n\nVersion number that the index generation is using on the corresponding `mongot`. When you update an index definition, the updated index builds with an incremented version number.\n\n
\n`definitionVersion.createdAt`\n\n\ndate\n\n\nTime when the index definition was created.\n\n
\n`definition`\n\n\ndocument\n\n\nThe definition that this index is being built with.\n\n
\n\n### Synonym Mapping Details\n\nThe following table describes the embedded fields of the following objects:\n\n- `statusDetail.mainIndex.synonymMappingStatusDetails.`\n\n- `statusDetail.stagedIndex.synonymMappingStatusDetails`\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nField\n\n\nType\n\n\nDescription\n\n
\n`status`\n\n\nstring\n\n\nStatus for the synonym mapping across on the corresponding `mongot` process.\n\n
\n`queryable`\n\n\nboolean\n\n\nIndicates whether the synonym mapping can support queries on the corresponding `mongot` process.\n\n
\n`message`\n\n\nstring\n\n\nDescribes an error for the synonym mapping, if applicable. Only appears if the `status` for this synonym mapping is `FAILED`.\n\n
\n\n### MongoDB Search Index Statuses\n\nThe `status` field in the `getSearchIndexes()` output can be one of the following:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nStatus\n\n\nDescription\n\n
\n`BUILDING`\n\n\nThe following scenarios can cause an index to be in the `BUILDING` state:\n\n- MongoDB is building the index or re-building the index after an edit.\n\n- MongoDB Search cannot keep up with indexing changes to the collection. In this case, Atlas rebuilds the index in the background.\n\nWhen the index is in the `BUILDING` state:\n\n- For a new index, MongoDB Search cannot use the index for queries until the index build is complete.\n\n- For an existing index, MongoDB Search uses the old index definition for queries until the index rebuild is complete.\n\nAn index in the `BUILDING` state may be queryable or non-queryable.\n\n
\n`DOES_NOT_EXIST`\n\n\nThe index does not exist.\n\nAn index in the `DOES_NOT_EXIST` state is always non-queryable.\n\n
\n`DELETING`\n\n\nMongoDB is deleting the index.\n\nAn index in the `DELETING` state is always non-queryable.\n\n
\n`FAILED`\n\n\nThe index build failed. Indexes can enter the `FAILED` state due to an invalid index definition.\n\nAn index in the `FAILED` state may be queryable or non-queryable.\n\n
\n`PENDING`\n\n\nMongoDB has not yet started building the index.\n\nAn index in the `PENDING` state is always non-queryable.\n\n
\n`READY`\n\n\nThe index is ready and can support queries.\n\nAn index in the `READY` state is always queryable.\n\n
\n`STALE`\n\n\nThe index is queryable but has stopped replicating data from the indexed collection. Searches on the index may return out-of-date data.\n\nIndexes can enter the `STALE` state due to replication errors.\n\nAn index in the `STALE` state is always queryable.\n\n
\n\n## Examples\n\nThese examples demonstrate how to:\n\n- Return All Search Indexes\n\n- Return a Single Search Index"} -{"chunk_id": "68a95b585e79d242619cce87-2", "page_id": "68a95b585e79d242619cce87", "source_name": "docs", "product_name": "MongoDB Server", "url": "https://mongodb.com/docs/manual/reference/method/db.collection.getSearchIndexes", "title": "db.collection.getSearchIndexes() (mongosh method)", "text": "### Return All Search Indexes\n\nThe following example returns all MongoDB Search indexes on the `movies` collection. The `movies` collection contains two search indexes: `default` and `synonym_mappings`.\n\n```javascript\ndb.movies.getSearchIndexes()\n```\n\nSample output:\n\n```javascript\n[\n {\n id: '6524096020da840844a4c4a7',\n name: 'default',\n status: 'BUILDING',\n queryable: true,\n latestDefinitionVersion: {\n version: 2,\n createdAt: ISODate(\"2023-10-09T14:51:57.355Z\")\n },\n latestDefinition: {\n mappings: { dynamic: true },\n storedSource: { include: [ 'awards.text' ] }\n },\n statusDetail: [\n {\n hostname: 'atlas-n1cm1j-shard-00-02',\n status: 'BUILDING',\n queryable: true,\n mainIndex: {\n status: 'READY',\n queryable: true,\n definitionVersion: {\n version: 0,\n createdAt: ISODate(\"2023-10-09T14:08:32.000Z\")\n },\n definition: { mappings: { dynamic: true, fields: {} } }\n },\n stagedIndex: {\n status: 'PENDING',\n queryable: false,\n definitionVersion: {\n version: 1,\n createdAt: ISODate(\"2023-10-09T14:51:29.000Z\")\n },\n definition: {\n mappings: { dynamic: true, fields: {} },\n storedSource: true\n }\n }\n },\n {\n hostname: 'atlas-n1cm1j-shard-00-01',\n status: 'BUILDING',\n queryable: true,\n mainIndex: {\n status: 'READY',\n queryable: true,\n definitionVersion: {\n version: 0,\n createdAt: ISODate(\"2023-10-09T14:08:32.000Z\")\n },\n definition: { mappings: { dynamic: true, fields: {} } }\n },\n stagedIndex: {\n status: 'PENDING',\n queryable: false,\n definitionVersion: {\n version: 1,\n createdAt: ISODate(\"2023-10-09T14:51:29.000Z\")\n },\n definition: {\n mappings: { dynamic: true, fields: {} },\n storedSource: true\n }\n }\n },\n {\n hostname: 'atlas-n1cm1j-shard-00-00',\n status: 'BUILDING',\n queryable: true,\n mainIndex: {\n status: 'READY',\n queryable: true,\n definitionVersion: {\n version: 0,\n createdAt: ISODate(\"2023-10-09T14:08:32.000Z\")\n },\n definition: { mappings: { dynamic: true, fields: {} } }\n }\n }\n ]\n },\n {\n id: '65240be420da840844a4d077',\n name: 'synonym_mappings',\n status: 'READY',\n queryable: true,\n latestDefinitionVersion: {\n version: 0,\n createdAt: ISODate(\"2023-10-09T14:19:16.305Z\")\n },\n latestDefinition: {\n mappings: {\n dynamic: true,\n fields: {\n fullplot: { type: 'string' }\n }\n },\n synonyms: [\n {\n name: 'synonym_mapping',\n analyzer: 'lucene.english',\n source: { collection: 'synonyms' }\n }\n ]\n },\n synonymMappingStatus: 'READY',\n synonymMappingStatusDetail: [\n {\n synonym_mapping: {\n status: 'READY',\n queryable: true\n }\n }\n ],\n statusDetail: [\n {\n hostname: 'atlas-n1cm1j-shard-00-02',\n status: 'READY',\n queryable: true,\n mainIndex: {\n status: 'READY',\n queryable: true,\n definitionVersion: {\n version: 0,\n createdAt: ISODate(\"2023-10-09T14:19:16.000Z\")\n },\n definition: {\n mappings: {\n dynamic: true,\n fields: {\n fullplot: {\n type: 'string',\n indexOptions: 'offsets',\n store: true,\n norms: 'include'\n }\n }\n },\n synonyms: [\n {\n name: 'synonym_mapping',\n analyzer: 'lucene.english',\n source: { collection: 'synonyms' }\n }\n ]\n },\n synonymMappingStatus: 'READY',\n synonymMappingStatusDetail: [\n {\n synonym_mapping: {\n status: 'READY',\n queryable: true\n }\n }\n ]\n }\n },\n {\n hostname: 'atlas-n1cm1j-shard-00-01',\n status: 'READY',\n queryable: true,\n mainIndex: {\n status: 'READY',\n queryable: true,\n definitionVersion: {\n version: 0,\n createdAt: ISODate(\"2023-10-09T14:19:16.000Z\")\n },\n definition: {\n mappings: {\n dynamic: true,\n fields: {\n fullplot: {\n type: 'string',\n indexOptions: 'offsets',\n store: true,\n norms: 'include'\n }\n }\n },\n synonyms: [\n {\n name: 'synonym_mapping',\n analyzer: 'lucene.english',\n source: { collection: 'synonyms' }\n }\n ]\n },\n synonymMappingStatus: 'READY',\n synonymMappingStatusDetail: [\n {\n synonym_mapping: {\n status: 'READY',\n queryable: true\n }\n }\n ]\n }\n },\n {\n hostname: 'atlas-n1cm1j-shard-00-00',\n status: 'READY',\n queryable: true,\n mainIndex: {\n status: 'READY',\n queryable: true,\n definitionVersion: {\n version: 0,\n createdAt: ISODate(\"2023-10-09T14:19:16.000Z\")\n },\n definition: {\n mappings: {\n dynamic: true,\n fields: {\n fullplot: {\n type: 'string',\n indexOptions: 'offsets',\n store: true,\n norms: 'include'\n }\n }\n },\n synonyms: [\n {\n name: 'synonym_mapping',\n analyzer: 'lucene.english',\n source: { collection: 'synonyms' }\n }\n ]\n },\n synonymMappingStatus: 'READY',\n synonymMappingStatusDetail: [\n {\n synonym_mapping: {\n status: 'READY',\n queryable: true\n }\n }\n ]\n }\n }\n ]\n }\n]\n```"} -{"chunk_id": "68a95b585e79d242619cce87-3", "page_id": "68a95b585e79d242619cce87", "source_name": "docs", "product_name": "MongoDB Server", "url": "https://mongodb.com/docs/manual/reference/method/db.collection.getSearchIndexes", "title": "db.collection.getSearchIndexes() (mongosh method)", "text": "### Return a Single Search Index\n\nThe following example returns the `synonym_mappings` index on the `movies` collection:\n\n```javascript\ndb.movies.getSearchIndexes(\"synonym_mappings\")\n```\n\nSample output:\n\n```javascript\n[\n {\n id: '65240be420da840844a4d077',\n name: 'synonym_mappings',\n status: 'READY',\n queryable: true,\n latestDefinitionVersion: {\n version: 0,\n createdAt: ISODate(\"2023-10-09T14:19:16.305Z\")\n },\n latestDefinition: {\n mappings: {\n dynamic: true,\n fields: {\n fullplot: { type: 'string' }\n }\n },\n synonyms: [\n {\n name: 'synonym_mapping',\n analyzer: 'lucene.english',\n source: { collection: 'synonyms' }\n }\n ]\n },\n synonymMappingStatus: 'READY',\n synonymMappingStatusDetail: [\n {\n synonym_mapping: {\n status: 'READY',\n queryable: true\n }\n }\n ],\n statusDetail: [\n {\n hostname: 'atlas-n1cm1j-shard-00-02',\n status: 'READY',\n queryable: true,\n mainIndex: {\n status: 'READY',\n queryable: true,\n definitionVersion: {\n version: 0,\n createdAt: ISODate(\"2023-10-09T14:19:16.000Z\")\n },\n definition: {\n mappings: {\n dynamic: true,\n fields: {\n fullplot: {\n type: 'string',\n indexOptions: 'offsets',\n store: true,\n norms: 'include'\n }\n }\n },\n synonyms: [\n {\n name: 'synonym_mapping',\n analyzer: 'lucene.english',\n source: { collection: 'synonyms' }\n }\n ]\n },\n synonymMappingStatus: 'READY',\n synonymMappingStatusDetail: [\n {\n synonym_mapping: {\n status: 'READY',\n queryable: true\n }\n }\n ]\n }\n },\n {\n hostname: 'atlas-n1cm1j-shard-00-01',\n status: 'READY',\n queryable: true,\n mainIndex: {\n status: 'READY',\n queryable: true,\n definitionVersion: {\n version: 0,\n createdAt: ISODate(\"2023-10-09T14:19:16.000Z\")\n },\n definition: {\n mappings: {\n dynamic: true,\n fields: {\n fullplot: {\n type: 'string',\n indexOptions: 'offsets',\n store: true,\n norms: 'include'\n }\n }\n },\n synonyms: [\n {\n name: 'synonym_mapping',\n analyzer: 'lucene.english',\n source: { collection: 'synonyms' }\n }\n ]\n },\n synonymMappingStatus: 'READY',\n synonymMappingStatusDetail: [\n {\n synonym_mapping: {\n status: 'READY',\n queryable: true\n }\n }\n ]\n }\n },\n {\n hostname: 'atlas-n1cm1j-shard-00-00',\n status: 'READY',\n queryable: true,\n mainIndex: {\n status: 'READY',\n queryable: true,\n definitionVersion: {\n version: 0,\n createdAt: ISODate(\"2023-10-09T14:19:16.000Z\")\n },\n definition: {\n mappings: {\n dynamic: true,\n fields: {\n fullplot: {\n type: 'string',\n indexOptions: 'offsets',\n store: true,\n norms: 'include'\n }\n }\n },\n synonyms: [\n {\n name: 'synonym_mapping',\n analyzer: 'lucene.english',\n source: { collection: 'synonyms' }\n }\n ]\n },\n synonymMappingStatus: 'READY',\n synonymMappingStatusDetail: [\n {\n synonym_mapping: {\n status: 'READY',\n queryable: true\n }\n }\n ]\n }\n }\n ]\n }\n]\n```"} -{"chunk_id": "68a95b585e79d242619cce7a-0", "page_id": "68a95b585e79d242619cce7a", "source_name": "docs", "product_name": "MongoDB Server", "url": "https://mongodb.com/docs/manual/reference/method/db.collection.findAndModify", "title": "db.collection.findAndModify() (mongosh method)", "text": "# db.collection.findAndModify() (mongosh method)\n\nThis page documents a `mongosh` method. To see the equivalent method in a MongoDB driver, see the corresponding page for your programming language:\n\nUse `findOneAndUpdate()`, `findOneAndDelete()`, or `findOneAndReplace()` instead.\n\n## Definition\n\n`db.collection.findAndModify(document)`\n`findAndModify` commandUpdates and returns a single document. By default, the returned document does not include the modifications made on the update. To return the document with the modifications made on the update, use the `new` option.\n\n## Compatibility\n\nmethodThis method is available in deployments hosted in the following environments:\n\n- MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud\n\nThis command is supported in all MongoDB Atlas clusters. For information on Atlas support for all commands, see Unsupported Commands.\n\n- MongoDB Enterprise: The subscription-based, self-managed version of MongoDB\n\n- MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB\n\n## Syntax\n\n`db.collection.findAndModify()` has the following form:\n\n```javascript\ndb.collection.findAndModify({\n query: ,\n sort: ,\n remove: ,\n update: ,\n new: ,\n fields: ,\n upsert: ,\n bypassDocumentValidation: ,\n writeConcern: ,\n maxTimeMS: ,\n collation: ,\n arrayFilters: [ , ... ],\n let: // Added in MongoDB 5.0\n});\n```"} -{"chunk_id": "68a95b585e79d242619cce7a-1", "page_id": "68a95b585e79d242619cce7a", "source_name": "docs", "product_name": "MongoDB Server", "url": "https://mongodb.com/docs/manual/reference/method/db.collection.findAndModify", "title": "db.collection.findAndModify() (mongosh method)", "text": "### Parameters\n\n`db.collection.findAndModify()` takes a document parameter with the following embedded document fields:\n\n`findAndModify()`\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nParameter\n\n\nType\n\n\nDescription\n\n
\n`query`\n\n\ndocument\n\n\nOptional. The selection criteria for the modification. The `query` field employs the same query selectors as used in the `db.collection.find()` method. Although the query may match multiple documents, `findAndModify()`\n**will only select one document to modify**.\n\nIf unspecified, defaults to an empty document.\n\nIf the query argument is not a document, the operation errors.\n\n
\n`sort`\n\n\ndocument\n\n\nOptional. Determines which document the operation updates if the query selects multiple documents. `findAndModify()` updates the first document in the sort order specified by this argument.\n\nIf the sort argument is not a document, the operation errors.\n\nMongoDB does not store documents in a collection in a particular order. When sorting on a field which contains duplicate values, documents containing those values may be returned in any order.\n\nThe `$sort` operation is not a \"stable sort,\" which means that documents with equivalent sort keys are not guaranteed to remain in the same relative order in the output as they were in the input.\n\nIf the field specified in the sort criteria does not exist in two documents, then the value on which they are sorted is the same. The two documents may be returned in any order.\n\nIf consistent sort order is desired, include at least one field in your sort that contains unique values. The easiest way to guarantee this is to include the `_id` field in your sort query.\n\nSee Sort Consistency for more information.\n\n
\n`remove`\n\n\nboolean\n\n\nMust specify either the `remove` or the `update` field. Removes the document specified in the `query` field. Set this to `true` to remove the selected document . The default is `false`.\n\n
\n`update`\n\n\ndocument or array\n\n\nMust specify either the `remove` or the `update` field. Performs an update of the selected document.\n\n- If passed a document with update operator expressions, `findAndModify()` performs the specified modification.\n\n- If passed a replacement document `{ : , ...}`, the `findAndModify()` performs a replacement.\n\n- If passed an aggregation pipeline\n `[ , , ... ]`, `findAndModify()` updates the document per the pipeline. The pipeline can consist of the following stages:\n\n - `$addFields` and its alias `$set`\n\n - `$project` and its alias `$unset`\n\n - `$replaceRoot` and its alias `$replaceWith`\n\n
\n`new`\n\n\nboolean\n\n\nOptional. When `true`, returns the updated document rather than the original. The default is `false`.\n\n
\n`fields`\n\n\ndocument\n\n\nOptional. A subset of fields to return. The `fields` document specifies an inclusion of a field with `1`, as in: `fields: { : 1, : 1, ... }`.\n\nIf the `fields` argument is not a document, the operation errors.\n\nFor more information on projection, see `fields` Projection.\n\n
\n`upsert`\n\n\nboolean\n\n\nOptional. Used in conjunction with the `update` field.\n\nWhen `true`, `findAndModify()` either:\n\n- Creates a new document if no documents match the `query`. For more details see upsert behavior.\n\n- Updates a single document that matches the `query`.\n\nTo avoid multiple upserts, ensure that the `query` field(s) are uniquely indexed. See Upsert with Unique Index for an example.\n\nDefaults to `false`, which does *not* insert a new document when no match is found.\n\n
\n`bypassDocumentValidation`\n\n\nboolean\n\n\nOptional. Enables `findAndModify()` to bypass schema validation during the operation. This lets you update documents that do not meet the validation requirements.\n\n
\n`writeConcern`\n\n\ndocument\n\n\nOptional. A document expressing the write concern. Omit to use the default write concern.\n\nDo not explicitly set the write concern for the operation if run in a transaction. To use write concern with transactions, see Transactions and Write Concern.\n\n
\n`maxTimeMS`\n\n\nnon-negative integer\n\n\nOptional.\n\nSpecifies a time limit in milliseconds. If you do not specify a value for `maxTimeMS`, operations will not time out. A value of `0` explicitly specifies the default unbounded behavior.\n\nMongoDB terminates operations that exceed their allotted time limit using the same mechanism as `db.killOp()`. MongoDB only terminates an operation at one of its designated interrupt points.\n\n
\n`collation`\n\n\ndocument\n\n\nOptional.\n\nOptional. Specifies the collation to use for the operation.\n\nCollation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.\n\nThe collation option has the following syntax:\n\n```javascript\ncollation: {\n locale: ,\n caseLevel: ,\n caseFirst: ,\n strength: ,\n numericOrdering: ,\n alternate: ,\n maxVariable: ,\n backwards: \n }\n```\n\nWhen specifying collation, the `locale` field is mandatory; all other collation fields are optional. For descriptions of the fields, see Collation Document.\n\nIf the collation is unspecified but the collection has a default collation (see `db.createCollection()`), the operation uses the collation specified for the collection.\n\nIf no collation is specified for the collection or for the operations, MongoDB uses the simple binary comparison used in prior versions for string comparisons.\n\nYou cannot specify multiple collations for an operation. For example, you cannot specify different collations per field, or if performing a find with a sort, you cannot use one collation for the find and another for the sort.\n\n
\n`arrayFilters`\n\n\narray\n\n\nOptional. An array of filter documents that determine which array elements to modify for an update operation on an array field.\n\nIn the update document, use the `$[]` filtered positional operator to define an identifier, which you then reference in the array filter documents. You cannot have an array filter document for an identifier if the identifier is not included in the update document.\n\nThe `` must begin with a lowercase letter and contain only alphanumeric characters.\n\nYou can include the same identifier multiple times in the update document; however, for each distinct identifier (`$[identifier]`) in the update document, you must specify **exactly one** corresponding array filter document. That is, you cannot specify multiple array filter documents for the same identifier. For example, if the update statement includes the identifier `x` (possibly multiple times), you cannot specify the following for `arrayFilters` that includes 2 separate filter documents for `x`:\n\n```javascript\n// INVALID\n\n[\n { \"x.a\": { $gt: 85 } },\n { \"x.b\": { $gt: 80 } }\n]\n```"} -{"chunk_id": "68a95b585e79d242619cce7a-2", "page_id": "68a95b585e79d242619cce7a", "source_name": "docs", "product_name": "MongoDB Server", "url": "https://mongodb.com/docs/manual/reference/method/db.collection.findAndModify", "title": "db.collection.findAndModify() (mongosh method)", "text": "However, you can specify compound conditions on the same identifier in a single filter document, such as in the following examples:\n\n```javascript\n// Example 1\n[\n { $or: [{\"x.a\": {$gt: 85}}, {\"x.b\": {$gt: 80}}] }\n]\n// Example 2\n[\n { $and: [{\"x.a\": {$gt: 85}}, {\"x.b\": {$gt: 80}}] }\n]\n// Example 3\n[\n { \"x.a\": { $gt: 85 }, \"x.b\": { $gt: 80 } }\n]\n```\n\nFor examples, see Specify `arrayFilters` for an Array Update Operations.\n\n`arrayFilters` is not available for updates that use an aggregation pipeline.\n\n
\nlet\n\n\ndocument\n\n\nOptional.\n\nSpecifies a document with a list of variables. This allows you to improve command readability by separating the variables from the query text.\n\nThe document syntax is:\n\n```javascript\n{\n : ,\n ...,\n : \n}\n```\n\nThe variable is set to the value returned by the expression, and cannot be changed afterwards.\n\nTo access the value of a variable in the command, use the double dollar sign prefix (`$$`) together with your variable name in the form `$$`. For example: `$$targetTotal`.\n\nTo use a variable to filter results, you must access the variable within the `$expr` operator.\n\nFor a complete example using `let` and variables, see Use Variables in `let`.\n\n
\n\n## Return Data\n\nFor remove operations, if the query matches a document, `findAndModify()` returns the removed document. If the query does not match a document to remove, `findAndModify()` returns `null`.\n\nFor update operations, `findAndModify()` returns one of the following:\n\n- If the `new` parameter is not set or is `false`:\n\n - the pre-modification document if the query matches a document;\n\n - otherwise, `null`.\n\n- If `new` is `true`:\n\n - the updated document if the query returns a match;\n\n - the inserted document if `upsert: true` and no document matches the query;\n\n - otherwise, `null`.\n\n## Behavior\n\n### Performance\n\n`findAndModify()`Retryable writes require the `findAndModify()` method to copy the entire document into a special side collection for each node in a replica set before it performs the update. This can make `findAndModify()` an expensive operation when dealing with large documents or large replica sets.\n\nTo update the first document in a user-defined ordering with better performance, use the `db.collection.updateOne()` method with the `sort` option.\n\n### `fields` Projection\n\nAs part of making `find()` and `findAndModify()` projection consistent with aggregation's `$project` stage,\n\n- The `find()` and `findAndModify()` projection can accept aggregation expressions and syntax.\n\n- MongoDB enforces additional restrictions with regards to projections. See Projection Restrictions for details.\n\nThe `fields` option takes a document in the following form:\n\n```javascript\n{ field1: , field2: ... }\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nProjection\n\n\nDescription\n\n
\n`: <1 or true>`\n\n\nSpecifies the inclusion of a field. If you specify a non-zero integer for the projection value, the operation treats the value as `true`.\n\n
\n`: <0 or false>`\n\n\nSpecifies the exclusion of a field.\n\n
\n`\".$\": <1 or true>`\n\n\nUses the `$` array projection operator to return the first element that matches the query condition on the array field. If you specify a non-zero integer for the projection value, the operation treats the value as `true`.\n\nNot available for views.\n\n
\n`: `\n\n\nUses the array projection operators (`$elemMatch`, `$slice`) to specify the array elements to include.\n\nNot available for views.\n\n
\n`: `\n\n\nSpecifies the value of the projected field.\n\nWith the use of aggregation expressions and syntax, including the use of literals and aggregation variables, you can project new fields or project existing fields with new values.\n\n- If you specify a non-numeric, non-boolean literal (such as a literal string or an array or an operator expression) for the projection value, the field is projected with the new value, for example:\n\n - `{ field: [ 1, 2, 3, \"$someExistingField\" ] }`\n\n - `{ field: \"New String Value\" }`\n\n - `{ field: { status: \"Active\", total: { $sum: \"$existingArray\" } } }`\n\n- To project a literal value for a field, use the `$literal` aggregation expression, for example:\n\n - `{ field: { $literal: 5 } }`\n\n - `{ field: { $literal: true } }`\n\n - `{ field: { $literal: { fieldWithValue0: 0, fieldWithValue1: 1 } } }`\n\n
#### Embedded Field Specification\n\nFor fields in an embedded documents, you can specify the field using either:\n\n- dot notation, for example `\"field.nestedfield\": `\n\n- nested form, for example `{ field: { nestedfield: } }`\n\n#### `_id` Field Projection\n\nThe `_id` field is included in the returned documents by default unless you explicitly specify `_id: 0` in the projection to suppress the field.\n\n#### Inclusion or Exclusion\n\nA `projection` *cannot* contain *both* include and exclude specifications, with the exception of the `_id` field:\n\n- In projections that *explicitly include* fields, the `_id` field is the only field that you can *explicitly exclude*.\n\n- In projections that *explicitly excludes* fields, the `_id` field is the only field that you can *explicitly include*; however, the `_id` field is included by default."} -{"chunk_id": "68a95b585e79d242619cce7a-3", "page_id": "68a95b585e79d242619cce7a", "source_name": "docs", "product_name": "MongoDB Server", "url": "https://mongodb.com/docs/manual/reference/method/db.collection.findAndModify", "title": "db.collection.findAndModify() (mongosh method)", "text": "### Upsert with Unique Index\n\nUpserts can create duplicate documents, unless there is a unique index to prevent duplicates.\n\nConsider an example where no document with the name `Andy` exists and multiple clients issue the following command at roughly the same time:\n\n```javascript\ndb.people.findAndModify(\n {\n query: { name: \"Andy\" },\n update: { $inc: { score: 1 } },\n upsert: true\n }\n)\n```\n\nIf all `findOneAndUpdate()` operations finish the query phase before any client successfully inserts data, **and** there is no unique index on the `name` field, each `findOneAndUpdate()` operation may result in an insert, creating multiple documents with `name: Andy`.\n\nA unique index on the `name` field ensures that only one document is created. With a unique index in place, the multiple `findOneAndUpdate()` operations now exhibit the following behavior:\n\n- Exactly one `findOneAndUpdate()` operation will successfully insert a new document.\n\n- Other `findOneAndUpdate()` operations either update the newly-inserted document or fail due to a unique key collision.\n\n In order for other `findOneAndUpdate()` operations to update the newly-inserted document, **all** of the following conditions must be met:\n\n - The target collection has a unique index that would cause a duplicate key error.\n\n - The update operation is not `updateMany` or `multi` is `false`.\n\n - The update match condition is either:\n\n - A single equality predicate. For example `{ \"fieldA\" : \"valueA\" }`\n\n - A logical AND of equality predicates. For example `{ \"fieldA\" : \"valueA\", \"fieldB\" : \"valueB\" }`\n\n - The fields in the equality predicate match the fields in the unique index key pattern.\n\n - The update operation does not modify any fields in the unique index key pattern.\n\nThe following table shows examples of `upsert` operations that, when a key collision occurs, either result in an update or fail.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nUnique Index Key Pattern\n\n\nUpdate Operation\n\n\nResult\n\n
\n```javascript\n{ name : 1 }\n```\n\n\n```javascript\ndb.people.updateOne(\n { name: \"Andy\" },\n { $inc: { score: 1 } },\n { upsert: true }\n)\n```\n\n\nThe `score` field of the matched document is incremented by 1.\n\n
\n```javascript\n{ name : 1 }\n```\n\n\n```javascript\ndb.people.updateOne(\n { name: { $ne: \"Joe\" } },\n { $set: { name: \"Andy\" } },\n { upsert: true }\n )\n```\n\n\nThe operation fails because it modifies the field in the unique index key pattern (`name`).\n\n
\n```javascript\n{ name : 1 }\n```\n\n\n```javascript\ndb.people.updateOne(\n { name: \"Andy\", email: \"andy@xyz.com\" },\n { $set: { active: false } },\n { upsert: true }\n)\n```\n\n\nThe operation fails because the equality predicate fields (`name`, `email`) do not match the index key field (`name`).\n\n
\n\n### Sharded Collections\n\nTo use `findAndModify` on a sharded collection:\n\n- If you only target one shard, you can use a partial shard key in the `query` field or,\n\n- You can provide an equality condition on a full shard key in the `query` field.\n\n- Starting in version 7.1, you do not need to provide the shard key or `_id` field in the query specification.\n\nDocuments in a sharded collection can be missing the shard key fields. To target a document that is missing the shard key, you can use the `null` equality match in conjunction with another filter condition (such as on the `_id` field). For example:\n\n```javascript\n{ _id: , : null } // _id of the document missing shard key\n```\n\n#### Shard Key Modification\n\nYou can update a document's shard key value unless the shard key field is the immutable `_id` field.\n\nDocuments in sharded collections can be missing the shard key fields. Take precaution to avoid accidentally removing the shard key when changing a document's shard key value.\n\nTo update the **existing** shard key value with `findAndModify()`:\n\n- You must run on a `mongos`. Do not issue the operation directly on the shard.\n\n- You must run either in a transaction or as a retryable write.\n\n- You must include an equality filter on the full shard key.\n\n#### Missing Shard Key\n\nDocuments in a sharded collection can be missing the shard key fields. To use `db.collection.findAndModify()` to set the document's **missing** shard key:\n\n- You must run on a `mongos`. Do not issue the operation directly on the shard.\n\n- You must run either in a transaction or as a retryable write if the new shard key value is not `null`.\n\n- You must include an equality filter on the full shard key.\n\nSince a missing key value is returned as part of a null equality match, to avoid updating a null-valued key, include additional query conditions (such as on the `_id` field) as appropriate.\n\n### Schema Validation\n\nThe `db.collection.findAndModify()` method adds support for the `bypassDocumentValidation` option, which lets you bypass schema validation when inserting or updating documents in a collection with validation rules.\n\n### Comparisons with the `update` Method\n\nthe pre-modified version of the documentWhen updating a document, `findAndModify()` and the `updateOne()` method operate differently:\n\n- If multiple documents match the update criteria, for `findAndModify()`, you can specify a `sort` to provide some measure of control on which document to update.\n\n `updateOne()` updates the first document that matches.\n\n- By default, `findAndModify()` returns the pre-modified version of the document. To obtain the updated document, use the `new` option.\n\n The `updateOne()` method returns a `WriteResult()` object that contains the status of the operation.\n\n To return the updated document, use the `find()` method. However, other updates may have modified the document between your update and the document retrieval. Also, if the update modified only a single document but multiple documents matched, you will need to use additional logic to identify the updated document.\n\nWhen modifying a *single* document, both `findAndModify()` and the `updateOne()` method *atomically* update the document. See Atomicity and Transactions for more details about interactions and order of operations of these methods.\n\n### Transactions\n\n`findAndModify()` can be used inside distributed transactions.\n\nIn most cases, a distributed transaction incurs a greater performance cost over single document writes, and the availability of distributed transactions should not be a replacement for effective schema design. For many scenarios, the denormalized data model (embedded documents and arrays) will continue to be optimal for your data and use cases. That is, for many scenarios, modeling your data appropriately will minimize the need for distributed transactions.\n\nFor additional transactions usage considerations (such as runtime limit and oplog size limit), see also Production Considerations.\n\n#### Upsert within Transactions\n\nYou can create collections and indexes inside a distributed transaction if the transaction is not a cross-shard write transaction.\n\n`findAndModify()` with `upsert: true` can be run on an existing collection or a non-existing collection. If run on a non-existing collection, the operation creates the collection.\n\nCreate Collections and Indexes in a Transaction\n\n#### Write Concerns and Transactions\n\nDo not explicitly set the write concern for the operation if run in a transaction. To use write concern with transactions, see Transactions and Write Concern."} -{"chunk_id": "68a95b585e79d242619cce7a-4", "page_id": "68a95b585e79d242619cce7a", "source_name": "docs", "product_name": "MongoDB Server", "url": "https://mongodb.com/docs/manual/reference/method/db.collection.findAndModify", "title": "db.collection.findAndModify() (mongosh method)", "text": "### Oplog Entries\n\nIf a `findAndModify()` operation successfully finds and modifies a document, the operation adds an entry on the oplog (operations log). If the operation fails or does not find a document to modify, the operation does not add an entry on the oplog.\n\n### Write Concern Errors\n\nIn MongoDB versions earlier than 6.0, if the `findAndModify` command is run on a sharded cluster, `mongos` discards the `writeConcernError` document if the shard response contains an error. In MongoDB 6.0 and later, `mongos` returns `writeConcernError`.\n\n## Examples\n\n### Update and Return\n\nThe following method updates and returns an existing document in the people collection where the document matches the query criteria:\n\n```javascript\ndb.people.findAndModify({\n query: { name: \"Tom\", state: \"active\", rating: { $gt: 10 } },\n sort: { rating: 1 },\n update: { $inc: { score: 1 } }\n})\n```\n\nThis method performs the following actions:\n\n1. The `query` finds a document in the `people` collection where the `name` field has the value `Tom`, the `state` field has the value `active` and the `rating` field has a value `greater than` 10.\n\n2. The `sort` orders the results of the query in ascending order. If multiple documents meet the `query` condition, the method will select for modification the first document as ordered by this `sort`.\n\n3. The update `increments` the value of the `score` field by 1.\n\n4. The method returns the original (i.e. pre-modification) document selected for this update:\n\n ```javascript\n {\n \"_id\" : ObjectId(\"50f1e2c99beb36a0f45c6453\"),\n \"name\" : \"Tom\",\n \"state\" : \"active\",\n \"rating\" : 100,\n \"score\" : 5\n }\n ```\n\n To return the updated document, add the `new:true` option to the method.\n\n If no document matched the `query` condition, the method returns `null`.\n\n### Upsert\n\nThe following method includes the `upsert: true` option for the `update` operation to either update a matching document or, if no matching document exists, create a new document:\n\n```javascript\ndb.people.findAndModify({\n query: { name: \"Gus\", state: \"active\", rating: 100 },\n sort: { rating: 1 },\n update: { $inc: { score: 1 } },\n upsert: true\n})\n```\n\nIf the method finds a matching document, the method performs an update.\n\nIf the method does **not** find a matching document, the method creates a new document. Because the method included the `sort` option, it returns an empty document `{ }` as the original (pre-modification) document:\n\n```javascript\n{ }\n```\n\nIf the method did **not** include a `sort` option, the method returns `null`.\n\n```javascript\nnull\n```\n\n### Return New Document\n\nThe following method includes both the `upsert: true` option and the `new:true` option. The method either updates a matching document and returns the updated document or, if no matching document exists, inserts a document and returns the newly inserted document in the `value` field.\n\nIn the following example, no document in the `people` collection matches the `query` condition:\n\n```javascript\ndb.people.findAndModify({\n query: { name: \"Pascal\", state: \"active\", rating: 25 },\n sort: { rating: 1 },\n update: { $inc: { score: 1 } },\n upsert: true,\n new: true\n})\n```\n\nThe method returns the newly inserted document:\n\n```javascript\n{\n \"_id\" : ObjectId(\"50f49ad6444c11ac2448a5d6\"),\n \"name\" : \"Pascal\",\n \"rating\" : 25,\n \"score\" : 1,\n \"state\" : \"active\"\n}\n```\n\n### Sort and Remove\n\nBy including a `sort` specification on the `rating` field, the following example removes from the `people` collection a single document with the `state` value of `active` and the lowest `rating` among the matching documents:\n\n```javascript\ndb.people.findAndModify(\n {\n query: { state: \"active\" },\n sort: { rating: 1 },\n remove: true\n }\n)\n```\n\nThe method returns the deleted document:\n\n```javascript\n{\n \"_id\" : ObjectId(\"52fba867ab5fdca1299674ad\"),\n \"name\" : \"XYZ123\",\n \"score\" : 1,\n \"state\" : \"active\",\n \"rating\" : 3\n}\n```\n\n### Specify Collation\n\nCollation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.\n\nA collection `myColl` has the following documents:\n\n```javascript\n{ _id: 1, category: \"caf\u00e9\", status: \"A\" }\n{ _id: 2, category: \"cafe\", status: \"a\" }\n{ _id: 3, category: \"cafE\", status: \"a\" }\n```\n\nThe following operation includes the collation option:\n\n```javascript\ndb.myColl.findAndModify({\n query: { category: \"cafe\", status: \"a\" },\n sort: { category: 1 },\n update: { $set: { status: \"Updated\" } },\n collation: { locale: \"fr\", strength: 1 }\n});\n```\n\nThe operation returns the following document:\n\n```javascript\n{ \"_id\" : 1, \"category\" : \"caf\u00e9\", \"status\" : \"A\" }\n```\n\n### Specify `arrayFilters` for an Array Update Operations\n\n`arrayFilters` is not available for updates that use an aggregation pipeline.\n\nWhen updating an array field, you can specify `arrayFilters` that determine which array elements to update.\n\n#### Update Elements Match `arrayFilters` Criteria\n\n`arrayFilters` is not available for updates that use an aggregation pipeline.\n\nCreate a collection `students` with the following documents:\n\n```javascript\ndb.students.insertMany( [\n { \"_id\" : 1, \"grades\" : [ 95, 92, 90 ] },\n { \"_id\" : 2, \"grades\" : [ 98, 100, 102 ] },\n { \"_id\" : 3, \"grades\" : [ 95, 110, 100 ] }\n] )\n```\n\nTo update all elements that are greater than or equal to `100` in the `grades` array, use the filtered positional operator `$[]` with the `arrayFilters` option in the `db.collection.findAndModify()` method:\n\n```javascript\ndb.students.findAndModify({\n query: { grades: { $gte: 100 } },\n update: { $set: { \"grades.$[element]\" : 100 } },\n arrayFilters: [ { \"element\": { $gte: 100 } } ]\n})\n```\n\nThe operation updates the `grades` field for a single document, and after the operation, the collection has the following documents:\n\n```javascript\n{ \"_id\" : 1, \"grades\" : [ 95, 92, 90 ] }\n{ \"_id\" : 2, \"grades\" : [ 98, 100, 100 ] }\n{ \"_id\" : 3, \"grades\" : [ 95, 110, 100 ] }\n```\n\n#### Update Specific Elements of an Array of Documents\n\n`arrayFilters` is not available for updates that use an aggregation pipeline.\n\nCreate a collection `students2` with the following documents:\n\n```javascript\ndb.students2.insertMany( [\n {\n \"_id\" : 1,\n \"grades\" : [\n { \"grade\" : 80, \"mean\" : 75, \"std\" : 6 },\n { \"grade\" : 85, \"mean\" : 90, \"std\" : 4 },\n { \"grade\" : 85, \"mean\" : 85, \"std\" : 6 }\n ]\n },\n {\n \"_id\" : 2,\n \"grades\" : [\n { \"grade\" : 90, \"mean\" : 75, \"std\" : 6 },\n { \"grade\" : 87, \"mean\" : 90, \"std\" : 3 },\n { \"grade\" : 85, \"mean\" : 85, \"std\" : 4 }\n ]\n }\n] )\n```\n\nThe following operation finds a document where the `_id` field equals `1` and uses the filtered positional operator `$[]` with the `arrayFilters` to update the `mean` for all elements in the `grades` array where the grade is greater than or equal to `85`.\n\n```javascript\ndb.students2.findAndModify({\n query: { _id : 1 },\n update: { $set: { \"grades.$[elem].mean\" : 100 } },\n arrayFilters: [ { \"elem.grade\": { $gte: 85 } } ]\n})\n```\n\nThe operation updates the `grades` field for a single document, and after the operation, the collection has the following documents:\n\n```javascript\n{\n \"_id\" : 1,\n \"grades\" : [\n { \"grade\" : 80, \"mean\" : 75, \"std\" : 6 },\n { \"grade\" : 85, \"mean\" : 100, \"std\" : 4 },\n { \"grade\" : 85, \"mean\" : 100, \"std\" : 6 }\n ]\n}\n{\n \"_id\" : 2,\n \"grades\" : [\n { \"grade\" : 90, \"mean\" : 75, \"std\" : 6 },\n { \"grade\" : 87, \"mean\" : 90, \"std\" : 3 },\n { \"grade\" : 85, \"mean\" : 85, \"std\" : 4 }\n ]\n}\n```"} -{"chunk_id": "68a95b585e79d242619cce7a-5", "page_id": "68a95b585e79d242619cce7a", "source_name": "docs", "product_name": "MongoDB Server", "url": "https://mongodb.com/docs/manual/reference/method/db.collection.findAndModify", "title": "db.collection.findAndModify() (mongosh method)", "text": "### Use an Aggregation Pipeline for Updates\n\n`db.collection.findAndModify()` can accept an aggregation pipeline for the update. The pipeline can consist of the following stages:\n\n- `$addFields` and its alias `$set`\n\n- `$project` and its alias `$unset`\n\n- `$replaceRoot` and its alias `$replaceWith`\n\nUsing the aggregation pipeline allows for a more expressive update statement, such as expressing conditional updates based on current field values or updating one field using the value of another field(s).\n\nFor example, create a collection `students2` with the following documents:\n\n```javascript\ndb.students2.insertMany( [\n {\n \"_id\" : 1,\n \"grades\" : [\n { \"grade\" : 80, \"mean\" : 75, \"std\" : 6 },\n { \"grade\" : 85, \"mean\" : 90, \"std\" : 4 },\n { \"grade\" : 85, \"mean\" : 85, \"std\" : 6 }\n ]\n },\n {\n \"_id\" : 2,\n \"grades\" : [\n { \"grade\" : 90, \"mean\" : 75, \"std\" : 6 },\n { \"grade\" : 87, \"mean\" : 90, \"std\" : 3 },\n { \"grade\" : 85, \"mean\" : 85, \"std\" : 4 }\n ]\n }\n] )\n```\n\nThe following operation finds a document where the `_id` field equals `1` and uses an aggregation pipeline to calculate a new field `total` from the `grades` field:\n\n```javascript\ndb.students2.findAndModify( {\n query: { \"_id\" : 1 },\n update: [ { $set: { \"total\" : { $sum: \"$grades.grade\" } } } ], // The $set stage is an alias for ``$addFields`` stage\n new: true\n} )\n```\n\nThe `$set` used in the pipeline refers to the aggregation stage `$set` and not the update operator `$set`.\n\nThe operation returns the *updated* document:\n\n```javascript\n{\n \"_id\" : 1,\n \"grades\" : [ { \"grade\" : 80, \"mean\" : 75, \"std\" : 6 }, { \"grade\" : 85, \"mean\" : 90, \"std\" : 4 }, { \"grade\" : 85, \"mean\" : 85, \"std\" : 6 } ],\n \"total\" : 250\n}\n```\n\n### Use Variables in `let`\n\nletTo define variables that you can access elsewhere in the command, use the let option.\n\nTo filter results using a variable, you must access the variable within the `$expr` operator.\n\nCreate a collection `cakeFlavors`:\n\n```javascript\ndb.cakeFlavors.insertMany( [\n { _id: 1, flavor: \"chocolate\" },\n { _id: 2, flavor: \"strawberry\" },\n { _id: 3, flavor: \"cherry\" }\n] )\n```\n\nThe following example defines a `targetFlavor` variable in `let` and uses the variable to change the cake flavor from cherry to orange:\n\n```javascript\ndb.cakeFlavors.findAndModify( {\n query: {\n $expr: { $eq: [ \"$flavor\", \"$$targetFlavor\" ] }\n },\n update: { flavor: \"orange\" },\n let: { targetFlavor: \"cherry\" }\n} )\n```\n\n### User Roles and Document Updates\n\nStarting in MongoDB 7.0, you can use the new `USER_ROLES` system variable to return user roles.\n\nThe example in this section shows updates to fields in a collection containing medical information. The example reads the current user roles from the `USER_ROLES` system variable and only performs the updates if the user has a specific role.\n\nTo use a system variable, add `$$` to the start of the variable name. Specify the `USER_ROLES` system variable as `$$USER_ROLES`.\n\nThe example creates these users:\n\n- `James` with a `Billing` role.\n\n- `Michelle` with a `Provider` role.\n\nPerform the following steps to create the roles, users, and collection:\n\n#### Create the roles\n\nCreate roles named `Billing` and `Provider` with the required privileges and resources.\n\nRun:\n\n```javascript\ndb.createRole( { role: \"Billing\", privileges: [ { resource: { db: \"test\",\n collection: \"medicalView\" }, actions: [ \"find\" ] } ], roles: [ ] } )\ndb.createRole( { role: \"Provider\", privileges: [ { resource: { db: \"test\",\n collection: \"medicalView\" }, actions: [ \"find\" ] } ], roles: [ ] } )\n```\n\n#### Create the users\n\nCreate users named `James` and `Michelle` with the required roles.\n\n```javascript\ndb.createUser( {\n user: \"James\",\n pwd: \"js008\",\n roles: [\n { role: \"Billing\", db: \"test\" }\n ]\n} )\n\ndb.createUser( {\n user: \"Michelle\",\n pwd: \"me009\",\n roles: [\n { role: \"Provider\", db: \"test\" }\n ]\n} )\n```\n\n#### Create the collection\n\nRun:\n\n```javascript\ndb.medical.insertMany( [\n {\n _id: 0,\n patientName: \"Jack Jones\",\n diagnosisCode: \"CAS 17\",\n creditCard: \"1234-5678-9012-3456\"\n },\n {\n _id: 1,\n patientName: \"Mary Smith\",\n diagnosisCode: \"ACH 01\",\n creditCard: \"6541-7534-9637-3456\"\n }\n] )\n```\n\nLog in as as `Michelle`, who has the `Provider` role, and perform an update:\n\n#### Log in as `Michelle`\n\nRun:\n\n```javascript\ndb.auth( \"Michelle\", \"me009\" )\n```\n\n#### Perform update\n\nRun:\n\n```javascript\n// Attempt to find and modify document\ndb.medical.findAndModify( {\n query:\n { $and: [\n {\n // Only update the document for Mary Smith\n patientName: { $eq: \"Mary Smith\" }\n },\n {\n // User must have the Provider role to perform the update\n $expr: { $ne: [ {\n $setIntersection: [ [ \"Provider\" ], \"$$USER_ROLES.role\" ]\n }, [] ] }\n }\n ]\n },\n // Update document\n update: {\n patientName: \"Mary Smith\",\n diagnosisCode: \"ACH 03\",\n creditCard: \"6541-7534-9637-3456\"\n }\n} )\n```\n\nThe previous example uses `$setIntersection` to return documents where the intersection between the `\"Provider\"` string and the user roles from `$$USER_ROLES.role` is not empty. `Michelle` has the `Provider` role, so the update is performed.\n\nNext, log in as as `James`, who does not have the `Provider` role, and attempt to perform the same update:\n\n#### Log in as `James`\n\nRun:\n\n```javascript\ndb.auth( \"James\", \"js008\" )\n```\n\n#### Attempt to perform update\n\nRun:\n\n```javascript\n// Attempt to find and modify document\ndb.medical.findAndModify( {\n query:\n { $and: [\n {\n // Only update the document for Mary Smith\n patientName: { $eq: \"Mary Smith\" }\n },\n {\n // User must have the Provider role to perform the update\n $expr: { $ne: [ {\n $setIntersection: [ [ \"Provider\" ], \"$$USER_ROLES.role\" ]\n }, [] ] }\n }\n ]\n },\n // Update document\n update: {\n patientName: \"Mary Smith\",\n diagnosisCode: \"ACH 03\",\n creditCard: \"6541-7534-9637-3456\"\n }\n} )\n```\n\nThe previous example does not update any documents."} -{"chunk_id": "68a95c2a5e79d242619df53d-0", "page_id": "68a95c2a5e79d242619df53d", "source_name": "docs-relational-migrator", "product_name": "MongoDB Relational Migrator", "url": "https://mongodb.com/docs/relational-migrator/mapping-rules/fields/calculated-fields/add-calculated-fields", "title": "Add Calculated Fields", "text": "# Add Calculated Fields\n\nCalculated fields let you create new fields in your documents by combining values from existing database columns using JavaScript expressions. Calculated fields are evaluated each time a row is processed during a migration job.\n\n## Before you Begin\n\nTo create a calculated field, you must define a mapping rule.\n\nTo create mapping rules, see the following pages:\n\n- Create Rules From Suggested Mappings\n\n- Create Mapping Rules\n\n- Create Mapping Rules\n\n## About this Task\n\nCalculated field expressions access values from the current source database row using the syntax `columns[\"\"]`.\n\nWhen defining Calculated Fields and Customize ID Fields, Relational Migrator shows an initial data type of default. When you run a migration job, Relational Migrator updates this data type.\n\n## Steps\n\n1. From the Mapping screen, click a table or collection name on the Schema model pane or diagram view.\n\n2. Add a new mapping rule or edit an existing mapping rule.\n\n3. Click the + icon to the right of the All fields label.\n\n4. Define a name for the new field in the Field Name text box.\n\n5. Define a valid JavaScript expression for the new field in the `Value expression` text box.\n\n6. Click Done.\n\n7. Click Save and close.\n\nThe new field is visible in MongoDB after your next migration job runs.\n\n## Examples\n\nThe following examples show JavaScript expressions that you can use in calculated fields:\n\n### Concatenate Strings\n\nCombine two columns into a single field.\n\nThe following example concatenates string values from the `firstName` and `lastName` columns.\n\nExpression:\n\n```none\ncolumns[\"firstName\"] + ' ' + columns[\"lastName\"]\n```\n\nInput:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nColumn\n\n\nValue\n\n
\n`firstName`\n\n\n`John`\n\n
\n`lastName`\n\n\n`Smith`\n\n
Output:\n\n```none\n\"John Smith\"\n```\n\n### Split Strings\n\nSplit column values into an array based on a specified character.\n\nThe following example splits the `fullName` column into an array using a space character as a delimiter, and returns the first element of the array.\n\nExpression:\n\n```none\ncolumns[\"fullName\"].split(' ')[0]\n```\n\nInput:\n\n\n\n\n\n\n\n\n\n\n
\nColumn\n\n\nValue\n\n
\n`fullName`\n\n\n`John Doe`\n\n
Output:\n\n```none\n\"John\"\n```\n\n### Replace Strings\n\nApply regex patterns to replace string values in a column.\n\nThe following example performs a case-insensitive regex search on the `fullName` column for the string `smith`. If a match is found, the expression replaces the matching string with `Doe`.\n\nExpression:\n\n```none\ncolumns[\"fullName\"].replace(/smith/i, \"Doe\")\n```\n\nInput:\n\n\n\n\n\n\n\n\n\n\n
\nColumn\n\n\nValue\n\n
\n`fullName`\n\n\n`John Smith`\n\n
Output:\n\n```none\n\"John Doe\"\n```\n\n### Check for String Values\n\nReturn true or false based on whether a column contains a string value.\n\nThe following example returns `true` if the value in the `fullName` column includes the string `Smith`. If the `fullName` column does not include the string `Smith`, the expression returns `false`.\n\nExpression:\n\n```none\ncolumns[\"fullName\"].includes(\"Smith\")\n```\n\nInput:\n\n\n\n\n\n\n\n\n\n\n
\nColumn\n\n\nValue\n\n
\n`fullName`\n\n\n`John Smith`\n\n
Output:\n\n```none\ntrue\n```\n\n### Perform Mathematic Operations\n\nPerform mathematic operations on column values.\n\nThe following example multiplies values from the columns `col1` and `col2`.\n\nExpression:\n\n```none\ncolumns[\"col1\"] * columns[\"col2\"]\n```\n\nInput:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nColumn\n\n\nValue\n\n
\n`coll1`\n\n\n`3`\n\n
\n`coll2`\n\n\n`2`\n\n
Output:\n\n```none\n6\n```\n\n### Assign Values Based on Logical Conditions\n\nAssign column values based on logical conditions.\n\nThe following example returns `yes` if the value of `col1` is `3`, and `no` if `col1` is a value other than `3`.\n\nExpression:\n\n```none\ncolumns[\"col1\"] === 3 ? \"yes\" : \"no\"\n```\n\nInput:\n\n\n\n\n\n\n\n\n\n\n
\nColumn\n\n\nValue\n\n
\n`coll1`\n\n\n`3`\n\n
Output:\n\n```none\nyes\n```\n\n### Extract JSON Values\n\nAccess data stored as JSON data type with calculated field expressions. Requires JSON data type columns (Postgres).\n\nThe following example returns the value of the embedded `state` field from values in the `Employee` column.\n\nExpression:\n\n```none\ncolumns[\"Employee\"].Address.state\n```\n\nInput:\n\n```json\n{\n Employee: {\n name: \"Mark\",\n Address: {\n state: \"California\"\n }\n }\n}\n```\n\nOutput:\n\n```none\n\"California\"\n```\n\n### Access Array Elements\n\nAccess data stored as array data type with calculated fields expressions. Requires array data type columns (Postgres or MySQL).\n\nThe following example returns the second element of the values in the `myArray` column.\n\nExpression:\n\n```none\ncolumns[\"myArray\"][1]\n```\n\nInput:\n\n\n\n\n\n\n\n\n\n\n
\nColumn\n\n\nValue\n\n
\n`myArray`\n\n\n[ \"a\", \"b\", \"c\" ]\n\n
Output:\n\n```none\n\"b\"\n```\n\n### Parse Dates\n\nParse an ISO8601-formatted date string into a date.\n\nThe following example converts string values from the `dateAsString` column into dates.\n\nExpression:\n\n```none\nnew Date(columns[\"dateAsString\"])\n```\n\nInput:\n\n\n\n\n\n\n\n\n\n\n
\nColumn\n\n\nValue\n\n
\n`dateAsString`\n\n\n\"2009-02-11\"\n\n
Output:\n\n```none\n2009-02-11T0:00:00Z\n```\n\n## Learn More\n\n- Delete Calculated Fields\n\n- Edit Calculated Fields\n\n- View Calculated Fields"} -{"chunk_id": "68a95c2a5e79d242619df508-0", "page_id": "68a95c2a5e79d242619df508", "source_name": "docs-relational-migrator", "product_name": "MongoDB Relational Migrator", "url": "https://mongodb.com/docs/relational-migrator/jobs/prerequisites/sql-server", "title": "Configure Migration Prerequisites for SQL Server", "text": "# Configure Migration Prerequisites for SQL Server\n\nTo run migration jobs from a SQL Server source database, the database may require some configuration changes. Before you start a migration job, Relational Migrator checks if the database is configured correctly. If Relational Migrator determines the database needs configuration changes, it automatically generates a SQL script with the required changes. It is recommended to have a Database Administrator (DBA) review the commands in this script and perform their execution on the database server. This topic provides more details on the required configuration steps.\n\n## About this Task\n\n- This page covers the details of the SQL scripts automatically generated by Relational Migrator.\n\n- Relational Migrator automatically detects configuration settings when connecting to your database and generates the appropriate SQL statements to enable CDC if required.\n\n- Relational Migrator does not create any indexes on SQL Server to facilitate migration jobs. The create index creation permission is not required.\n\n## Steps\n\nTo configure your SQL Server instance for snapshot jobs, you must enable CDC at the database level.\n\nThe easiest way to set up your database is to run the automatically generated script that Relational Migrator prompts you to download when you create a migration job. To understand the permissions or run the SQL manually, read the following procedure.\n\nTo enable CDC at the database level use the `sys.sp_cdc_enable_db` stored procedure.\n\nThe code blocks below are a sample of the code automatically generated by Relational Migrator. You can run the code manually by replacing the database name for `MyDB`:\n\n```sql\nUSE MyDB\nGO\nEXEC sys.sp_cdc_enable_db\nGO\n```\n\nFor SQL Server instances hosted on AWS RDS:\n\n```sql\nUSE MyDB\nGO\nEXEC msdb.dbo.rds_cdc_enable_db 'MyDB';\nGO\n```\n\nEnabling CDC at the database-level CDC generates a small number of system tables in the database, leaves user tables unchanged, and does not add any performance overhead. Enabling CDC alone does not result in changes being captured.\n\n## Learn More\n\nRelational Migrator relies on the open-source Debezium connector to capture row-level changes. For more details, see Debezium SQL Server."} -{"chunk_id": "68a95c2a5e79d242619df511-0", "page_id": "68a95c2a5e79d242619df511", "source_name": "docs-relational-migrator", "product_name": "MongoDB Relational Migrator", "url": "https://mongodb.com/docs/relational-migrator/mapping-rules/edit-rules", "title": "Edit Rules", "text": "# Edit Rules\n\nYou can update a mapping rule after it is created. Edited mapping rules take effect the next time a migration job is run.\n\n## About this Task\n\nOptions available on the edit pane depend on the type of mapping rule you are editing. For an overview of each mapping rule option, see:\n\n- New Documents\n\n- Embedded Array\n\n- Embedded Documents\n\n## Steps\n\n1. From the Mapping screen, click a table or collection name on the Schema model pane or Diagram view.\n\n2. From the Mappings pane, click the icon.\n\n3. Define the options for the mapping rule. When defining the mapping rule, you can:\n\n - Change the collection name.\n\n - Change field names.\n\n - To include or exclude a field from your migration job, click the icon next to the field name.\n\n4. Optionally, if you want to select a BSON type or set null handling rules for your mapping rule:\n\n - Click the icon next to the field you want to customize.\n\n - Select a BSON type.\n\n - Select a Null handling option.\n\n - Insert as null: preserves null values, and nulls are inserted into your destination collection.\n\n - Omit: skips any null values, and nulls are not inserted into the destination collection.\n\n You can view a field's Original name and Original type in the expanded customized field menu.\n\n For additional details on field customization and data type conversions, see field customizations.\n\n5. Click Save and close to save your edits.\n\n## Learn More\n\nTo learn more about managing mapping rules, see:\n\n- Create rules\n\n- Delete mapping rules\n\n- View mapping rules"} -{"chunk_id": "68a95c2a5e79d242619df4c3-0", "page_id": "68a95c2a5e79d242619df4c3", "source_name": "docs-relational-migrator", "product_name": "MongoDB Relational Migrator", "url": "https://mongodb.com/docs/relational-migrator/diagrams/understand-diagrams", "title": "Understand Diagrams", "text": "# Understand Diagrams\n\nThis page explains how to interpret diagrams created in the Relational Migrator. Each diagram is comprised of two views, one for your relational database and one for your MongoDB database. The views show the relationships between entities in your databases.\n\n## Relational View\n\nIn the relational view, each box represents a table in your relational database. The box title indicates the table name.\n\nEach box lists the columns in the corresponding table. For each column, the box indicates the column name and its data type.\n\nSome columns have icons to indicate their role within the table:\n\n- A key icon indicates the table's primary key.\n\n- A link icon indicates a foreign key.\n\n## MongoDB View\n\nIn the MongoDB view, each box represents a collection in your MongoDB database. The box title indicates the collection name.\n\nEach box lists the fields in the corresponding collection. For each field, the box indicates the field name and its data type.\n\nIf a collection contains embedded documents or arrays, those fields are shown in-line in the same collection.\n\nSome fields have icons to indicate their role within the table:\n\n- A key icon indicates the collection's `_id` field. When you use the `wrapped` key handling strategy, the `_id` field contains sub-fields. In this case, the box contains multiple key icons which apply to a single field.\n\n- A link icon indicates that the field maps to a relational column used in a foreign key.\n\n## Choose View Mode\n\nRelational Migrator provides different diagram view modes: Horizontal Split, Vertical Split, Relational view, and MongoDB view.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nView Mode\n\n\nDescription\n\n
\nHorizontal Split\n\n\nDisplays the relational view on top and the MongoDB view is on the bottom. When you create a new project, Horizontal Split is the default view mode.\n\n
\nVertical Split\n\n\nDisplays the relational view on the left and the MongoDB view on the right.\n\n
\nRelational View\n\n\nDisplays only your relational database diagram.\n\n
\nMongoDB View\n\n\nDisplays only your MongoDB database diagram.\n\n
To switch view modes, click a view mode option in the left navigation bar:\n\n## Color Coding\n\nEntities in the diagram are color-coded based on whether they represent the relational or MongoDB database:\n\n- Entities with pink highlights are relational tables.\n\n- Entities with green highlights are MongoDB collections.\n\n## Entity Links\n\nThe lines between boxes represent the relationships that connect database entities. If two boxes are connected, the corresponding entities are linked with a foreign key. The lines may show the following features of relationships:\n\n- A small bar across a relationship link indicates a one-to-one relationship between entities.\n\n- A prong (or \"crow's feet\") indicates \"many\" in the relationship.\n\n## Undo or Redo Diagram Actions\n\nRelational Migrator diagrams support undo and redo functions. To reverse or reapply the previous diagram action, use the undo or redo capability. You can use either the diagram toolbar or keyboard shortcuts to perform these actions.\n\n### Toolbar\n\nYou can use the and buttons on the diagram toolbar:\n\n### Keyboard Shortcut\n\nAlternatively, you can use keyboard shortcuts:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nFunction\n\n\nWindows Shortcut\n\n\nMac Shortcut\n\n
\nUndo\n\n\nControl + Z\n\n\nCommand + Z\n\n
\nRedo\n\n\nControl + Y\n\n\nCommand + Y\n\n
\n\n## Relational and MongoDB View Links\n\nWhen you click a box in either the relational or MongoDB view, the Relational Migrator highlights the corresponding entity in the opposite view. This allows you to see how your relational tables and MongoDB collections are mapped to one another.\n\n## Examples\n\nThe following example shows a sample diagram for a database that tracks orders at a store.\n\n### Relational View\n\nThis relational view shows the relationship of several tables within a relational database:\n\nThe view shows the following relationships:\n\n- In the `Order` table, `OrderID` is the primary key. `CustomerID` and `OrderStatusID` are foreign keys. The `Customer` and `OrderStatus` tables contain the references for these foreign keys, respectively.\n\n - `Order` to `Customer` and `Order` to `OrderStatus` are both many-to-one relationships:\n\n - A customer can have multiple orders, and each order only applies to a single customer. In this example, Order is the parent and Customer is the child.\n\n - An order status can apply to multiple orders, and each order only has a single order status. In this example, Order is the parent and OrderStatus is the child.\n\n- In the `OrderLine` table, `OrderLineID` is the primary key. `OrderID` and `ProductID` are foreign keys. The `Order` and `Product` tables contain the references for these foreign keys, respectively.\n\n - `OrderLine` to `Order` and `OrderLine` to `Product` are both many-to-one relationships:\n\n - An order line is an individual transaction within an order. An order can have multiple order lines, and each order line applies to a single order. In this example, OrderLine is the parent and Order is the child.\n\n - A product can apply to multiple order lines, and each order line contains a single product. In this example, OrderLine is the parent and Product is the child.\n\n### MongoDB View\n\nThis MongoDB view corresponds to the previous Relational view:\n\nThe collections and data types presented in the view reflect the mapping rules specified for the project.\n\nThe link icons indicate fields which map to a relational column used in a foreign key. For example, in the `Order` collection, the `OrderStatusID` field represents a foreign key that links the `Order` and `OrderStatus` tables.\n\n### New Mapping Rules\n\nThe following new mapping rules have been created to better utilize MongoDB's embedded data model:\n\n- The `Order` collection contains a rule that maps `OrderLines` as an Embedded array. The `OrderLine` table from the relational schema is mapped as an array of objects inside the `Order` documents, using the foreign key relationship from the relational schema.\n\n- The `Customer` collection contains a rule which maps `Orders` as an Embedded array. The `Order` table from the relational schema is mapped as an array of objects inside the `Customer` documents, using the foreign key relationship from the relational schema.\n\nBoth of the preceding mapping rules remove the ID fields from the mapping. Since the `OrderLines` and `Orders` fields are embedded in their parent fields rather than being referenced with a foreign key, the ID fields are not required to link the fields together."} -{"chunk_id": "68a95c2a5e79d242619df519-0", "page_id": "68a95c2a5e79d242619df519", "source_name": "docs-relational-migrator", "product_name": "MongoDB Relational Migrator", "url": "https://mongodb.com/docs/relational-migrator/mapping-rules/example-insurance-data/migrate-data", "title": "Migrate Your Data to MongoDB", "text": "# Migrate Your Data to MongoDB\n\nNow that you have simplified your data model into five collections, you can migrate your data from PostgreSQL to MongoDB Atlas.\n\n## Before You Begin\n\nThis task is the final step of the insurance data model example tutorial. Before you migrate your data, ensure you have access to a MongoDB Atlas cluster with `dbAdmin` permissions on the new database to where you will migrate the data.\n\n## Steps\n\n### Create a new migration job\n\nIn the top navigation bar, navigate to the Data Migration tab and click Create migration job. This opens the New Migration Job modal.\n\n### Select the source database\n\nClick Use a saved connection and select your PostgreSQL database from the drop-down menu. After you input your username and password, click Connect.\n\n### Input information for your destination database\n\nFill in the connection information for your MongoDB Atlas deployment and click Connect. Ensure that you specify the database where you want to migrate your data.\n\n### Review Migration Options\n\nIn this example, we will leave all options as default. This will migrate our data in Snapshot mode, which loads all your data at once.\n\nAfter you review the options, click Review Summary\n\n### Click Start\n\nIn the Review Summary stage, click Start to begin the migration job. The migration can take a couple of minutes.\n\nOnce ready, Relational Migrator displays the the `COMPLETED` tag in the Snapshot stage card. You can now connect to your database and view how all your data loaded in MongoDB Atlas or Compass.\n\n## Learn More\n\n- Data Migration with Snapshot Jobs"} -{"chunk_id": "68a95c2a5e79d242619df44a-0", "page_id": "68a95c2a5e79d242619df44a", "source_name": "docs-relational-migrator", "product_name": "MongoDB Relational Migrator", "url": "https://mongodb.com/docs/relational-migrator/api-docs", "title": "Relational Migrator REST API", "text": "# Relational Migrator REST API\n\nThe Relational Migrator REST API provides you with programmatic access to Relation Migrator with HTTPS endpoints. The REST API is a Relational Migrator service between your application and your source and destination databases that you can send requests to manage your migration jobs.\n\nYou don't need to install any additional extensions or packages to use the Relational Migrator REST API. The functionality is part of the Relational Migrator product. The REST API runs on the same port that you access the application on (either `8278`, `8080`, or `443`).\n\n## How the REST API Works\n\nThe Relational Migrator REST API runs on the client computer or server that has Relational Migrator installed. By default, Relational Migrator does not expose the API to any remote computers. If you use the default security settings, you must make all calls to the API on the same computer that you are running Relational Migrator on.\n\nIf you want to remotely access the REST API, configure the `unattended` profile by installing Relational Migrator on an unattended server.\n\nThe REST API does not support authentication. If you enable remote access, users do not need to authenticate to call the API which may cause security vulnerabilities.\n\n## When to Use REST API\n\nUse the Relational Migrator REST API when:\n\n- You want to use a task scheduler such as cron to run migration jobs on a cadence, such as daily, instead of running them once.\n\n- You want to define dynamic table filters within a project to control which data each migration job processes. For example, using a table filter with `WHERE DATEDIFF(CURDATE(), last_modified) <= 1` to migrate only recently modified data in each batch.\n\n- You want to programmatically create Relational Migrator migration jobs dynamically. For example, using connection strings from multiple databases without manually configuring them in the GUI.\n\n- You generally prefer scripting your workflows instead of using a GUI.\n\nMigration jobs are non-idempotent by default. If you schedule jobs to run on a cadence, enable idempotency so that each run replaces the documents from the previous run instead of creating duplicate documents. For information about enabling idempotency, see Data Migration with Snapshot Jobs.\n\n## Learn More\n\nFor Relational Migrator REST API endpoints, example requests, and responses, see the Endpoints."} -{"chunk_id": "68a95c2a5e79d242619df53a-0", "page_id": "68a95c2a5e79d242619df53a", "source_name": "docs-relational-migrator", "product_name": "MongoDB Relational Migrator", "url": "https://mongodb.com/docs/relational-migrator/mapping-rules/mapping-rule-options/introduction", "title": "Mapping Rule Options", "text": "# Mapping Rule Options\n\nMapping rule options are important options that help define the state of your MongoDB collection after a migration.\n\nThese options are defined when creating or editing a mapping rule.\n\n## Mapping Rule Concepts\n\nEvery mapping rule joins a source table to a destination collection. You can create mapping rules from either a table or a collection. When creating a mapping rule you must select the other entity. For example:\n\n- If you select a table and choose to create a mapping rule you must choose the destination collection.\n\n- If you select a collection and choose to create a mapping rule, you must select the source table.\n\nFor Embedded array and Embedded document mapping rules, you must also configure where you want the embedded data inserted into your document.\n\nThe table below provides a summary of the concepts associated with mapping rule options and the mapping rules they apply to.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nConcept\n\n\nDescription\n\n\nApplies To\n\n
\nCollection Name\n\n\nThe destination collection where the relational rows of data are migrated.\n\n\nNew documents\n\n
\nParent collection\n\n\nThe destination collection where the relational rows of data are migrated.\n\n\nEmbedded documents Embedded array\n\n
\nPrefix\n\n\nA drop-down where you can specify your rule hierarchy.\n\n\nEmbedded documents Embedded array\n\n
\nField name\n\n\nIndicates the field containing the array or document.\n\n\nEmbedded documents Embedded array\n\n
\nCreate an array of primitive values\n\n\nCreates a single field array in the parent collection.\n\n\nEmbedded array\n\n
\nMerge fields into the parent\n\n\nMerges the table rows as fields at the parent collection level.\n\n\nEmbedded documents\n\n
\nMapping rule filter\n\n\nExplicitly include rows where an expression returns true.\n\n\nNew documents Embedded documents Embedded array\n\n
\nArray conditions\n\n\nSort, limit, and order an embedded array.\n\n\nEmbedded array\n\n
Relational Migratory primary key id field migration is defined at the project level.\n\nFor details on how these project setting affect your migration, see Key Handling Options.\n\n## Get Started\n\n- New Documents\n\n- Embedded Array\n\n- Embedded documents\n\n- Mapping Rule Filters\n\n## Details\n\nTo conceptualize the examples of each mapping rule, the following `Mongo Enterprise` relational schema is used to help explain each mapping rule option."} -{"chunk_id": "68a95c2a5e79d242619df54c-0", "page_id": "68a95c2a5e79d242619df54c", "source_name": "docs-relational-migrator", "product_name": "MongoDB Relational Migrator", "url": "https://mongodb.com/docs/relational-migrator/mapping-rules/schema-mapping", "title": "Schema Mapping", "text": "# Schema Mapping\n\nSchema mapping is the process by which you decide how your source relational schema should be represented in your target MongoDB database. Facilitate the schema mapping process in Relational Migrator through customized mappings rules.\n\n## Mapping Rules\n\nDuring the schema mapping design process, Relational Migrator automatically derives the source data model from the schema of your relational database. The destination data model can be influenced by customizing:\n\n- Mapping Rule options\n\n- Project ID field options\n\nRelational Migrator supports Oracle materialized views. If your data model requires complex mappings that involve many tables, you can create a materialized view using a custom SQL query instead. The materialized view acts as a single source table and simplifies the required mappings. Performing complex joins in your Oracle source database can streamline your migration project and may improve performance compared to a migration job that performs the same transformations live. For more information, see the Oracle SQL Language Reference.\n\nRelational Migrator does not support materialized views for other databases at this time.\n\n## Example\n\nThis section provides a scenario and example implementation for the schema mapping process. This example converts a relational data model to a MongoDB data model.\n\nUsing the `MongoEnterprises` relational database, the goal is to flatten all of the database's tables, so that all the order and customer data is available in a single MongoDB collection.\n\n### Use-Case Denormalizing Table Structure\n\nThe following image shows the relational data model to be denormalized using the Relational Migrator.\n\n### Mapping Rule Results\n\nWhen using Relational Migrator, the goal is to achieve the following MongoDB data model. The `Order` collection contains all the child elements from the `Customer`, `Order`, `Product` and `Order Line` tables. The collection has nested objects for the migrated tables. The results look like this:\n\n```json\n{\n \"_id\": {\n \"OrderID\": 1\n },\n \"CustomerID\": 1,\n \"OrderStatusID\": 1,\n \"TotalAmount\": 550,\n \"Customer\": {\n \"CustomerID\": 1,\n \"Name\": \"Joelynn Fawthrop\",\n \"Address1\": \"86 Dwight Pass\",\n \"Address2\": \"Carregal\",\n \"Address3\": \"3800-854\"\n },\n \"OrderLines\": [\n {\n \"OrderLineID\": 1,\n \"OrderID\": 1,\n \"ProductID\": 1,\n \"Quantity\": 1,\n \"Product\": {\n \"ProductID\": 1,\n \"Name\": \"MongoDB 5.0 Action Figure\",\n \"Price\": 50\n }\n },\n {\n \"OrderLineID\": 4,\n \"OrderID\": 1,\n \"ProductID\": 3,\n \"Quantity\": 1,\n \"Product\": {\n \"ProductID\": 3,\n \"Name\": \"Gold Plated MongoDB Compass\",\n \"Price\": 500\n }\n }\n ],\n \"OrderStatus\": {\n \"OrderStatusID\": 1,\n \"Name\": \"Order Placed\"\n }\n}\n```\n\n### Mapping Rule Implementation\n\nTo accomplish the target data model results with Relational Migrator, configure the `Order` table with the following mapping rule options:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nRelational Table\n\n\nMapping Rule Type\n\n\nRoot Path\n\n
\nOrder\n\n\nNew Documents\n\n\nN/A\n\n
\nOrderLine\n\n\nEmbedded array\n\n\n`OrderLines`\n\n
\nCustomer\n\n\nEmbedded documents\n\n\n`Customer`\n\n
\nOrderStatus\n\n\nEmbedded documents\n\n\n`OrderStatus`\n\n
\nProduct\n\n\nEmbedded documents\n\n\n`OrderLInes.Product`\n\n
"} -{"chunk_id": "68a95c2a5e79d242619df4a9-0", "page_id": "68a95c2a5e79d242619df4a9", "source_name": "docs-relational-migrator", "product_name": "MongoDB Relational Migrator", "url": "https://mongodb.com/docs/relational-migrator/database-connections/mysql", "title": "Connect to MySQL", "text": "# Connect to MySQL\n\nMySQLThis page shows how to save a new MySQL connection from the Connections page. You can use a saved connection for any Relational Migrator task that requires connecting to a database.\n\n## About this Task\n\nTo save a new MySQL connection in Relational Migrator, you must:\n\n- Identify your database connection string or database information.\n\n- Connect to MySQL.\n\nTo plan your migration and map your MySQL schema to a MongoDB schema, you must connect using an account with the correct `read` permissions.\n\nTo migrate data, you must connect to your MySQL database using a service account with the required permissions.\n\nFor information on database configuration and required permissions, see Configure MySQL.\n\n## Steps\n\n### Database Connection String\n\nRelational Migrator requires a connection string to connect to your MySQL instance.\n\nThe MySQL connection string looks like:\n\n```\njdbc:mysql:///?\n```\n\nFor example, the `test` MySQL database running on `host1` at port `3306` uses the following connection string:\n\n```\njdbc:mysql://host1:3306/test\n```\n\nAlternatively, Relational Migrator can create the appropriate connection string based on user-provided database information.\n\n### Connect to MySQL\n\nTo save a new connection from the Connections page, perform the following actions:\n\n#### Add a connection\n\nIn the list of Relational connections, click + Add connection.\n\n#### Select the database type\n\nIn the Database type drop-down, select MySQL.\n\n#### To enter a connection string directly:\n\n- Above JDBC URI, enable the Enter URI manually toggle.\n\n- Paste your connection string into the JDBC URI.\n\n#### To create a connection string, enter the following:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nField\n\n\nValue\n\n
\nHost\n\n\nThe host IP or DNS name.\n\n
\nPort\n\n\nThe port number.\n\n
\nDatabase\n\n\nThe database name. Leave blank to load all databases.\n\n
\nUsername and Password\n\n\nThe credentials to use for authentication.\n\nChecking Save password saves the password securely on your machine, so you don't have to enter the Username and Password again when using the saved connection.\n\n
\nGeneral / SSL toggle\n\n\nView SSL settings for the connection.\n\nTo use SSL, you must first uncomment and update the `server.ssl` configuration properties in your `user.properties` file.\n\n
\nSSL: Use SSL\n\n\nEnable or disable SSL.\n\n
\nSSL: SSL mode\n\n\nWith SSL enabled, choose from:\n\n- Preferred (default): Make an encrypted connection if possible, otherwise fall back to an unencrypted connection.\n\n- Required: Require an encrypted connection.\n\n- Verify CA: Verify the server certificate against a trusted Certificate Authority.\n\n- Verify identity: Verify the database connection information against the certificate contents.\n\n
\n\n#### Identify the connection\n\nEnter a Connection name and optional Environment tag.\n\nEnvironment tags color code and organize connections for convenience. Leaving the drop-down empty is the same as selecting the \"None\" tag.\n\n#### Test and save your connection\n\n- (Optional) Click Test connection\n\n Relational Migrator attempts to authenticate and connect to the database.\n\n- Click Save\n\n The saved connection is available for use in all jobs and projects.\n\n## Learn More\n\n- Relational Migrator relies on the open-source Debezium connector to capture row-level changes. For more details, see Debezium MySQL.\n\n- For information about supported databases and versions, see Supported Databases and Versions.\n\n- For information on managing saved connections, see Manage Database Connections.\n\n- For information on Relational Migrator projects, see Create and Manage Projects."} -{"chunk_id": "68a95c2a5e79d242619df517-0", "page_id": "68a95c2a5e79d242619df517", "source_name": "docs-relational-migrator", "product_name": "MongoDB Relational Migrator", "url": "https://mongodb.com/docs/relational-migrator/mapping-rules/example-insurance-data", "title": "Example: Insurance Data Models", "text": "# Example: Insurance Data Models\n\nThis sample tutorial uses the Relational Migrator to transform a 21-table insurance data schema into a simple five-collection MongoDB model.\n\n## About this Task\n\nIn the sample data set, all people, organizations, and groups are represented as Parties, which can be related to other major objects with specified roles. The Party design also provides a common approach for describing communication identifiers, relationships between parties, and legal identifiers.\n\nIn this tutorial, you will use the Relational Migrator to port the Object Management Group\u2019s Party Role model from a relational structure to MongoDB\u2019s document model. Specifically, you will refactor the Party model in the context of the Policy, Claim, and Litigation domains.\n\n## Before You Begin\n\nThis example requires the following applications:\n\n- MongoDB Relational Migrator version 1.4.3 or higher. To download the latest version, see the MongoDB Relational Migrator release page.\n\n- MongoDB Atlas: Ensure you have access to an Atlas cluster with write permissions to create the new database to where you will migrate the data.\n\n- PostgreSQL version 16 or higher: Ensure you have access to a PostgreSQL database server instance with permissions to create a new database and user. The instance can be in the cloud, on-prem, or on your local machine. In addition to PostgreSQL, install the following PostgreSQL Client Applications:\n\n - psql: a command-line application that allows you to interactively type in queries, issue them to PostgreSQL, and see the query results.\n\n - pg_restore: A command-line application that restores the PostgreSQL database from the sample archive file.\n\nAdditionally, download the `mongodb_insurance_model.tar`\nsample archive file. This file contains all the tables, relationships, and sample data from the Party Role model in a tabular format.\n\nTo replicate the Party Role model in PostgreSQL, follow the following steps:\n\n### Connect to the PostgreSQL database\n\n```\npsql -h -p -U -d \n```\n\nIf you have a newly installed local instance with default parameters, use `127.0.0.1` as your host, `5432` as your port, `postgres` as your database, and type `whoami` in your terminal for a default username.\n\n### Create a database to load your data\n\n```\nCREATE DATABASE mongodb_insurance_model;\n```\n\n### Create a user that has access to the new database\n\n```\nCREATE USER istadmin WITH PASSWORD '';\nALTER DATABASE mongodb_insurance_model OWNER TO istadmin;\n```\n\nEnsure that you replace `` with a strong password of your choice.\n\n### Populate the database with the Party Role model.\n\nNavigate to the folder where you downloaded the archive file's backup of the database and run the following command to load the data:\n\n```\npg_restore -h -p -U -d mongodb_insurance_model mongodb_insurance_model.tar\n```\n\n### Verify the successful restore of the database\n\n```\npsql -h -p -U -d mongodb_insurance_model -c \"SELECT * FROM pg_catalog.pg_tables WHERE schemaname='omg';\"\n```\n\nYou should see a list of 21 tables similar to the following image:\n\n## Steps\n\nThe example tutorial consists of the following steps:\n\n### Connect to Relational Migrator\n\nConnect your PostgreSQL database to Relational Migrator. See Connect to Relational Migrator.\n\n### Refactor the Party domain\n\nRefactor the Party domain in the MongoDB view of Relational Migrator. See Refactor the Party Domain.\n\n### Refactor the Policy domain\n\nRefactor the Policy domain in the MongoDB view of Relational Migrator. See Refactor the Policy Domain.\n\n### Refactor the Claim domain\n\nRefactor the Claim domain in the MongoDB view of Relational Migrator. See Refactor the Claim Domain.\n\n### Refactor the Litigation domain\n\nRefactor the Litigation domain in the MongoDB view of Relational Migrator. See Refactor the Litigation Domain.\n\n### Migrate your data to MongoDB\n\nMigrate your data to your MongoDB instance by using the Relational Migrator. See Migrate Your Data to MongoDB."} -{"chunk_id": "695dfad9e50b91a6be6e4d2b-0", "page_id": "695dfad9e50b91a6be6e4d2b", "source_name": "drivers", "product_name": "MongoDB Drivers", "url": "https://mongodb.com/docs/drivers/node-frameworks/meteor-vue", "title": "Integrate MongoDB with Meteor and Vue", "text": "# Integrate MongoDB with Meteor and Vue\n\n## Overview\n\nIn this guide, you can learn how to create a full-stack **Meteor** application that uses **Vue** as the front-end framework. Meteor is a JavaScript framework for creating web and mobile applications. This framework supports a range of front-end libraries for building the user interface, including Vue.\n\nThe application in this tutorial consists of the following layers:\n\n- **Database layer**: MongoDB provides data storage and retrieval\n\n- **Application layer**: Meteor handles both client and server-side logic with integrated build tools\n\n- **Presentation layer**: Vue implements the user interface with reactive data binding\n\n### Why Use MongoDB with Meteor and Vue?\n\nMeteor is built on MongoDB's document model, and Meteor applications configure MongoDB by default. You can quickly create a full-stack application that stores data in MongoDB with minimal dependency installations or boilerplate code.\n\nMongoDB's flexible document structure naturally aligns with JavaScript objects. As a result, you can work seamlessly with MongoDB data in your Vue components. When you use Meteor to query MongoDB, the documents you receive can be directly used in your Vue templates without complex data transformation.\n\nAdditionally, Meteor provides built-in real-time data synchronization that automatically updates your Vue components when data changes in MongoDB. When one user modifies data, all connected users see the changes instantly in their Vue interfaces without a manual refresh or polling. By using MongoDB with Meteor and Vue, you can leverage Meteor's real-time data synchronization capabilities alongside Vue's reactive component system.\n\n## Quick Start Tutorial\n\nThis tutorial shows you how to build a web application by using Meteor and Vue. The application accesses sample restaurant data, queries the data, and displays the results on a locally hosted site. The tutorial also includes instructions on connecting to a MongoDB cluster hosted on MongoDB Atlas and accessing and displaying data from your database.\n\nIf you prefer to connect to MongoDB by using the Node.js driver without Meteor, see the Get Started with the Node.js Driver guide.\n\n### Set Up Your Project\n\nFollow the steps in this section to install the project dependencies, create an Atlas cluster, and set up the application directories.\n\n#### Verify the prerequisites\n\nTo create the Quick Start application, install the following software in your development environment:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nPrerequisite\n\n\nNotes\n\n
\nNode.js\n\n\nUse version 20 or later.\n\n
\nCode editor\n\n\nThis tutorial uses Visual Studio Code, but you can use the editor of your choice.\n\n
\nTerminal app and shell\n\n\nFor MacOS users, use Terminal or a similar app. For Windows users, use PowerShell.\n\n
\n\n#### Create a MongoDB Atlas cluster\n\nMongoDB Atlas is a fully managed cloud database service that hosts your MongoDB deployments. If you do not have a MongoDB deployment, you can create a MongoDB cluster for free (no credit card required) by completing the MongoDB Get Started tutorial. The MongoDB Get Started tutorial also demonstrates how to load sample datasets into your cluster, including the `sample_restaurants` database that is used in this tutorial.\n\nTo connect to your MongoDB cluster, you must use a **connection URI**. To learn how to retrieve your connection URI, see the Add your connection string section of the MongoDB Get Started tutorial.\n\nSave your connection string in a secure location.\n\n#### Install Meteor\n\nInstall Meteor by running the following command in your terminal:\n\n```bash\nnpx meteor\n```\n\nIf you encounter any issues, refer to the Meteor installation guide.\n\n#### Install the MongoDB Node.js Driver\n\nInstall the Node.js driver by running the following command in your terminal:\n\n```bash\nnpm install mongodb\n```\n\nTo learn more about installing the driver, see the Get Started with the Node.js Driver guide.\n\n#### Create your Meteor project\n\nRun the following command to create a new Meteor project with Vue:\n\n```bash\nmeteor create --vue meteor-vue-quickstart\ncd meteor-vue-quickstart\n```\n\nThe `--vue` flag creates a Meteor project configured with Vue 3, Vite, and Tailwind CSS for styling.\n\n#### Clean up the project structure\n\nBefore adding application code, remove the unnecessary template files by running the following commands from your `meteor-vue-quickstart` directory:\n\n```bash\ncd imports/ui\nrm components/AppMenu.vue components/Hello.vue components/Info.vue views/About.vue views/Home.vue\n```\n\nThis removes the default template components that the restaurant application does not use."} -{"chunk_id": "695dfad9e50b91a6be6e4d2b-1", "page_id": "695dfad9e50b91a6be6e4d2b", "source_name": "drivers", "product_name": "MongoDB Drivers", "url": "https://mongodb.com/docs/drivers/node-frameworks/meteor-vue", "title": "Integrate MongoDB with Meteor and Vue", "text": "### Configure Your MongoDB Connection\n\nAfter setting up the project structure, follow the steps in this section to connect your Meteor application to MongoDB.\n\n#### Provide your connection URI\n\nRetrieve the connection URI that you saved in a previous step.\n\nTo access the `sample_restaurants` database, modify your connection URI to include the database name. Use the following format to update your URI:\n\n```none\nmongodb+srv://:@/sample_restaurants?\n```\n\nThen, set the `MONGO_URL` environment variable to this modified connection URI by running the following command from the `meteor-vue-quickstart` directory:\n\n```bash\nexport MONGO_URL=\"\"\n```\n\nReplace the `` placeholder with your connection URI.\n\n#### Access the `restaurants` collection\n\nIn the `imports/api` directory, create a file named `restaurantsCollection.js` and paste the following code:\n\n```js\nimport { Mongo } from 'meteor/mongo';\n\nexport const RestaurantsCollection = new Mongo.Collection('restaurants');\n```\n\nThis file accesses and exports the `sample_restaurants.restaurants` collection.\n\n#### Set up data publications\n\nCreate a file named `restaurantsPublications.js` in the `imports/api` directory and paste the following code:\n\n```js\nimport { Meteor } from 'meteor/meteor';\nimport { RestaurantsCollection } from './restaurantsCollection';\n\n// Publishes all restaurants\nMeteor.publish('restaurants', function publishRestaurants() {\n console.log('Publishing all restaurants...');\n const cursor = RestaurantsCollection.find({}, { limit: 200 }); // Limit for performance\n console.log('Publication cursor created for all restaurants');\n return cursor;\n});\n\n// Publishes restaurants that match the \"borough\" and \"name\" filters\nMeteor.publish('restaurants.filtered', function publishFilteredRestaurants() {\n console.log('Publishing filtered restaurants...');\n const query = {\n borough: 'Queens',\n name: { $regex: 'Moon', $options: 'i' }\n };\n const cursor = RestaurantsCollection.find(query);\n console.log('Publication cursor created for filtered restaurants');\n return cursor;\n});\n```\n\nThis file defines Meteor publications that allow the client to subscribe to restaurant data. It includes the following publications:\n\n- `restaurants`: Publishes all restaurants, but limits them to `200` to avoid performance issues\n\n- `restaurants.filtered`: Publishes restaurants in Queens that have `\"Moon\"` in the name. The `$options` argument specifies that this regex string matching is case-insensitive.\n\n#### Define an insert operation\n\nCreate a new directory named `scripts`, and then create a file in this directory called `insertDemo.js`. Paste the following code into `insertDemo.js`:\n\n```js\nconst { MongoClient } = require('mongodb');\n\nconst MONGO_URL = process.env.MONGO_URL;\n\nasync function insertSampleRestaurant() {\n\n const client = new MongoClient(MONGO_URL);\n\n try {\n await client.connect();\n const db = client.db();\n const collection = db.collection('restaurants');\n\n const doc = {\n name: \"Honey Moon Coffee Shop\",\n borough: \"Queens\",\n cuisine: \"Caf\u00e9/Coffee/Tea\",\n };\n const result = await collection.insertOne(doc);\n\n console.log('Inserted restaurant with ID:', result.insertedId);\n\n } catch (error) {\n console.error('Error:', error);\n } finally {\n await client.close();\n }\n}\n\ninsertSampleRestaurant();\n```\n\nThis file defines a method named `insertSampleRestaurant()`, which inserts a document that stores the following fields:\n\n- `name`: `\"Honey Moon Coffee Shop\"`\n\n- `borough`: `\"Queens\"`\n\n- `cuisine`: `\"Caf\u00e9/Coffee/Tea\"`\n\nYou will use this file to demonstrate Meteor's real-time data synchronization capabilities in a future step.\n\n#### Update the server configuration\n\nReplace the contents of `server/main.js` with the following code:\n\n```js\nimport { Meteor } from 'meteor/meteor';\nimport { RestaurantsCollection } from '../imports/api/restaurantsCollection';\nimport '../imports/api/restaurantsPublications';\n\nMeteor.startup(async () => {\n // Check connection to restaurants collection\n try {\n const restaurantCount = await RestaurantsCollection.find().countAsync();\n console.log(`Connected to MongoDB Atlas. Found ${restaurantCount} restaurants in the collection`);\n } catch (error) {\n console.error('Error connecting to restaurants collection:', error);\n }\n});\n\n```\n\nThis file imports the necessary collections and publications. It also creates a startup function that verifies the MongoDB connection by printing the number of documents in the `restaurants` collection."} -{"chunk_id": "695dfad9e50b91a6be6e4d2b-2", "page_id": "695dfad9e50b91a6be6e4d2b", "source_name": "drivers", "product_name": "MongoDB Drivers", "url": "https://mongodb.com/docs/drivers/node-frameworks/meteor-vue", "title": "Integrate MongoDB with Meteor and Vue", "text": "### Configure Vue Components\n\nAfter setting up the data layer, follow the steps in this section to create Vue components that display the restaurant data.\n\n#### Set up routing\n\nNavigate to the `imports/ui/router.js` file and paste the following code:\n\n```js\nimport { createRouter, createWebHistory } from 'vue-router';\nimport RestaurantList from './views/RestaurantList.vue';\n\nexport const router = createRouter({\n history: createWebHistory(),\n routes: [\n {\n path: '/',\n name: 'home',\n component: RestaurantList,\n meta: { filter: false }\n },\n {\n path: '/browse',\n name: 'browse',\n component: RestaurantList,\n meta: { filter: true }\n }\n ],\n});\n\n```\n\nThis file configures the Vue routes and determines what content to render for each one. The `/` route displays all restaurant data, and the `/browse` route displays filtered restaurant data.\n\n#### Create the `Restaurant` component\n\nIn the `imports/ui/components` directory, create a file named `Restaurant.vue` that contains the following code:\n\n```vue\n\n\n\n```\n\nThis component displays individual restaurant information as a row in a table.\n\n#### Create the `RestaurantList` view\n\nIn the `imports/ui/views` directory, create a file named `RestaurantList.vue` that contains the following code:\n\n```vue\n\n\n\n```\n\nThis component handles the restaurant list display and automatically switches between showing all restaurants or filtered results based on the current route.\n\n#### Update the main `App` component\n\nReplace the contents of `imports/ui/App.vue` with the following code:\n\n```vue\n\n\n\n```\n\nThis is the main application component that includes navigation and renders the appropriate child components based on the current route.\n\n### Run Your Application\n\nFinally, follow the steps in this section to run your application and view the rendered restaurant data.\n\n#### Start the `Meteor` application\n\nNavigate to your project directory and run the following command from your terminal:\n\n```bash\nmeteor npm run start\n```\n\nIf successful, the command output resembles the following example:\n\n```bash\n[[[[[ ~/meteor-vue-quickstart ]]]]]\n\n=> Started proxy.\n=> Started HMR server.\n...\nConnected to MongoDB Atlas. Found 25368 restaurants in the collection\n=> Started your app.\n\n=> App running at: http://localhost:3000/\n```\n\n#### Open the application in your browser\n\nOpen http://localhost:3000/ in your web browser. The initial landing page displays a list of 200 unfiltered restaurants in the `sample_restaurants.restaurants` collection:\n\nAt the top of the page, click the Browse Filtered button to view restaurants in Queens that have `\"Moon\"` in their name:\n\n#### View real-time data changes\n\nYou can explore Meteor's real-time data synchronization features by inserting a sample document and viewing the changes in your application's front end.\n\nOpen a second terminal window and navigate to your project directory. Export your MongoDB connection URI by running the same command as shown in a previous step:\n\n```bash\nexport MONGO_URL=\"\"\n```\n\nThen, run the following command to insert a sample document that has a `name` value of `\"Honey Moon Coffee Shop\"`:\n\n```bash\nnode scripts/insertDemo.js\n```\n\nYou can see the new document in the Filtered Restaurants table at the http://localhost:3000/browse URL.\n\nCongratulations on completing the Quick Start tutorial!\n\nAfter you complete these steps, you have a Meteor and Vue web application that connects to your MongoDB deployment, runs queries on sample restaurant data, and renders the results with real-time reactivity."} -{"chunk_id": "695dfad9e50b91a6be6e4d2b-3", "page_id": "695dfad9e50b91a6be6e4d2b", "source_name": "drivers", "product_name": "MongoDB Drivers", "url": "https://mongodb.com/docs/drivers/node-frameworks/meteor-vue", "title": "Integrate MongoDB with Meteor and Vue", "text": "## Additional Resources\n\nTo learn more about Meteor, Vue, and MongoDB, view the following resources:\n\n- Meteor documentation\n\n- Vue 3 documentation\n\n- vue-meteor-tracker package\n\n- Node.js driver documentation"} -{"chunk_id": "6996ab7d1435ec531ea17f15-0", "page_id": "6996ab7d1435ec531ea17f15", "source_name": "drivers", "product_name": "MongoDB Drivers", "url": "https://mongodb.com/docs/drivers/node-frameworks/nuxt-vue", "title": "Integrate MongoDB with Nuxt and Vue", "text": "# Integrate MongoDB with Nuxt and Vue\n\n## Overview\n\nThis tutorial guides you through building a Nuxt application that uses Vue and integrates with MongoDB. Nuxt is a Vue framework that provides file-based routing, server-side rendering, and built-in API routes through its Nitro server engine. Nuxt combined with Vue allows you to build complete applications without a separate back-end server.\n\nThe application in this tutorial contains the following layers:\n\n- **Database layer**: MongoDB provides data storage and retrieval\n\n- **Server layer**: Nuxt server routes handle API logic and database interactions\n\n- **Presentation layer**: Vue implements the user interface with reactive data binding\n\n### Why Use MongoDB with Nuxt and Vue?\n\nNuxt builds on Vue to provide a full-stack framework with a Node.js runtime for server routes, making it a natural fit for the MongoDB Node.js driver. You can connect to MongoDB directly from your Nuxt server routes or server-side utilities and return documents to your Vue components without maintaining a separate back-end service or API layer.\n\nMongoDB's flexible document structure maps easily to JavaScript objects. As a result, you can work seamlessly with MongoDB data in your Vue components, whether you are using the Options API or the Composition API. The documents you fetch from MongoDB can be passed straight into your components and templates, reducing the need for complex data transformation or an additional object-relational mapping (ORM) layer.\n\nNuxt's server-side rendering (SSR) and data-fetching utilities let you query MongoDB on the server before rendering pages. This lets you hydrate your Vue components with ready-to-use data, improving perceived performance and SEO for data-driven applications.\n\n## Quick Start Tutorial\n\nThis tutorial shows you how to build a web application by using Nuxt and Vue. The application accesses sample restaurant data, queries the data, and displays the results on a locally hosted site. The tutorial also includes instructions on connecting to a MongoDB cluster hosted on MongoDB Atlas and accessing and displaying data from your database.\n\nIf you prefer to connect to MongoDB by using the Node.js driver without Nuxt, see the Get Started with the Node.js Driver guide.\n\n### Set Up Your Project\n\nFollow the steps in this section to install the project dependencies, create an Atlas cluster, and set up the application directories.\n\n#### Verify the prerequisites\n\nTo create the Quick Start application, install the following software in your development environment:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nPrerequisite\n\n\nNotes\n\n
\nNode.js\n\n\nUse version 20 or later.\n\n
\nCode editor\n\n\nThis tutorial uses Visual Studio Code, but you can use the editor of your choice.\n\n
\nTerminal app and shell\n\n\nFor macOS or Linux users, use Terminal or a similar app. For Windows users, use PowerShell.\n\n
\n\n#### Create a MongoDB Atlas cluster\n\nMongoDB Atlas is a fully managed cloud database service that hosts your MongoDB deployments. If you do not have a MongoDB deployment, you can create a MongoDB cluster for free (no credit card required) by completing the MongoDB Get Started tutorial.\n\nEnsure that the `sample_restaurants` dataset is loaded into your cluster. This tutorial queries data from that dataset. To learn how to load the `sample_restaurants` dataset into your cluster, see the MongoDB Get Started tutorial.\n\nTo connect to your MongoDB cluster, you must use a **connection URI**. To learn how to retrieve your connection URI, see the Add your connection string section of the MongoDB Get Started tutorial.\n\nSave your MongoDB Atlas connection string in a secure location. You will add it to your `.env` file in a later step.\n\n#### Install Nuxt and Vue\n\nUse the official Nuxt CLI to initialize a new Nuxt project with Vue. Open your terminal and navigate to your desired project directory.\n\nRun the initialization command:\n\n```bash\nnpm create nuxt@latest\n```\n\n##### Configuration Prompts\n\nThe CLI prompts you to configure your project. Use the following responses:\n\n1. **Prompt:** Need to install the following packages: create-nuxt@latest-number. Ok to proceed?\n\n **Response:** Type `y` and press Enter.\n\n2. **Prompt:** Which template would you like to use?\n\n **Response:** Select `minimal - Minimal setup for Nuxt 4 (recommended)`.\n\n3. **Prompt:** Where would you like to create your project?\n\n **Response:** Press `Enter` to accept the default directory or type a different path.\n\n4. **Prompt:** Which package manager would you like to use?\n\n **Response:** Select `npm`.\n\n5. **Prompt:** Initialize git repository?\n\n **Response:** Select `Yes` or `No` based on your preference.\n\n6. **Prompt:** Would you like to install any of the official modules?\n\n **Response:** Select `No`.\n\n#### Install dependencies\n\nNavigate to your project directory and install the MongoDB driver, Lucide icons, Tailwind, and related dependencies by running the following commands:\n\n```bash\nnpm install mongodb lucide-vue-next\nnpm install -D @types/node @nuxtjs/tailwindcss\n```\n\nYou can safely ignore any warnings about deprecated packages from the Tailwind installation."} -{"chunk_id": "6996ab7d1435ec531ea17f15-1", "page_id": "6996ab7d1435ec531ea17f15", "source_name": "drivers", "product_name": "MongoDB Drivers", "url": "https://mongodb.com/docs/drivers/node-frameworks/nuxt-vue", "title": "Integrate MongoDB with Nuxt and Vue", "text": "### Configure the Back End\n\nAfter setting up the project structure, follow the steps in this section to set up the back end.\n\n#### Configure your environment variable\n\nCreate a `.env` file at the root of your project to securely store your connection URI by running the following command in your project root:\n\n```bash\ntouch .env\n```\n\nOpen the `.env` file and add your connection URI:\n\n```bash\nMONGODB_URI=\n```\n\nReplace `` with the connection URI you received from MongoDB Atlas.\n\n#### Update your Nuxt configuration\n\nOpen the `nuxt.config.ts` file in your project root and replace its contents with the following code to load environment variables and configure the Tailwind CSS module:\n\n```typescript\n// https://nuxt.com/docs/api/configuration/nuxt-config\nexport default defineNuxtConfig({\n compatibilityDate: '2025-07-15',\n devtools: { enabled: true },\n\n future:{\n compatibilityVersion: 4,\n },\n\n runtimeConfig:{\n // Server-side only config. Not exposed to the client\n mongoURI: process.env.MONGODB_URI,\n },\n\n css:['@/assets/css/main.css'],\n modules: ['@nuxtjs/tailwindcss'],\n})\n```\n\nThe `nuxt.config.ts` file loads environment variables from the `.env` file and configures Tailwind support for styling your Vue components.\n\n#### Create a database connection\n\nRun the following commands in your project root to create a utility file to hold the MongoDB connection logic:\n\n```bash\nmkdir -p server/utils\ntouch server/utils/mongodb.ts\n```\n\nOpen the `server/utils/mongodb.ts` file and add the following code:\n\n```typescript\nimport { MongoClient, type Db } from \"mongodb\";\n\nlet cachedClient: MongoClient | null = null;\nlet cachedDb: Db | null = null;\n\nexport async function connectToDatabase(){\n if (cachedClient && cachedDb){\n return { client: cachedClient, db: cachedDb };\n }\n\nconst config = useRuntimeConfig();\nconst uri = config.mongoURI;\n\nif (!uri){\n throw new Error(\"Please define the MONGO_URI environment variable inside .env\");\n}\n\nconst client = new MongoClient(uri);\nawait client.connect();\n\nconst db = client.db(\"sample_restaurants\");\ncachedClient = client;\ncachedDb = db;\n\nconsole.log(\"Connected to MongoDB Atlas\");\n\nreturn { client, db };\n}\n```\n\nThis code creates a reusable MongoDB client that connects to your Atlas cluster by using the connection URI stored in your environment variable. The client connects to the `sample_restaurants` database, which contains information about restaurants around New York City.\n\n#### Create restaurant route\n\nNuxt server routes handle API requests and interact with the database. Run the following commands in your project root to create a server route for fetching restaurant data:\n\n```bash\nmkdir -p server/api/restaurants\ntouch server/api/restaurants/index.get.ts\n```\n\nOpen the `server/api/restaurants/index.get.ts` file and add the following code:\n\n```typescript\nimport { connectToDatabase } from \"~~/server/utils/mongodb\";\n\nexport default defineEventHandler(async () =>{\n const { db } = await connectToDatabase();\n const collection = db.collection(\"restaurants\");\n\n const restaurants = await collection\n .find({})\n .limit(50)\n .project({ name: 1, borough: 1, cuisine: 1, grades: 1})\n .toArray();\n\n return restaurants.map((doc) => ({\n ...doc,\n _id: doc._id.toString(),\n }))\n})\n```\n\nThis file defines a server route that queries the `restaurants` collection. It retrieves the first 50 restaurant documents and returns them as a JSON response.\n\n#### Create filtered restaurant route\n\nRun the following command in your project root to create the new route file:\n\n```bash\ntouch server/api/restaurants/browse.get.ts\n```\n\nOpen the `server/api/restaurants/browse.get.ts` file and add the following code:\n\n```typescript\nimport { connectToDatabase } from '~~/server/utils/mongodb'\n\nexport default defineEventHandler(async () => {\n const { db } = await connectToDatabase();\n const collection = db.collection(\"restaurants\");\n // Filter: Queens borough + name contains \"Moon\" (case-insensitive)\n const query = {\n borough: 'Queens',\n name: { $regex: 'Moon', $options: 'i' },\n }\n\n const restaurants = await collection\n .find(query)\n .project({ name: 1, borough: 1, cuisine: 1, grades: 1 })\n .toArray()\n\n return restaurants.map((doc) => ({\n ...doc,\n _id: doc._id.toString(),\n }))\n})\n\n```\n\nThis file defines a server route that queries the `sample_restaurants` database for restaurants in `Queens` whose names contain the word `Moon` and returns the matching documents as a JSON response."} -{"chunk_id": "6996ab7d1435ec531ea17f15-2", "page_id": "6996ab7d1435ec531ea17f15", "source_name": "drivers", "product_name": "MongoDB Drivers", "url": "https://mongodb.com/docs/drivers/node-frameworks/nuxt-vue", "title": "Integrate MongoDB with Nuxt and Vue", "text": "### Configure the Front End\n\nAfter setting up the back end, follow the steps in this section to set up the presentation layer for your application.\n\n#### Create a main.css file\n\nRun the following command in your project root to create a main CSS file for global styles:\n\n```bash\nmkdir -p app/assets/css\ntouch app/assets/css/main.css\n```\n\nOpen the `app/assets/css/main.css` file and add the following code:\n\n```css\n@tailwind base;\n@tailwind components;\n@tailwind utilities;\n```\n\nThis file imports Tailwind CSS directives that generate utility classes for styling your application. Tailwind provides a comprehensive set of pre-built classes for layout, spacing, colors, and typography without requiring custom CSS.\n\n#### Create restaurant list component\n\nRun the following commands in your project root to create a Vue component for displaying restaurant data:\n\n```bash\nmkdir -p app/components\ntouch app/components/RestaurantList.vue\n```\n\nOpen the `app/components/RestaurantList.vue` file and add the following code:\n\n```vue\n\n\n\n```\n\nThis Vue component fetches restaurant data from your Nuxt server route and displays it in a responsive grid layout. It dynamically adapts the API endpoint and page content based on the current route, showing either all restaurants or filtered results.\n\n#### Create the navbar component\n\nRun the following command in your project root to create a Vue component for the navigation bar:\n\n```bash\ntouch app/components/Navbar.vue\n```\n\nOpen the `app/components/Navbar.vue` file and add the following code:\n\n```vue\n\n```\n\nThis Vue component renders the navbar above the restaurant results, and contains the All Restaurants and Filtered Restaurants links. These allow you to navigate between the routes.\n\n#### Create the index page\n\nRun the following command in your project root to create an index page for the application:\n\n```bash\nmkdir -p app/pages\ntouch app/pages/index.vue\n```\n\nOpen the `app/pages/index.vue` file and add the following code:\n\n```vue\n\n```\n\nThis file displays the results from the `index.get.ts` server route by using the `RestaurantList` and `Navbar` components.\n\n#### Create the filtered restaurants page\n\nRun the following command in your project root to create a new Vue page for displaying filtered restaurant data:\n\n```bash\ntouch app/pages/browse.vue\n```\n\nOpen the `app/pages/browse.vue` file and add the following code:\n\n```vue\n\n```\n\nThis file displays the results of a filtered query on the `sample_restaurants` database that returns all restaurants in `Queens` with names that contain the word `Moon`. It also uses the `RestaurantList` and `Navbar` components to construct the page.\n\n#### Update the app.vue file\n\nOpen the `app/App.vue` file and replace its contents with the following code to connect the components:\n\n```vue\n\n```\n\n#### Verify your file structure"} -{"chunk_id": "6996ab7d1435ec531ea17f15-3", "page_id": "6996ab7d1435ec531ea17f15", "source_name": "drivers", "product_name": "MongoDB Drivers", "url": "https://mongodb.com/docs/drivers/node-frameworks/nuxt-vue", "title": "Integrate MongoDB with Nuxt and Vue", "text": "Before continuing, ensure your file tree closely matches the structure below. You can safely ignore any additional project files.\n\n```text\nyour-project-directory/\n\u251c\u2500\u2500 .env <-- Environment variable file\n\u251c\u2500\u2500 app/\n\u2502 \u251c\u2500\u2500 app.vue <-- Main application component\n\u2502 \u251c\u2500\u2500 assets/\n\u2502 \u2502 \u2514\u2500\u2500 css/\n\u2502 \u2502 \u2514\u2500\u2500 main.css <-- Tailwind config\n\u2502 \u251c\u2500\u2500 components/\n\u2502 \u2502 \u251c\u2500\u2500 Navbar.vue <-- All restaurants and filtered restaurants links\n\u2502 \u2502 \u2514\u2500\u2500 RestaurantList.vue <-- Container for restaurant data\n\u2502 \u2514\u2500\u2500 pages/\n\u2502 \u251c\u2500\u2500 browse.vue <-- Filtered restaurants page\n\u2502 \u2514\u2500\u2500 index.vue <-- All restaurants page\n\u251c\u2500\u2500 server/\n\u2502 \u251c\u2500\u2500 api/\n\u2502 \u2502 \u2514\u2500\u2500 restaurants/\n\u2502 \u2502 \u251c\u2500\u2500 browse.get.ts <-- Filtered restaurants route\n\u2502 \u2502 \u2514\u2500\u2500 index.get.ts <-- All restaurants route\n\u2502 \u2514\u2500\u2500 utils/\n\u2502 \u2514\u2500\u2500 mongodb.ts <-- MongoDB connection utility\n\u251c\u2500\u2500 nuxt.config.ts <-- Nuxt configuration file\n\u2514\u2500\u2500 package.json\n```\n\n### Run Your Application\n\nPerform the following steps to start the server and view the rendered restaurant data.\n\n#### Start the server\n\nRun the following command in your project root to start the development server:\n\n```bash\nnpm run dev\n```\n\nIf successful, the command outputs the following information in the terminal:\n\n```text\nNuxt 4.2.2 (with Nitro 2.13.1, Vite 7.3.1 and Vue 3.5.27)\n\nLocal: http://localhost:3000/\nNetwork: use --host to expose\n\nUsing default Tailwind CSS file\nDevTools: press Shift + Option + D in the browser (v3.1.1)\n\nVite client built in 22ms\nVite server built in 19ms\nNuxt Nitro server built in 247ms\nVite server warmed up in 0ms\nVite client warmed up in 1ms\nConnected to MongoDB Atlas\n```\n\n#### View the application\n\nOpen `http://localhost:3000/` in your browser. The initial landing page displays the first 50 restaurants in the `sample_restaurants` database.\n\n#### View the filtered results\n\nClick the Filtered Restaurants link in the navigation bar to view the filtered restaurant results. The page displays all restaurants in `Queens` with names that contain the word `Moon`.\n\nCongratulations on completing the Quick Start tutorial!\n\nAfter you complete these steps, you have a Nuxt and Vue application that connects to your MongoDB deployment, runs queries on sample restaurant data, and renders the results in your browser.\n\n## Additional Resources\n\nTo learn more about using MongoDB, Nuxt, and Vue, view the following resources:\n\n- Nuxt documentation\n\n- Vue documentation\n\n- Node.js driver documentation"} -{"chunk_id": "69955a228215a63d4ee0ee05-0", "page_id": "69955a228215a63d4ee0ee05", "source_name": "drivers", "product_name": "MongoDB Drivers", "url": "https://mongodb.com/docs/drivers/csharp-frameworks/ef-odata", "title": "Integrate MongoDB with Entity Framework and ASP.NET Core", "text": "# Integrate MongoDB with Entity Framework and ASP.NET Core\n\n## Overview\n\nIn this guide, you can learn how to create a **ASP.NET Core** application that offers **OData** endpoints and uses the **Entity Framework (EF) Core Provider** to access MongoDB. ASP.NET Core is a cross-platform framework for creating cloud-based applications. OData is a standardized protocol for building and consuming RESTful APIs, and it allows you to interact with data by using HTTP requests.\n\nThe application in this tutorial consists of the following layers:\n\n- **Database layer**: MongoDB provides data storage and retrieval.\n\n- **Application layer**: ASP.NET Core handles HTTP requests, routing, and dependency injection.\n\n- **Data access layer**: The EF Core Provider provides MongoDB document mapping and OData query translation.\n\n### Why Use MongoDB with ASP.NET Core and OData?\n\nThis tutorial uses the ASP.NET Core OData framework with the Entity Framework (EF) Core Provider for MongoDB to create queryable REST APIs. OData provides a uniform way to expose and interact with data and provides advanced querying capabilities such as filtering, sorting, paging, and field selection.\n\nBy integrating MongoDB with ASP.NET Core and OData, you can use EF's familiar patterns alongside MongoDB's flexible document model and OData's query capabilities. This combination supports applications that require complex query interfaces, type safety, and standards-based API design. You can use MongoDB, ASP.NET Core, and OData to create real world applications such as data analytics dashboards, reporting systems, or any application that requires complex data querying.\n\n## Quick Start Tutorial\n\nThis tutorial shows you how to build an OData REST API that uses MongoDB, ASP.NET Core, and the EF Core Provider. The application accesses sample restaurant data, exposes OData-compliant endpoints, and supports advanced querying capabilities such as filtering, sorting, paging, and field selection. The tutorial also includes instructions for connecting to a MongoDB cluster hosted on MongoDB Atlas.\n\nIf you prefer to connect to MongoDB by using the EF Core Provider without ASP.NET Core, see the Entity Framework Provider Quick Start tutorial.\n\n### Set Up Your Project\n\nFollow the steps in this section to install the project dependencies, create an Atlas cluster, and set up the application structure.\n\n#### Verify the prerequisites.\n\nTo create the Quick Start application, install the following software in your development environment:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nPrerequisite\n\n\nNotes\n\n
\n.NET SDK\n\n\nInstall .NET 8.0 or later.\n\n
\nCode editor\n\n\nUse the code editor of your choice.\n\n
\nTerminal app and shell\n\n\nFor Windows users, use PowerShell or Command Prompt. For macOS/Linux users, use Terminal or a similar app.\n\n
\n\n#### Create a MongoDB Atlas cluster.\n\nMongoDB Atlas is a fully managed cloud database service that hosts your MongoDB deployments. If you do not have a MongoDB deployment, you can create a MongoDB cluster for free by completing the MongoDB Get Started tutorial. The MongoDB Get Started tutorial also demonstrates how to load sample datasets into your cluster, including the `sample_restaurants` database that is used in this tutorial.\n\nTo connect to your MongoDB cluster, you must use a **connection string**. To learn how to retrieve your connection string, see the Add your connection string section of the MongoDB Get Started tutorial.\n\nSave your connection string in a secure location.\n\n#### Create your ASP.NET Core project.\n\nFrom your terminal, run the following commands to create a new ASP.NET Core Web API project named `RestaurantODataApi`:\n\n```bash\ndotnet new webapi -n RestaurantODataApi\ncd RestaurantODataApi\n```\n\n#### Add the required dependencies.\n\nIn your `RestaurantODataApi` directory, run the following commands to add the required NuGet packages:\n\n```bash\ndotnet add package MongoDB.EntityFrameworkCore\ndotnet add package Microsoft.AspNetCore.OData\n```\n\nThese commands install the following packages:\n\n- `MongoDB.EntityFrameworkCore`: The MongoDB EF Core Provider\n\n- `Microsoft.AspNetCore.OData`: OData support for ASP.NET Core\n\n#### Configure your database connection.\n\nNavigate to the `appsettings.json` file in your `RestaurantODataApi` project and paste the following code:\n\n```json\n{\n \"Logging\": {\n \"LogLevel\": {\n \"Default\": \"Information\",\n \"Microsoft.AspNetCore\": \"Warning\"\n }\n },\n \"AllowedHosts\": \"*\",\n \"MongoDB\": {\n \"ConnectionString\": \"\",\n \"DatabaseName\": \"sample_restaurants\"\n }\n}\n```\n\nReplace the `` placeholder with the connection string that you saved from the MongoDB Get Started tutorial."} -{"chunk_id": "69955a228215a63d4ee0ee05-1", "page_id": "69955a228215a63d4ee0ee05", "source_name": "drivers", "product_name": "MongoDB Drivers", "url": "https://mongodb.com/docs/drivers/csharp-frameworks/ef-odata", "title": "Integrate MongoDB with Entity Framework and ASP.NET Core", "text": "### Create Your Application\n\nAfter setting up the project structure and dependencies, follow the steps in this section to create your data models, `DbContext`, and OData endpoints.\n\n#### Create the data models.\n\nIn your `RestaurantODataApi` directory, create a `Models` subdirectory. Then, create a file named `Restaurant.cs` in the `Models` directory and add the following code:\n\n```csharp\nusing Microsoft.EntityFrameworkCore;\nusing MongoDB.Bson;\nusing MongoDB.Bson.Serialization.Attributes;\nusing System.ComponentModel.DataAnnotations;\n\nnamespace RestaurantODataApi.Models\n{\n public class Restaurant\n {\n [Key]\n [BsonId]\n [BsonRepresentation(BsonType.ObjectId)]\n public string Id { get; set; } = string.Empty;\n\n [BsonElement(\"name\")]\n public string? Name { get; set; }\n\n [BsonElement(\"cuisine\")]\n public string? Cuisine { get; set; }\n\n [BsonElement(\"borough\")]\n public string? Borough { get; set; }\n }\n}\n```\n\nThis model class defines the structure of restaurant data from the MongoDB `sample_restaurants.restaurants` collection and includes the Entity Framework and MongoDB serialization attributes.\n\n#### Configure your database connection.\n\nIn your `RestaurantODataApi` directory, create a file named `RestaurantDbContext.cs` and add the following code:\n\n```csharp\nusing Microsoft.EntityFrameworkCore;\nusing MongoDB.Driver;\nusing MongoDB.EntityFrameworkCore.Extensions;\nusing RestaurantODataApi.Models;\n\nnamespace RestaurantODataApi\n{\n public class RestaurantDbContext : DbContext\n {\n public DbSet Restaurants { get; set; }\n\n public RestaurantDbContext(DbContextOptions options)\n : base(options)\n {\n }\n\n protected override void OnModelCreating(ModelBuilder modelBuilder)\n {\n base.OnModelCreating(modelBuilder);\n\n // Configures the Restaurant entity to map to the \"restaurants\" collection\n modelBuilder.Entity().ToCollection(\"restaurants\");\n }\n }\n}\n```\n\nThis class derives from DBContext, which configures the relationship between your models and the underlying database. The code configures EF to work with MongoDB and maps the `Restaurant` entity to the `sample_restaurants.restaurants` collection.\n\n#### Create the OData controller.\n\nIn your `RestaurantODataApi` directory, create a `Controllers` subdirectory. Then, add a file named `RestaurantsController.cs` to the subdirectory and paste the following code:\n\n```csharp\nusing Microsoft.AspNetCore.Mvc;\nusing Microsoft.AspNetCore.OData.Query;\nusing Microsoft.AspNetCore.OData.Routing.Controllers;\nusing Microsoft.AspNetCore.OData.Routing.Attributes;\nusing RestaurantODataApi.Models;\n\nnamespace RestaurantODataApi.Controllers\n{\n public class RestaurantsController : ODataController\n {\n private readonly RestaurantDbContext _context;\n\n public RestaurantsController(RestaurantDbContext context)\n {\n _context = context;\n }\n\n [EnableQuery(PageSize = 50, AllowedQueryOptions = AllowedQueryOptions.All)]\n public IQueryable Get()\n {\n return _context.Restaurants;\n }\n\n [HttpGet(\"odata/GetRestaurantsByBorough(borough={borough})\")]\n [EnableQuery(PageSize = 20)]\n public IQueryable GetRestaurantsByBorough(string borough)\n {\n return _context.Restaurants.Where(r => r.Borough == borough);\n }\n\n [HttpGet(\"odata/GetRestaurantsByCuisine(cuisine={cuisine})\")]\n [EnableQuery(PageSize = 20)]\n public IQueryable GetRestaurantsByCuisine(string cuisine)\n {\n return _context.Restaurants.Where(r => r.Cuisine == cuisine);\n }\n }\n}\n```\n\nThis controller defines the following OData REST endpoints:\n\n- `GET /odata/Restaurants`: Retrieves all documents in the `restaurants` collection. The `EnableQuery` attribute and its configuration options allow you to use OData query parameters, such as `$filter` and `$orderby`, in your HTTP requests.\n\n- `GET /odata/GetRestaurantsByBorough(borough='{borough}')`: Retrieves documents that have the specified `borough` value.\n\n- `GET /odata/GetRestaurantsByCuisine(cuisine='{cuisine}')`: Retrieves documents that have the specified `cuisine` value.\n\n#### Define the application logic.\n\nNavigate to the `Program.cs` file and replace its contents with the following code:\n\n```csharp\nusing Microsoft.AspNetCore.OData;\nusing Microsoft.EntityFrameworkCore;\nusing Microsoft.OData.ModelBuilder;\nusing MongoDB.Driver;\nusing RestaurantODataApi;\nusing RestaurantODataApi.Models;\n\nvar builder = WebApplication.CreateBuilder(args);\n\n// Configures the MongoDB connection\nvar connectionString = builder.Configuration[\"MongoDB:ConnectionString\"];\nvar databaseName = builder.Configuration[\"MongoDB:DatabaseName\"] ?? \"sample_restaurants\";\n\nif (string.IsNullOrEmpty(connectionString))\n{\n throw new InvalidOperationException(\"MongoDB connection string is required. Please set MongoDB:ConnectionString in appsettings.json\");\n}\n\n// Registers a MongoDB client\nbuilder.Services.AddSingleton(sp => new MongoClient(connectionString));\n\n// Registers the DbContext\nbuilder.Services.AddDbContext(options =>\n{\n var mongoClient = new MongoClient(connectionString);\n options.UseMongoDB(mongoClient, databaseName);\n});\n\n// Configures the OData EDM model\nvar modelBuilder = new ODataConventionModelBuilder();\nmodelBuilder.EntitySet(\"Restaurants\");\nmodelBuilder.EntityType().HasKey(r => r.Id);\n\n// Registers the unbound functions\nvar getRestaurantsByBoroughFunction = modelBuilder.Function(\"GetRestaurantsByBorough\");\ngetRestaurantsByBoroughFunction.Parameter(\"borough\");\ngetRestaurantsByBoroughFunction.ReturnsCollectionFromEntitySet(\"Restaurants\");\n\nvar getRestaurantsByCuisineFunction = modelBuilder.Function(\"GetRestaurantsByCuisine\");\ngetRestaurantsByCuisineFunction.Parameter(\"cuisine\");\ngetRestaurantsByCuisineFunction.ReturnsCollectionFromEntitySet(\"Restaurants\");\n\n// Configures OData with ASP.NET Core\nbuilder.Services.AddControllers()\n .AddOData(opt => opt\n .AddRouteComponents(\"odata\", modelBuilder.GetEdmModel())\n .Select()\n .Filter()\n .OrderBy()\n .Expand()\n .Count()\n .SetMaxTop(100));\n\nvar app = builder.Build();\n\napp.UseRouting();\napp.MapControllers();\n\napp.Run();\n```\n\nThis code sets up the MongoDB connection, Entity Framework `DbContext`, and OData services. The OData configuration code enables the following query parameters, which you can use in your HTTP endpoints:\n\n- `$select`: Return the specified fields in the results\n\n- `$filter`: Return data based on filter criteria\n\n- `$orderby`: Sort the results by a specified field\n\n- `$expand`: Include related data in the results\n\n- `$count`: Include a count of the results\n\n- `$top`: Set the maximum number of results, limited to `100`"} -{"chunk_id": "69955a228215a63d4ee0ee05-2", "page_id": "69955a228215a63d4ee0ee05", "source_name": "drivers", "product_name": "MongoDB Drivers", "url": "https://mongodb.com/docs/drivers/csharp-frameworks/ef-odata", "title": "Integrate MongoDB with Entity Framework and ASP.NET Core", "text": "### Run Your Application\n\nFinally, follow the steps in this section to run your OData REST API and test the endpoints by using HTTP requests.\n\n#### Start the ASP.NET Core application.\n\nFrom your `RestaurantODataApi` directory, run the following command to compile and start the application:\n\n```bash\ndotnet run\n```\n\nIf successful, your command output resembles the following example:\n\n```bash\ninfo: Microsoft.Hosting.Lifetime[14]\n Now listening on: http://localhost:5236\ninfo: Microsoft.Hosting.Lifetime[0]\n Application started. Press Ctrl+C to shut down.\n```\n\n#### Test your OData endpoints.\n\nIn a separate terminal, run the following `curl` commands to test the OData endpoints. Each endpoint returns JSON data in OData format that includes restaurant information from the `sample_restaurants.restaurants` collection. If successful, your `curl` commands return data similar to the sample outputs provided. The commands also limit the results to 5 documents.\n\n- Retrieve all restaurants.\n\n ```bash\n curl 'http://localhost:5236/odata/Restaurants?$top=5'\n ```\n\n ```\n {\"@odata.context\":\"http://localhost:5236/odata/$metadata#Restaurants\",\n \"value\":[\n {\"Id\":\"...\",\"Name\":\"Riviera Caterer\",\"Cuisine\":\n \"American\",\"Borough\":\"Brooklyn\",\"RestaurantId\":\"40356018\"},\n {\"Id\":\"...\",\"Name\":\"Wilken'S Fine Food\",\"Cuisine\":\n \"Delicatessen\",\"Borough\":\"Brooklyn\",\"RestaurantId\":\"40356483\"},\n {\"Id\":\"...\",\"Name\":\"Kosher Island\",\"Cuisine\":\n \"Jewish/Kosher\",\"Borough\":\"Staten Island\",\"RestaurantId\":\"40356442\"},\n {\"Id\":\"...\",\"Name\":\"Wendy'S\",\"Cuisine\":\"Hamburgers\",\n \"Borough\":\"Brooklyn\",\"RestaurantId\":\"30112340\"},\n {\"Id\":\"...\",\"Name\":\"Morris Park Bake Shop\",\"Cuisine\":\n \"Bakery\",\"Borough\":\"Bronx\",\"RestaurantId\":\"30075445\"}\n ]}\n ```\n\n- Filter restaurants by borough.\n\n The following command retrieves restaurants that have a `borough` value of `\"Queens\"`:\n\n ```bash\n curl 'http://localhost:5236/odata/GetRestaurantsByBorough(borough=%27Queens%27)?$top=5'\n ```\n\n ```\n {\"@odata.context\":\"http://localhost:5236/odata/$metadata#Restaurants\",\n \"value\":[\n {\"Id\":\"...\",\"Name\":\"Tov Kosher Kitchen\",\"Cuisine\":\"Jewish/Kosher\",\n \"Borough\":\"Queens\",\"RestaurantId\":\"40356068\"},\n {\"Id\":\"...\",\"Name\":\"Brunos On The Boulevard\",\"Cuisine\":\"American\",\n \"Borough\":\"Queens\",\"RestaurantId\":\"40356151\"},\n {\"Id\":\"...\",\"Name\":\"Carvel Ice Cream\",\"Cuisine\":\"Ice Cream, Gelato, Yogurt, Ices\",\n \"Borough\":\"Queens\",\"RestaurantId\":\"40361322\"},\n {\"Id\":\"...\",\"Name\":\"Sal'S Deli\",\"Cuisine\":\"Delicatessen\",\n \"Borough\":\"Queens\",\"RestaurantId\":\"40361618\"},\n {\"Id\":\"...\",\"Name\":\"Steve Chu'S Deli & Grocery\",\"Cuisine\":\"Delicatessen\",\n \"Borough\":\"Queens\",\"RestaurantId\":\"40361998\"}\n ]}\n ```\n\n- Filter restaurants by cuisine.\n\n The following command retrieves restaurants that have a `cuisine` value of `\"Mexican\"`:\n\n ```bash\n curl 'http://localhost:5236/odata/GetRestaurantsByCuisine(cuisine=%27Mexican%27)?$top=5'\n ```\n\n ```\n {\"@odata.context\":\"http://localhost:5236/odata/$metadata#Restaurants\",\n \"value\":[\n {\"Id\":\"...\",\"Name\":\"Panchito'S\",\"Cuisine\":\"Mexican\",\"Borough\":\"Manhattan\"},\n {\"Id\":\"...\",\"Name\":\"Mexico Lindo Restaurant\",\"Cuisine\":\"Mexican\",\"Borough\":\"Manhattan\"},\n {\"Id\":\"...\",\"Name\":\"Casa Pepe\",\"Cuisine\":\"Mexican\",\"Borough\":\"Brooklyn\"},\n {\"Id\":\"...\",\"Name\":\"Cuchifrito\",\"Cuisine\":\"Mexican\",\"Borough\":\"Manhattan\"},\n {\"Id\":\"...\",\"Name\":\"Mary Ann'S\",\"Cuisine\":\"Mexican\",\"Borough\":\"Manhattan\"}\n ]}\n ```\n\n#### Test OData's advanced query capabilities.\n\nYou can use the endpoints to run complex queries by including OData query parameters and operators. The following `curl` commands test these capabilities.\n\n- Filter by multiple fields.\n\n The following command uses OData query operators to retrieve documents that have a `borough` value of `\"Queens\"` and a `name` value that contains `\"Moon\"`:\n\n ```bash\n curl 'http://localhost:5236/odata/Restaurants?$filter=Borough%20eq%20%27Queens%27%20and%20contains(Name,%20%27Moon%27)'\n ```\n\n ```\n {\"@odata.context\":\"http://localhost:5236/odata/$metadata#Restaurants\",\n \"value\":[\n {\"Id\":\"...\",\"Name\":\"New Moon Star Restaurant\",\"Cuisine\":\"Chinese\",\"Borough\":\"Queens\"},\n {\"Id\":\"...\",\"Name\":\"Moon Tikka Grill\",\"Cuisine\":\"Indian\",\"Borough\":\"Queens\"},\n {\"Id\":\"...\",\"Name\":\"Silver Moon Diner\",\"Cuisine\":\"American\",\"Borough\":\"Queens\"},\n {\"Id\":\"...\",\"Name\":\"Mooney'S Public House\",\"Cuisine\":\"Irish\",\"Borough\":\"Queens\"},\n {\"Id\":\"...\",\"Name\":\"Moon Light Crill Rest\",\"Cuisine\":\"Indian\",\"Borough\":\"Queens\"},\n {\"Id\":\"...\",\"Name\":\"Full Moon Cafe\",\"Cuisine\":\"Caf\u00e9/Coffee/Tea\",\"Borough\":\"Queens\"},\n {\"Id\":\"...\",\"Name\":\"Pacific Moon\",\"Cuisine\":\"Chinese\",\"Borough\":\"Queens\"},\n {\"Id\":\"...\",\"Name\":\"Moon Palace Kitchen\",\"Cuisine\":\"Chinese\",\"Borough\":\"Queens\"},\n {\"Id\":\"...\",\"Name\":\"Honey Moon Coffee Shop\",\"Cuisine\":\"Caf\u00e9/Coffee/Tea\",\"Borough\":\"Queens\"},\n {\"Id\":\"...\",\"Name\":\"Honey Moon Coffee Shop\",\"Cuisine\":\"Caf\u00e9/Coffee/Tea\",\"Borough\":\"Queens\"}\n ]}%\n ```\n\n- Order and count your results.\n\n The following command sorts documents that match the `cuisine` filter by their `name` value and counts the total number of matching documents:\n\n ```bash\n curl 'http://localhost:5236/odata/GetRestaurantsByCuisine(cuisine=%27Czech%27)?$orderby=Name&$count=true'\n ```\n\n ```\n {\"@odata.context\":\"http://localhost:5236/odata/$metadata#Restaurants\",\n \"@odata.count\":6,\n \"value\":[\n {\"Id\":\"...\",\"Name\":\"Bohemian Beer Garden\",\"Cuisine\":\"Czech\",\"Borough\":\"Queens\"},\n {\"Id\":\"...\",\"Name\":\"Brooklyn Beet Company\",\"Cuisine\":\"Czech\",\"Borough\":\"Brooklyn\"},\n {\"Id\":\"...\",\"Name\":\"Hospoda\",\"Cuisine\":\"Czech\",\"Borough\":\"Manhattan\"},\n {\"Id\":\"...\",\"Name\":\"Koliba Restaurant\",\"Cuisine\":\"Czech\",\"Borough\":\"Queens\"},\n {\"Id\":\"...\",\"Name\":\"Milan'S Restaurant\",\"Cuisine\":\"Czech\",\"Borough\":\"Brooklyn\"},\n {\"Id\":\"...\",\"Name\":\"Olde Prague Tavern\",\"Cuisine\":\"Czech\",\"Borough\":\"Queens\"}\n ]}\n ```\n\nCongratulations on completing the EF, ASP.NET, and OData Quick Start tutorial! After you complete these steps, you have an ASP.NET Core OData REST API that connects to your MongoDB deployment, returns restaurant data by using OData endpoints, and supports advanced query capabilities like filtering, sorting, paging, field selection, and searching.\n\n## Additional Resources\n\nTo learn more about the concepts mentioned in this tutorial, see the following resources:\n\n- ASP.NET Core OData documentation\n\n- OData Protocol documentation\n\n- MongoDB Entity Framework Core Provider documentation\n\n- MongoDB .NET/C# Driver documentation"} -{"chunk_id": "69a67d623328a617852a8e82-0", "page_id": "69a67d623328a617852a8e82", "source_name": "drivers", "product_name": "MongoDB Drivers", "url": "https://mongodb.com/docs/drivers/node-frameworks/next-integration", "title": "Integrate Next.js with MongoDB", "text": "# Integrate Next.js with MongoDB\n\n## Overview\n\nIn this guide, you can learn how to create a **Next.js** web application that integrates with MongoDB. Next.js is a React framework that provides server-side rendering, static site generation, and API routes in a single application. The application in this tutorial consists of the following layers:\n\n- **Database layer**: MongoDB provides data storage and retrieval.\n\n- **API layer**: Next.js API routes handle server-side logic and database operations.\n\n- **Presentation layer**: React components implement the user interface and front-end interactions.\n\n### Why Use MongoDB in a Next.js Application?\n\nNext.js is a full-stack React framework that enables you to build both the front end and back end of your application in a single codebase. By integrating MongoDB with Next.js, you can leverage the following benefits:\n\n- **Unified development**: Write both client and server code in JavaScript/TypeScript\n\n- **Server-side rendering**: Fetch data from MongoDB during server-side rendering for improved SEO and performance\n\n- **API routes**: Create serverless API endpoints that connect directly to MongoDB\n\n- **Flexible data model**: MongoDB's document model aligns naturally with JavaScript objects and React component state\n\nNext.js with MongoDB is well-suited for applications that require dynamic content, user authentication, real-time updates, and complex data relationships.\n\n## Quick Start Tutorial\n\nThis tutorial shows you how to build a web application by using Next.js and MongoDB. The application accesses sample restaurant data, queries the data, and displays the results on a locally hosted site. The tutorial also includes instructions for connecting to a MongoDB cluster hosted on MongoDB Atlas and accessing and displaying data from your database.\n\nIf you prefer to connect to MongoDB by using the Node.js driver without Next.js, see the Get Started with the Node.js Driver guide.\n\n### Set Up Your Project\n\nFollow the steps in this section to install the project dependencies, create an Atlas cluster, and set up the application directories.\n\n#### Verify the prerequisites\n\nTo create the application, you need the following installed in your development environment:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nPrerequisite\n\n\nNotes\n\n
\nNode.js\n\n\nDownload either the **Latest LTS** or **Latest Release** version.\n\n
\nCode editor\n\n\nThis tutorial uses Visual Studio Code, but you can use the editor of your choice.\n\n
\nTerminal app or shell\n\n\nFor MacOS users, use Terminal or a similar app. For Windows users, use PowerShell.\n\n
\n\n#### Create a MongoDB Atlas cluster\n\nMongoDB Atlas is a fully managed cloud database service that hosts your MongoDB deployments. If you do not have a MongoDB deployment, you can create a MongoDB cluster for free (no credit card required) by completing the MongoDB Get Started tutorial. The MongoDB Get Started tutorial also demonstrates how to load sample datasets into your cluster, including the `sample_restaurants` database that is used in this tutorial.\n\nTo connect to your MongoDB cluster, you must use a **connection URI**. To learn how to retrieve your connection URI, see the Add your connection string section of the MongoDB Get Started tutorial.\n\nSave your connection string in a secure location.\n\n#### Create your Next.js application\n\nRun the following command in your terminal to create a new Next.js application.\n\n```bash\nnpx create-next-app@latest next-quickstart\n```\n\nThe command prompts you to select some configuration options for your project. When prompted, select the option to use the recommended defaults.\n\nAfter running the command, navigate to the project directory:\n\n```bash\ncd next-quickstart\n```\n\n#### Install the MongoDB driver\n\nRun the following command to install the MongoDB Node.js Driver:\n\n```bash\nnpm install mongodb\n```\n\nThis command installs the Node.js Driver, which allows your Next.js application to connect to and interact with MongoDB.\n\n### Configure the Database Connection\n\nAfter you set up the project structure and dependencies, follow the steps in this section to configure your database connection.\n\n#### Set environment variables\n\nIn the `next-quickstart` directory, create a `.env.local` file that stores your MongoDB connection URI:\n\n```none\nMONGODB_URI=\n```\n\nReplace the `` placeholder with the connection URI that you saved in a previous step.\n\nNext.js automatically loads environment variables from `.env.local` files. Variables prefixed with `NEXT_PUBLIC_` are exposed to the browser, while other variables are only available on the server.\n\n#### Create the database connection utility\n\nIn the root directory, create a new directory called `lib`. Add a new file named `mongodb.ts` to this directory and paste the following code:\n\n```ts\nimport { MongoClient } from \"mongodb\";\n\ndeclare global {\n var _mongoClientPromise: Promise | undefined;\n}\n\nconst uri = process.env.MONGODB_URI;\nconst options = {};\n\nlet client: MongoClient;\nlet clientPromise: Promise;\n\nif (!uri) {\n throw new Error(\"Please add your Mongo URI to .env.local\");\n}\n\nclient = new MongoClient(uri, options);\nclientPromise = client.connect();\n\n// Export a module-scoped MongoClient promise. By doing this in a\n// separate module, the client can be shared across functions.\nexport default clientPromise;\n\n```\n\nThis file creates a reusable MongoDB client connection that is shared across your application. The connection is cached to prevent creating multiple connections during development when Next.js hot-reloads your code.\n\n### Create API Routes\n\nAfter you set up the database connection, follow the steps in this section to create API routes that query MongoDB and return restaurant data.\n\n#### Create the restaurant API route\n\nIn the `app` directory, create a new `api/restaurants` directory. Add a new file named `route.ts` to this directory and paste the following code:\n\n```ts\nimport { NextResponse } from \"next/server\";\nimport clientPromise from \"@/lib/mongodb\";\n\nexport async function GET() {\n try {\n const client = await clientPromise;\n const db = client.db(\"sample_restaurants\");\n const restaurants = await db\n .collection(\"restaurants\")\n .find({})\n .toArray();\n\n return NextResponse.json(restaurants);\n } catch {\n return NextResponse.json(\n { error: \"Failed to fetch restaurants\" },\n { status: 500 }\n );\n }\n}\n\n```\n\nThis file defines a `GET` endpoint at `/api/restaurants` that retrieves all restaurants from the `sample_restaurants` database.\n\n#### Create the browse API route\n\nIn the `app/api` directory, create a new directory called `browse`. Create a new file named `route.ts` in this directory and paste the following code:\n\n```ts\nimport { NextResponse } from \"next/server\";\nimport clientPromise from \"@/lib/mongodb\";\n\nexport async function GET() {\n try {\n const client = await clientPromise;\n const db = client.db(\"sample_restaurants\");\n\n const query = {\n borough: \"Queens\",\n name: { $regex: \"Moon\", $options: \"i\" },\n };\n\n const restaurants = await db\n .collection(\"restaurants\")\n .find(query)\n .toArray();\n\n return NextResponse.json(restaurants);\n } catch {\n return NextResponse.json(\n { error: \"Failed to fetch restaurants\" },\n { status: 500 }\n );\n }\n}\n\n```\n\nThis file defines a `GET` endpoint at `/api/browse` that retrieves restaurants matching specific query criteria. The query filters for restaurants in Queens that contain the word `\"Moon\"` in the name."} -{"chunk_id": "69a67d623328a617852a8e82-1", "page_id": "69a67d623328a617852a8e82", "source_name": "drivers", "product_name": "MongoDB Drivers", "url": "https://mongodb.com/docs/drivers/node-frameworks/next-integration", "title": "Integrate Next.js with MongoDB", "text": "### Configure the Front End\n\nAfter you set up the API routes, follow the steps in this section to create the React components that display the restaurant data.\n\n#### Create the Navbar component\n\nIn the root directory, create a new directory called `components`. Add a new file named `Navbar.tsx` to this directory and paste the following code:\n\n```js\nimport Link from \"next/link\";\n\nexport default function Navbar() {\n return (\n \n );\n}\n\n```\n\nThis component creates a navigation bar with links to view all restaurants and filtered restaurants.\n\n#### Create the RestaurantList component\n\nIn the `components` directory, create a new file named `RestaurantList.tsx` and paste the following code:\n\n```js\n\"use client\";\n/* The above directive tells Next.js to render this component\n on the client side instead of the server side.\n Client components can use React hooks like useState\n and useEffect, while server components cannot.\n*/\n\nimport { useEffect, useState } from \"react\";\nimport { ObjectId } from \"mongodb\";\n\ninterface Restaurant {\n _id: ObjectId;\n name: string;\n borough: string;\n cuisine: string;\n}\n\ninterface RestaurantProps {\n restaurant: Restaurant;\n}\n\nconst Restaurant = (props: RestaurantProps) => (\n \n \n {props.restaurant.name}\n \n \n {props.restaurant.borough}\n \n \n {props.restaurant.cuisine}\n \n \n);\n\ninterface RestaurantListProps {\n endpoint: string;\n title: string;\n}\n\nexport default function RestaurantList({ endpoint, title }: RestaurantListProps) {\n const [restaurants, setRestaurants] = useState([]);\n const [loading, setLoading] = useState(true);\n\n useEffect(() => {\n async function getRestaurants() {\n try {\n const response = await fetch(endpoint);\n if (!response.ok) {\n const message = `An error occurred: ${response.statusText}`;\n console.error(message);\n return;\n }\n const restaurants = await response.json();\n setRestaurants(restaurants);\n } catch (error) {\n console.error(\"Error fetching restaurants:\", error);\n } finally {\n setLoading(false);\n }\n }\n getRestaurants();\n }, [endpoint]);\n\n function restaurantList() {\n return restaurants.map((restaurant) => {\n return ;\n });\n }\n\n if (loading) {\n return
Loading...
;\n }\n\n return (\n <>\n

{title}

\n
\n
\n \n \n \n \n \n \n \n \n \n {restaurantList()}\n \n
\n Name\n \n Borough\n \n Cuisine\n
\n
\n
\n \n );\n}\n\n```\n\nThis component fetches and displays restaurant data from the API routes. It uses React hooks to manage state and fetch data when the component mounts.\n\n#### Update the home page\n\nNavigate to the `app/page.tsx` file and replace the contents with the following code:\n\n```js\nimport RestaurantList from \"@/components/RestaurantList\";\n\nexport default function Home() {\n return (\n
\n \n
\n );\n}\n\n```\n\nThis file renders the home page, which displays all restaurants from the database.\n\n#### Create the browse page\n\nIn the `app` directory, create a new directory called `browse`. Add a new file named `page.tsx` to this directory and paste the following code:\n\n```js\nimport RestaurantList from \"@/components/RestaurantList\";\n\nexport default function Browse() {\n return (\n
\n \n
\n );\n}\n\n```\n\nThis file renders the browse page, which displays filtered restaurants based on the query criteria.\n\n#### Update the layout\n\nNavigate to the `app/layout.tsx` file and replace the contents with the following code:\n\n```js\nimport \"./globals.css\";\nimport Navbar from \"@/components/Navbar\";\nimport { Metadata } from \"next\";\n\nexport const metadata: Metadata = {\n title: \"MongoDB Next.js App\",\n description: \"A Next.js application with MongoDB integration\",\n};\n\nexport default function RootLayout({ children }: { children: React.ReactNode }) {\n return (\n \n \n \n {children}\n \n \n );\n}\n\n```\n\nThis file defines the root layout for your application, which includes the navigation bar and wraps all pages.\n\n### Run Your Application\n\nFinally, follow the steps in this section to run your application and view the rendered restaurant data.\n\n#### Start the development server\n\nNavigate to the `next-quickstart` directory and run the following command to start the Next.js development server:\n\n```bash\nnpm run dev\n```\n\nIf successful, this command outputs the following information:\n\n```bash\n\u25b2 Next.js 15.1.6\n- Local: http://localhost:3000\n\n\u2713 Starting...\n\u2713 Ready in 2.3s\n```\n\n#### Open the application site\n\nOpen the http://localhost:3000/ URL. The initial landing page displays a list of all restaurants in the `sample_restaurants.restaurants` collection:\n\nClick the Filtered Restaurants link in the navigation bar to view the restaurants that match the `name` and `borough` field query:\n\nCongratulations on completing the Quick Start tutorial!\n\nAfter you complete these steps, you have a Next.js web application that connects to your MongoDB deployment, runs queries on sample restaurant data, and renders the results on a locally hosted website.\n\n## Additional Resources\n\nTo learn more about Next.js and MongoDB, view the following resources:\n\n- Node.js driver documentation\n\n- Next.js documentation\n\n- Next.js API Routes documentation"} -{"chunk_id": "68a95bec5e79d242619d8d40-0", "page_id": "68a95bec5e79d242619d8d40", "source_name": "drivers", "product_name": "MongoDB Drivers", "url": "https://mongodb.com/docs/drivers/odm", "title": "ORMs, ODMs, and Libraries", "text": "# ORMs, ODMs, and Libraries\n\nMongoDB Client Libraries offer idiomatic APIs and helpers for most programming languages, but some applications are suited to higher level abstraction. In particular, developers may be used to interacting with data in a more declarative fashion, for example by using ActiveRecord for Ruby. Object-Relational Mappers (or ORMs) can improve the developer experience customizing database interactions in the following ways:\n\n- Abstracting away the need for query language.\n\n- Managing serialization/deserialization of data into objects.\n\n- Enforcing schema requirements.\n\nBecause MongoDB is a non-relational database management system, ORMs are sometimes referred to as ODMs (Object Document Mappers), but the terms can be used interchangeably in the MongoDB domain. MongoDB, our community, and our partners provide several ODM libraries.\n\nThe following are some examples of the best MongoDB ODM libraries for a number of programming languages, including Ruby, Python, Java, C#, Node.js, and PHP.\n\n## Ruby\n\n### Mongoid\n\nThe official Mongoid ODM provides API parity with Rails wherever possible to ensure developers that are used to working with a Ruby on Rails framework can use the methods and mechanics they\u2019re already familiar with in ActiveRecord.\n\nSee the Mongoid documentation for more information.\n\n## Python\n\n### Beanie\n\nBeanie is a third-party, asynchronous Python ODM based on Pydantic. Beanie uses corresponding documents to interact with each database collection, and supports adding, updating, and deleting documents. Beanie saves you time by removing boilerplate code, and it helps you focus on the parts of your app that actually matter.\n\nSee the Beanie documentation for more information.\n\n### MongoEngine\n\nMongoEngine is a third-party, synchronous Python ORM for MongoDB. It uses a simple declarative API and is built on top of the MongoDB PyMongo Driver.\n\nSee the MongoEngine documentation for more information.\n\n### Django\n\nDjango MongoDB Backend is the official MongoDB integration for Django and MongoDB. This integration supports many core Django features, including the Django ORM. It translates Django ORM methods into equivalent MongoDB queries, allowing developers to use the familiar Django interface.\n\nSee the Django MongoDB Backend documentation for more information.\n\n## Java\n\n### Hibernate ORM\n\nThe MongoDB Extension for Hibernate ORM is the official extension that integrates Hibernate ORM with MongoDB.\n\nHibernate ORM is an object-relational mapping framework for Java applications that maps Java classes to relational database tables. The MongoDB Extension for Hibernate ORM adds support for MongoDB, allowing you to represent and interact with MongoDB data by using Hibernate ORM's data-mapping and querying capabilities.\n\nSee the MongoDB Extension for Hibernate ORM documentation for more information.\n\n### Spring Data MongoDB\n\nSpring Data MongoDB is a third-party Java ORM for MongoDB. The Spring Data project provides a familiar and consistent Spring-based programming model which is enhanced by MongoDB-specific features and capabilities. Spring Data MongoDB uses a POJO-centric model for interacting with collections and writing repository-style data access layers.\n\nSee the Spring Data MongoDB documentation or the Spring Boot Integration with MongoDB Tutorial for more information.\n\n## .NET/C#\n\n### Entity Framework\n\nMongoDB Entity Framework Core Provider (EF Core Provider) is the official intergration for MongoDB and EF Core. It allows developers using C# in the .NET ecosystem to use Entity Framework Core as their ODM which provides a familiar API interface, query paradigm (LINQ), and design pattern.\n\nSee the EF Core provider documentation for more information.\n\n## Node.js\n\n### Mongoose\n\nMongoose is a third-party Node.js-based ODM library for MongoDB. It enforces a specific schema at the application layer and offers a variety of hooks, model validation, and other features.\n\nFor more information about Mongoose compatibility with MongoDB server, see MongoDB Server Version Compatibility in the Mongoose documentation.\n\n### Prisma\n\nPrisma is a third-party ODM for Node.js and Typescript that fundamentally differs from traditional ORMs. It uses declarative Prisma schemas as the single source of truth for both your database schema and models. The Prisma client reads and writes data in a type-safe manner, and returns plain JavaScript objects.\n\nSee Prisma & MongoDB for more information.\n\n## PHP\n\n### Doctrine\n\nDoctrine is a third-party PHP MongoDB ODM. This library provides PHP object mapping functionality and transparent persistence for PHP objects to MongoDB, as well as a mechanism to map embedded or referenced documents. It can also create references between PHP documents in different databases and work with GridFS buckets.\n\nSee the Doctrine MongoDB ODM documentation for more information.\n\n### Symfony\n\nThe Doctrine MongoDB ODM can be used to integrate MongoDB with the Symfony PHP framework. Doctine's object mapping enables developers to get the benefits of MongoDB features, such as flexible schema design and advanced searches, alongside Symfony's reusable components and streamlined web design.\n\nSee the Symfony MongoDB Integration page for more information.\n\n### Laravel\n\nLaravel MongoDB is the official integration for MongoDB and Laravel. It extends methods in the PHP Laravel API to provide developers the full suite of Laravel's Eloquent and Query Builder features while using MongoDB as their datastore. With this package, Laravel developers can take advantage of MongoDB's flexible schema and extensive capabilities, while maintaining familiar patterns, relationships, and features such as querying, caching, and more.\n\nSee the Laravel MongoDB documentation for more information."} -{"chunk_id": "6996ab7d1435ec531ea17f13-0", "page_id": "6996ab7d1435ec531ea17f13", "source_name": "drivers", "product_name": "MongoDB Drivers", "url": "https://mongodb.com/docs/drivers/java-frameworks/quarkus", "title": "Integrate MongoDB with Quarkus", "text": "# Integrate MongoDB with Quarkus\n\n## Overview\n\nIn this guide, you can learn how to create a **Java** REST API that uses **Quarkus** as the web framework and **Eclipse JNoSQL** to access MongoDB. Quarkus is an open-source Java framework designed for cloud-native microservices and serverless development. Eclipse JNOSQL implements the Jakarta NoSQL and Jakarta Data specifications to simplify the integration of Java applications with NoSQL databases.\n\nThe application in this tutorial consists of the following layers:\n\n- **Database layer**: MongoDB provides data storage and retrieval.\n\n- **Application layer**: Quarkus handles HTTP requests, routing, and dependency injection.\n\n- **Data access layer**: JNoSQL provides MongoDB document mapping and repository patterns.\n\n### Why Use MongoDB with Quarkus?\n\nThis tutorial uses the Quarkus JNoSQL Extension to access MongoDB, which provides a unified API for NoSQL databases and allows you to work with MongoDB by using familiar Java patterns and annotations. As a result, you can use MongoDB and Quarkus to develop lightweight applications with minimal configuration.\n\nBy integrating MongoDB with Quarkus, you can leverage Quarkus' fast startup times and efficient resource use alongside MongoDB's flexible document model. This combination supports applications that require type safety, scalability, and rapid development cycles. You can use MongoDB and Quarkus to create real world applications such as microservices, cloud-native APIs, or systems that require high performance and low resource consumption.\n\n## Quick Start Tutorial\n\nThis tutorial shows you how to build a REST API that uses MongoDB and Quarkus. The application accesses sample restaurant data, queries the data, and returns the results through RESTful endpoints. The tutorial also includes instructions for connecting to a MongoDB cluster hosted on MongoDB Atlas.\n\nIf you prefer to connect to MongoDB by using the Java driver without Quarkus, see the Get Started with the Java Driver tutorial.\n\n### Set Up Your Project\n\nFollow the steps in this section to install the project dependencies, create an Atlas cluster, and set up the application structure.\n\n#### Verify the prerequisites.\n\nTo create the Quick Start application, install the following software in your development environment:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nPrerequisite\n\n\nNotes\n\n
\nJava\n\n\nInstall JDK version 21 or later.\n\n
\nMaven\n\n\nUse version 3.8.1 or later.\n\n
\nQuarkus CLI\n\n\nThis command-line interface allows you to create and manage Quarkus projects from your terminal.**Important:** This tutorial uses version 3.30.6, and later versions might cause errors. Follow the installation instructions corresponding to your operating system to install the specific version.\n\n
\nCode editor\n\n\nUse the code editor of your choice.\n\n
\nTerminal app and shell\n\n\nFor MacOS users, use Terminal or a similar app. For Windows users, use PowerShell or Command Prompt.\n\n
\n\n#### Create a MongoDB Atlas cluster.\n\nMongoDB Atlas is a fully managed cloud database service that hosts your MongoDB deployments. If you do not have a MongoDB deployment, you can create a MongoDB cluster for free by completing the MongoDB Get Started tutorial. The MongoDB Get Started tutorial also demonstrates how to load sample datasets into your cluster, including the `sample_restaurants` database that is used in this tutorial.\n\nTo connect to your MongoDB cluster, you must use a **connection string**. To learn how to retrieve your connection string, see the Add your connection string section of the MongoDB Get Started tutorial.\n\nSave your connection string in a secure location.\n\n#### Create your Quarkus project.\n\nFrom your terminal, run the following command to create a new Quarkus project named `quarkus-quickstart` that configures the Quarkus JNoSQL Extension for MongoDB and JSON serialization for REST endpoints:\n\n```bash\nquarkus create app quarkus-quickstart --extensions=jnosql-mongodb,resteasy-jackson\n```\n\nThen, navigate to your project directory by running the following command:\n\n```bash\ncd quarkus-quickstart\n```\n\n#### Configure your database connection.\n\nNavigate to the `src/main/resources/application.properties` file and add the following configuration properties:\n\n```properties\njnosql.document.database=sample_restaurants\nquarkus.mongodb.connection-string=\n```\n\nThis code configures your connection to the `sample_restaurants` database in your MongoDB cluster. Replace the `` placeholder with the connection string that you saved in a previous step.\n\n#### Clean up template files.\n\nThe Quarkus project template includes some sample files that you can remove for this tutorial. To delete these unneeded files, select the tab corresponding to your operating system and run the following commands from your `quarkus-quickstart` directory:\n\n\n\n\n\n```bash\nrm src/main/java/org/acme/Car.java\nrm src/main/java/org/acme/Garage.java\nrm src/test/java/org/acme/GarageTest.java\nrm src/main/java/org/acme/GreetingResource.java\nrm src/test/java/org/acme/GreetingResourceIT.java\nrm src/test/java/org/acme/GreetingResourceTest.java\n```\n\n\n\n\n\n```bash\ndel src/main/java/org/acme/Car.java\ndel src/main/java/org/acme/Garage.java\ndel src/test/java/org/acme/GarageTest.java\ndel src/main/java/org/acme/GreetingResource.java\ndel src/test/java/org/acme/GreetingResourceIT.java\ndel src/test/java/org/acme/GreetingResourceTest.java\n```\n\n\n\n"} -{"chunk_id": "6996ab7d1435ec531ea17f13-1", "page_id": "6996ab7d1435ec531ea17f13", "source_name": "drivers", "product_name": "MongoDB Drivers", "url": "https://mongodb.com/docs/drivers/java-frameworks/quarkus", "title": "Integrate MongoDB with Quarkus", "text": "### Create Your Application\n\nAfter setting up the project structure and dependencies, follow the steps in this section to create your data model, repository class, and REST endpoints.\n\n#### Create the `Restaurant` model.\n\nCreate a file named `Restaurant.java` in the `src/main/java/org/acme` directory and paste the following code:\n\n```java\npackage org.acme;\n\nimport jakarta.nosql.Column;\nimport jakarta.nosql.Entity;\nimport jakarta.nosql.Id;\n\n/**\n * Represents a restaurant entity from the sample_restaurants database .\n * This class is used as an entity in the MongoDB database.\n */\n@Entity(\"restaurants\")\npublic class Restaurant {\n\n @Id\n private String id;\n\n @Column\n private String name;\n\n @Column\n private String borough;\n\n @Column\n private String cuisine;\n\n // Default constructor required by JNoSQL\n public Restaurant() {}\n\n // Constructor\n public Restaurant(String id, String name, String borough,String cuisine) {\n this.id = id;\n this.name = name;\n this.borough = borough;\n this.cuisine = cuisine;\n }\n\n // Getters and setters\n public String getId() { return id; }\n public void setId(String id) { this.id = id; }\n\n public String getName() { return name; }\n public void setName(String name) { this.name = name; }\n\n public String getBorough() { return borough; }\n public void setBorough(String borough) { this.borough = borough; }\n\n public String getCuisine() { return cuisine; }\n public void setCuisine(String cuisine) { this.cuisine = cuisine; }\n}\n\n```\n\nThis file defines the `Restaurant` entity class, which maps to documents in the `sample_restaurants.restaurants` collection. The `@Entity` annotation marks this class as a JNoSQL entity, and the field annotations map Java properties to document fields.\n\n#### Create the repository class.\n\nCreate a file named `RestaurantRepository.java` in the `src/main/java/org/acme` directory and paste the following code:\n\n```java\npackage org.acme;\n\nimport jakarta.data.repository.Repository;\nimport org.eclipse.jnosql.mapping.NoSQLRepository;\n\nimport java.util.List;\n\n/**\n * Interface for managing restaurant data.\n *\n * It uses the Jakarta Data Specification capabilities.\n *\n */\n@Repository\npublic interface RestaurantRepository extends NoSQLRepository {\n\n List findByBorough(String borough);\n\n List findByCuisine(String cuisine);\n}\n\n```\n\nThis repository class provides methods for accessing restaurant data in MongoDB. It defines custom `findByBorough()` and `findByCuisine()` query methods, and you can also use a `RestaurantRepository` instance to access built-in create, read, update, and delete methods.\n\n#### Create the REST resource class.\n\nIn the `src/main/java/org/acme` directory, create a file named `RestaurantResource.java` and paste the following code:\n\n```java\npackage org.acme;\n\nimport jakarta.inject.Inject;\nimport jakarta.ws.rs.*;\nimport jakarta.ws.rs.core.MediaType;\nimport jakarta.ws.rs.core.Response;\nimport java.util.List;\n\n/**\n * REST API controller for restaurant operations.\n * Provides endpoints for retrieving restaurant data from MongoDB.\n */\n@Path(\"/restaurants\")\n@Produces(MediaType.APPLICATION_JSON)\n@Consumes(MediaType.APPLICATION_JSON)\npublic class RestaurantResource {\n\n @Inject\n RestaurantRepository restaurantRepository;\n\n /**\n * Retrieves all restaurants from the database.\n *\n * @return List of all restaurants\n */\n @GET\n public Response getAllRestaurants() {\n try {\n List restaurants = restaurantRepository.findAll().toList();\n System.out.println(\"Found \" + restaurants.size() + \" restaurants\");\n return Response.ok(restaurants).build();\n } catch (Exception e) {\n e.printStackTrace();\n return Response.status(Response.Status.INTERNAL_SERVER_ERROR)\n .entity(\"Error retrieving restaurants: \" + e.getMessage())\n .build();\n }\n }\n\n /**\n * Retrieves filtered restaurants in Queens that contain \"Moon\" in the name.\n *\n * @return List of filtered restaurants\n */\n @GET\n @Path(\"/browse\")\n public Response getFilteredRestaurants() {\n try {\n // Temporarily use findAll() to test basic connectivity\n List allRestaurants = restaurantRepository.findAll().toList();\n System.out.println(\"Total restaurants found: \" + allRestaurants.size());\n\n // Filter for Queens restaurants that also have \"Moon\" in the name\n List queensRestaurants = allRestaurants.stream()\n .filter(restaurant -> \"Queens\".equals(restaurant.getBorough()) &&\n restaurant.getName() != null &&\n restaurant.getName().toLowerCase().contains(\"moon\"))\n .toList();\n System.out.println(\"Queens restaurants found: \" + queensRestaurants.size());\n\n return Response.ok(queensRestaurants).build();\n } catch (Exception e) {\n e.printStackTrace();\n return Response.status(Response.Status.INTERNAL_SERVER_ERROR)\n .entity(\"Error retrieving filtered restaurants: \" + e.getMessage())\n .build();\n }\n }\n\n /**\n * Retrieves restaurants by cuisine type.\n *\n * @param cuisine The cuisine type to filter for\n * @return List of restaurants that have the specified cuisine\n */\n @GET\n @Path(\"/cuisine/{cuisine}\")\n public Response getRestaurantsByCuisine(@PathParam(\"cuisine\") String cuisine) {\n try {\n List restaurants = restaurantRepository.findByCuisine(cuisine);\n return Response.ok(restaurants).build();\n } catch (Exception e) {\n return Response.status(Response.Status.INTERNAL_SERVER_ERROR)\n .entity(\"Error retrieving restaurants by cuisine: \" + e.getMessage())\n .build();\n }\n }\n}\n```\n\nThis REST resource class defines the following HTTP endpoints:\n\n- `GET /restaurants/`: Retrieves all documents from the `restaurants` collection\n\n- `GET /restaurants/browse`: Retrieves documents that represent restaurants in Queens containing `\"Moon\"` in their name, performing a case-insenstive query\n\n- `GET /restaurants/cuisine/{cuisine}`: Retrieves documents that represent restaurants offering the specified `cuisine` value\n\n#### Create a test class.\n\nIn the `src/test/java/org/acme` directory, create a file named `RestaurantRepositoryTest.java` and paste the following code:\n\n```java\npackage org.acme;\n\nimport io.quarkus.test.junit.QuarkusTest;\nimport jakarta.inject.Inject;\nimport org.junit.jupiter.api.DisplayName;\nimport org.junit.jupiter.api.Test;\n\nimport java.util.List;\n\nimport static org.assertj.core.api.Assertions.assertThat;\n\n/**\n * RestaurantRepositoryTest is a test class for testing the RestaurantRepository operations.\n *\n * It uses the Quarkus Test framework to test the restaurant data access.\n */\n@QuarkusTest\npublic class RestaurantRepositoryTest {\n\n @Inject\n RestaurantRepository restaurantRepository;\n\n @Test\n @DisplayName(\"Should retrieve restaurants from the database\")\n public void testRetrieveRestaurants() {\n // Test repository injection and MongoDB connection\n assertThat(restaurantRepository).isNotNull();\n }\n\n @Test\n @DisplayName(\"Should find restaurants by borough\")\n public void testFindRestaurantsByBorough() {\n // Test that the method exists and returns data\n List restaurants = restaurantRepository.findByBorough(\"Queens\");\n assertThat(restaurants).isNotNull();\n }\n}\n```\n\nThis file uses Quarkus's testing framework for integration testing. The code defines the following methods to test your MongoDB connection:\n\n- `testRetrieveRestaurants()`: Verifies that your `RestaurantRepository` class accesses MongoDB"} -{"chunk_id": "6996ab7d1435ec531ea17f13-2", "page_id": "6996ab7d1435ec531ea17f13", "source_name": "drivers", "product_name": "MongoDB Drivers", "url": "https://mongodb.com/docs/drivers/java-frameworks/quarkus", "title": "Integrate MongoDB with Quarkus", "text": "- `testFindRestaurantsByBorough()`: Verifies that the `findByBorough()` method retrieves MongoDB data\n\n### Run Your Application\n\nFinally, follow the steps in this section to run your REST API and test the endpoints by using `curl` commands.\n\n#### Run the tests.\n\nFirst, run the following command from your project directory to run the test suite:\n\n```bash\n./mvnw test\n```\n\nThis command runs the `RestaurantRepositoryTest` class and verifies that your application can access MongoDB data. If successful, your command output contains the following information:\n\n```bash\n[INFO] Results:\n[INFO]\n[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0\n[INFO]\n[INFO] ------------------------------------------------------------------------\n[INFO] BUILD SUCCESS\n[INFO] ------------------------------------------------------------------------\n[INFO] Total time: ... s\n[INFO] Finished at: ...\n[INFO] ------------------------------------------------------------------------\n```\n\n#### Start the Quarkus application.\n\nFrom your project directory, run the following command to compile and start the application in development mode:\n\n```bash\n./mvnw quarkus:dev\n```\n\n#### Manually test the REST endpoints.\n\nIn a separate terminal window, run the following `curl` commands to test the REST endpoints. Each endpoint returns JSON data containing restaurant information from the `sample_restaurants.restaurants` collection. If successful, your commands return data similar to the sample outputs.\n\n- Retrieve all restaurants.\n\n ```bash\n curl http://localhost:8080/restaurants/\n ```\n\n ```\n [{\"id\":\"...\",\"name\":\"Morris Park Bake Shop\",\"borough\":\"Bronx\",\"cuisine\":\"Bakery\"},\n {\"id\":\"...\",\"name\":\"Wilken'S Fine Food\",\"borough\":\"Brooklyn\",\"cuisine\":\"Delicatessen\"},\n {\"id\":\"...\",\"name\":\"Taste The Tropics Ice Cream\",\"borough\":\"Brooklyn\",\"cuisine\":\"Ice Cream,\n Gelato, Yogurt, Ices\"},\n {\"id\":\"...\",\"name\":\"Carvel Ice Cream\",\"borough\":\"Queens\",\"cuisine\":\"Ice Cream, Gelato, Yogurt,\n Ices\"},\n ...]\n ```\n\n- Retrieve restaurants in Queens that have `\"Moon\"` in the name.\n\n ```bash\n curl http://localhost:8080/restaurants/browse\n ```\n\n ```\n [{\"id\":\"...\",\"name\":\"Somoon\",\"borough\":\"Queens\",\"cuisine\":\"Asian\"},\n {\"id\":\"...\",\"name\":\"New Moon Star Restaurant\",\"borough\":\"Queens\",\"cuisine\":\"Chinese\"},\n {\"id\":\"...\",\"name\":\"Moon Tikka Grill\",\"borough\":\"Queens\",\"cuisine\":\"Indian\"},\n {\"id\":\"...\",\"name\":\"Silver Moon Diner\",\"borough\":\"Queens\",\"cuisine\":\"American\"},\n {\"id\":\"...\",\"name\":\"Mooney'S Public House\",\"borough\":\"Queens\",\"cuisine\":\"Irish\"},\n {\"id\":\"...\",\"name\":\"Moon Light Crill Rest.\",\"borough\":\"Queens\",\"cuisine\":\"Indian\"},\n {\"id\":\"...\",\"name\":\"Full Moon Cafe\",\"borough\":\"Queens\",\"cuisine\":\"Caf\u00e9/Coffee/Tea\"},\n {\"id\":\"...\",\"name\":\"Pacific Moon\",\"borough\":\"Queens\",\"cuisine\":\"Chinese\"},\n {\"id\":\"...\",\"name\":\"Moon Palace Kitchen\",\"borough\":\"Queens\",\"cuisine\":\"Chinese\"},\n {\"id\":\"...\",\"name\":\"Honey Moon Coffee Shop 1766096115682\",\"borough\":\"Queens\",\"cuisine\":\"Caf\u00e9/Coffee/Tea\"},\n {\"id\":\"...\",\"name\":\"Honey Moon Coffee Shop\",\"borough\":\"Queens\",\"cuisine\":\"Caf\u00e9/Coffee/Tea\"}]\n ```\n\n- Retrieve restaurants by cuisine type.\n\n The following command queries for restaurants that have a `cuisine` value of `\"Czech\"`, but you can replace this parameter with any cuisine:\n\n ```bash\n curl http://localhost:8080/restaurants/cuisine/Czech\n ```\n\n ```\n [{\"id\":\"...\",\"name\":\"Koliba Restaurant\",\"borough\":\"Queens\",\"cuisine\":\"Czech\"},\n {\"id\":\"...\",\"name\":\"Milan'S Restaurant\",\"borough\":\"Brooklyn\",\"cuisine\":\"Czech\"},\n {\"id\":\"...\",\"name\":\"Bohemian Beer Garden\",\"borough\":\"Queens\",\"cuisine\":\"Czech\"},\n {\"id\":\"...\",\"name\":\"Hospoda\",\"borough\":\"Manhattan\",\"cuisine\":\"Czech\"},\n {\"id\":\"...\",\"name\":\"Olde Prague Tavern\",\"borough\":\"Queens\",\"cuisine\":\"Czech\"},\n {\"id\":\"...\",\"name\":\"Brooklyn Beet Company\",\"borough\":\"Brooklyn\",\"cuisine\":\"Czech\"}]\n ```\n\nCongratulations on completing the Quarkus Quick Start tutorial! After you complete these steps, you have a Java Quarkus REST API that connects to your MongoDB deployment, runs queries on sample restaurant data, and exposes the results through HTTP endpoints that you can test by using `curl` commands.\n\n## Additional Resources\n\nTo learn more about Quarkus, JNoSQL, and MongoDB, see the following resources:\n\n- Quarkus documentation\n\n- Eclipse JNoSQL documentation\n\n- MongoDB Java Driver documentation"} -{"chunk_id": "698d7183894acc7ddb91207c-0", "page_id": "698d7183894acc7ddb91207c", "source_name": "drivers", "product_name": "MongoDB Drivers", "url": "https://mongodb.com/docs/drivers/node-frameworks/angular", "title": "Integrate MongoDB with Angular", "text": "# Integrate MongoDB with Angular\n\n## Overview\n\nIn this guide, you can learn how to create an **Angular** web application that uses the **MEAN stack**. The MEAN stack is a web development framework that uses MongoDB, Express, Angular, and Node.js and consists of the following layers:\n\n- **Database layer**: MongoDB provides data storage and retrieval.\n\n- **Application layer**: Express and Node.js make up the middle tier for server-side logic.\n\n- **Presentation layer**: Angular implements the user interface and front-end interactions.\n\n### Why Use MongoDB in an Angular Application?\n\nAngular is a TypeScript framework used to create dynamic web applications. It provides built-in packages for a range of application features, and its component-based architecture makes applications highly reusable.\n\nSince TypeScript is built on JavaScript, each element of the MEAN stack is based on JavaScript and JSON. As a result, the integration between these elements is straightforward. The Angular front end creates JSON documents that MongoDB can store directly in BSON format, a binary JSON extension, and Express provides a minimalist framework that uses JavaScript. MongoDB provides advanced indexing and querying features for BSON documents and includes a native Node.js driver, which makes it an ideal data store for JavaScript applications.\n\n## Quick Start Tutorial\n\nThis tutorial shows you how to build a web application by using the MEAN stack. The application accesses sample restaurant data, queries the data, and displays the results on a locally hosted site. The tutorial also includes instructions for connecting to a MongoDB cluster hosted on MongoDB Atlas and accessing and displaying data from your database.\n\nIf you prefer to connect to MongoDB by using the Node.js driver without Angular, see the Get Started with the Node.js Driver guide.\n\n### Set Up Your Project\n\nFollow the steps in this section to install the project dependencies, create an Atlas cluster, and set up the application directories.\n\n#### Verify the prerequisites.\n\nTo create the Quick Start application, install the following software in your development environment:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nPrerequisite\n\n\nNotes\n\n
\nNode.js\n\n\nDownload either the **Latest LTS** or **Latest Release** version.\n\n
\nAngular CLI\n\n\nInstall globally by running `npm install -g @angular/cli` in your terminal.\n\n
\nCode editor\n\n\nUse the editor of your choice.\n\n
\nTerminal app and shell\n\n\nFor MacOS users, use Terminal or a similar app. For Windows users, use PowerShell.\n\n
\n\n#### Create a MongoDB Atlas cluster.\n\nMongoDB Atlas is a fully managed cloud database service that hosts your MongoDB deployments. If you do not have a MongoDB deployment, you can create a MongoDB cluster for free by completing the MongoDB Get Started tutorial. The MongoDB Get Started tutorial also demonstrates how to load sample datasets into your cluster, including the `sample_restaurants` database that is used in this tutorial.\n\nTo connect to your MongoDB cluster, you must use a **connection URI**. To learn how to retrieve your connection URI, see the Add your connection string section of the MongoDB Get Started tutorial.\n\nSave your connection string in a secure location.\n\n#### Create your project directories.\n\nRun the following commands in your terminal to create a directory for your project named `angular-quickstart`:\n\n```bash\nmkdir angular-quickstart\ncd angular-quickstart\n```\n\nThen, run the following commands from the `angular-quickstart` directory to create a folder for the back end named `server` and initialize the `package.json` file:\n\n```bash\nmkdir server\ncd server\nnpm init -y\n```\n\n#### Modify your `package.json` file.\n\nNavigate to the `package.json` file in the `angular-quickstart/server` directory. To use ECMAScript modules, the standard format for packaging JavaScript code for reuse, replace the existing line that specifies the `\"type\"` field with the following line:\n\n```bash\n\"type\": \"module\",\n```\n\n#### Install the dependencies.\n\nRun the following command to install the `mongodb`, `express`, `cors`, and `dotenv` dependencies:\n\n```bash\nnpm install mongodb express cors dotenv\n```\n\nThis command installs MongoDB, the Express web framework, the `cors` Node.js package for cross-origin resource sharing, and Dotenv to load environment variables.\n\nNext, run the following command to install TypeScript and the required type definitions:\n\n```bash\nnpm install -D typescript @types/node @types/cors @types/express tsx\n```\n\nThis command installs TypeScript, type definitions for Node.js and Express, and `tsx`, a tool for running TypeScript files directly."} -{"chunk_id": "698d7183894acc7ddb91207c-1", "page_id": "698d7183894acc7ddb91207c", "source_name": "drivers", "product_name": "MongoDB Drivers", "url": "https://mongodb.com/docs/drivers/node-frameworks/angular", "title": "Integrate MongoDB with Angular", "text": "### Configure the Back End\n\nAfter setting up the project structure and dependencies, follow the steps in this section to configure your web server and connect to MongoDB.\n\n#### Configure your Express web server.\n\nCreate a file named `server.ts` in your `angular-quickstart/server` directory and paste the following code:\n\n```typescript\nimport express from \"express\";\nimport cors from \"cors\";\nimport restaurants from \"./routes/restaurant.js\";\n\nconst PORT = process.env.PORT || 5050;\nconst app = express();\n\napp.use(cors());\napp.use(express.json());\napp.use(\"/restaurant\", restaurants);\n\n// start the Express server\napp.listen(PORT, () => {\n console.log(`Server listening on port ${PORT}`);\n});\n\n```\n\n#### Set environment variables.\n\nIn the `server` directory, create an `.env` file and paste the following code:\n\n```none\nMONGODB_URI=\nPORT=5050\n```\n\nReplace the `` placeholder with the connection string that you saved in a previous step.\n\n#### Connect your server to the database.\n\nIn the `server` directory, create a subdirectory named `db`. Add a new file named `connection.ts` to this subdirectory and paste the following code:\n\n```typescript\nimport \"dotenv/config\";\nimport { MongoClient, Db } from \"mongodb\";\n\nconst uri = process.env.MONGODB_URI || \"\";\nconst client = new MongoClient(uri);\n\ntry {\n // Connects the client to the server\n await client.connect();\n // Sends a ping to confirm a successful connection\n await client.db(\"admin\").command({ ping: 1 });\n console.log(\n \"Pinged your deployment. You successfully connected to MongoDB!\"\n );\n} catch(err) {\n console.error(err);\n}\n\nconst db: Db = client.db(\"sample_restaurants\");\n\nexport default db;\n\n```\n\nThis file connects to your MongoDB deployment, accesses the `sample_restaurants` database, and tests the database connection.\n\n#### Create server API endpoints.\n\nIn the `server` directory, create a subdirectory named `routes`. Create a file named `restaurant.ts` in this subdirectory and paste the following code:\n\n```typescript\nimport express, { Request, Response } from \"express\";\nimport db from \"../db/connection.js\";\n\n// Creates an instance of the Express router, used to define our routes\nconst router = express.Router();\n\n// Gets a list of all the restaurants\nrouter.get(\"/\", async (req: Request, res: Response) => {\n let collection = db.collection(\"restaurants\");\n let results = await collection.find({}).toArray();\n res.send(results).status(200);\n});\n\n// Lists restaurants that match the query filter\nrouter.get(\"/browse\", async (req: Request, res: Response) => {\n try {\n let collection = db.collection(\"restaurants\");\n let query = {\n borough: \"Queens\",\n name: { $regex: \"Moon\", $options: \"i\" },\n };\n let results = await collection.find(query).toArray();\n res.send(results).status(200);\n } catch (err) {\n console.error(err);\n res.status(500).send(\"Error browsing restaurants\");\n }\n});\n\nexport default router;\n\n```\n\nThis file accesses the `restaurants` collection in the `sample_restaurants` database and defines the following `GET` endpoints:\n\n- `/`: Retrieves all restaurants from the sample collection\n\n- `/browse`: Retrieves restaurants that match the query criteria, which filters for restaurants in Queens that contain the word `\"Moon\"` in the name"} -{"chunk_id": "698d7183894acc7ddb91207c-2", "page_id": "698d7183894acc7ddb91207c", "source_name": "drivers", "product_name": "MongoDB Drivers", "url": "https://mongodb.com/docs/drivers/node-frameworks/angular", "title": "Integrate MongoDB with Angular", "text": "### Configure the Front End\n\nAfter setting up the application's back end, follow the steps in this section to configure Angular and add the front end components.\n\n#### Create the Angular application.\n\nNavigate to the `angular-quickstart` directory and run the following command to create a new Angular application:\n\n```bash\nng new client\n```\n\nThis command prompts you to respond to a series of configuration questions. For each question, choose the following responses:\n\n- Which stylesheet system would you like to use? Select **Tailwind CSS**\n\n- Do you want to enable Server-Side Rendering (SSR) and Static Site Generation (SSG/Prerendering)? Enter **N**\n\n- Which AI tools do you want to configure with Angular best practices? Select the tools of your choice\n\nAfter running the command, your project has a `client` directory that contains front-end scaffolding. The command also configures your project to use TailwindCSS, a framework for UI formatting.\n\n#### Install Zone.js.\n\nRun the following commands from your project's root directory to install Zone.js:\n\n```bash\ncd client\nnpm install zone.js\n```\n\nYour application uses the Zone.js library for tracking changes and automatically updating the UI.\n\n#### Create the restaurant service.\n\nFrom the `client` directory, run the following command to generate a service that handles API calls to your back end:\n\n```bash\nng generate service restaurant\n```\n\nNavigate to the `client/src/app/restaurant.ts` file and replace the contents with the following code:\n\n```typescript\nimport { Injectable } from '@angular/core';\nimport { HttpClient } from '@angular/common/http';\nimport { Observable } from 'rxjs';\n\nexport interface Restaurant {\n _id: string;\n name: string;\n borough: string;\n cuisine: string;\n}\n\n@Injectable({\n providedIn: 'root'\n})\nexport class RestaurantService {\n private apiUrl = 'http://localhost:5050/restaurant';\n\n constructor(private http: HttpClient) {}\n\n getAllRestaurants(): Observable {\n return this.http.get(this.apiUrl);\n }\n\n getFilteredRestaurants(): Observable {\n return this.http.get(`${this.apiUrl}/browse`);\n }\n}\n\n```\n\nThis service defines methods to fetch restaurant data from your Express API.\n\n#### Configure routing.\n\nNavigate to the `client/src/app/app.routes.ts` file and replace the contents with the following code:\n\n```typescript\nimport { Routes } from '@angular/router';\nimport { RestaurantListComponent } from './restaurant-list/restaurant-list';\n\nexport const routes: Routes = [\n { path: '', component: RestaurantListComponent },\n { path: 'browse', component: RestaurantListComponent }\n];\n\n```\n\nThis file configures client-side routing and defines the following routes:\n\n- `/`: Displays all restaurants from the `/restaurant/` API endpoint\n\n- `/browse`: Displays filtered restaurants from the `/restaurant/browse` API endpoint\n\n#### Update the application configuration.\n\nNavigate to the `client/src/app/app.config.ts` file and replace the contents with the following code:\n\n```typescript\nimport { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';\nimport { provideRouter } from '@angular/router';\nimport { provideHttpClient } from '@angular/common/http';\n\nimport { routes } from './app.routes';\n\nexport const appConfig: ApplicationConfig = {\n providers: [\n provideZoneChangeDetection({ eventCoalescing: true }),\n provideRouter(routes),\n provideHttpClient()\n ]\n};\n\n```\n\nThis configuration enables HTTP client functionality for making API requests.\n\n#### Create the restaurant list component.\n\nRun the following command from the `client` directory to generate a component for displaying restaurants:\n\n```bash\nng generate component restaurant-list\n```\n\nNavigate to the `client/src/app/restaurant-list/restaurant-list.ts` file and replace the contents with the following code:\n\n```typescript\nimport { Component, OnInit } from '@angular/core';\nimport { CommonModule } from '@angular/common';\nimport { Router } from '@angular/router';\nimport { RestaurantService, Restaurant } from '../restaurant';\n\n@Component({\n selector: 'app-restaurant-list',\n standalone: true,\n imports: [CommonModule],\n templateUrl: './restaurant-list.html',\n styleUrl: './restaurant-list.css'\n})\nexport class RestaurantListComponent implements OnInit {\n restaurants: Restaurant[] = [];\n loading = true;\n error = '';\n\n constructor(\n private restaurantService: RestaurantService,\n public router: Router\n ) {}\n\n ngOnInit(): void {\n this.loadRestaurants();\n }\n\n loadRestaurants(): void {\n const isFiltered = this.router.url === '/browse';\n\n const observable = isFiltered\n ? this.restaurantService.getFilteredRestaurants()\n : this.restaurantService.getAllRestaurants();\n\n observable.subscribe({\n next: (data) => {\n this.restaurants = data;\n this.loading = false;\n },\n error: (err) => {\n this.error = 'Failed to load restaurants';\n this.loading = false;\n console.error('Error loading restaurants:', err);\n }\n });\n }\n}\n\n```\n\nThen, navigate to the `client/src/app/restaurant-list/restaurant-list.html` file and replace the contents with the following code:\n\n```html\n
\n

Loading restaurants...

\n
\n\n
\n {{ error }}\n
\n\n
\n

\n {{ router.url === '/browse' ? 'Filtered Restaurants (Queens, containing \"Moon\")' : 'All Restaurants' }}\n

\n
\n
\n \n \n \n \n \n \n \n \n \n @for (restaurant of restaurants; track restaurant._id) {\n \n \n \n \n \n }\n \n
\n Name\n \n Borough\n \n Cuisine\n
\n {{ restaurant.name }}\n \n {{ restaurant.borough }}\n \n {{ restaurant.cuisine }}\n
\n
\n
\n
\n\n```\n\nThis component retrieves and displays the restaurant information based on the current route.\n\n#### Update the main application component.\n\nNavigate to the `client/src/app/app.ts` file and replace the contents with the following code:\n\n```typescript\nimport { Component } from '@angular/core';\nimport { RouterOutlet, RouterLink, RouterLinkActive } from '@angular/router';\n\n@Component({\n selector: 'app-root',\n standalone: true,\n imports: [RouterOutlet, RouterLink, RouterLinkActive],\n templateUrl: './app.html',\n styleUrl: './app.css'\n})\nexport class AppComponent {\n title = 'Restaurant Browser';\n}\n```\n\nThen, navigate to the `client/src/app/app.html` file and replace the contents with the following code:"} -{"chunk_id": "698d7183894acc7ddb91207c-3", "page_id": "698d7183894acc7ddb91207c", "source_name": "drivers", "product_name": "MongoDB Drivers", "url": "https://mongodb.com/docs/drivers/node-frameworks/angular", "title": "Integrate MongoDB with Angular", "text": "```html\n\n\n```\n\nThis is the main application component that includes navigation and renders the appropriate child components based on the current route.\n\n#### Update your main file.\n\nNavigate to the `client/src/main.ts` file and replace the contents with the following code:\n\n```typescript\nimport 'zone.js';\nimport { bootstrapApplication } from '@angular/platform-browser';\nimport { appConfig } from './app/app.config';\nimport { AppComponent } from './app/app';\n\nbootstrapApplication(AppComponent, appConfig)\n .catch((err) => console.error(err));\n```\n\nThis file acts as the entry point to your application, and it applies and renders your configuration.\n\n### Run Your Application\n\nFinally, follow the steps in this section to run your application and view the rendered restaurant data.\n\n#### Run the server application.\n\nFrom your `server` directory, run the following command to start the server:\n\n```bash\nnpx tsx server.ts\n```\n\nIf successful, this command outputs the following information:\n\n```bash\nPinged your deployment. You successfully connected to MongoDB!\nServer listening on port 5050\n```\n\n#### Run the client application.\n\nIn a separate terminal window, navigate to the `client` directory. Run the following command to start the Angular front end:\n\n```bash\nng serve\n```\n\nIf successful, this command outputs the following information:\n\n```bash\nApplication bundle generation complete.\nWatch mode enabled. Watching for file changes...\nNOTE: Raw file sizes do not reflect development server per-request transformations.\n \u279c Local: http://localhost:4200/\n \u279c press h + enter to show help\n```\n\nYour Angular application makes HTTP requests from port `4200` to port `5050` to retrieve data.\n\n#### Open the application site.\n\nOpen the http://localhost:4200/ URL. The initial landing page displays a list of all restaurants in the `sample_restaurants.restaurants` collection:\n\nThen, click the Filtered Restaurants link in the navigation bar to view the restaurants that match the `name` and `borough` field query:\n\nCongratulations on completing the Quick Start tutorial!\n\nAfter you complete these steps, you have an Angular web application that connects to your MongoDB deployment, runs a query on sample restaurant data, and renders the results on a locally hosted website.\n\n## Additional Resources\n\nTo learn more about Angular, MongoDB, and the MEAN stack, view the following resources:\n\n- Angular documentation\n\n- Express documentation\n\n- Node.js driver documentation\n\n- What is the MEAN stack? article"} -{"chunk_id": "68a95bec5e79d242619d8d38-0", "page_id": "68a95bec5e79d242619d8d38", "source_name": "drivers", "product_name": "MongoDB Drivers", "url": "https://mongodb.com/docs/drivers", "title": "Start Developing with MongoDB", "text": "# Start Developing with MongoDB\n\nYou can connect your application to your MongoDB Atlas deployment or a self-hosted MongoDB cluster by using one of the official MongoDB libraries. To learn more about Atlas, see What is MongoDB Atlas?. To learn how to download and install a self-hosted MongoDB cluster, see Install MongoDB.\n\nThe following libraries are officially supported by MongoDB. MongoDB actively develops new features, adds performance enhancements, fixes bugs, and applies security patches to them.\n\n## Featured Community-Supported Libraries\n\nThe following libraries are developed and maintained by the MongoDB community. They are not official MongoDB client libraries and are not supported by MongoDB. For questions, issues, or updates, please refer to the respective project repositories and maintainers.\n\nDon't see your desired language? Browse more community-supported libraries.\n\n## Compatibility with Other Document Databases\n\nSee the following pages for information about other document databases' compatibility with MongoDB:\n\n- Amazon DocumentDB Compatibility\n\n- Azure Cosmos DB Compatibility\n\n## Client Libraries Best Practices\n\nTo learn best practices for developing your application when you use MongoDB client libraries, see Client Libraries Best Practices."} -{"chunk_id": "6937bee7d1b0fc8b0a85b5c3-0", "page_id": "6937bee7d1b0fc8b0a85b5c3", "source_name": "drivers", "product_name": "MongoDB Drivers", "url": "https://mongodb.com/docs/drivers/node-frameworks/react", "title": "Integrate MongoDB with React", "text": "# Integrate MongoDB with React\n\n## Overview\n\nIn this guide, you can learn how to create a **React** web application that uses the **MERN stack**. The MERN stack is a web development framework that uses MongoDB, Express, React, and Node.js and consists of the following layers:\n\n- **Database layer**: MongoDB provides data storage and retrieval.\n\n- **Application layer**: Express and Node.js make up the middle tier for server-side logic.\n\n- **Presentation layer**: React implements the user interface and client-side interactions.\n\n### Why Use MongoDB in a React Application?\n\nBy storing your React application data in MongoDB, you can use the document data model to build complex query expressions. The document model's flexibility allows you to store nested data structures and iterate quickly on your application design. You can also grow your application by using the horizontal scaling capabilities in MongoDB.\n\nThe MERN stack with MongoDB supports applications that require dynamic, evolving data structures. As a result, this framework is well-designed for real world applications such as real-time dashboards or one-page applications that update content continuously.\n\n## Quick Start Tutorial\n\nThis tutorial shows you how to build a web application by using the MERN stack. The application accesses sample restaurant data, queries the data, and displays the results on a locally hosted site. The tutorial also includes instructions for connecting to a MongoDB cluster hosted on MongoDB Atlas and accessing and displaying data from your database.\n\nIf you prefer to connect to MongoDB by using the Node.js driver without React, see the Get Started with the Node.js Driver guide.\n\n### Set Up Your Project\n\nFollow the steps in this section to install the project dependencies, create an Atlas cluster, and set up the application directories.\n\n#### Verify the prerequisites\n\nTo create the Quick Start application, you need the following software installed in your development environment:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nPrerequisite\n\n\nNotes\n\n
\nNode.js\n\n\nDownload either the **Latest LTS** or **Latest Release** version.\n\n
\nCode editor\n\n\nThis tutorial uses Visual Studio Code, but you can use the editor of your choice.\n\n
\nTerminal app and shell\n\n\nFor MacOS users, use Terminal or a similar app. For Windows users, use PowerShell.\n\n
\n\n#### Create a MongoDB Atlas cluster\n\nMongoDB Atlas is a fully managed cloud database service that hosts your MongoDB deployments. If you do not have a MongoDB deployment, you can create a MongoDB cluster for free (no credit card required) by completing the MongoDB Get Started tutorial. The MongoDB Get Started tutorial also demonstrates how to load sample datasets into your cluster, including the `sample_restaurants` database that is used in this tutorial.\n\nTo connect to your MongoDB cluster, you must use a **connection URI**. To learn how to retrieve your connection URI, see the Add your connection string section of the MongoDB Get Started tutorial.\n\nSave your connection string in a secure location.\n\n#### Create your project directories\n\nRun the following command in your terminal to create a directory for your project named `react-quickstart`:\n\n```bash\nmkdir react-quickstart\ncd react-quickstart\n```\n\nThen, run the following commands from the `react-quickstart` directory to create a folder for the back end named `server` and initialize the `package.json` file:\n\n```bash\nmkdir server\ncd server\nnpm init -y\n```\n\n#### Modify your `package.json` file\n\nNavigate to the `package.json` file in the `react-quickstart/server` directory. To use ECMAScript modules, the standard format for packaging JavaScript code for reuse, replace the existing line that specifies the `\"type\"` field with the following line:\n\n```bash\n\"type\": \"module\",\n```\n\nRun the following command to install the `mongodb`, `express`, and `cors` dependencies:\n\n```bash\nnpm install mongodb express cors\n```\n\nThis command installs MongoDB, the Express web framework, and the `cors` Node.js package that enables cross-origin resource sharing."} -{"chunk_id": "6937bee7d1b0fc8b0a85b5c3-1", "page_id": "6937bee7d1b0fc8b0a85b5c3", "source_name": "drivers", "product_name": "MongoDB Drivers", "url": "https://mongodb.com/docs/drivers/node-frameworks/react", "title": "Integrate MongoDB with React", "text": "### Configure the Server\n\nAfter setting up the project structure and dependencies, follow the steps in this section to configure your web server and connect to MongoDB.\n\n#### Configure your Express web server\n\nRun the following command from the `react-quickstart/server` directory to create a file named `server.js`:\n\n\n\n\n\n```bash\ntouch server.js\n```\n\n\n\n\n\n```bash\nNew-Item -ItemType File server.js\n```\n\n\n\n\n\nPaste the following code into the file:\n\n```js\nimport express from \"express\";\nimport cors from \"cors\";\nimport restaurants from \"./routes/restaurant.js\";\n\nconst PORT = process.env.PORT || 5050;\nconst app = express();\n\napp.use(cors());\napp.use(express.json());\napp.use(\"/restaurant\", restaurants);\n\n// start the Express server\napp.listen(PORT, () => {\n console.log(`Server listening on port ${PORT}`);\n});\n```\n\nThis file is the entry point for your back end. It starts an Express server, enables Cross-Origin Resource Sharing (CORS) so that your React client can call the server, and mounts the routes defined in `routes/restaurant.js` at the `/restaurant` path. You create the `routes/restaurant.js` file in a later step.\n\n#### Set environment variables\n\nRun the following command from the `server` directory to create a file named `config.env`:\n\n\n\n\n\n```bash\ntouch config.env\n```\n\n\n\n\n\n```bash\nNew-Item -ItemType File config.env\n```\n\n\n\n\n\nAdd the following variables to the file:\n\n```none\nMONGODB_URI=\nPORT=5050\n```\n\nReplace the `` placeholder with the connection URI that you saved in a previous step.\n\n#### Connect your server to the database\n\nRun the following commands from the `server` directory to create a new folder named `db` that contains a `connection.js` file:\n\n\n\n\n\n```bash\nmkdir db\ntouch db/connection.js\n```\n\n\n\n\n\n```bash\nmkdir db\nNew-Item -ItemType File db/connection.js\n```\n\n\n\n\n\nPaste the following code into the `connection.js` file:\n\n```js\nimport { MongoClient } from \"mongodb\";\n\nconst uri = process.env.MONGODB_URI || \"\";\nconst client = new MongoClient(uri);\n\ntry {\n// Connect the client to the server\nawait client.connect();\n// Send a ping to confirm a successful connection\nawait client.db(\"admin\").command({ ping: 1 });\nconsole.log(\n \"Pinged your deployment. You successfully connected to MongoDB!\"\n);\n} catch(err) {\n console.error(err);\n}\n\nlet db = client.db(\"sample_restaurants\");\n\nexport default db;\n```\n\nThis file connects to your MongoDB deployment, accesses the `sample_restaurants` database, and tests the database connection. It exports the database connection as `db`. In the next step, the `routes/restaurant.js` file imports this `db` connection from `../db/connection.js` to query the database.\n\n#### Create server API endpoints\n\nRun the following commands from the `server` directory to create a new folder named `routes` that contains a `restaurant.js` file:\n\n\n\n\n\n```bash\nmkdir routes\ntouch routes/restaurant.js\n```\n\n\n\n\n\n```bash\nmkdir routes\nNew-Item -ItemType File routes/restaurant.js\n```\n\n\n\n\n\nPaste the following code into the `restaurant.js` file:\n\n```js\nimport express from \"express\";\nimport db from \"../db/connection.js\";\n\n// Creates an instance of the Express router, used to define our routes\nconst router = express.Router();\n\n// Gets a list of all the restaurants\nrouter.get(\"/\", async (req, res) => {\n let collection = await db.collection(\"restaurants\");\n let results = await collection.find({}).toArray();\n res.send(results).status(200);\n});\n\n// Lists restaurants that match the query filter\nrouter.get(\"/browse\", async (req, res) => {\n try {\n let collection = await db.collection(\"restaurants\");\n let query = {\n borough: \"Queens\",\n name: { $regex: \"Moon\", $options: \"i\" },\n };\n let results = await collection.find(query).toArray();\n res.send(results).status(200);\n } catch (err) {\n console.error(err);\n res.status(500).send(\"Error browsing restaurants\");\n }\n});\n\nexport default router;\n\n```\n\nThis file imports the `db` connection from `db/connection.js`, accesses the `restaurants` collection in the `sample_restaurants` database, and defines the following `GET` endpoints:\n\n- `/`: Retrieves all restaurants from the sample collection\n\n- `/browse`: Retrieves restaurants that match the query criteria, which filters for restaurants in Queens that contain the word `\"Moon\"` in the name"} -{"chunk_id": "6937bee7d1b0fc8b0a85b5c3-2", "page_id": "6937bee7d1b0fc8b0a85b5c3", "source_name": "drivers", "product_name": "MongoDB Drivers", "url": "https://mongodb.com/docs/drivers/node-frameworks/react", "title": "Integrate MongoDB with React", "text": "### Configure the Client\n\nAfter setting up the application's server, follow the steps in this section to configure React and add the client components.\n\n#### Add the React template\n\nNavigate to the `react-quickstart` directory. Then, run the following command to add the React template files by using Vite:\n\n```bash\nnpm create vite@latest client\n```\n\nThis command prompts you to respond to a series of configuration questions. For each question, choose the following responses from the dropdown menu:\n\n- Select a framework: **React**\n\n- Select a variant: **JavaScript**\n\n- Use rolldown-vite (Experimental)?: **No**\n\n- Install with npm and start now?: **No**\n\nAfter running the command, your project has a `client` directory that contains client-side scaffolding.\n\n#### Install Tailwind CSS\n\nThis sample application uses the Tailwind CSS framework for UI formatting. Navigate to the `client` directory, then run the following command to install Tailwind CSS:\n\n```bash\nnpm install tailwindcss @tailwindcss/vite\n```\n\nAfter installing, navigate to your `vite.config.js` file. Add the `@tailwindcss/vite` plugin by updating the import statements and `plugins` array, as shown in the highlighted lines:\n\n```js\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\nimport tailwindcss from '@tailwindcss/vite'\n\n// https://vite.dev/config/\nexport default defineConfig({\nplugins: [\n react(),\n tailwindcss()\n ],\n})\n```\n\nThen, replace the contents of the `client/src/index.css` file with the following import statement:\n\n```css\n@import \"tailwindcss\";\n```\n\n#### Install the React router\n\nTo enable client-side page routing to React, install the `react-router-dom` package by running the following command in the `client` directory:\n\n```bash\nnpm install react-router-dom\n```\n\n#### Set up the React router\n\nNavigate to the `client/src/main.jsx` file and paste the following code:\n\n```js\nimport * as React from \"react\";\nimport * as ReactDOM from \"react-dom/client\";\nimport { createBrowserRouter, RouterProvider } from \"react-router-dom\";\nimport App from \"./App\";\nimport RestaurantList from \"./components/RestaurantList\";\nimport \"./index.css\";\n\nconst router = createBrowserRouter([\n {\n path: \"/\",\n element: ,\n children: [\n {\n path: \"/\",\n element: ,\n },\n ],\n },\n {\n path: \"/browse\",\n element: ,\n children: [\n {\n path: \"/browse\",\n element: ,\n },\n ],\n },\n]);\n\nReactDOM.createRoot(document.getElementById(\"root\")).render(\n \n \n ,\n);\n```\n\nThis file is the entry point for your client. It imports the `App` layout component and the `RestaurantList` component, configures client-side routing, and defines the following routes:\n\n- `/`: Renders the `RestaurantList` component, which calls the `/restaurant/` API endpoint to display all restaurants\n\n- `/browse`: Renders the `RestaurantList` component, which calls the `/restaurant/browse` API endpoint to display filtered restaurants\n\n#### Create the components\n\nRun the following commands from the `client` directory to create a new folder named `components` that contains two files:\n\n\n\n\n\n```bash\nmkdir src/components\ncd src/components\ntouch Navbar.jsx RestaurantList.jsx\n```\n\n\n\n\n\n```bash\nmkdir src/components\ncd src/components\nNew-Item -ItemType File Navbar.jsx\nNew-Item -ItemType File RestaurantList.jsx\n```\n\n\n\n\n\nThe `Navbar.jsx` file configures a navigation bar that links to the required components. Paste the following code into this file:\n\n```js\nimport { NavLink } from \"react-router-dom\";\n\nexport default function Navbar() {\n return (\n
\n \n
\n );\n}\n```\n\nThe `RestaurantList.jsx` file is the viewing component for the restaurants, and it retrieves and displays the restaurant information. It sends requests to the `/restaurant` API endpoints defined in `server/routes/restaurant.js`. Paste the following code into this file:\n\n```js\nimport { useEffect, useState } from \"react\";\nimport { useLocation } from \"react-router-dom\";\n\nconst Restaurant = (props) => (\n \n \n {props.restaurant.name}\n \n \n {props.restaurant.borough}\n \n \n {props.restaurant.cuisine}\n \n \n);\n\nexport default function RestaurantList() {\n const [restaurants, setRestaurants] = useState([]);\n const location = useLocation();\n\n // Fetches the restaurants from the database\n useEffect(() => {\n async function getRestaurants() {\n // Determines which endpoint to call based on current route\n const endpoint =\n location.pathname === \"/browse\"\n ? \"http://localhost:5050/restaurant/browse\"\n : \"http://localhost:5050/restaurant/\";\n\n const response = await fetch(endpoint);\n if (!response.ok) {\n const message = `An error occurred: ${response.statusText}`;\n console.error(message);\n return;\n }\n const restaurants = await response.json();\n setRestaurants(restaurants);\n }\n getRestaurants();\n return;\n }, [location.pathname]);\n\n // Maps each restaurant on the table\n function restaurantList() {\n return restaurants.map((restaurant) => {\n return ;\n });\n }\n\n // Retrieves the dynamic title based on current route\n const getTitle = () => {\n return location.pathname === \"/browse\"\n ? 'Filtered Restaurants (Queens, containing \"Moon\")'\n : \"All Restaurants\";\n };\n\n // Displays the restaurants table\n return (\n <>\n

{getTitle()}

\n
\n
\n \n \n \n \n \n \n \n \n \n {restaurantList()}\n \n
\n Name\n \n Borough\n \n Cuisine\n
\n
\n
\n \n );\n}\n```\n\nFinally, navigate to the `client/src/App.jsx` file. This file is the main layout component, and it ensures that the `Navbar` component renders at the top of each page above the child component. Paste the following code into this file:\n\n```js\nimport { Outlet } from \"react-router-dom\";\nimport Navbar from \"./components/Navbar\";\n\nconst App = () => {\n return (\n
\n \n \n
\n );\n};\nexport default App;\n```"} -{"chunk_id": "6937bee7d1b0fc8b0a85b5c3-3", "page_id": "6937bee7d1b0fc8b0a85b5c3", "source_name": "drivers", "product_name": "MongoDB Drivers", "url": "https://mongodb.com/docs/drivers/node-frameworks/react", "title": "Integrate MongoDB with React", "text": "### Run Your Application\n\nFinally, follow the steps in this section to run your application and view the rendered restaurant data.\n\n#### Run the server application\n\nNavigate to the `react-quickstart/server` directory and run the following command to start the server:\n\n```bash\nnode --env-file=config.env server\n```\n\nIf successful, this command outputs the following information:\n\n```bash\nPinged your deployment. You successfully connected to MongoDB!\nServer listening on port 5050\n```\n\n#### Run the client application\n\nIn a separate terminal window, navigate to the `react-quickstart/client` directory. Run the following command to start the React client:\n\n```bash\nnpm run dev\n```\n\nIf successful, this command outputs the following information:\n\n```bash\nVITE v7.2.4 ready in 298 ms\n\n\u279c Local: http://localhost:5173/\n\u279c Network: use --host to expose\n\u279c press h + enter to show help\n```\n\n#### Open the application site\n\nOpen the http://localhost:5173/ URL, retrieved from the preceding step. The initial landing page displays a list all restaurants in the `sample_restaurants.restaurants` collection:\n\nThen, navigate to the http://localhost:5173/browse URL to view the restaurants that match the `name` and `borough` field query:\n\nCongratulations on completing the Quick Start tutorial!\n\nAfter you complete these steps, you have a React web application that connects to your MongoDB deployment, runs a query on sample restaurant data, and renders a retrieved result.\n\n## Troubleshooting\n\nIf you encounter issues while completing this tutorial, review the following common problems and solutions.\n\n### Connection Errors\n\nIf the server terminal prints a connection error instead of the `Pinged your deployment.` message, verify the following:\n\n- The `MONGODB_URI` value in your `config.env` file matches the connection string from Atlas and includes your database username and password.\n\n- You loaded the `sample_restaurants` dataset into your cluster.\n\n### CORS Errors\n\nIf your browser console shows a CORS error when the client requests data, confirm that your `server.js` file calls `app.use(cors())` before the route definitions.\n\n### No Data Displays\n\nIf the web page loads but no restaurants appear, confirm that both the server and the client are running at the same time in separate terminal windows. The React client fetches data from the server at `http://localhost:5050`, so the server must be running for data to display.\n\n### Port Conflicts\n\nIf the server fails to start because port `5050` is already in use, change the `PORT` value in your `config.env` file. If you change the server port, update the endpoint URLs in `RestaurantList.jsx` to match. If the client port `5173` is in use, Vite automatically selects the next available port and prints the URL in the terminal.\n\n## Additional Resources\n\nTo learn more about React, MongoDB, and the MERN stack, view the following resources:\n\n- React documentation\n\n- Express documentation\n\n- Node.js driver documentation"} -{"chunk_id": "69609dbf89ef050357dbe5cf-0", "page_id": "69609dbf89ef050357dbe5cf", "source_name": "drivers", "product_name": "MongoDB Drivers", "url": "https://mongodb.com/docs/drivers/node-frameworks/tanstack", "title": "Integrate MongoDB with TanStack Start", "text": "# Integrate MongoDB with TanStack Start\n\n## Overview\n\nThis guide demonstrates how to build a modern web application with TanStack Start and MongoDB. TanStack Start is a full-stack framework that integrates frontend and backend development by using React and popular libraries like TanStack Router and TanStack Query from the TanStack ecosystem.\n\nThe application in this tutorial consists of the following layers:\n\n- **Database Layer**: MongoDB stores and retrieves data.\n\n- **Server Layer**: TanStack Start provides the API endpoints and logic to connect your frontend to your MongoDB database.\n\n- **Data Management Layer**: TanStack Query manages server-side state on the frontend, unifying the logic for data fetching, loading states, and error handling.\n\n- **Presentation Layer**: React implements the UI by using the TanStack Query data.\n\n### Why Use MongoDB in a TanStack Start Application?\n\nMongoDB's document model stores data as JSON-like documents, making it easy to work with JavaScript objects without complex mapping. This aligns with TanStack Start's React components and TypeScript interfaces.\n\nTanStack Query handles the data layer efficiently by caching MongoDB responses, managing loading states, and synchronizing data across components. This eliminates manual state management and reduces redundant database calls.\n\nThis combination works well for applications that need the following features:\n\n- Flexible data structures that can evolve over time\n\n- Real-time data updates with minimal client-side code\n\n- Type safety from database to UI\n\n- Efficient caching and background data synchronization\n\n## Quick Start Tutorial\n\nThis tutorial guides you through building a TanStack Start application that integrates with MongoDB. The application accesses sample restaurant data and displays the results on a locally hosted site. It includes instructions on connecting your MongoDB cluster hosted on MongoDB Atlas and accessing and displaying information from your database.\n\nIf you prefer to connect to MongoDB by using the Node.js driver without TanStack Start, see the Get Started with the Node.js Driver guide.\n\n### Set Up Your Project\n\nFollow the steps in this section to install project dependencies, create an Atlas cluster, and set up the application directories.\n\n#### Verify the prerequisites\n\nTo create the Quick Start application, ensure you have the following software installed:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nPrerequisite\n\n\nNotes\n\n
\nNode.js\n\n\nUse version 20 or later.\n\n
\nCode Editor\n\n\nThis tutorial uses Visual Studio Code, but you can use the editor of your choice.\n\n
\nTerminal\n\n\nFor MacOS users, use Terminal or similar app. For Windows users, use PowerShell.\n\n
\n\n#### Create a MongoDB Atlas cluster\n\nMongoDB Atlas is a fully managed cloud database service that hosts your MongoDB deployments. If you do not have a MongoDB deployment, create a free cluster (no credit card required) by completing the MongoDB Get Started tutorial. The MongoDB Get Started tutorial also demonstrates how to load sample databases into your cluster, including the `sample_restaurants` database that is used in this tutorial.\n\nTo connect to your cluster, you must use a **connection URI**. To retrieve your connection URI, follow the instructions in the Connect to Your Cluster tutorial in the Atlas documentation.\n\nSave your connection URI in a secure location.\n\n#### Create the project skeleton\n\nUse the official TanStack Start CLI to initialize the project skeleton. Open your terminal and navigate to your desired project directory.\n\nRun the initialization command:\n\n```bash\nnpm create @tanstack/start@latest\n```\n\n##### Configuration Prompts\n\nThe installation wizard guides you through the setup. Select the following options:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nPrompt\n\n\nInput\n\n\nAction\n\n
\nWhat would you like to name your project?\n\n\nYour desired project name\n\n\nType the name, press Enter\n\n
\nWould you like to use Tailwind CSS?\n\n\nYes\n\n\nType Y, press Enter\n\n
\nSelect a toolchain\n\n\nDefault (None)\n\n\nSelect None, press Enter\n\n
\nSelect your deployment adapter\n\n\nDefault: (Nitro)\n\n\nPress Enter\n\n
\nWhat add-ons would you like for your project?\n\n\nNone\n\n\nPress Enter (TanStack Query will be installed manually)\n\n
\nWould you like any examples?\n\n\nNone\n\n\nPress Enter\n\n
After installation completes, navigate into your project directory.\n\n#### Configure Vite for MongoDB compatibility\n\nTanStack Start uses Vite as the build tool. By default, Vite attempts to bundle dependencies for the browser. However, the Node.js Driver relies on `mongodb-client-encryption`, a server-side native module that causes errors when Vite bundles it for browser environments.\n\nTo prevent this, configure Vite to exclude the `mongodb-client-encryption` module from optimization and server-side rendering.\n\nNavigate to `vite.config.ts` in your project root and replace the contents with the following code:\n\n```typescript\nimport { defineConfig } from 'vite'\nimport { devtools } from '@tanstack/devtools-vite'\nimport { tanstackStart } from '@tanstack/react-start/plugin/vite'\nimport viteReact from '@vitejs/plugin-react'\nimport viteTsConfigPaths from 'vite-tsconfig-paths'\nimport tailwindcss from '@tailwindcss/vite'\nimport { nitro } from 'nitro/vite'\n\nconst config = defineConfig({\n plugins: [\n devtools(),\n nitro(),\n // this is the plugin that enables path aliases\n viteTsConfigPaths({\n projects: ['./tsconfig.json'],\n }),\n tailwindcss(),\n tanstackStart(),\n viteReact(),\n ],\n optimizeDeps: {\n // Exclude this server-side dependency to avoid bundling errors\n exclude: ['mongodb-client-encryption'],\n },\n ssr: {\n // Ensure this module is externalized during server-side rendering\n external: ['mongodb-client-encryption'],\n },\n})\n\nexport default config\n```\n\n#### Install MongoDB & TanStack Query\n\nInstall the Node.js Driver to allow the server code to connect to the database and install TanStack Query to manage data fetching on the frontend.\n\nRun the following command in your project root:\n\n```bash\nnpm install mongodb @tanstack/react-query\n```\n\n#### Clean up the project structure\n\nThe installation wizard created files you do not need. To keep the project clean and avoid auto-import confusion, delete the `data` and `demo` directories.\n\nRun the following commands in your project root:\n\n```bash\nrm -rf src/data\nrm -rf src/routes/demo\n```"} -{"chunk_id": "69609dbf89ef050357dbe5cf-1", "page_id": "69609dbf89ef050357dbe5cf", "source_name": "drivers", "product_name": "MongoDB Drivers", "url": "https://mongodb.com/docs/drivers/node-frameworks/tanstack", "title": "Integrate MongoDB with TanStack Start", "text": "### Configure the Back End\n\nAfter setting up the project structure, follow the steps in this section to set up the backend.\n\n#### Configure your environment variable\n\nCreate a `.env` file at the root of your project to securely store your connection URI.\n\nRun the following command in your project root:\n\n```bash\ntouch .env\n```\n\nOpen the `.env` file and add your connection URI:\n\n```bash\nMONGODB_URI=\n```\n\nReplace `` with the connection URI you received from MongoDB Atlas.\n\n#### Create the database connection\n\nCreate a dedicated TypeScript file to initialize the MongoDB client.\n\nRun the following commands in your project root to create the file structure:\n\n```bash\nmkdir -p src/lib\ntouch src/lib/db.ts\n```\n\nOpen `src/lib/db.ts` and paste the following code:\n\n```typescript\nimport { MongoClient } from \"mongodb\"\n\n// Connection string from the MongoDB atlas dashboard\nconst uri = process.env.MONGODB_URI\n\nlet connected = false\nlet client: MongoClient\n\nexport async function connectToDatabase() {\n if (!uri) {\n throw new Error(\"MONGODB_URI is not defined in environment variables\")\n }\n\n if (!connected) {\n try {\n client = new MongoClient(uri)\n await client.connect()\n connected = true\n } catch (error) {\n throw new Error(`Failed to connect to database: ${error instanceof Error ? error.message : 'Unknown error'}`)\n }\n }\n return client.db(\"sample_restaurants\")\n}\n```\n\nThis file contains the `connectToDatabase()` function that connects to your MongoDB cluster, and to the `sample_restaurants` database. The `sample_restaurants` database contains restaurant data from New York City including fields like restaurant name, cuisine type, borough, and address information.\n\n#### Create the server functions\n\nTanStack Start uses server functions to run code securely on the server. Create a dedicated file to handle the database queries.\n\nRun the following commands in your project root to create a `restaurants.ts` file:\n\n```bash\nmkdir -p src/server\ntouch src/server/restaurants.ts\n```\n\nOpen `src/server/restaurants.ts` and paste the following code:\n\n```typescript\nimport { createServerFn } from \"@tanstack/react-start\"\nimport { connectToDatabase } from \"../lib/db\"\n\nexport interface Restaurant {\n _id: string\n address: {\n building: string\n coord: [number, number]\n street: string\n zipcode: string\n }\n borough: string\n cuisine: string\n name: string\n restaurant_id: string\n}\n\n// Gets a list of all restaurants from the database\nexport const getAllRestaurants = createServerFn({ method: 'GET'})\n.handler(async () => {\n const db = await connectToDatabase()\n const restaurants = await db\n .collection(\"restaurants\")\n .find({})\n .limit(100)\n .toArray()\n return restaurants.map((restaurant) => ({\n ...restaurant,\n _id: restaurant._id.toString(),\n }))\n})\n\n// Gets a list of restaurants in Queens with \"Moon\" in the name\nexport const getRestaurantsByBorough = createServerFn({ method: 'GET'})\n.handler(async () => {\n const db = await connectToDatabase()\n const restaurants = await db\n .collection(\"restaurants\")\n .find({\n borough: 'Queens',\n name: {$regex: 'Moon', $options: 'i'} // case-insensitive match\n })\n .limit(100)\n .toArray()\n // Convert ObjectId to string for client-side serialization\n return restaurants.map((restaurant) => ({\n ...restaurant,\n _id: restaurant._id.toString(),\n }))\n })\n```\n\nThis file contains two functions, `getAllRestaurants()` and `getRestaurantsByBorough()`. These two functions query your MongoDB cluster and return the requested data."} -{"chunk_id": "69609dbf89ef050357dbe5cf-2", "page_id": "69609dbf89ef050357dbe5cf", "source_name": "drivers", "product_name": "MongoDB Drivers", "url": "https://mongodb.com/docs/drivers/node-frameworks/tanstack", "title": "Integrate MongoDB with TanStack Start", "text": "### Configure the Front End\n\nAfter setting up the database and server layer, follow the steps in this section to complete the data management and presentation layer.\n\n#### Create the header component\n\nNavigate to `src/components/Header.tsx` and replace the content with the following code:\n\n```react\nimport { Link } from \"@tanstack/react-router\"\n\nexport function Header() {\n return(\n <>\n \n \n )\n}\n```\n\nThis component renders the header above the restaurant results, and contains the browse link and logo. These allow you to navigate between routes.\n\n#### Create the restaurant list component\n\nRun the following command from your project root to create the `RestaurantList` component:\n\n```bash\ntouch src/components/RestaurantList.tsx\n```\n\nPaste the following code into `src/components/RestaurantList.tsx`:\n\n```react\nimport {Restaurant} from \"../server/restaurants\"\n\ntype Props = {\n restaurants: Restaurant[]\n}\n\nexport function RestaurantList({restaurants}: Props) {\n return (\n
\n \n \n \n \n \n \n \n \n \n {restaurants.map((restaurant) => (\n \n \n \n \n \n ))}\n \n
NameBoroughCuisine
{restaurant.name}{restaurant.borough}{restaurant.cuisine}
\n
\n )\n}\n```\n\nThis component handles the display of the restaurants. The query data is handled as props, and the props are displayed within a table.\n\n#### Configure application routing\n\nNavigate to `src/routes/__root.tsx`. Replace the contents of `__root.tsx` with the following code:\n\n```react\nimport { HeadContent, Scripts, createRootRoute, Outlet } from '@tanstack/react-router'\nimport { QueryClient, QueryClientProvider } from '@tanstack/react-query'\nimport '../styles.css'\nimport {Header} from '../components/Header'\n\n//Configure TanStack Query Client with cache and retry options\nconst queryClient = new QueryClient({\n defaultOptions: {\n queries: {\n staleTime: 60 * 1000, // Data stays fresh for one minute\n retry: 1, // Retry failed requests once\n retryDelay: 1000 // Wait one second before retrying\n },\n },\n})\n\nexport const Route = createRootRoute({\n component: () => (\n \n \n \n \n \n \n
\n
\n \n
\n \n \n \n \n ),\n // Handle 404 errors for non-existent routes\n notFoundComponent: () => {\n return (\n
\n

404 - Page Not Found

\n

The page you're looking for doesn't exist.

\n
\n )\n }\n})\n```\n\nThis file is a wrapper around your entire application. The code uses a `QueryClientProvider` to ensure TanStack Query manages the data state.\n\n#### Configure the home page\n\nNavigate to `src/routes/index.tsx`. Replace the contents of `index.tsx` with the following code:\n\n```react\nimport { createFileRoute } from \"@tanstack/react-router\";\nimport {useSuspenseQuery} from '@tanstack/react-query'\nimport { RestaurantList } from \"../components/RestaurantList\";\nimport { getAllRestaurants } from \"../server/restaurants\";\n\nexport const Route = createFileRoute('/')({\n component: Home,\n pendingComponent: () => (\n
\n Loading restaurants...\n
\n ),\n errorComponent: ({error}) => (\n
\n

Connection Error

\n

{error.message}

\n

Please check your MongoDB connection string in your .env file

\n
\n ),\n})\n\nfunction Home() {\n const{data: restaurants} = useSuspenseQuery({\n queryKey:['restaurants'],\n queryFn: () => getAllRestaurants(),\n })\n return (\n
\n

All Restaurants

\n \n
\n )\n}\n```\n\nThis route displays the results of the `getAllRestaurants()` by using the `Header` and `RestaurantList` components.\n\n#### Create the browse page\n\nRun the following command from your project root to create the `browse.tsx` route.\n\n```bash\ntouch src/routes/browse.tsx\n```\n\nPaste the following code into `src/routes/browse.tsx`:\n\n```react\nimport { createFileRoute } from '@tanstack/react-router'\nimport { useSuspenseQuery } from '@tanstack/react-query'\nimport { RestaurantList } from '../components/RestaurantList'\nimport { getRestaurantsByBorough } from '../server/restaurants'\n\nexport const Route = createFileRoute('/browse')({\n component: BrowsePage,\n // Display error UI if MongoDB connection or query fails\n errorComponent: ({ error }) => (\n
\n

Connection Error

\n

{error.message}

\n

\n Please check your MongoDB connection string in your .env file\n

\n
\n ),\n})\n\nfunction BrowsePage() {\n // Fetch filtered restaurants using TanStack Query\n // Query includes borough and search term in the key for proper caching\n const { data: restaurants } = useSuspenseQuery({\n queryKey: ['restaurants', 'queens', 'moon'], // Unique cache key for this filtered query\n queryFn: () => getRestaurantsByBorough(), // Server function with MongoDB filter\n })\n\n return (\n
\n

\n Queens Restaurants with \"Moon\" in the Name\n

\n \n
\n )\n}\n```\n\nThis page displays a filtered query of the `sample_restaurants` database. It displays all the restaurants in Queens with `Moon` in their name. It also uses the `Header` and `RestaurantList` components."} -{"chunk_id": "69609dbf89ef050357dbe5cf-3", "page_id": "69609dbf89ef050357dbe5cf", "source_name": "drivers", "product_name": "MongoDB Drivers", "url": "https://mongodb.com/docs/drivers/node-frameworks/tanstack", "title": "Integrate MongoDB with TanStack Start", "text": "You may have red underline warnings in your IDE on the `createFileRoute` lines until you run the server. This is normal. TanStack Router generates the necessary TypeScript type definitions for your routes when you first run the application with `npm run dev`. After the server starts, the warnings will disappear.\n\n#### Verify your file structure\n\nBefore continuing, ensure your file tree closely matches the structure below. You can safely ignore any additional project files.\n\n```text\nyour-app/\n\u251c\u2500 node_modules/\n\u251c\u2500 public/\n\u251c\u2500 src/\n\u2502 \u251c\u2500 components/\n\u2502 \u2502 \u251c\u2500 Header.tsx <-- Logo and browse link\n\u2502 \u2502 \u251c\u2500 RestaurantList.tsx <-- Table that displays results of DB query\n\u2502 \u251c\u2500 routes/\n\u2502 \u2502 \u251c\u2500 __root.tsx <-- Application wrapper\n\u2502 \u2502 \u251c\u2500 browse.tsx <-- Browse page, holds results of getRestaurantsByBorough()\n\u2502 \u2502 \u251c\u2500 index.tsx <-- Home page, holds results of getAllRestaurants()\n\u2502 \u251c\u2500 server/\n\u2502 \u2502 \u251c\u2500 restaurants.ts <--- Server functions\n\u2502 \u251c\u2500 lib/\n\u2502 \u2502 \u251c\u2500 db.ts <--- Database connection\n\u251c\u2500 .env <-- Connection URI\n```\n\n### Run Your Application\n\nFollow the remaining steps to start the server and view the rendered restaurant data.\n\n#### Start the server\n\nRun the following command in your project root to start the development server:\n\n```bash\nnpm run dev\n```\n\nIf successful, the command outputs the following information in the terminal:\n\n```text\nVITE v7.2.4 ready in 939 ms\n\n\u279c Local: http://localhost:3000/\n\u279c Network: use --host to expose\n\u279c press h + enter to show help\n```\n\n#### Open the application\n\nOpen `http://localhost:3000/` in your browser. The initial landing page displays all of the restaurants in the `sample_restaurants` database.\n\n#### View the browse page\n\nClick the Browse link in the header to view a filtered list of restaurants in Queens with `Moon` in the name.\n\nCongratulations on completing the Quick Start tutorial!\n\nAfter you complete these steps, you will have a TanStack Start application that connects to your MongoDB deployment, runs queries on sample restaurant data, and renders the results with real-time reactivity.\n\n## Additional Resources\n\nTo learn more about TanStack Start, the TanStack ecosystem and MongoDB, view the following resources:\n\n- TanStack Start documentation\n\n- TanStack documentation\n\n- Node.js driver documentation"} -{"chunk_id": "6a514d22d727379c91b99eac-0", "page_id": "6a514d22d727379c91b99eac", "source_name": "entity-framework", "product_name": "MongoDB Entity Framework Provider", "url": "https://mongodb.com/docs/entity-framework/current/interact-data/write-data", "title": "Write Data to MongoDB", "text": "# Write Data to MongoDB\n\n## Overview\n\nEntity Framework Core allows you to work with data in your application without explicitly running database commands. You can insert, update, or delete data within your application and persist those changes to MongoDB by using the `SaveChanges()` or `SaveChangesAsync()` method.\n\nWhen you call the `SaveChanges()` or `SaveChangesAsync()` method, the EF Core Provider automatically detects any changes made to your data and runs the necessary commands to update the database by using the MongoDB Query API.\n\nIn this guide, you can see examples of how to perform common write operations on an application configured to use the EF Core Provider.\n\nTo learn how to configure an application to use the EF Core Provider, see Configure the EF Core Provider.\n\n## Transactional Write Operations\n\nThe `SaveChanges()` and `SaveChangesAsync()` methods are transactional by default. This means that if an error occurs during an operation, the provider rolls back any changes made to the database. Because of this, your application must be connected to a transaction-capable deployment of MongoDB server, such as a replica set.\n\nYou can disable automatic transactions in the `SaveChanges()` and `SaveChangesAsync()` methods by setting the `AutoTransactionBehavior` property to `AutoTransaction.Never` on your `DbContext` subclass during application setup. However, we do not recommend disabling this feature. Doing so causes any concurrency changes or operation failures during the save operation to leave the database in an inconsistent state.\n\nThe following example shows how to disable automatic transactions in the `SaveChanges()` and `SaveChangesAsync()` methods:\n\n```csharp\ndbContext.Database.AutoTransactionBehavior = AutoTransactionBehavior.Never;\n```\n\nDisabling automatic transactions can lead to data inconsistencies. We recommend that you do not disable this feature.\n\n## Insert\n\nYou can use the `Add()` method to insert a single entity into your collection, or you can use the `AddRange()` method to insert multiple entities at once.\n\n### Insert One Entity\n\nThe `Add()` method accepts a single entity of the same type that you specified on the `DbSet` instance that you are modifying.\n\nThe following code uses the `Add()` method to add a new `Planet` object to the `DbSet` called `Planets`. It then calls the `SaveChanges()` method to insert that entity into the MongoDB collection.\n\n```csharp\ndb.Planets.Add(new Planet()\n{\n name = \"Pluto\",\n hasRings = false,\n orderFromSun = 9\n});\n\ndb.SaveChanges();\n\n```\n\n### Insert Multiple Entities\n\nThe `AddRange()` method accepts an array of entities that you want to add to the `DbSet`.\n\nThe following code uses the `AddRange()` method to add an array of `Planet` objects to the `DbSet` called `Planets`. It then calls the `SaveChanges()` method to insert those entities into the MongoDB collection.\n\n```csharp\nvar planets = new[]\n{\n new Planet()\n {\n _id = ObjectId.GenerateNewId(),\n name = \"Pluto\",\n hasRings = false,\n orderFromSun = 9\n },\n new Planet()\n {\n _id = ObjectId.GenerateNewId(),\n name = \"Scadrial\",\n hasRings = false,\n orderFromSun = 10\n }\n};\n\ndb.Planets.AddRange(planets);\ndb.SaveChanges();\n\n```\n\n## Update\n\nTo update an entity, first retrieve the entity that you want to update. Then make the changes to that entity. The provider tracks any changes made to the entity, such as setting properties or adding and removing items from fields with list values. To save the update to MongoDB, call the `SaveChanges()` method. The EF Core Provider compares the updated entity with a snapshot of the entity before the change and automatically updates the collection by using the MongoDB Query API.\n\nThe following code retrieves an entity in which the `name` value is `\"Mercury\"`, then updates the `name` field. The code then calls the `SaveChanges()` method to persist that change to the collection.\n\n```csharp\nvar planet = db.Planets.FirstOrDefault(p => p.name == \"Mercury\");\nplanet!.name = \"Mercury the first planet\";\n\ndb.SaveChanges();\n\n```\n\n## Delete\n\nYou can use the `Remove()` method to delete a single entity from your collection, or the `RemoveRange()` method to delete multiple entities at once.\n\n### Delete One Entity\n\nThe `Remove()` method accepts a single entity of the same type that you specified on the `DbSet` instance that you are modifying.\n\nThe following code removes a `Planet` entity in which the `name` value is `\"Pluto\"`. It then calls the `SaveChanges()` method to delete that entity from the MongoDB collection.\n\n```csharp\nvar planet = db.Planets.FirstOrDefault(p => p.name == \"Pluto\");\ndb.Planets.Remove(planet!);\n\ndb.SaveChanges();\n\n```\n\n### Delete Multiple Entities\n\nThe `RemoveRange()` method accepts an array of entities to remove from the `DbSet`.\n\nThe following code finds two `Planet` entities and adds them to an array. It then uses the `RemoveRange()` method to remove both entities from the `DbSet`. Finally, it uses the `SaveChanges()` method to remove those entities from the MongoDB collection.\n\n```csharp\nvar pluto = db.Planets.FirstOrDefault(p => p.name == \"Pluto\");\nvar scadrial = db.Planets.FirstOrDefault(p => p.name == \"Scadrial\");\nvar planets = new[] { pluto!, scadrial! };\ndb.Planets.RemoveRange(planets);\n\ndb.SaveChanges();\n\n```\n\n## Additional Information\n\nTo learn more about the methods discussed in this guide, see the following .NET API documentation links:\n\n- SaveChanges()\n\n- Add()\n\n- AddRange()\n\n- Remove()\n\n- RemoveRange()"} -{"chunk_id": "6a514d22d727379c91b99e9a-0", "page_id": "6a514d22d727379c91b99e9a", "source_name": "entity-framework", "product_name": "MongoDB Entity Framework Provider", "url": "https://mongodb.com/docs/entity-framework/current/interact-data/queryable-encryption", "title": "Configure Queryable Encryption", "text": "# Configure Queryable Encryption\n\nIn this guide, you can learn how to use the EF Core Provider to encrypt specific document fields by using **Queryable Encryption (QE)**.\n\n## Overview\n\nQueryable Encryption encrypts sensitive document fields at the application layer before writing data to MongoDB, while still allowing your application to query those fields. Only applications that have access to your encryption keys can read the plaintext data. If an attacker gains access to the database, they can only see only ciphertext because they lack access to the encryption keys.\n\nFor example, you can use Queryable Encryption to encrypt fields that contain:\n\n- Social Security numbers\n\n- Credit card numbers\n\n- Health or medical information\n\n- Financial information\n\n- Any other sensitive or personally identifiable information\n\nThe EF Core Provider supports Queryable Encryption through a fluent model API. You configure which entity properties to encrypt by using the `OnModelCreating()` method, and the provider handles encryption automatically when reading and writing data.\n\n### Prerequisites\n\nBefore configuring Queryable Encryption with the EF Core Provider, ensure that you have the following:\n\n- A MongoDB Enterprise or MongoDB Atlas cluster running MongoDB 7.0 or later.\n\n- Access to a Key Management Service (KMS). Supported KMS providers include Amazon Web Services, Azure, Google Cloud Platform, the Key Management Interoperability Protocol (KMIP), and local key providers.\n\n- The Automatic Encryption Shared Library (`CRYPT_SHARED`) or `mongocryptd` installed in your environment. To learn how to install the shared library, see Install a Query Analysis Component in the MongoDB Server documentation.\n\n## Enable Queryable Encryption\n\nThe following sections describe how to configure encryption options on your context and mark entity properties for encryption in your model:\n\n### Configure Encryption Options\n\nBefore you configure any context that uses Queryable Encryption, you must register the automatic encryption provider once for your application by running the following code:\n\n```csharp\nMongoClientSettings.Extensions.AddAutoEncryption();\n\n```\n\nThen, create a `MongoOptionsExtension` instance and chain the following methods before passing the instance to the `UseMongoDB()` method:\n\n- `WithKmsProviders()` \u2014 specifies your KMS provider and credentials.\n\n- `WithKeyVaultNamespace()` \u2014 specifies the collection used to store data encryption keys.\n\n- `WithCryptProvider()` \u2014 specifies the encryption library to use and its path.\n\nThe following example configures a local KMS provider for development use:\n\n```csharp\nvar kmsProviders = new Dictionary<\n string, IReadOnlyDictionary>\n{\n {\n \"local\",\n new Dictionary\n {\n { \"key\", localMasterKey }\n }\n }\n};\n\nvar keyVaultNamespace = CollectionNamespace.FromFullName(\n \"encryption.__keyVault\");\n\nvar mongoOptions = new MongoOptionsExtension()\n .WithConnectionString(connectionString)\n .WithDatabaseName(\"myDatabase\")\n .WithKmsProviders(kmsProviders)\n .WithKeyVaultNamespace(keyVaultNamespace)\n .WithCryptProvider(\n CryptProvider.AutoEncryptSharedLibrary,\n Environment.GetEnvironmentVariable(\"CRYPT_SHARED_LIB_PATH\"));\n\nvar optionsBuilder = new DbContextOptionsBuilder()\n .UseMongoDB(mongoOptions);\n\n```\n\nTo use `mongocryptd` instead of the shared library, pass `CryptProvider.Mongocryptd` and the path to the `mongocryptd` binary to the `WithCryptProvider()` method.\n\nDo not use a local KMS provider in production. Without a remote KMS, you risk unauthorized access to the master key or permanent loss of the key needed to decrypt your data.\n\n### Mark Fields for Encryption\n\nIn the `OnModelCreating()` method, call an encryption method on each property you want to encrypt. The method you choose controls which query types are available on that field:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nMethod\n\n\nQuery support\n\n\nNotes\n\n
\n`IsEncrypted(dataKeyId)`\n\n\nNone\n\n\nEncrypts the field without query support. Use for fields you store but never filter on directly.\n\n
\n`IsEncryptedForEquality(dataKeyId)`\n\n\nEquality (`==`)\n\n\nNot available for `Decimal128`, `Double`, `Document`, or `Array` BSON storage types.\n\n
\n`IsEncryptedForRange(min, max, dataKeyId)`\n\n\nRange (`>`, `<`, `>=`, `<=`)\n\n\nSupported only for `DateTime`, `Decimal128`, `Double`, `Int32`, and `Int64` BSON storage types.\n\n
To encrypt an owned entity rather than a scalar property, call `IsEncrypted(dataKeyId)` on the `OwnedNavigationBuilder` or `OwnershipBuilder` returned from `OwnsOne()` or `OwnsMany()`.\n\nFor a complete example that uses the preceding methods, see the Example: Encrypt Patient Data section.\n\n## Example: Encrypt Patient Data\n\nThe following `Patient` entity defines the document model, with the `SSN` and `DateOfBirth` fields to encrypt:\n\n```csharp\npublic class Patient\n{\n public ObjectId Id { get; set; }\n public string Name { get; set; } = null!;\n public string SSN { get; set; } = null!;\n public DateTime DateOfBirth { get; set; }\n}\n\n```\n\nThe following `HospitalContext` marks those fields for encryption in the `OnModelCreating()` method. `SSN` is encrypted without query support, and `DateOfBirth` is encrypted with range query support. The constructor accepts the IDs of two data encryption keys, which you create in your key vault before you initialize the context:\n\n```csharp\npublic class HospitalContext : DbContext\n{\n public DbSet Patients { get; set; } = null!;\n private readonly Guid _ssnDataKeyId;\n private readonly Guid _dobDataKeyId;\n\n public HospitalContext(\n DbContextOptions options,\n Guid ssnDataKeyId,\n Guid dobDataKeyId)\n : base(options)\n {\n _ssnDataKeyId = ssnDataKeyId;\n _dobDataKeyId = dobDataKeyId;\n }\n\n protected override void OnModelCreating(ModelBuilder modelBuilder)\n {\n base.OnModelCreating(modelBuilder);\n modelBuilder.Entity(entity =>\n {\n entity.ToCollection(\"patients\");\n entity.Property(p => p.SSN)\n .IsEncrypted(_ssnDataKeyId);\n\n entity.Property(p => p.DateOfBirth)\n .IsEncryptedForRange(\n new DateTime(1900, 1, 1),\n new DateTime(2100, 12, 31),\n _dobDataKeyId);\n });\n }\n}\n\n```\n\nThe following code configures the encryption options, instantiates the `HospitalContext` with the data key IDs, and inserts and queries a `Patient` document:\n\n```csharp\nvar mongoOptions = new MongoOptionsExtension()\n .WithConnectionString(\"\")\n .WithDatabaseName(\"hospitalDb\")\n .WithKmsProviders(kmsProviders)\n .WithKeyVaultNamespace(keyVaultNamespace)\n .WithCryptProvider(\n CryptProvider.AutoEncryptSharedLibrary,\n Environment.GetEnvironmentVariable(\"CRYPT_SHARED_LIB_PATH\"));\n\nusing var context = new HospitalContext(\n new DbContextOptionsBuilder()\n .UseMongoDB(mongoOptions)\n .Options,\n ssnDataKeyId,\n dobDataKeyId);\n\ncontext.Database.EnsureCreated();\ncontext.Patients.Add(new Patient\n{\n Name = \"John Doe\",\n SSN = \"123-45-6789\",\n DateOfBirth = new DateTime(1985, 6, 15)\n});\ncontext.SaveChanges();\n\nvar results = context.Patients\n .Where(p => p.DateOfBirth > new DateTime(1980, 1, 1))\n .ToList();\n\n```"} -{"chunk_id": "6a514d22d727379c91b99e9a-1", "page_id": "6a514d22d727379c91b99e9a", "source_name": "entity-framework", "product_name": "MongoDB Entity Framework Provider", "url": "https://mongodb.com/docs/entity-framework/current/interact-data/queryable-encryption", "title": "Configure Queryable Encryption", "text": "## Server-Side Schema Support\n\nBy default, the EF Core Provider applies your field encryption configuration only to the client. Client-only encryption is appropriate during development, when your encryption schema may still be evolving.\n\nFor production deployments, register the encryption schema on the server when you create the collection. Once the server holds the schema, it enforces encryption independently of the client configuration, protecting against accidental plaintext writes from misconfigured clients. After registering the schema on the server, you cannot change which fields are encrypted without recreating the collection.\n\nTo create a collection with a server-side schema, pass your context's `Model` to `QueryableEncryptionSchemaGenerator.GenerateSchemas()`. Then, pass the result to the `CreateCollection()` method, as shown in the following example:\n\n```csharp\nvar encryptedSchemas =\n QueryableEncryptionSchemaGenerator.GenerateSchemas(\n context.Model);\n\nusing var client = new MongoClient(\n \"\");\nvar database = client.GetDatabase(\"hospitalDb\");\n\nforeach (var entityType in context.Model\n .GetEntityTypes()\n .Where(e => e.IsDocumentRoot()))\n{\n var collectionName = entityType.GetCollectionName();\n if (encryptedSchemas.TryGetValue(\n collectionName, out var schema))\n {\n database.CreateCollection(\n collectionName,\n new CreateCollectionOptions\n {\n EncryptedFields = schema\n });\n }\n}\n\ncontext.Database.EnsureCreated();\n\n```\n\nAfter the encrypted collection exists on the server, you can configure new context instances to use only the server schema. Set `QueryableEncryptionSchemaMode.Ignore` on the `MongoOptionsExtension`, as shown in the following example:\n\n```csharp\nvar mongoOptions = new MongoOptionsExtension()\n .WithConnectionString(\"\")\n .WithDatabaseName(\"hospitalDb\")\n .WithKmsProviders(kmsProviders)\n .WithKeyVaultNamespace(keyVaultNamespace)\n .WithCryptProvider(\n CryptProvider.AutoEncryptSharedLibrary,\n Environment.GetEnvironmentVariable(\"CRYPT_SHARED_LIB_PATH\"))\n .WithQueryableEncryptionSchemaMode(\n QueryableEncryptionSchemaMode.Ignore);\n\n```\n\nIn `Ignore` mode, any `IsEncrypted` configuration in the `OnModelCreating()` method has no effect on encryption. The server schema controls which fields are encrypted.\n\n## Additional Information\n\nTo learn more about Queryable Encryption, see the Queryable Encryption and Queryable Encryption Use Cases sections in the MongoDB Server manual.\n\nFor complete implementation details, see the EF Core Provider API documentation."} -{"chunk_id": "6a514d22d727379c91b99ebf-0", "page_id": "6a514d22d727379c91b99ebf", "source_name": "entity-framework", "product_name": "MongoDB Entity Framework Provider", "url": "https://mongodb.com/docs/entity-framework/current/reference/upgrade", "title": "Upgrade Provider Version", "text": "# Upgrade Provider Version\n\n## Overview\n\nIn this section, you can identify essential changes you must make to your application when you upgrade your provider to a new version.\n\nBefore you upgrade, perform the following actions:\n\n- Ensure the new version is compatible with the MongoDB Server version your application connects to and the .NET version your application runs on. See the Compatibility page for this information.\n\n- Address any breaking changes between the current version of the provider your application is using and your planned upgrade version in the Breaking Changes section.\n\n## Breaking Changes\n\nA breaking change is a modification of a convention or a behavior starting in a specific version of the provider. This type of change might prevent your application from working properly if not addressed before upgrading the provider.\n\nThe breaking changes in this section are categorized by the provider version that introduced them. When upgrading provider versions, address all the breaking changes between the current and upgrade versions. For example, if you are upgrading the provider from v8.0 to v8.5, address all breaking changes from the version after v8.0, including any listed under v8.5.\n\n### Version 9.0.0 Breaking Changes\n\nVersion 9.0.0 of the EF Core Provider includes the same breaking changes as version 8.3.0 of the EF Core Provider.\n\nFor more information about the breaking changes in version 9.0.0 and how to address them, see the Version 8.3.0 Breaking Changes section.\n\n### Version 8.3.0 Breaking Changes\n\nVersion 8.3.0 of the EF Core Provider introduces a breaking change that corrects the handling of nullable properties configured with an alternative BSON representation. In previous versions, configurations set by the `[BsonRepresentation]` attribute or the `HasBsonRepresentation()` fluent API were not applied.\n\nYou can take action to address this discrepency in one of two ways:\n\n- If using the alternative BSON representation is not critical, remove the configuration from your application before it starts.\n\n- Alternatively, you can update the affected elments to the new representation. As part of your upgrade process, use the `updateMany` method for each affected MongoDB collection to rewrite any affected nullable properties or elements into the desired BSON representation using the `$convert` operation.\n\n For example, you can convert a `dateOfBirth` element in a collection named `people` from a BSON `date` into BSON `int` as shown in the following code:\n\n ```csharp\n db.people.updateMany(\n { dateOfBirth: {$type: \"date\" } },\n [\n { $set: {\n dateOfBirth:\n { $convert:\n { input: \"$dateOfBirth\",\n to: \"int\",\n onNull: null\n }\n }\n }\n }\n ]\n )\n ```\n\n### Version 8.2.0 Breaking Changes\n\nVersion 8.2.0 of the EF Core Provider does not directly introduce any breaking changes. However, the underlying .NET/C# Driver introduces many potentially breaking changes in the v3.0 release, which might affect your application. To learn more about the breaking changes in v3.0 of the .NET/C# Driver, see the Upgrade to Version 3.0 guide in the .NET/C# Driver documentation.\n\n### Version 8.1.0 Breaking Changes\n\n- Updated the EF Core Provider to run all changes as MongoDB transactions. If your application uses MongoDB Server earlier than v5.0, or does not run in a replica set, you must make the following changes to your application:\n\n - If your application is configured for a MongoDB Server version earlier than v5.0, you must upgrade to MongoDB Server v5.0 or later.\n\n - If your application runs on a standalone server, you must reconfigure your standalone server to a single-instance replica set. To learn more about how to reconfigure your standalone server, see Convert a Standalone Self-Managed mongod to a Replica Set in the MongoDB Server manual.\n\n - If your application runs in a container environment, switch to a single-instance replica set container if one is available.\n\n To avoid snapshot issues during transactions, call the `EnsureCreated()` or `EnsureCreatedAsync()` method during your application start-up, rather than creating the collection or database implicitly.\n\n Calling the `EnsureCreated()` or `EnsureCreatedAsync()` method throws an error if your application is running on a shared cluster. Applications running on free and shared clusters should not call these methods.\n\n If you don't want to ensure optimistic concurrency with transactions, you can disable automatic transactions by setting `Database.AutoTransactionBehavior = AutoTrasactionBehavior.Never` on your `DbContext` subclass during your application setup.\n\n- Changed the default GUID storage format from `CSharpLegacy` binary format to `Standard` format. If your database contains existing GUIDs that are not in `Standard` format, we recommend converting them to `Standard` format.\n\n- The `CamelCaseElementNameConvention` converts the casing of owned entities based on their property name instead of their class name. If your application uses the `CamelCaseElementNameConvention`, the casing of your data might change.\n\nFor more information about the breaking changes in this version, see the Breaking Changes section of the provider repository on GitHub."} -{"chunk_id": "6a514d22d727379c91b99e89-0", "page_id": "6a514d22d727379c91b99e89", "source_name": "entity-framework", "product_name": "MongoDB Entity Framework Provider", "url": "https://mongodb.com/docs/entity-framework/current/connect/configure", "title": "Configure the EF Core Provider", "text": "# Configure the EF Core Provider\n\nIn this guide, you will learn how to configure an application to use the MongoDB Entity Framework Core Provider. To learn how to set up a new project and install the EF Core Provider, see the Get Started with the EF Core Provider.\n\n## Create a POCO\n\nCreate a Plain old CLR/Class object, or **POCO**, to use as a model for your entity. A POCO is a simple class object that doesn't inherit features from any framework-specific base classes or interfaces.\n\nThe following code example shows how to create a POCO that represents a customer:\n\n```csharp\npublic class Customer\n{\n public ObjectId Id { get; set; }\n public string Name { get; set; } = null!;\n public string Order { get; set; } = null!;\n}\n\n```\n\nTo learn more about POCOs, see the POCO guide in the .NET/C# Driver documentation.\n\n## Create a DB Context Class\n\nTo begin using Entity Framework Core, create a context class that derives from DBContext. The `DbContext` derived class instance represents a database session and is used to query and save instances of your entities.\n\nThe `DBContext` class exposes `DBSet` properties that specify the entities you can interact with while using that context.\n\nThe following example creates an instance of a `DBContext` derived class and specifies the `Customer` object as a `DBSet` property:\n\n```csharp\npublic class MyDbContext : DbContext\n{\n public DbSet Customers { get; init; } = null!;\n\n public MyDbContext(DbContextOptions options)\n : base(options)\n {\n }\n\n protected override void OnModelCreating(ModelBuilder modelBuilder)\n {\n base.OnModelCreating(modelBuilder);\n modelBuilder.Entity().ToCollection(\"customers\");\n }\n}\n\n```\n\nThe previous code example overrides the `OnModelCreating()` method. Overriding the `OnModelCreating()` method allows you to specify configuration details for your model and its properties. This example uses the `ToCollection()` method to specify that the `Customer` entities in your application map to the `customers` collection in MongoDB.\n\n## Use MongoDB\n\nOnce you've created a `DBContext` class, construct a `DbContextOptionsBuilder` object and call its `UseMongoDB()` method. This method takes two parameters: a `MongoClient` instance and the name of the database that stores the collections you are working with.\n\nThe `UseMongoDB()` method returns a `DbContextOptions` object. Pass the `Options` property of this object to the constructor for your `DBContext` class.\n\nThe following example shows how to construct a `DBContext` object in this way:\n\n```csharp\nvar mongoClient = new MongoClient(\"\");\n\nvar dbContextOptions =\n new DbContextOptionsBuilder().UseMongoDB(mongoClient, \"\");\n\nvar db = new MyDbContext(dbContextOptions.Options);\n\n```\n\nYou can call methods from the MongoDB .NET/C# Driver when using the EF Core Provider. The previous example uses the `MongoClient()` method from the .NET/C# Driver to create a MongoDB client that connects to a MongoDB instance.\n\nTo learn more about using the MongoDB .NET/C# Driver to connect to MongoDB, see the Connection guide in the .NET/C# Driver documentation.\n\n## MongoClient and DbContext Lifetimes\n\nThe lifetime and configuration of your `MongoClient` and `DbContext` objects directly affect memory usage and connection pool efficiency.\n\nRegister `MongoClient` as a **singleton** and share a single instance across all `DbContext` registrations. Because each `MongoClient` object manages its own internal connection pool, creating a separate instance for each `DbContext` scope wastes connections and increases latency. To learn more, see Manage MongoClient Disposables in the .NET/C# Driver documentation.\n\nRegister `DbContext` as a **scoped** service so that each request uses a new change tracker. A singleton `DbContext` accumulates tracked entity state across all requests, which causes stale data, memory growth, and increasingly slow change-detection as the tracker grows larger. To learn more, see DbContext in Dependency Injection for ASP.NET Core in the Microsoft Entity Framework Core documentation.\n\n## Example\n\nThe following code example shows how to register services by using dependency injection, configure the EF Core Provider, and insert a document into the database:\n\n```csharp\nvar serviceCollection = new ServiceCollection();\nserviceCollection.AddSingleton(\n new MongoClient(\"\"));\n\nserviceCollection.AddDbContext((serviceProvider, options) =>\n{\n var mongoClient = serviceProvider.GetRequiredService();\n options.UseMongoDB(mongoClient, \"\");\n});\n\nusing var app = serviceCollection.BuildServiceProvider();\nusing (var scope = app.CreateScope())\n{\n var db = scope.ServiceProvider.GetRequiredService();\n\n // Add a new customer and save it to the database\n db.Customers.Add(new Customer() { Name = \"John Doe\", Order = \"1 Green Tea\" });\n db.SaveChanges();\n}\n\n```"} -{"chunk_id": "68a95beb5e79d242619d8c78-0", "page_id": "68a95beb5e79d242619d8c78", "source_name": "entity-framework", "product_name": "MongoDB Entity Framework Provider", "url": "https://mongodb.com/docs/entity-framework/current/limitations", "title": "Feature Limitations", "text": "# Feature Limitations\n\n## Overview\n\nOn this page, you can find a list of Entity Framework and MongoDB features that the EF Core Provider does not support. Because the provider is in active development, some features listed on this page might be considered for future releases based on customer demand.\n\n## Unsupported Entity Framework Core Features\n\nThe following sections describe Entity Framework Core features that the EF Core Provider does not support.\n\n### Select Projections\n\nSelect projections use the `Select()` method in a LINQ query to change the structure of the created object. The projection changes the object by performing groupings, or selecting fields into anonymous types or alternative types not recognized by Entity Framework.\n\nThis version of the EF Core Provider does not support Select Projections.\n\n### Migrations\n\nMigrations in Entity Framework Core are designed for relational databases. Because MongoDB is a document database, migrations are not supported by the EF Core Provider.\n\n### Database-First Development\n\nMongoDB is designed to be flexible and does not require a database schema. Because of MongoDB's schema-flexible design, database-first development is not supported in the EF Core Provider.\n\n### Foreign Keys\n\nBecause MongoDB is a document database, the EF Core Provider does not support foreign keys.\n\n### Table Splitting\n\nMongoDB is a document database and does not have normalized tables. Because of this, table splitting is not supported by the EF Core Provider.\n\n### Temporal Tables\n\nThe EF Core Provider does not support temporal tables.\n\n### Spatial Data\n\nThe EF Core Provider does not support spatial data.\n\n## Unsupported MongoDB Features\n\nThe following sections describe MongoDB features that the EF Core Provider does not support.\n\n### Time Series\n\nThe EF Core Provider does not support time series data or time series collections. These are MongoDB-exclusive features that are not available in Entity Framework Core.\n\n### Atlas Search\n\nThe EF Core Provider does not support MongoDB Atlas search. Atlas Search is a MongoDB-exclusive feature with no similar feature available in Entity Framework Core."} -{"chunk_id": "6a514d22d727379c91b99e96-0", "page_id": "6a514d22d727379c91b99e96", "source_name": "entity-framework", "product_name": "MongoDB Entity Framework Provider", "url": "https://mongodb.com/docs/entity-framework/current/interact-data/query-data", "title": "Find and Query Entity Data with LINQ", "text": "# Find and Query Entity Data with LINQ\n\n## Overview\n\nEntity Framework Core allows you to work with data in your application without explicitly running database commands. To query your data, use the Language-Integrated Query (LINQ) syntax. LINQ allows you to write strongly typed queries using C#-specific keywords and operators. When you run the application, the EF Core Provider automatically translates the LINQ queries and runs them on the database using the MongoDB Query API.\n\nIn this guide you can see examples of common query operations on an application configured to use the EF Core Provider.\n\nTo learn how to configure an application to use the EF Core Provider, see Configure the EF Core Provider.\n\n### Sample Data\n\nThe examples in this guide use the `planets` collection from the `sample_guides` database. The documents in this collection use the following `Planet` class as a model:\n\n```csharp\npublic class Planet\n{\n public ObjectId _id { get; set; }\n public string name { get; set; } = null!;\n public int orderFromSun { get; set; }\n public bool hasRings { get; set; }\n}\n\n```\n\nThis collection is from the sample datasets provided by Atlas. See the Get Started with the EF Core Provider guide to learn how to create a free MongoDB cluster and load this sample data.\n\n## Find Entities\n\nFind a single entity by using the `FirstOrDefault()` method, or find multiple entities by using the `Where()` method.\n\n### Find a Single Entity\n\nThe `FirstOrDefault()` method returns the first entity it finds in your collection that matches the search criteria, and returns `null` if no matching entities are found.\n\nThe following code uses the `FirstOrDefault()` method to find a planet with the `name` field of \"Mercury\" from a `DBSet` called `Planets` and prints the planet name to the console:\n\n```csharp\nvar planet = db.Planets.FirstOrDefault(p => p.name == \"Mercury\");\nConsole.WriteLine(planet?.name);\n\n```\n\n### Find Multiple Entities\n\nYou can use the `Where()` method to retrieve multiple entities from your collections. `Where()` returns all entities that match the search criteria.\n\nThe following code uses the `Where()` method to find all planets that have the `hasRings` field set to `true` and prints the planet names to the console.\n\n```csharp\nvar planets = db.Planets.Where(p => p.hasRings);\n\nforeach (var p in planets)\n{\n Console.WriteLine(p.name);\n}\n\n```\n\n### Query a Shadow Property\n\nA *shadow property* is a property that isn't defined on your .NET entity class but is included in the Entity Framework model and mapped to fields in the database. You can use shadow properties to query or track data in your documents without exposing it as a property on your entity.\n\nTo reference a shadow property in a LINQ query, call the `EF.Property()` method and pass the configured property name as an argument. The generic type argument must match the data type of the shadow property.\n\nFor example, the `Planet` class does not define a property for the `mainAtmosphere` field. To configure this field as a shadow property, call the `Property()` method in the `OnModelCreating()` method of `PlanetDbContext`, as shown in the following example:\n\n```csharp\npublic class PlanetDbContext : DbContext\n{\n public DbSet Planets { get; init; } = null!;\n\n public static PlanetDbContext Create(IMongoDatabase database) =>\n new(new DbContextOptionsBuilder()\n .UseMongoDB(database.Client, database.DatabaseNamespace.DatabaseName)\n .Options);\n\n public PlanetDbContext(DbContextOptions options)\n : base(options)\n {\n }\n\n protected override void OnModelCreating(ModelBuilder modelBuilder)\n {\n base.OnModelCreating(modelBuilder);\n modelBuilder.Entity().ToCollection(\"planets\");\n modelBuilder.Entity().Property(\"mainAtmosphere\");\n }\n}\n\n```\n\nThe call to `modelBuilder.Entity().Property(\"mainAtmosphere\")` instructs the framework to include `mainAtmosphere` in the model and map it to a `string[]` field in MongoDB.\n\nThe following code uses the `EF.Property()` method to find all planets that have a non-empty `mainAtmosphere` shadow property and prints the planet names to the console:\n\n```csharp\nvar planets = db.Planets.Where(\n p => EF.Property(p, \"mainAtmosphere\").Length > 0);\n\nforeach (var p in planets)\n{\n Console.WriteLine(p.name);\n}\n\n```\n\n## Check Field Existence\n\nYou can query documents based on whether a field exists, is missing, or has a `null` value by using methods in the `Mql` class.\n\nThese methods work with both real properties and shadow properties.\n\n### Mql.Exists\n\nThe `Mql.Exists()` method matches documents that contain the specified field, including documents where the field value is `null`.\n\nThe following code uses the `Mql.Exists()` method to find all planets that have the `hasRings` field and prints the planet names to the console:\n\n```csharp\nvar planetNames = db.Planets\n .Where(p => Mql.Exists(p.hasRings))\n .Select(p => p.name);\n\nforeach (var name in planetNames)\n{\n Console.WriteLine(name);\n}\n\n```\n\n### Mql.IsMissing\n\nThe `Mql.IsMissing()` method matches documents that do not contain the specified field.\n\nThe following code uses the `Mql.IsMissing()` method to find all planets that do not have the `hasRings` field and prints the planet names to the console:\n\n```csharp\nvar planetNames = db.Planets\n .Where(p => Mql.IsMissing(p.hasRings))\n .Select(p => p.name);\n\nforeach (var name in planetNames)\n{\n Console.WriteLine(name);\n}\n\n```\n\n### Mql.IsNullOrMissing\n\nThe `Mql.IsNullOrMissing()` method matches documents where the specified field is either missing or has a `null` value.\n\nThe following code uses the `Mql.IsNullOrMissing()` method to find all planets where the `hasRings` field is missing or `null` and prints the planet names to the console:\n\n```csharp\nvar planetNames = db.Planets\n .Where(p => Mql.IsNullOrMissing(p.hasRings))\n .Select(p => p.name);\n\nforeach (var name in planetNames)\n{\n Console.WriteLine(name);\n}\n\n```"} -{"chunk_id": "6a514d22d727379c91b99e96-1", "page_id": "6a514d22d727379c91b99e96", "source_name": "entity-framework", "product_name": "MongoDB Entity Framework Provider", "url": "https://mongodb.com/docs/entity-framework/current/interact-data/query-data", "title": "Find and Query Entity Data with LINQ", "text": "## Sort Entities\n\nUse the `OrderBy()` method to specify an order in which to return entities from a query. `OrderBy()` sorts the elements in ascending order based on a specified sort criteria.\n\nThe following code uses the `OrderBy()` method to find all planets and sort them by the value of the `orderFromSun` field in ascending order. It then prints the results to the console.\n\n```csharp\nvar planetList = db.Planets.OrderBy(p => p.orderFromSun);\nforeach (var p in planetList)\n{\n Console.WriteLine(p.name);\n}\n\n```\n\n```none\n{\"_id\":\"...\",\"name\":\"Mercury\",\"orderFromSun\":1,\"hasRings\":false}\n{\"_id\":\"...\",\"name\":\"Venus\",\"orderFromSun\":2,\"hasRings\":false}\n{\"_id\":\"...\",\"name\":\"Earth\",\"orderFromSun\":3,\"hasRings\":false}\n{\"_id\":\"...\",\"name\":\"Mars\",\"orderFromSun\":4,\"hasRings\":false}\n{\"_id\":\"...\",\"name\":\"Jupiter\",\"orderFromSun\":5,\"hasRings\":true}\n{\"_id\":\"...\",\"name\":\"Saturn\",\"orderFromSun\":6,\"hasRings\":true}\n{\"_id\":\"...\",\"name\":\"Uranus\",\"orderFromSun\":7,\"hasRings\":true}\n{\"_id\":\"...\",\"name\":\"Neptune\",\"orderFromSun\":8,\"hasRings\":true}\n\n```\n\nYou can sort the results of a query in descending order by using the `OrderByDescending()` method.\n\nYou can perform a secondary sort on your query by using the `ThenBy()` method. The `ThenBy()` method sorts the results of the `OrderBy()` method in ascending order based on a specified sort criteria. The `ThenBy()` method should be chained to the `OrderBy()` method.\n\nYou can perform a secondary sort in descending order by using the `ThenByDescending()` method.\n\nThe following code uses the `OrderBy()` and `ThenBy()` methods to find all planets and sort them by the `hasRings()` field, with a secondary sort on the `name` field.\n\n```csharp\nvar planetList = db.Planets.OrderBy(o => o.hasRings).ThenBy(o => o.name);\n\nforeach (var p in planetList)\n{\n Console.WriteLine(\"Has rings: \" + p.hasRings + \", Name: \" + p.name);\n}\n\n```\n\n```none\n{\"_id\":\"...\",\"name\":\"Earth\",\"orderFromSun\":3,\"hasRings\":false}\n{\"_id\":\"...\",\"name\":\"Mars\",\"orderFromSun\":4,\"hasRings\":false}\n{\"_id\":\"...\",\"name\":\"Mercury\",\"orderFromSun\":1,\"hasRings\":false}\n{\"_id\":\"...\",\"name\":\"Venus\",\"orderFromSun\":2,\"hasRings\":false}\n{\"_id\":\"...\",\"name\":\"Jupiter\",\"orderFromSun\":5,\"hasRings\":true}\n{\"_id\":\"...\",\"name\":\"Neptune\",\"orderFromSun\":8,\"hasRings\":true}\n{\"_id\":\"...\",\"name\":\"Saturn\",\"orderFromSun\":6,\"hasRings\":true}\n{\"_id\":\"...\",\"name\":\"Uranus\",\"orderFromSun\":7,\"hasRings\":true}\n\n```\n\nWhen sorting on fields with a boolean value, entities with a field value of `false` show before those with a value of `true`.\n\n## Scalar Aggregations\n\nThe EF Core Provider supports the following scalar aggregation methods:\n\n- `Count()`: Returns the number of elements in a collection or the number of documents that match a predicate\n\n- `LongCount()`: Returns the number of elements in a collection as a `long` or the number of documents that match a predicate\n\n- `Any()`: Returns `true` if any elements in a collection match the predicate\n\n- `Max()`: Returns the maximum value of a specified field in a collection\n\n- `Min()`: Returns the minimum value of a specified field in a collection\n\n- `Sum()`: Returns the sum of values of a specified field in a collection\n\n- `Average()`: Returns the average of values of a specified field in a collection\n\nThe following sections show examples of each of the preceding methods.\n\n### Count\n\nThe following example uses the `Count()` method to count the number of elements in the `Planets` collection:\n\n```csharp\nvar planetCount = db.Planets.Count();\n\nConsole.WriteLine(\"Planet Count: \" + planetCount);\n\n```\n\nThe following example uses the `Count()` method to count the number of elements in the `Planets` collection that have a `hasRings` field set to `true`:\n\n```csharp\nvar planetCountWithRings = db.Planets.Count(p => p.hasRings);\n\nConsole.WriteLine(\"Planet Count with Rings: \" + planetCountWithRings);\n\n```\n\n### LongCount\n\nThe following example uses the `LongCount()` method to count the number of elements in the `Planets` collection and returns the result as a `long`:\n\n```csharp\nvar planetCountLong = db.Planets.LongCount();\n\nConsole.WriteLine(\"Long Planet Count: \" + planetCountLong);\n\n```\n\nThe following example uses the `LongCount()` method to count the number of elements in the `Planets` collection that have a `hasRings` field set to `true` and returns the result as a `long`:\n\n```csharp\nvar planetCountLongWithRings = db.Planets.LongCount(p => p.hasRings);\n\nConsole.WriteLine(\"Long Planet Count with Rings: \" + planetCountLongWithRings);\n\n```\n\n### Any\n\nThe following example uses the `Any()` method to check if any elements in the `Planets` collection have a `hasRings` field set to `true`:\n\n```csharp\nvar results = db.Planets.Any(p => p.hasRings);\n\nConsole.WriteLine(\"Planet with Rings: \" + results);\n\n```\n\n### Max\n\nThe following example uses the `Max()` method to find the maximum value of the `orderFromSun` field in the `Planets` collection:\n\n```csharp\nvar furthestPlanet = db.Planets.Max(p => p.orderFromSun);\n\nConsole.WriteLine(\"Furthest Planet: \" + furthestPlanet);\n\n```\n\n### Min\n\nThe following example uses the `Min()` method to find the minimum value of the `orderFromSun` field in the `Planets` collection:\n\n```csharp\nvar closestPlanet = db.Planets.Min(p => p.orderFromSun);\n\nConsole.WriteLine(\"Closest Planet: \" + closestPlanet);\n\n```\n\n### Sum\n\nThe following example uses the `Sum()` method to find the sum of the `orderFromSun` field in the `Planets` collection:\n\n```csharp\nvar totalOrderFromSun = db.Planets.Sum(p => p.orderFromSun);\nConsole.WriteLine(\"Total Order From Sun: \" + totalOrderFromSun);\n\n```\n\n### Average\n\nThe following example uses the `Average()` method to find the average value of the `orderFromSun` field in the `Planets` collection:\n\n```csharp\nvar averageOrderFromSun = db.Planets.Average(p => p.orderFromSun);\n\nConsole.WriteLine(\"Average Order From Sun: \" + averageOrderFromSun);\n\n```\n\n## Inspect the Queries Sent to MongoDB\n\nAfter you write a LINQ query, inspect the generated query to confirm that the provider is sending the expected shape to MongoDB Server. To inspect queries during development, enable EF Core logging on your `DbContext` by using the LogTo() method.\n\nThe following example shows how to enable logging to the console when creating a `DbContext` object:\n\n```csharp\nvar mongoClient = new MongoClient(\"\");\n\nvar dbContextOptions =\n new DbContextOptionsBuilder()\n .UseMongoDB(mongoClient, \"sample_guides\")\n .LogTo(Console.WriteLine)\n .Options;\n\nvar db = new MyDbContext(dbContextOptions);\n\n```\n\n### Enable Sensitive Data Logging\n\nThe provider logs full MQL query text only when sensitive data logging is enabled. If you don't enable sensitive data logging, query logs might omit values. To enable sensitive data logging, call the EnableSensitiveDataLogging() method from your `DbContextOptionsBuilder` object, as shown in the following example:\n\n```csharp\nvar mongoClient = new MongoClient(\"\");\n\nvar dbContextOptions =\n new DbContextOptionsBuilder()\n .UseMongoDB(mongoClient, \"sample_guides\")\n .LogTo(Console.WriteLine)\n .EnableSensitiveDataLogging()\n .Options;\n\nvar db = new MyDbContext(dbContextOptions);\n\n```\n\nEnable sensitive data logging only in development environments."} -{"chunk_id": "6a514d22d727379c91b99e96-2", "page_id": "6a514d22d727379c91b99e96", "source_name": "entity-framework", "product_name": "MongoDB Entity Framework Provider", "url": "https://mongodb.com/docs/entity-framework/current/interact-data/query-data", "title": "Find and Query Entity Data with LINQ", "text": "### Custom Serialization Conventions\n\nIf you register custom BSON serialization conventions on the `MongoClient`, such as camel-case field naming, those conventions can change the field names stored in MongoDB so that they differ from the property names in your entity model. The EF Core Provider uses entity property names to generate MQL, so a mismatch can cause queries to target the wrong fields and bypass any indexes on those fields. When your stored field names differ from your entity property names, you can explicitly map a property to its stored field name in `OnModelCreating()` by using `HasElementName()`, as shown in the following example:\n\n```csharp\nprotected override void OnModelCreating(ModelBuilder modelBuilder)\n{\n base.OnModelCreating(modelBuilder);\n modelBuilder.Entity()\n .Property(p => p.name)\n .HasElementName(\"name\");\n}\n\n```\n\nIf you need lower-level visibility into MongoDB commands, you can use the .NET/C# Driver monitoring APIs on your `MongoClient` object. To learn more about these APIs, see Monitoring in the .NET/C# Driver documentation.\n\n## Additional Information\n\nTo learn more about aggregations in MongoDB, see the Aggregation Operations guide in the MongoDB Server manual.\n\nTo learn more about the EF Core methods discussed in this guide, see the following .NET API documentation links:\n\n- FirstOrDefault()\n\n- Where()\n\n- OrderBy()\n\n- OrderByDescending()\n\n- ThenBy()\n\n- ThenByDescending()\n\n- LogTo()\n\n- EnableSensitiveDataLogging()\n\nTo learn more about the .NET/C# Driver methods used on this page, see the following API documentation links:\n\n- Mql.Exists()\n\n- Mql.IsMissing()\n\n- Mql.IsNullOrMissing()\n\nTo learn more about the `HasElementName()` method, see the following EF Core Provider API documentation link:\n\n- HasElementName()"} -{"chunk_id": "6a514d22d727379c91b99eb1-0", "page_id": "6a514d22d727379c91b99eb1", "source_name": "entity-framework", "product_name": "MongoDB Entity Framework Provider", "url": "https://mongodb.com/docs/entity-framework/current/model-data/optimistic-concurrency", "title": "Ensure Data Consistency with Optimistic Concurrency", "text": "# Ensure Data Consistency with Optimistic Concurrency\n\n## Overview\n\nIn this guide, you can learn how to use **optimistic concurrency control** with the EF Core Provider. Optimistic concurrency control ensures that data is not overwritten between the time an application reads it and the time the application writes it back to the database. The EF Core Provider supports two ways to implement optimistic concurrency control:\n\n- Concurrency tokens, by using the `ConcurrencyCheck` attribute or the `IsConcurrencyToken()` fluent API method\n\n- Row versioning, by using the `Timestamp` attribute or the `IsRowVersion()` fluent API method\n\nWe recommend ensuring optimistic concurrency by using only one of the preceding implementations per entity.\n\n## Concurrency Tokens\n\nYou can ensure optimistic concurrency on a specified property by using a concurrency token. When querying the entity, the EF Core Provider tracks the concurrency token. Then, when the provider calls the `SaveChanges()` or `SaveChangesAsync()` method, it compares the value of the concurrency token the value saved in the database to ensure that the original value hasn't changed.\n\nYou can configure a concurrency token by specifying the `ConcurrencyCheck` attribute when defining a class. The following example shows how to specify the `ConcurrencyCheck` attribute on the `LastModified` property of a `Customer` class:\n\n```csharp\npublic class Customer\n{\n public ObjectId Id { get; set; }\n public String Name { get; set; }\n public String Order { get; set; }\n [ConcurrencyCheck]\n public DateTimeOffset LastModified { get; set; }\n}\n```\n\nYou can also configure a concurrency token by using the `IsConcurrencyToken()` method. Call the `IsConcurrencyToken()` method in the `OnModelCreating()` method of the `DbContext` class, as shown in the following example:\n\n```csharp\nprotected override void OnModelCreating(ModelBuilder modelBuilder)\n{\n base.OnModelCreating(modelBuilder);\n modelBuilder.Entity()\n .Property(p => p.LastModified)\n .IsConcurrencyToken();\n}\n\n```\n\nThe EF Core Provider supports setting concurrency tokens on any property type supported by the driver. You can also set multiple concurrency tokens on a single entity. If you need to update a concurrency token, you must do so manually.\n\n## Row Versioning\n\nYou can ensure optimistic concurrency by using row versioning. Row versioning allows you to track changes to an entity by specifying a version field that increments automatically when the entity changes. You can configure row versioning by specifying the `Timestamp` attribute when defining a class. The following example shows how to specify the `Timestamp` attribute on the `Version` property of a `Customer` class:\n\n```csharp\npublic class Customer\n{\n public ObjectId Id { get; set; }\n public String Name { get; set; }\n public String Order { get; set; }\n [Timestamp]\n public long Version { get; set; }\n}\n```\n\nYou can also configure row versioning by using the `IsRowVersion()` method. Call the `IsRowVersion()` method in the `OnModelCreating()` method of the `DbContext` class, as shown in the following example:\n\n```csharp\nprotected override void OnModelCreating(ModelBuilder modelBuilder)\n{\n base.OnModelCreating(modelBuilder);\n modelBuilder.Entity()\n .Property(p => p.Version)\n .IsRowVersion();\n}\n\n```\n\nThe EF Core Provider supports row versioning on only a single property of an entity. The property must be of type `long`, `int`, `ulong`, or `uint`.\n\n## Limitations\n\nConsider the following limitations when configuring optimistic concurrency control on a database that shares data with other applications:\n\n- Other applications must support the same mechanisms you are using for optimistic concurrency control in your Entity Framework Core application.\n\n- Other applications must support checks for concurrency tokens and row version fields during any update or delete operation.\n\n- If you are using row versioning, other applications must map row versioned fields to the property's name followed by the string: `_version`. The application must increment the field's value by 1 for each update.\n\n## Additional Information\n\nFor more information about optimistic concurrency control with Entity Framework Core, see Optimistic Concurrency in the Microsoft Entity Framework Core documentation."} -{"chunk_id": "6a514d22d727379c91b99ebc-0", "page_id": "6a514d22d727379c91b99ebc", "source_name": "entity-framework", "product_name": "MongoDB Entity Framework Provider", "url": "https://mongodb.com/docs/entity-framework/current/reference/faq", "title": "FAQ", "text": "# FAQ\n\nThis page contains frequently asked questions and their corresponding answers.\n\nIf you can't find an answer to your problem on this page, see the Report Issues and Request Help page for next steps and more resources.\n\n## What is the Difference Between the .NET/C# Driver and the EF Core Provider?\n\nThe MongoDB .NET/C# Driver is a library that exposes MongoDB functionality directly and includes a LINQ provider with projections, group operations, and flexible mapping. The driver includes features such as the following:\n\n- Transactions\n\n- Bulk operations\n\n- LINQ queries\n\n- Operations that directly modify the database\n\n- Aggregation operations\n\n- Custom mapping\n\nThe EF Core Provider allows you to use Microsoft's Entity Framework Core with MongoDB in your .NET/C# applications. The EF Core Provider supports change tracking, entity-based LINQ operations, and modeling familiar to Entity Framework Core users. The provider includes features such as the following:\n\n- Intelligent object tracking\n\n- Entity-based LINQ operations\n\n- Entity Framework modeling and mapping with the fluent API\n\n- Automatic database updates through change tracking\n\n## How Can I Manage Indexes with the EF Core Provider?\n\nYou can create indexes with the EF Core Provider by calling the `HasIndex()` method in the `OnModelCreating()` method of your `DbContext` class. To learn more about how to create indexes with the EF Core Provider, see the Indexes guide.\n\nBecause the EF Core Provider is built on top of the .NET/C# Driver, you can also manage indexes in your application by using the .NET/C# Driver directly. To use driver methods in your EF Core Provider application, call them on the `MongoClient` used to set up your `DbContext`.\n\nThe following example creates indexes on the `movies` collection by using .NET/C# Driver methods:\n\n```csharp\npublic static async Task CreateIndex()\n{\n var client = new MongoClient(\"\");\n var database = client.GetDatabase(\"sample_mflix\");\n var moviesIndex = new CreateIndexModel(Builders.IndexKeys\n .Ascending(x => x.Title)\n .Ascending(x => x.Genres));\n await database.GetCollection(\"movies\")\n .Indexes.CreateOneAsync(moviesIndex);\n}\n\n```\n\nTo learn more about creating indexes by using the driver, see the Indexes guide in the MongoDB .NET/C# Driver documentation.\n\n## Can I Access .NET/C# Driver Features in the EF Core Provider?\n\nYou can use the .NET/C# Driver directly in your EF Core Provider application by calling driver methods on the `MongoClient` used to set up your `DbContext`. The EF Core Provider is built on top of the .NET/C# Driver, so you can use all driver features in your application. For example, you can use the driver to perform an Atlas Search query as shown in the following example:\n\n```csharp\npublic static void AtlasSearch()\n{\n // Client used to set up your DbContext\n var client = new MongoClient(\"\");\n\n var clientDB = client.GetDatabase(\"sample_guides\");\n var collection = clientDB.GetCollection(\"planets\");\n\n var searchResult = collection.Aggregate()\n .Search(Builders.Search.Equals(p => p.hasRings, true))\n .ToList();\n\n foreach (var p in searchResult)\n {\n Console.WriteLine(p.name);\n }\n}\n\n```\n\nTo learn more about performing Atlas Search queries with the .NET/C# Driver, see the Atlas Search guide in the driver documentation."} -{"chunk_id": "6a514d22d727379c91b99e92-0", "page_id": "6a514d22d727379c91b99e92", "source_name": "entity-framework", "product_name": "MongoDB Entity Framework Provider", "url": "https://mongodb.com/docs/entity-framework/current/interact-data/atlas-vector-search", "title": "Run an Atlas Vector Search Query", "text": "# Run an Atlas Vector Search Query\n\n## Overview\n\nYou can use MongoDB Vector Search with the EF Core Provider to perform semantic search on data stored in Atlas. Vector search queries your data based on semantic meaning rather than keyword matches, allowing you to retrieve more relevant results. You can use MongoDB Vector Search to support use cases such as semantic search, hybrid search, and Retrieval-Augmented Generation (RAG).\n\nTo learn more about MongoDB Vector Search, see the MongoDB Vector Search Overview in the Atlas documentation.\n\n### Sample Data\n\nThe examples in this guide use the `embedded_movies` collection from the `sample_mflix` database. The documents in this collection use the following `Movie` class as a model:\n\n```csharp\npublic class Movie\n{\n public ObjectId Id { get; set; }\n public string Title { get; set; } = null!;\n public string Plot { get; set; } = null!;\n public float[] PlotEmbedding { get; set; } = null!;\n}\n\n```\n\nThe `embedded_movies` collection is part of the sample datasets provided by Atlas. To set up a cluster and load this sample data, see the Get Started with the EF Core Provider guide.\n\n## Model Definition\n\nTo use MongoDB Vector Search with the EF Core Provider, define a vector field on your entity class. Configure a vector index on that field by using the `IsVectorIndex()` fluent API method.\n\nThe following example defines a `Movie` entity with a vector field named `PlotEmbedding` and configures a vector index on that field.\n\n```csharp\npublic class MoviesDbContext : DbContext\n{\n public DbSet Movies { get; init; } = null!;\n\n public MoviesDbContext(DbContextOptions options) : base(options) { }\n\n protected override void OnModelCreating(ModelBuilder modelBuilder)\n {\n modelBuilder.Entity(entity =>\n {\n entity.ToCollection(\"embedded_movies\");\n entity.Property(m => m.Title).HasElementName(\"title\");\n entity.Property(m => m.Plot).HasElementName(\"plot\");\n entity.Property(m => m.PlotEmbedding).HasElementName(\"plot_embedding\")\n .HasBinaryVectorDataType(BinaryVectorDataType.Float32);\n entity.HasIndex(m => m.PlotEmbedding, \"vector_index\")\n .IsVectorIndex(VectorSimilarity.Cosine, 1536);\n });\n }\n}\n\n```\n\nYou cannot change or delete indexes by using the EF Core Provider after they are created. To change or delete an index, use the .NET/C# Driver. To learn more, see the MongoDB Search and MongoDB Vector Search Indexes guide in the .NET/C# Driver documentation.\n\n## Supported Vector Embedding Types\n\nThe EF Core Provider supports vector embeddings of the following types:\n\n### Array Representations\n\nThe EF Core Provider supports the following array types as vector embeddings:\n\n- `float[]`\n\n- `double[]`\n\n- `Memory` and `ReadOnlyMemory`\n\n- `Memory` and `ReadOnlyMemory`\n\n### Binary Representations\n\nThe EF Core Provider supports the following binary vector types, which reduce storage and improve query performance compared to array types:\n\n- `BinaryVectorFloat32` \u2014 full-precision 32-bit floats\n\n- `BinaryVectorInt8` \u2014 8-bit quantized integers\n\n- `BinaryVectorPackedBit` \u2014 1-bit packed binary values\n\nThe `MongoDB.Driver` namespace of the .NET/C# Driver contains the `VectorQuantization` and `VectorSimilarity` enums used to configure binary vector indexes.\n\n## Vector Search Query Example\n\nYou can use the `VectorSearch()` method to run a vector search query. The following example queries the `embedded_movies` collection for movies with a `PlotEmbedding` field value that is semantically similar to \"time travel adventure\", and then returns up to 10 matching documents.\n\n```csharp\n// Replace queryVector with a 1536-dimension embedding vector from your model\nfloat[] queryVector = new float[] { 0.1f, -0.2f, 0.3f, ... };\nvar results = context.Movies\n .VectorSearch(m => m.PlotEmbedding, queryVector, limit: 10)\n .ToList();\n\n```\n\n## Additional Information\n\nTo learn more about MongoDB Vector Search, see the MongoDB Vector Search documentation.\n\nFor API documentation, see the following resources:\n\n- MongoQueryableExtensions\n\n- MongoQueryableExtensions.VectorSearch()"} -{"chunk_id": "6a514d22d727379c91b99e8b-0", "page_id": "6a514d22d727379c91b99e8b", "source_name": "entity-framework", "product_name": "MongoDB Entity Framework Provider", "url": "https://mongodb.com/docs/entity-framework/current/get-started", "title": "Get Started with the EF Core Provider", "text": "# Get Started with the EF Core Provider\n\nThis guide shows you how to create a .NET application that uses the EF Core Provider to connect to a **MongoDB Atlas cluster**. If you prefer to connect to MongoDB using another programming language, see our list of official MongoDB drivers.\n\nThe EF Core Provider simplifies operations on data in MongoDB clusters by mapping the data to .NET objects.\n\nMongoDB Atlas is a fully-managed cloud database service that hosts your data on MongoDB clusters. In this guide, we show you how to get started with your own free (no credit card required) cluster.\n\nFollow the steps below to connect your EF Core Provider application to a MongoDB Atlas cluster.\n\n## Create a MongoDB Cluster\n\n### Set Up a Free Cluster in Atlas\n\nTo set up your Atlas free cluster required for this Get Started guide, complete the MongoDB Atlas Setup guide.\n\nAfter completing the steps in the Atlas guide, you have a new MongoDB cluster deployed in Atlas, a new database user, and sample datasets loaded into your cluster. You also have a connection string similar to the following in your copy buffer:\n\n```bash\n\"mongodb+srv://:@cluster0.abc.mongodb.net/?retryWrites=true&w=majority\"\n```\n\n### Update the Placeholders\n\nPaste the connection string in your copy buffer into a file in your preferred text editor. Replace the `` and `` placeholders with your database user's username and password.\n\nSave this file to a safe location for use in the next step.\n\n### Add Your Connection String to an Environment Variable\n\nRun the following code in your shell to save the MongoDB connection string in your copy buffer from the previous step to an environment variable. Storing your connection string in an environment variable keeps your credentials separate from your source code. This separation makes it less likely to expose your credentials when sharing your code.\n\n```bash\nexport MONGODB_URI=''\n```\n\nMake sure to replace the `` and `` sections of the connection string with the username and password of your database user.\n\n## Set Up Your Project\n\n### Create the Project\n\nCreate a new directory and use the `dotnet new` command to initialize your project as follows:\n\n```shell\nmkdir entity-quickstart\ncd entity-quickstart\ndotnet new console\n```\n\n### Add the EF Core Provider as a Dependency\n\nUse the `dotnet add` command to add the EF Core Provider to your project as a dependency.\n\n```shell\ndotnet add package MongoDB.EntityFrameworkCore\n```\n\n## Query Your MongoDB Cluster from Your Application\n\n### Add the Sample Code\n\nOpen the file named `Program.cs` in the base directory of your project. Copy the following sample code into `Program.cs`:\n\n```csharp\npublic class MflixDbContext : DbContext\n{\n public DbSet Movies { get; init; } = null!;\n\n public static MflixDbContext Create(IMongoDatabase database) =>\n new(new DbContextOptionsBuilder()\n .UseMongoDB(database.Client, database.DatabaseNamespace.DatabaseName)\n .Options);\n\n public MflixDbContext(DbContextOptions options)\n : base(options)\n {\n }\n\n protected override void OnModelCreating(ModelBuilder modelBuilder)\n {\n base.OnModelCreating(modelBuilder);\n\n modelBuilder.Entity().ToCollection(\"movies\");\n }\n}\n\npublic class Movie\n{\n [BsonId]\n public ObjectId _id { get; set; }\n\n [BsonElement(\"title\")]\n public string Title { get; set; } = null!;\n\n [BsonElement(\"rated\")]\n public string Rated { get; set; } = null!;\n\n [BsonElement(\"plot\")]\n public string Plot { get; set; } = null!;\n}\n\n```\n\n### Query the Sample Data\n\nRun the following command in your shell. It should print the plot of the movie \"Back to the Future\" from the sample dataset:\n\n```none\ndotnet run entity-quickstart.csproj\n```\n\n```none\nA young man is accidentally sent 30 years into the past in a time-traveling\nDeLorean invented by his friend, Dr. Emmett Brown, and must make sure his\nhigh-school-age parents unite in order to save his own existence.\n```\n\nIf your output is empty, ensure you have loaded the sample datasets into your cluster.\n\nAfter completing these steps, you should have a working Entity Framework application that connects to your MongoDB cluster, runs a query on the sample data, and prints out the result.\n\n## Next Steps\n\nLearn how to use the EF Core Provider to perform common operations in Quick Reference."} -{"chunk_id": "699fe5cda6fa0684a38c2add-0", "page_id": "699fe5cda6fa0684a38c2add", "source_name": "golang", "product_name": "Go Driver", "url": "https://mongodb.com/docs/drivers/go/current/crud/query/distinct", "title": "Retrieve Distinct Values", "text": "# Retrieve Distinct Values\n\n## Overview\n\nIn this guide, you can learn how to retrieve distinct values for a specified field across a single collection.\n\n### Sample Data\n\nThe example in this guide uses the following `Course` struct as a model for documents in the `courses` collection:\n\n```go\ntype Course struct {\n\tTitle string\n\tDepartment string\n\tEnrollment int32\n}\n\n```\n\nTo run the example, load the sample data into the `db.courses` collection with the following snippet:\n\n```go\ncoll := client.Database(\"db\").Collection(\"courses\")\ndocs := []any{\n\tCourse{Title: \"World Fiction\", Department: \"English\", Enrollment: 35},\n\tCourse{Title: \"Abstract Algebra\", Department: \"Mathematics\", Enrollment: 60},\n\tCourse{Title: \"Modern Poetry\", Department: \"English\", Enrollment: 12},\n\tCourse{Title: \"Plate Tectonics\", Department: \"Geology\", Enrollment: 30},\n}\n\nresult, err := coll.InsertMany(context.TODO(), docs)\n```\n\nIf the necessary database and collection don't exist when you perform a write operation, the server implicitly creates them.\n\nEach document contains a description of a university course that includes the course title, department, and enrollment. These items correspond to the `title`, `department`, and `enrollment` fields in each document.\n\n## Distinct\n\nTo retrieve distinct values for a specified field across a single collection, pass the following parameters to the `Distinct()` method:\n\n- The field name for which you want to retrieve the distinct values\n\n- A `non-nil` query filter specifying which documents to match\n\nIf you specify an empty query filter, the `Distinct()` method searches for distinct values across all documents in a collection.\n\n### Modify Behavior\n\nYou can modify the behavior of the `Distinct()` method by passing in a `DistinctOptions`. If you don't specify a `DistinctOptions`, the driver uses the default values for each option.\n\nThe `DistinctOptions` type allows you to configure options with the following methods:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nMethod\n\n\nDescription\n\n
\n`SetCollation()`\n\n\nThe type of language collation to use when sorting results.Default: `nil`\n\n
\n`SetComment()`\n\n\nSets a comment to attach to the distinct operation.Default: `nil`\n\n
#### Example\n\nThe following example matches documents with an `enrollment` field value less than `50` and prints the distinct values of the `department` field by using the `Distinct()` method:\n\n```go\nfilter := bson.D{{\"enrollment\", bson.D{{\"$lt\", 50}}}}\n\nvar arr []string\nerr = coll.Distinct(context.TODO(), \"department\", filter).Decode(&arr)\nif err != nil {\n\tpanic(err)\n}\n\nfmt.Printf(\"%s\\n\", arr)\n```\n\n```none\n[English Geology]\n```\n\n## Retrieve Distinct Values Example: Full File\n\nThis example connects to an instance of MongoDB by using a connection URI. To learn more about connecting to your MongoDB instance, see Create a MongoClient. This example also uses the `restaurants` collection in the `sample_restaurants` database included in the Atlas sample datasets. You can load them into your database on a free cluster on MongoDB Atlas by following the steps in Get Started with Atlas.\n\nThis example performs the following actions on the `restaurant` collection:\n\n- Matches documents in which the value of the `cuisine` field is `\"Tapas\"`\n\n- Returns distinct values of the `borough` field from the matched documents\n\n```go\n// Retrieves distinct values of a field by using the Go driver\npackage main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com/joho/godotenv\"\n\t\"go.mongodb.org/mongo-driver/v2/bson\"\n\t\"go.mongodb.org/mongo-driver/v2/mongo\"\n\t\"go.mongodb.org/mongo-driver/v2/mongo/options\"\n)\n\ntype Restaurant struct {\n\tID bson.ObjectID `bson:\"_id\"`\n\tName string\n\tRestaurantId string `bson:\"restaurant_id\"`\n\tCuisine string\n\tAddress interface{}\n\tBorough string\n\tGrades interface{}\n}\n\nfunc main() {\n\tif err := godotenv.Load(); err != nil {\n\t\tlog.Println(\"No .env file found\")\n\t}\n\n\tvar uri string\n\tif uri = os.Getenv(\"MONGODB_URI\"); uri == \"\" {\n\t\tlog.Fatal(\"You must set your 'MONGODB_URI' environment variable. See\\n\\t https://www.mongodb.com/docs/drivers/go/current/usage-examples/#environment-variable\")\n\t}\n\n\tclient, err := mongo.Connect(options.Client().ApplyURI(uri))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer func() {\n\t\tif err = client.Disconnect(context.TODO()); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}()\n\n\t// Filters the collection for documents where the value of cuisine is \"Tapas\"\n\tcoll := client.Database(\"sample_restaurants\").Collection(\"restaurants\")\n\tfilter := bson.D{{\"cuisine\", \"Tapas\"}}\n\n\t// Retrieves the distinct values of the \"borough\" field in documents\n\t// that match the filter\n\tvar arr []string\n\terr = coll.Distinct(context.TODO(), \"borough\", filter).Decode(&arr)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Prints the distinct \"borough\" values\n\tfor _, result := range arr {\n\t\tfmt.Println(result)\n\t}\n\n\t// When you run this file, it should print:\n\t// Brooklyn\n\t// Manhattan\n\t// Queens\n}\n\n```\n\n```none\nBrooklyn\nManhattan\nQueens\n```\n\n## Additional Information\n\nTo learn about constructing a query filter, see Specify a Query.\n\n### API Documentation\n\nTo learn more about any of the methods or types discussed in this guide, see the following API Documentation:\n\n- Distinct()\n\n- DistinctOptions"} -{"chunk_id": "699fe5cda6fa0684a38c2b39-0", "page_id": "699fe5cda6fa0684a38c2b39", "source_name": "golang", "product_name": "Go Driver", "url": "https://mongodb.com/docs/drivers/go/current/reference/release-notes", "title": "Release Notes", "text": "# Release Notes\n\nTo learn more about changes and updates between versions, you can read the release notes published with the driver source code.\n\nLearn what's new in:\n\n- Version 2.9.2\n\n- Version 2.9.1\n\n- Version 2.9\n\n- Version 2.8.2\n\n- Version 2.8.1\n\n- Version 2.8\n\n- Version 2.7\n\n- Version 2.6\n\n- Version 2.5.1\n\n- Version 2.5\n\n- Version 2.4.4\n\n- Version 2.4.1\n\n- Version 2.4\n\n- Version 2.3\n\n- Version 2.2\n\n- Version 2.1\n\n- Version 2.0\n\n- Version 1.17.10\n\n- Version 1.17.9\n\n- Version 1.17.8\n\n- Version 1.17\n\n- Version 1.16\n\n- Version 1.15.1\n\n- Version 1.15\n\n- Version 1.14\n\n- Version 1.13\n\n- Version 1.12.1\n\n- Version 1.12\n\n## What's New in 2.9.2\n\nThe Go driver v2.9.2 release includes the following changes:\n\nGo driver v2.9.2 includes a fix for CVE-2026-81521.\n\nFor the latest information about MongoDB security updates, see MongoDB Security Bulletins.\n\n- Returns an error if the database name in a `BulkWrite` call contains a period (`.`).\n\n- Restores a fix from v2.8.1 that was missing from v2.9.0 and v2.9.1. When a command's first attempt fails with a server error and the retry reports `NoWritesPerformed`, the driver returns the original server error. Operations such as `Database.RunCommand()` no longer return `nil`.\n\n- Sessions inherit `timeoutMS` from the client, so operations that run in a session honor the client-level timeout.\n\n- Returns an error if `DecompressPayload()` receives a negative uncompressed size.\n\n- Returns an error if a BSON document's length is less than 5 bytes.\n\n- Fixes `Truncate()` truncating one character too many when the width ends exactly on a multi-byte UTF-8 character.\n\n- Fixes duplicate error logging for network errors.\n\n- Fixes a crash in the `decodeOpReply()` method when a server reply reports a query failure but contains no error document.\n\nFor a complete list of changes in this version, see the v2.9.2 release notes on GitHub.\n\n## What's New in 2.9.1\n\nThe Go driver v2.9.1 release includes the following change:\n\nGo driver v2.9.1 includes a fix for CVE-2026-88031.\n\nFor the latest information about MongoDB security updates, see MongoDB Security Bulletins.\n\nFor a complete list of changes in this version, see the v2.9.1 release notes on GitHub.\n\n## What's New in 2.9\n\nThe Go driver v2.9 release contains breaking changes. For more information, see Version 2.9 Breaking Changes.\n\nThis release includes the following improvements and fixes:\n\n- Adds the experimental `ext/awsauth` module, which supports all AWS authentication methods through the official AWS SDK for Go. You can use the module's `awsauth.CredentialsProvider` type with `ClientOptions`, `ClientEncryptionOptions`, and `AutoEncryptionOptions`.\n\n- Improves support for MongoDB 9.0 Intelligent Workload Management (IWM) by only retrying overload errors when doing so is not expected to worsen server conditions. To learn more about IWM, see Write-Blocking in the Atlas documentation.\n\n- Fixes a panic in `Collection.InsertMany` when you use unordered inserts (`SetOrdered(false)`) and more than one document fails. If the server returns write errors in a different order than the documents, the driver now returns the errors instead of panicking.\n\n- Adds the `tlsDisableCertificateRevocationCheck` connection option, which disables certificate revocation checking for TLS connections. When enabled, the driver skips revocation checks but still verifies the certificate chain and hostname. For more information about connection options, see Specify Connection Options.\n\nFor more information about the changes in this version, see the v2.9 release notes on GitHub.\n\n## What's New in 2.8.2\n\nThe Go driver v2.8.2 release includes the following change:\n\nGo driver v2.8.2 includes a fix for CVE-2026-81521.\n\nFor the latest information about MongoDB security updates, see MongoDB Security Bulletins.\n\nFor a complete list of changes in this version, see the v2.8.2 release notes on GitHub.\n\n## What's New in 2.8.1\n\nThis release includes the following fix:\n\n- Fixes an issue where a failed write operation could appear to succeed. In earlier versions, when a write's first try failed with a `NoWritesPerformed` error label, the driver could return a `nil`/`ErrNoDocuments` result instead of the actual error. The driver now returns the real server error in this case.\n\nFor more information about the changes in this version, see the v2.8.1 release notes on GitHub.\n\n## What's New in 2.8\n\nThis release includes the following improvements and fixes:\n\n- Promotes Queryable Encryption (QE) `prefix`, `suffix`, and `substring` queries to general availability (GA). These query types require MongoDB Server v9.0 or later.\n\n- Renames the QE string-query API from `Text` to `String`. To perform a QE string query, make the following changes:\n\n - Use the `options.String()` method instead of `options.Text()`.\n\n - Use the `StringOptions*` types instead of `TextOptions*`.\n\n - Use the `EncryptOptionsBuilder.SetStringOptions()` method instead of `SetTextOptions()`.\n\n- Upgrades the `libmongocrypt` version to 1.20.0.\n\nFor more information about the changes in this version, see the v2.8 release notes on GitHub.\n\n## What's New in 2.7\n\nThis release includes the following improvements and fixes:\n\n- Adds support for sending `afterClusterTime` on writes in causally consistent sessions, improving alignment between read and write behavior in session-based workflows.\n\n- Deprecates the `x/mongo/driver/session` package to clarify which surfaces are intended for long-term public use.\n\n- Deprecates `AggregateOptions.Custom` as an internal-only option.\n\n- Fixes `Collection.Clone()` to propagate `BSONOptions` to the cloned collection.\n\n- Fixes `mongo.ErrorCodes()` to correctly parse server error codes from a `ClientBulkWriteException`.\n\n- Fixes a panic in `bson.Raw.Validate()` when called on a zero-length BSON document.\n\n- Fixes a nil cursor error when calling `SetBatchSize` on a change stream.\n\nTo learn more about this release, see the v2.7.0 Release Notes on GitHub.\n\n## What's New in 2.6\n\nThis release includes the following improvements and fixes:\n\n- Deprecates MongoDB Server 4.2 support. The minimum required server version in future releases will be MongoDB Server 4.4 or later.\n\n- Adds support for MongoDB's Intelligent Workload Management (IWM). The Go driver now gracefully handles write-blocking scenarios and optimizes connection establishment during high-load conditions to maintain application availability. To learn more about IWM, see Write-Blocking in the Atlas documentation. These features will be available on Atlas clusters running MongoDB 9.0 and later.\n\n- Introduces two methods of `ClientOptions`:\n\n - `SetAutoEncryptionOptions()`: specifies the maximum number of times the driver should retry operations that fail with a server-side overload error.\n\n - `SetAutoEncryptionOptionsFromClient()`: specifies whether the driver should enable overload retargeting for operations that fail with a server-side overload error.\n\n You can also set these options by using the `maxAdaptiveRetries` and `enableOverloadRetargeting` URI options. To learn more about these options and how to set them, see Customize Cluster Settings.\n\nFor information about the changes in this version, see the v2.6 release notes on GitHub.\n\n## What's New in 2.5.1\n\nThis release includes the following fixes:\n\n- Fixes two BSON unmarshaling edge cases.\n\nFor more information about the changes in this version, see the v2.5.1 release notes on GitHub."} -{"chunk_id": "699fe5cda6fa0684a38c2b39-1", "page_id": "699fe5cda6fa0684a38c2b39", "source_name": "golang", "product_name": "Go Driver", "url": "https://mongodb.com/docs/drivers/go/current/reference/release-notes", "title": "Release Notes", "text": "## What's New in 2.5\n\nThis release includes the following improvements and fixes:\n\n- Adds a preview of CRUD support for Queryable Encryption prefix, suffix, and substring indexes. These features are are unstable and their security is not guaranteed until released as Generally Available (GA). The GA version of these features may not be backwards compatible with the preview version.\n\n- Adds `AsFloat64()` and `AsFloat64OK()` methods to `bson.RawValue`.\n\n- Adds the `DefaultDocumentMap()` method to `bson.Decoder`.\n\n- Adds the `ErrorCodes()` method to parse server error codes from an arbitrary Go error.\n\n- Exposes `atClusterTime` in snapshot sessions.\n\n- Fixes several bugs, including a potential heap out-of-bounds read in GSSAPI error handling.\n\nFor more information about the changes in this version, see the v2.5 release notes on GitHub.\n\n## What's New in 2.4.4\n\nThis release includes the following fixes:\n\n- Fixes a resource leak in the round-trip time (RTT) monitor.\n\n- Adds command logging for transaction operations.\n\nFor more information about the changes in this version, see the v2.4.4 release notes on GitHub.\n\n## What's New in 2.4.1\n\nThis release includes the following fixes:\n\n- Adds handling for an empty `options` parameter in the `SearchIndexModel`\n\n## What's New in 2.4\n\nThe Go driver v2.4 release contains breaking changes. For more information, see Version 2.4 Breaking Changes.\n\nThis release includes the following improvements and fixes:\n\n- Adds a new `Client.AppendDriverInfo()` method that adds information to the driver metadata sent on subsequent connection handshakes.\n\n- The driver no longer sends `$clusterTime` with heartbeat commands, and heartbeat commands no longer parse `$clusterTime` from responses.\n\n- Renames the internal file `internal/decinal123/decinal123.go` to `internal/decimal123/decimal123.go` to fix a typo in the package name.\n\nFor more information about the changes in this version, see the v2.4 release notes on GitHub.\n\n## What's New in 2.3\n\nThe Go driver v2.3 release is the last release to support MongoDB 4.0. The Go driver v2.4 release will require MongoDB 4.2 or later. The minimum Go version for the Go driver v2.3 release is Go 1.19.\n\nThis release includes the following improvements and fixes:\n\n- Fixes an issue where calls to `cursor.Next()` with a `maxAwaitTimeMS` value greater than or equal to the operation timeout result in socket timeouts. The driver now short-circuits these calls to prevent timeout errors.\n\n- Fixes an issue where `Element.StringN()` did not truncate strings as expected.\n\n- Improves `bson.Unmarshal()` performance.\n\nFor more information about the changes in this version, see the v2.3 release notes on GitHub.\n\n## What's New in 2.2\n\nThe Go driver v2.2 release contains breaking changes. For more information, see Version 2.2 Breaking Changes.\n\nThis release includes the following improvements and fixes:\n\n- Adds the `OmitEmpty` BSON option to globally prevent empty values from being serialized. To learn more about setting the `OmitEmpty` global flag, see the example in the BSON Options section of the BSON guide.\n\n- Adds support for Kubernetes OIDC authentication. To learn more about how to configure MongoDB authentication for a Kubernetes cluster, see the Kubernetes OIDC section of the Enterprise Authentication Mechanisms guide.\n\n- Adds support to configure the lifetime of the Data Encryption Key (DEK) cache. To learn more about DEK management, see the Encryption Key Management guide in the MongoDB Server manual.\n\n- Adds support for `error.Is` and `error.As` functions for improved error management. To learn more, see the error.Is and error.As Go API documentation.\n\nFor more information about the changes in this version, see the v2.2 release notes on GitHub.\n\n## What's New in 2.1\n\nThe 2.1 Go driver release includes the following improvements and fixes:\n\n- Introduces the Client.BulkWrite method, enabling clients to perform multiple insert, update, and delete operations across multiple databases and collections in a single request. To learn more, see the Bulk Operations guide.\n\n- Introduces the bson.Vector type to make inserting and querying vector data by using MongoDB Vector Search easier and more efficient. To view an example that uses the `bson.Vector` type, see the MongoDB Vector Search guide.\n\n- Extends the ServerError interface to include `ErrorCodes`, which returns a list of deduplicated error codes returned by the server during the lifetime of operation execution.\n\n- Adds the `sort` option to UpdateOneOptions and ReplaceOptions for standalone update and replace operations and in bulk operations.\n\nFor more information about the changes in this version, see the v2.1 release notes on GitHub."} -{"chunk_id": "699fe5cda6fa0684a38c2b39-2", "page_id": "699fe5cda6fa0684a38c2b39", "source_name": "golang", "product_name": "Go Driver", "url": "https://mongodb.com/docs/drivers/go/current/reference/release-notes", "title": "Release Notes", "text": "## What's New in 2.0\n\nThe 2.0 Go driver release supports OpenID Connect (OIDC) authentication, provides a smoother client-side operations timeout (CSOT) experience, and implements clearer, more idiomatic Go code by streamlining APIs, improving errors descriptions, and simplifying the driver package structure.\n\nYou can learn more about these changes in this section, or by viewing the v2.0 Migration Guide in the Go driver source code on GitHub.\n\nThe Go driver v2.0 release contains breaking changes. For more information, see Version 2.0 Breaking Changes.\n\nThis release includes the following improvements and fixes:\n\n- Documentation support for OpenID Connect (OIDC) authentication. To learn more, see the OIDC Authentication Mechanism guide.\n\n- You can access the GridFS API from the `mongo` package. In previous versions, you could access GridFS functions from the separate `gridfs` package, but this functionality is now merged with the main driver `mongo` package. To learn more, see the GridFS guide.\n\n- The `Comment` field in any options struct takes a value of type `any` instead of type `string`. To set this field, you can use the `SetComment()` method and pass a parameter of type `any`.\n\n- Updates to monitoring event documents:\n\n - The `CommandStartedEvent` and `CommandFinishedEvent` structs have a single `ServerConnectionID` field of type `int64` to capture the connection ID.\n\n - The `ConnectionID` field of the `PoolEvent` struct takes a value of type `int64` instead of `uint64`.\n\n To view sample event documents, see the Monitor Application Events guides.\n\n- The `Session` interface is converted to a struct. See the Transactions guide to learn more.\n\n- The `Distinct()` method returns a struct that can be decoded into a specified type. See the Retrieve Distinct Values guide to learn more.\n\n- The `IndexView.DropOne()` method returns only an error, if present. In previous versions, this method also returned the server response, which contained the number of dropped indexes. See the Remove an Index section of the Indexes guide to learn more.\n\n- Updates to the builder pattern for types in the `options` package. The pattern maintains a slice of setter functions, so you cannot set data directly to an options object. This update does not generally change how you create and use options. To learn more, see the feature JIRA ticket.\n\n- The driver no longer supports the `mongo.ErrUnacknowledgedWrite` sentinel error if a write operation is not acknowledged. To confirm that the server acknowledged a write operation, you must access the `Acknowledged` property from the result struct returned by the write method.\n\n The following example shows how to confirm acknowledgment of an insert operation:\n\n ```go\n res, err := coll.InsertOne(context.TODO(), bson.D{{\"x\", 2}})\n if err != nil {\n panic(err)\n }\n\n fmt.Print(res.Acknowledged)\n ```\n\n- You can set options for transactions run in a given session by creating a `TransactionOptions` instance and passing the instance to the `SetDefaultTransactionOptions()` method of the `SessionOptions` type. To learn more, see the Session and Transaction Options section of the Transactions guide.\n\n- The `Collection.Clone()` method does not return an error.\n\n- Renames the `canonical` parameter of the `UnmarshalExtJSON()` method to `canonicalOnly`. If you set `canonicalOnly` to `true`, the method returns an error if the extended JSON is not marshaled in canonical mode. If set to `false`, the method can unmarshal canonical or relaxed extended JSON. To learn more, see the UnmarshalExtJSON() API documentation.\n\n## What's New in 1.17.10\n\nThe 1.17.10 Go driver patch release includes the following bug fix:\n\n- Fixes a Common Vulnerabilities and Exposures (CVE) issue where a caller-supplied structured file identifier was interpreted as a query condition rather than as a literal identifier in GridFS methods. To learn more, see the related CVE-2026-88031 issue.\n\n## What's New in 1.17.9\n\nThe 1.17.9 Go driver patch release includes the following bug fix:\n\n- Fixes the following Common Vulnerabilities and Exposures (CVE) issue: a length\u2011delimited GSSAPI buffer being treated as a null\u2011terminated C string. To learn more, see the related CVE-2026-2303 issue.\n\n## What's New in 1.17.8\n\nThe 1.17.8 Go driver patch release formally deprecates the v1 Go driver.\n\nThe 1.17.8 Go driver patch includes the following change:\n\n- Deprecates Go driver v1 and adds a depreciation notice to the `go.mongodb.org/mongo-driver`. Users should migrate to `go.mongodb.org/mongo-driver/v2`. To learn how to upgrade your application from v1 to v2, see the Go Driver 2.0 Migration Guide.\n\nFor more information about the changes in this version, see the v1.17.8 release notes on GitHub.\n\n## What's New in 1.17\n\nv1.17 is the final planned 1.x version release. This version will receive security and bug fixes, but future development and features will be included only in 2.x versions of the driver.\n\nThe 1.17 Go driver release includes the following improvements and fixes:\n\n- Adds support for OpenID Connect (OIDC) authentication. To learn more, see the OIDC Authentication Mechanism guide.\n\n- Adds support for Queryable Encryption (QE) range queries. To use this feature, your app must connect to MongoDB Server 8.0 or later. For more information about QE range queries, see Queryable Encryption in the MongoDB Server manual.\n\n- Adds support for MongoDB Server 8.0, except for the client bulk write feature.\n\n- Extends the `IndexView` type to include the `DropOneWithKey()` and `DropWithKey()` methods so you can drop indexes by using their key specifications instead of their names.\n\nFor more information about the changes in this version, see the v1.17 release notes on GitHub.\n\n## What's New in 1.16\n\nThe 1.16 Go driver release includes the following improvements and fixes:\n\n- Adds support for specifying an index type when creating a MongoDB Search index.\n\n- Reduces memory usage when the `zstd` compression algorithm is enabled.\n\n- Upgrades some dependency requirements. For a list of upgrades, see the \"Upgrade Dependencies\" section of the v1.16 release notes.\n\nFor more information about these changes, see the v1.16 release notes on Github.\n\n## What's New in 1.15.1\n\nThe 1.15.1 Go driver patch release includes the following improvements and fixes:\n\n- Fixes a possible connection leak where disconnecting from a replica set cluster left behind `rttMonitor` connections.\n\n- Adds support for manually specifying a `maxTimeMS` value for read and aggregation operations when a client-wide timeout and an operation timeout are set.\n\n- Adds a `RemainingBatchLength()` method that you can call on a change stream.\n\nFor more information about these changes, see the v1.15.1 release notes on Github.\n\n## What's New in 1.15\n\nThe 1.15 Go driver release includes the following improvements and fixes:\n\n- Connection churn can be mitigated by setting a client-wide timeout by specifying the `timeoutMS` connection option or by calling the SetTimeout() function. When the timeout is set, the driver attempts to reuse a connection after an operation times out and waits for up to one second to check if the connection can be reused before closing it.\n\n- Connection pool events include a `Duration` field to measure the checkout duration and total amount of time it took to establish a connection.\n\n## What's New in 1.14\n\nThe 1.14 Go driver release includes the following improvements and fixes:\n\n- Go versions before 1.18 are no longer supported.\n\n- In case of a heartbeat timeout, in-progress operations are preemptively canceled.\n\n- Connection strings that include the `\"mongodb+srv://\"` prefix can contain capital letters in the SRV hostname."} -{"chunk_id": "699fe5cda6fa0684a38c2b39-3", "page_id": "699fe5cda6fa0684a38c2b39", "source_name": "golang", "product_name": "Go Driver", "url": "https://mongodb.com/docs/drivers/go/current/reference/release-notes", "title": "Release Notes", "text": "## What's New in 1.13\n\nThe 1.13 Go driver release includes the following improvements and fixes:\n\n- Logging for server selection and SDAM. To learn more about logging, see the Logging documentation.\n\n- Methods on the `Collection` type that allow you to manage search indexes programmatically.\n\n- The `event.CommandStartedEvent` and `event.CommandFinishedEvent` events return the `DatabaseName` field. This field is also included in the command-logging analogs.\n\n- In a sharded topology, when selecting a server to retry an unsuccessful query, the driver excludes the server used for the initial attempt. Instead, if there's more than one eligible `mongos` instance, the driver randomly selects one. Unhealthy instances are automatically excluded from selection.\n\n- Streaming SDAM is disabled by default on AWS Lambda and similar function-as-a-service (FaaS) platforms. You can enable monitoring by using the `serverMonitoringMode` URI option.\n\n## What's New in 1.12.1\n\nThe 1.12 Go driver release includes the following improvements and fixes:\n\n- The driver unpins connections when ending a session. This prevents connections from leaking when a user runs a transaction while connected to a load balancer.\n\n- The driver does not throw a runtime error when you unmarshal an empty `bson.RawValue` type with an invalid type or marshal a `nil` pointer of a `ReadConcern` instance.\n\n- Setting `options.LogComponentAll` as the log component correctly results in the publication of logs against all components.\n\n## What's New in 1.12\n\n- The `mongo.NewClient()` and `client.Connect()` methods are deprecated. You can create a client and connect in one call by using the `mongo.Connect()` method.\n\nNew features of the 1.12 Go driver release include:\n\n### Queryable Encryption\n\nThis driver version adds support for Queryable Encryption (QE). To learn more about the requirements for using the QE feature, see the Queryable Encryption Driver Compatibility Table.\n\nThe `ClientEncryption.CreateEncryptedCollection()` method automatically creates data encryption keys when you create a new encrypted collection. To learn how to use the QE feature, see the Queryable Encryption Quick Start in the Server manual.\n\n### Logging Interface\n\nYou can now record connection management and command execution events by using the `LogSink` logging interface.\n\nTo learn more, see the Logging guide.\n\n### Additional BSON Marshalling Options\n\nThis driver version adds features to the `options` package to specify how the driver marshals and unmarshals BSON.\n\nThe following example shows how to set BSON options on your `Client`. The options specify the following behaviors:\n\n- The driver falls back to `json` struct tags if `bson` struct tags are absent.\n\n- The driver marshals `nil` Go map types as empty BSON documents.\n\n- The driver marshals `nil` Go slice types as empty BSON arrays.\n\n```go\nbsonOpts := &options.BSONOptions{\n UseJSONStructTags: true,\n NilMapAsEmpty: true,\n NilSliceAsEmpty: true,\n}\noptions.Client().SetBSONOptions(bsonOpts)\n```\n\nFor a full example of how to specify and implement the `BSONOptions` type, see the API documentation.\n\n### Simplified Write Concern Specification\n\nThis driver version simplifies the `WriteConcern` API. To learn more about the changes, see Write Concern.\n\n### Additional Changes\n\n- Support for authentication with AWS IAM roles in EKS.\n\n- Addition of the `Cursor.SetBatchSize()` method to allow specification of the size of batches fetched when iterating through a cursor.\n\n- Addition of the `UnmarshalValue()` method to allow ummarshalling of BSON values marshalled with the `MarshalValue()` method."} -{"chunk_id": "699fe5cda6fa0684a38c2aa6-0", "page_id": "699fe5cda6fa0684a38c2aa6", "source_name": "golang", "product_name": "Go Driver", "url": "https://mongodb.com/docs/drivers/go/current/connect/connection-troubleshooting", "title": "Connection Troubleshooting", "text": "# Connection Troubleshooting\n\nThis page offers potential solutions to issues you might encounter when using the MongoDB Go Driver to connect to a MongoDB deployment.\n\nThis page addresses only connection issues. If you encounter any other issues with MongoDB or the driver, visit the following resources:\n\n- The Issues & Help page, which has information about reporting bugs, contributing to the driver, and finding additional resources\n\n- The MongoDB Stack Overflow tag or the MongoDB Reddit community for questions, discussions, or general technical support\n\n## Connection Error\n\nThe following error message is a general message indicating that the driver cannot connect to a server on the specified hostname or port:\n\n```none\nError: couldn't connect to server 127.0.0.1:27017\n```\n\nThe following sections describe methods that may help resolve the issue.\n\n### Check Connection String\n\nVerify that the hostname and port number in the connection string are both accurate. In the sample error message, the hostname is `127.0.0.1` and the port is `27017`. The default port value for a MongoDB instance is `27017`, but you can configure MongoDB to communicate on another port.\n\n### Configure Firewall\n\nAssuming that your MongoDB deployment uses the default port, verify that port `27017` is open in your firewall. If your deployment uses a different port, verify the correct port is open in your firewall.\n\nDo not open a port in your firewall unless you are sure that it is the port used by your MongoDB instance.\n\n## Authentication Error\n\nThe Go driver can fail to connect to a MongoDB instance if the authorization is not configured correctly. In these cases, the driver raises an error message similar to one of the following messages:\n\n```none\nCommand failed with error 18 (AuthenticationFailed): 'Authentication\nfailed.' on server localhost:27017.\n```\n\n```none\nconnection() error occurred during connection handshake: auth error:\nsasl conversation error: unable to authenticate using mechanism\n\"SCRAM-SHA-256\": (AuthenticationFailed) Authentication failed.\n```\n\nThe following sections describe methods that may help resolve the issue.\n\n### Check Connection String\n\nAn invalid connection string is the most common cause of authentication issues when attempting to connect to MongoDB.\n\nFor more information about connection strings, see the Connection URI section of the Create a MongoClient guide.\n\nIf your connection string contains a username and password, ensure that they are in the correct format.\n\nIf the username or password includes any of the following characters, they must be percent encoded:\n\n```none\n: / ? # [ ] @\n```\n\nWhen connecting to a replica set, include all the replica set hosts in your connection string. Separate each of the hosts in the connection string with a comma. This enables the driver to establish a connection if one of the hosts is unreachable.\n\n### Verify the Authentication Mechanism\n\nEnsure that your credentials and authentication mechanism are correct. You can store your authentication credentials in environment variables or you can pass them to the `SetAuth()` method.\n\nTo learn more about authentication, see the Authentication Mechanisms guide.\n\n### Verify User Is in Authentication Database\n\nTo successfully authenticate a connection by using a database username and password, the username must be defined in the authentication database. The default authentication database is the `admin` database. To use a different database for authentication, specify the `authSource` in the connection string. The following example instructs the driver to use `users` as the authentication database:\n\n```go\nuri := \"mongodb://:@:/?authSource=users\"\nclient, err := mongo.Connect(options.Client().ApplyURI(uri))\n```\n\n## Error Sending Message\n\nWhen the driver fails to send a command after you make a request, it often displays the following general error message:\n\n```none\ncom.mongodb.MongoSocketWriteException: Exception sending message\n```\n\nThe following sections describe methods that may help resolve the issue.\n\n### Check Connection String\n\nVerify that the connection string in your app is accurate. For more information about verifying your connection string, see Connection Error and Authentication Error.\n\n### Verify the Authentication Mechanism\n\nMake sure you are using the correct authentication mechanism and credentials. For more information about authentication errors, see Authentication Error.\n\n### Verify User Is in Authentication Database\n\nVerify the user is in the correct authentication database. For more information about the authentication database, see Authentication Error.\n\n### Configure Firewall\n\nThe firewall must have an open port for communicating with the MongoDB instance. For more information about configuring the firewall, see Connection Error.\n\n### Check the Number of Connections\n\nEach `Client` instance supports a maximum number of concurrent open connections in its connection pool. The configuration parameter `maxPoolSize` defines this value and is set to `100` by default. If there are already a number of open connections equal to `maxPoolSize`, the server waits until a connection becomes available. If this wait time exceeds the `maxIdleTimeMS` value, the driver responds with an error. For more information about how connection pooling works, see Create a Connection Pool.\n\n## Timeout Error\n\nSometimes when you send a request through the driver to the server, the request times out. When this happens, you might receive an error message similar to the following message:\n\n```none\ntimed out while checking out a connection from connection pool: context canceled\n```\n\nIf you receive this error, try the following methods to resolve the issue.\n\n### Set Timeout Option\n\nThe `Client` supports a single `Timeout` option that controls the amount of time a single operation can take to execute. You can set this value by using the `SetTimeout()` method or by specifying the `timeoutMS` option in your connection string.\n\nThe following example sets the single timeout value to 5 seconds using the connection string option:\n\n```go\nuri := \"mongodb://:@:27017/?timeoutMS=5000\"\nclient, err := mongo.Connect(options.Client().ApplyURI(uri))\n```\n\n### Check the Number of Connections\n\nThe number of connections to the server may exceed `maxPoolSize`. For more information about checking the number of connections, see Error Sending Message."} -{"chunk_id": "699fe5cda6fa0684a38c2b01-0", "page_id": "699fe5cda6fa0684a38c2b01", "source_name": "golang", "product_name": "Go Driver", "url": "https://mongodb.com/docs/drivers/go/current/crud/update/upsert", "title": "Insert or Update in a Single Operation", "text": "# Insert or Update in a Single Operation\n\n## Overview\n\nIn this guide, you can learn how to perform an upsert.\n\n### Sample Data\n\nThe example in this guide uses the following `Plant` struct as a model for documents in the `plants` collection:\n\n```go\ntype Plant struct {\n\tSpecies string\n\tPlantID int32 `bson:\"plant_id\"`\n\tHeight float64\n}\n\n```\n\nTo run the example in this guide, load the sample data into the `db.plants` collection with the following snippet:\n\n```go\ncoll := client.Database(\"db\").Collection(\"plants\")\ndocs := []any{\n\tPlant{Species: \"Polyscias fruticosa\", PlantID: 1, Height: 27.6},\n\tPlant{Species: \"Polyscias fruticosa\", PlantID: 2, Height: 34.9},\n\tPlant{Species: \"Ledebouria socialis\", PlantID: 1, Height: 11.4},\n}\n\nresult, err := coll.InsertMany(context.TODO(), docs)\n```\n\nEach document contains a description of an individual plant that includes the species, plant ID, and height corresponding to the `species`, `plant_id`, and `height` fields in each document.\n\nIf the necessary database and collection don't exist when you perform a write operation, the server implicitly creates them.\n\n## Upsert\n\nApplications use insert and update operations to store and modify data. Sometimes, you must choose between an insert and an update operation depending on whether the document exists. MongoDB simplifies this decision for us with an **upsert** option.\n\nAn upsert performs one of the following actions:\n\n- Updates documents that match your query filter\n\n- Inserts a new document if there are no matches to your query filter\n\nYou can specify an upsert by passing `true` to the `SetUpsert()` method in the options of the following write operation methods:\n\n- `UpdateOne()`\n\n- `UpdateByID()`\n\n- `UpdateMany()`\n\n- `ReplaceOne()`\n\n- `FindOneAndUpdate()`\n\n- `FindOneAndReplace()`\n\nIf you don't specify an upsert, no change occurs in the write operation when zero documents match your query filter. This is equivalent to passing `false` to the `SetUpsert()` method.\n\n## Example\n\nThe following example performs the following actions:\n\n- Matches documents where the `species` is `\"Ledebouria socialis\"` and the `plant_id` is `3`\n\n- Updates the `height` of the matched document to `8.3`\n\n- Inserts this document if there are no matches to the query filter\n\n```go\nfilter := bson.D{{\"species\", \"Ledebouria socialis\"}, {\"plant_id\", 3}}\nupdate := bson.D{{\"$set\", bson.D{{\"species\", \"Ledebouria socialis\"}, {\"plant_id\", 3}, {\"height\", 8.3}}}}\n\n// Sets the upsert option to true\nopts := options.UpdateOne().SetUpsert(true)\n\n// Updates a documents or inserts a document if no documents are\n// matched and prints the results\nresult, err := coll.UpdateOne(context.TODO(), filter, update, opts)\nif err != nil {\n\tpanic(err)\n}\n\nfmt.Printf(\"Number of documents updated: %v\\n\", result.ModifiedCount)\nfmt.Printf(\"Number of documents upserted: %v\\n\", result.UpsertedCount)\n```\n\n```none\nNumber of documents updated: 0\nNumber of documents upserted: 1\n```\n\nIf you query the `plants` collection to view all documents, you can see that since the query filter did not match any documents, a new document was inserted with the specified fields:\n\n```none\n{\"species\":\"Polyscias fruticosa\",\"plant_id\":1,\"height\":27.6}\n{\"species\":\"Polyscias fruticosa\",\"plant_id\":2,\"height\":34.9}\n{\"species\":\"Ledebouria socialis\",\"plant_id\":1,\"height\":11.4}\n{\"species\":\"Ledebouria socialis\",\"plant_id\":3,\"height\":8.3}\n```\n\n## Additional Information\n\nTo learn more about the operations mentioned, see the following guides:\n\n- Specify a Query\n\n- Update Documents\n\n- Compound Operations\n\n### API Documentation\n\nTo learn more about any of the methods or types mentioned in this guide, see the following API Documentation:\n\n- UpdateOne()\n\n- UpdateByID()\n\n- UpdateMany()\n\n- ReplaceOne()\n\n- FindOneAndUpdate()\n\n- FindOneAndReplace()\n\n- UpdateOneOptionsBuilder.SetUpsert()\n\n- ReplaceOptionsBuilder.SetUpsert()\n\n- UpdateResult"} -{"chunk_id": "699fe5cda6fa0684a38c2b44-0", "page_id": "699fe5cda6fa0684a38c2b44", "source_name": "golang", "product_name": "Go Driver", "url": "https://mongodb.com/docs/drivers/go/current/reference/upgrade", "title": "Upgrade Driver Versions", "text": "# Upgrade Driver Versions\n\n## Overview\n\nThis page describes the changes you must make to your application when you upgrade to a new version of the Go driver.\n\nBefore you upgrade, perform the following actions:\n\n- Ensure the new Go driver version is compatible with the MongoDB Server version your application connects to and the Go version your application runs on. For more information, see the Compatibility page.\n\n- Address any breaking changes between the driver versions your application uses and your planned upgrade version in the Breaking Changes section.\n\nTo minimize the number of changes your application requires when upgrading driver versions in the future, use the Stable API.\n\n## Breaking Changes\n\nA breaking change is a change of a convention or a behavior starting in a specific version of the driver. This type of change may prevent your application from working properly if not addressed before upgrading the driver.\n\nThe breaking changes in this section are categorized by the driver version that introduced them. When upgrading driver versions, address all the breaking changes between the current and upgrade versions.\n\n### Version 2.9 Breaking Changes\n\n- Drops support for Go versions earlier than 1.25. The minimum supported Go version is now 1.25, and the Go driver supports the two most recent Go minor versions. To learn more about compatibility with Go versions, see the Compatibility page.\n\n- Drops support for MongoDB Server v4.2. The minimum supported MongoDB Server version is now 4.4. To learn more about compatibility with MongoDB Server versions, see the Compatibility page.\n\n- Upgrades the `golang.org/x/text` module to v0.39.0 to resolve CVE-2026-56852. This upgrade raises the minimum required Go version to 1.25. For the latest information about MongoDB security updates, see MongoDB Security Bulletins.\n\n### Version 2.4 Breaking Changes\n\n- Drops support for MongoDB Server v4.0. The minimum supported MongoDB Server version is now v4.2. To learn more about compatibility with MongoDB Server versions, see the Compatibility page.\n\n### Version 2.2 Breaking Changes\n\n- Drops support for MongoDB Server v3.6. The minimum supported MongoDB Server version is now v4.0. This also drops support for the `MONGODB-CR` authentication mechanism. To learn more about compatibility with MongoDB Server versions, see the Compatibility page.\n\n### Version 2.0 Breaking Changes\n\n- `mongo.Connect()` does not accept a Context parameter. This method accepts only an options object. To view an example that uses this method, see the Connection Example Code in the Connection Guide.\n\n- The `Cursor.SetMaxTime()` method is renamed to `Cursor.SetMaxAwaitTime()`. This method specifies the maximum time that the server waits for new documents retrieved from a capped collection with a tailable cursor.\n\n- Removal of operation-specific timeout options. The following fields and setter methods have been removed from the driver:\n\n - `AggregateOptions.MaxTime`, `AggregateOptions.SetMaxTime()`\n\n - `ClientOptions.SocketTimeout`, `ClientOptions.SetSocketTimeout()`\n\n - `CountOptions.MaxTime`, `CountOptions.SetMaxTime()`\n\n - `DistinctOptions.MaxTime`, `DistinctOptions.SetMaxTime()`\n\n - `EstimatedDocumentCountOptions.MaxTime`, `EstimatedDocumentCountOptions.SetMaxTime()`\n\n - `FindOptions.MaxTime`, `FindOptions.SetMaxTime()`\n\n - `FindOneOptions.MaxTime`, `FindOneOptions.SetMaxTime()`\n\n - `FindOneAndReplaceOptions.MaxTime`, `FindOneAndReplaceOptions.SetMaxTime()`\n\n - `FindOneAndUpdateOptions.MaxTime`, `FindOneAndUpdateOptions.SetMaxTime()`\n\n - `GridFSFindOptions.MaxTime`, `GridFSFindOptions.SetMaxTime()`\n\n - `CreateIndexesOptions.MaxTime`, `CreateIndexesOptions.SetMaxTime()`\n\n - `DropIndexesOptions.MaxTime`, `DropIndexesOptions.SetMaxTime()`\n\n - `ListIndexesOptions.MaxTime`, `ListIndexesOptions.SetMaxTime()`\n\n - `SessionOptions.DefaultMaxCommitTime`, `SessionOptions.SetDefaultMaxCommitTime()`\n\n - `TransactionOptions.MaxCommitTime`, `TransactionOptions.SetMaxCommitTime()`\n\n - `WriteConcern.WTimeout`\n\n Instead, you can set a timeout on your client or within a Context. Learn more in the Limit Server Execution Time guide.\n\n- Removal of the `bson/primitive` package. This package is now merged with the `bson` package. To update your code, remove any `bson/primitive` import statements and change any instance of `primitive.ObjectID` to `bson.ObjectId`.\n\nTo learn how to upgrade your application from v1 to v2, see the Go Driver 2.0 Migration Guide."} -{"chunk_id": "699fe5cda6fa0684a38c2af7-0", "page_id": "699fe5cda6fa0684a38c2af7", "source_name": "golang", "product_name": "Go Driver", "url": "https://mongodb.com/docs/drivers/go/current/crud/update/replace", "title": "Replace Documents", "text": "# Replace Documents\n\n## Overview\n\nIn this guide, you can learn how to use the Go driver to perform a replace operation on a document in a MongoDB collection. A replace operation performs differently than an update operation. An update operation modifies only the specified fields in a target document. A replace operation removes all fields in the target document and replaces them with new ones.\n\n## Parameters\n\n`ReplaceOne()` expects a **replacement document**, which is the document that you want to take the place of an existing document. Replacement documents use the following format:\n\n```go\nbson.D{{\"\", \"\"}, {\"\", \"\"}, ... }\n```\n\n## Return Values\n\n`ReplaceOne()` returns an `UpdateResult` type that contains information about the replace operation if the operation is successful. The `UpdateResult` type contains the following properties:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nProperty\n\n\nDescription\n\n
\n`MatchedCount`\n\n\nThe number of documents matched by the filter\n\n
\n`ModifiedCount`\n\n\nThe number of documents modified by the operation\n\n
\n`UpsertedCount`\n\n\nThe number of documents upserted by the operation\n\n
\n`UpsertedID`\n\n\nThe `_id` of the upserted document, or `nil` if there is none\n\n
If multiple documents match the query filter passed to `ReplaceOne()`, the method selects and replaces the first matched document. Your replace operation fails if no documents match the query filter.\n\n## Example\n\nThe following document describes a kitchen item:\n\n```json\n{\n \"_id\" : 2056,\n \"item\" : \"Mug\",\n \"brand\" : \"Simply Ceramics\",\n \"price\" : 2.99,\n \"material\" : \"Glass\"\n}\n```\n\nThe following example uses the `ReplaceOne()` method to substitute this document with one that contains an `item` field with a value of \"Cup\" and a `quantity` field with a value of 107:\n\n```go\nfilter := bson.D{{\"_id\", 2056}}\nreplacement := bson.D{{\"item\", \"Cup\"}, {\"quantity\", 107}}\n\nresult, err := collection.ReplaceOne(context.TODO(), filter, replacement)\nfmt.Printf(\"Documents matched: %v\\n\", result.MatchedCount)\nfmt.Printf(\"Documents replaced: %v\\n\", result.ModifiedCount)\n```\n\n```none\nDocuments matched: 1\nDocuments replaced: 1\n```\n\nThe replaced document contains the contents of the replacement document and the immutable `_id` field as follows:\n\n```json\n{\n \"_id\" : 2056,\n \"item\" : \"Cup\",\n \"quantity\" : 107\n}\n```\n\n## Replace One Document Example: Full File\n\nThis example connects to an instance of MongoDB by using a connection URI. To learn more about connecting to your MongoDB instance, see Create a MongoClient. This example also uses the `restaurants` collection in the `sample_restaurants` database included in the Atlas sample datasets. You can load them into your database on a free cluster on MongoDB Atlas by following the steps in Get Started with Atlas.\n\nThis example performs the following actions on the `restaurants` collection:\n\n- Matches a document in which the value of `name` is `\"Rizzo's Fine Pizza\"`\n\n- Replaces the matched document with a new document\n\n```go\n// Replaces the first document that matches a filter by using the Go driver\npackage main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com/joho/godotenv\"\n\t\"go.mongodb.org/mongo-driver/v2/bson\"\n\t\"go.mongodb.org/mongo-driver/v2/mongo\"\n\t\"go.mongodb.org/mongo-driver/v2/mongo/options\"\n)\n\ntype Restaurant struct {\n\tName string\n\tRestaurantId string `bson:\"restaurant_id,omitempty\"`\n\tCuisine string `bson:\"cuisine,omitempty\"`\n\tAddress any `bson:\"address,omitempty\"`\n\tBorough string `bson:\"borough,omitempty\"`\n\tGrades []any `bson:\"grades,omitempty\"`\n}\n\nfunc main() {\n\tif err := godotenv.Load(); err != nil {\n\t\tlog.Println(\"No .env file found\")\n\t}\n\n\tvar uri string\n\tif uri = os.Getenv(\"MONGODB_URI\"); uri == \"\" {\n\t\tlog.Fatal(\"You must set your 'MONGODB_URI' environment variable. See\\n\\t https://www.mongodb.com/docs/drivers/go/current/connect/mongoclient/#environment-variable\")\n\t}\n\n\tclient, err := mongo.Connect(options.Client().ApplyURI(uri))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer func() {\n\t\tif err = client.Disconnect(context.TODO()); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}()\n\n\tcoll := client.Database(\"sample_restaurants\").Collection(\"restaurants\")\n\tfilter := bson.D{{\"name\", \"Rizzo's Fine Pizza\"}}\n\n\t// Creates a new document containing \"Name\" and \"Cuisine\" fields\n\treplacement := Restaurant{Name: \"Rizzo's Pizza\", Cuisine: \"Pizza/American\"}\n\n\t// Replaces the first document that matches the filter with a new document\n\tresult, err := coll.ReplaceOne(context.TODO(), filter, replacement)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Prints the number of modified documents\n\tif result.MatchedCount != 0 {\n\t\tfmt.Println(\"Number of documents replaced:\", result.ModifiedCount)\n\t}\n\n\t// When you run this file for the first time, it should print:\n\t// Number of documents replaced: 1\n}\n\n```\n\n```none\nNumber of documents replaced: 1\n```\n\n### Expected Result\n\nAfter you run the full example, you can find the following replaced document in the `restaurants` collection:\n\n```none\n{\n \"_id\" : ObjectId(\"...\"),\n \"name\" : \"Rizzo's Pizza\",\n \"cuisine\" : \"Pizza/American\"\n}\n```\n\n## API Documentation\n\nTo learn more about any of the methods or types discussed in this guide, see the following API Documentation:\n\n- ReplaceOne()\n\n- UpdateResult"} -{"chunk_id": "699fe5cda6fa0684a38c2b07-0", "page_id": "699fe5cda6fa0684a38c2b07", "source_name": "golang", "product_name": "Go Driver", "url": "https://mongodb.com/docs/drivers/go/current", "title": "MongoDB Go Driver", "text": "# MongoDB Go Driver\n\n## Overview\n\nWelcome to the documentation site for the official MongoDB Go Driver. You can add the driver to your application to work with MongoDB in Go. Download it by using go get or set up a runnable project by following the Get Started guide.\n\n## Get Started\n\nLearn how to install the driver, establish a connection to MongoDB, and begin working with data in the Getting Started with Go tutorial.\n\n## Connect to MongoDB\n\nLearn how to create and configure a connection to a MongoDB deployment in the Connect section.\n\n## Context Package\n\nLearn how to use the context package from the Go standard library to manage blocking method calls in the Context Package guide.\n\n## Databases and Collections\n\nLearn how to interact with MongoDB databases and collections in the Databases and Collections section.\n\n## Read and Write Data\n\nLearn how to find, update, and delete data in the CRUD Operations section.\n\n## Transform Your Data with Aggregation\n\nLearn how to use the Go driver to perform aggregation operations in the Aggregation section.\n\n## Data Formats\n\nLearn how to work with specialized data formats in the Data Formats section.\n\n## Optimize Queries with Indexes\n\nLearn how to work with common types of indexes in the Indexes section.\n\n## Run a Database Command\n\nLearn how to run a database command in the Run a Database Command section.\n\n## Time Series\n\nLearn how to work with time series collections in the Time Series Collections guide.\n\n## MongoDB Search\n\nLearn how to use MongoDB Search to build full-text search capabilities in the Run a MongoDB Search Query guide.\n\n## MongoDB Vector Search\n\nLearn how to use MongoDB Vector Search to query your Atlas data based on semantic meaning rather than keyword matches in the Run a MongoDB Vector Search Query guide.\n\n## Monitoring and Logging\n\nLearn how to monitor changes to your application and write them to logs in the Monitoring and Logging section.\n\n## Secure Your Data\n\nLearn about ways you can authenticate your application and secure your data in the Security section.\n\n## Reference\n\nFind more information about Go driver versions, compatibility, release notes, and quick reference syntax for common commands in the Reference section.\n\n## API\n\nFor detailed information about types and methods in the MongoDB Go driver, see the MongoDB Go Driver API documentation.\n\n## Connection Troubleshooting\n\nFor solutions to some issues you might see when connecting to a MongoDB deployment while using the MongoDB Go Driver, see Connection Troubleshooting.\n\n## Issues & Help\n\nLearn how to report bugs, contribute to the driver, and find additional resources for asking questions in the Issues & Help section.\n\nTo ask questions and engage in discussions with fellow developers who use the Go driver, see the MongoDB communities on Reddit or Stack Overflow."} -{"chunk_id": "699fe5cda6fa0684a38c2b03-0", "page_id": "699fe5cda6fa0684a38c2b03", "source_name": "golang", "product_name": "Go Driver", "url": "https://mongodb.com/docs/drivers/go/current/data-formats/struct-tagging", "title": "Use Struct Tags", "text": "# Use Struct Tags\n\nYou can specify the way that the Go Driver converts Go structs to BSON by using struct tags.\n\n## Example: Full File\n\nThis example connects to an instance of MongoDB by using a connection URI. To learn more about connecting to your MongoDB instance, see Create a MongoClient. This example also uses the `restaurants` collection in the `sample_restaurants` database included in the Atlas sample datasets. You can load them into your database on a free cluster on MongoDB Atlas by following the steps in Get Started with Atlas.\n\nThis example declares a struct of type `Restaurant` with the following struct tags:\n\n- A struct tag that maps the `RestaurantId` field to the BSON field name `restaurant_id`. By default, the driver marshals the other fields as the lowercase of the struct field name.\n\n- The `omitempty` struct tag omits the corresponding field from the inserted document when left empty.\n\nThe following code shows the `Restaurant` struct used in the example:\n\n```go\ntype Restaurant struct {\n\tName string\n\tRestaurantId string `bson:\"restaurant_id,omitempty\"`\n\tCuisine string `bson:\"cuisine,omitempty\"`\n\tAddress interface{} `bson:\"address,omitempty\"`\n\tBorough string `bson:\"borough,omitempty\"`\n\tGrades []interface{} `bson:\"grades,omitempty\"`\n}\n```\n\nThe following example creates a `Restaurant` instance and inserts it into the `restaurants` collection. During the insert operation, the driver interprets the struct tags to marshal the `RestaurantId` struct field as `restaurant_id` and omits fields that are left empty in the sample document:\n\n```go\n// Specifies struct tags on a struct by using the Go driver\npackage main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com/joho/godotenv\"\n\t\"go.mongodb.org/mongo-driver/v2/mongo\"\n\t\"go.mongodb.org/mongo-driver/v2/mongo/options\"\n)\n\n// Specifies a different name for RestaurantID\n// and marks certain fields as omitempty\ntype Restaurant struct {\n\tName string\n\tRestaurantId string `bson:\"restaurant_id,omitempty\"`\n\tCuisine string `bson:\"cuisine,omitempty\"`\n\tAddress interface{} `bson:\"address,omitempty\"`\n\tBorough string `bson:\"borough,omitempty\"`\n\tGrades []interface{} `bson:\"grades,omitempty\"`\n}\n\nfunc main() {\n\tif err := godotenv.Load(); err != nil {\n\t\tlog.Println(\"No .env file found\")\n\t}\n\n\tvar uri string\n\tif uri = os.Getenv(\"MONGODB_URI\"); uri == \"\" {\n\t\tlog.Fatal(\"You must set your 'MONGODB_URI' environment variable. See\\n\\t https://www.mongodb.com/docs/drivers/go/current/usage-examples/#environment-variable\")\n\t}\n\n\tclient, err := mongo.Connect(options.Client().ApplyURI(uri))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer func() {\n\t\tif err = client.Disconnect(context.TODO()); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}()\n\n\tcoll := client.Database(\"sample_restaurants\").Collection(\"restaurants\")\n\n\t// Creates a Restaurant document\n\n\tnewRestaurant := Restaurant{\n\t\tName: \"Amazing Pizza\",\n\t\tRestaurantId: \"123456789\",\n\t\tCuisine: \"American\",\n\t}\n\n\t// Inserts the sample document describing a restaurant into the collection\n\n\tresult, err := coll.InsertOne(context.TODO(), newRestaurant)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Prints the ID of the inserted document\n\tfmt.Printf(\"Document inserted with ID: %s\\n\", result.InsertedID)\n\n\t// When you run this file, it should print:\n\t// Document inserted with ID: ObjectID(\"...\")\n}\n\n```\n\n```none\nDocument inserted with ID: ObjectID(\"...\")\n```\n\n## Expected Result\n\nAfter you run the full example, you can find the following document in the `restaurants` collection:\n\n```json\n{\n \"_id\" : ObjectId(\"...\"),\n \"name\" : \"Amazing Pizza\",\n \"restaurant_id\" : \"123456789\",\n \"cuisine\" : \"American\n}\n```\n\nFor an example on how to find a document, see the Find Documents guide.\n\n## Additional Information\n\nTo learn more about using struct tags, converting to/from BSON, and handling potential errors, see the Work with BSON guide.\n\n### API Documentation\n\n- Structs and Struct Tags\n\n- InsertOne()\n\n- FindOne()"} -{"chunk_id": "699fe5cea6fa0684a38c2c74-0", "page_id": "699fe5cea6fa0684a38c2c74", "source_name": "golang", "product_name": "Go Driver", "url": "https://mongodb.com/docs/drivers/go/current/crud/insert", "title": "Insert Documents", "text": "# Insert Documents\n\n## Overview\n\nIn this guide, you can learn how to **insert** documents into a MongoDB collection.\n\nBefore you can find, update, and delete documents in MongoDB, you must insert those documents. You can insert one document by using the `InsertOne()` method, or insert multiple documents by using either the `InsertMany()` or `BulkWrite()` method.\n\nThe following sections focus on `InsertOne()` and `InsertMany()`. To learn how to use the `BulkWrite()` method, see the Bulk Operations guide.\n\n## The _id Field\n\nIn MongoDB, each document *must* contain a unique `_id` field.\n\nThe two options for managing this field are:\n\n- Managing this field yourself, ensuring that each value you use is unique.\n\n- Letting the driver automatically generate unique `ObjectId` values. The driver generates unique `ObjectId` values for documents that you do not explicitly specify an `_id`.\n\nUnless you provide strong guarantees for uniqueness, MongoDB recommends you let the driver automatically generate `_id` values.\n\nDuplicate `_id` values violate unique index constraints, which causes the driver to return a `WriteError`.\n\nTo learn more about the `_id` field, see the Server Manual Entry on Unique Indexes.\n\nTo learn more about document structure and rules, see the Server Manual Entry on Documents.\n\n## Insert a Document\n\nUse the `InsertOne()` method to insert a single document into a collection.\n\nUpon successful insertion, the method returns an `InsertOneResult` instance that contains the `_id` of the new document.\n\n### Example\n\nThis example uses the following `Book` struct as a model for documents in the `books` collection:\n\n```go\ntype Book struct {\n\tTitle string\n\tAuthor string\n}\n\n```\n\nThe following example creates and inserts a document into the `books` collection using the `InsertOne()` method:\n\n```go\ncoll := client.Database(\"db\").Collection(\"books\")\ndoc := Book{Title: \"Atonement\", Author: \"Ian McEwan\"}\n\nresult, err := coll.InsertOne(context.TODO(), doc)\n\nfmt.Printf(\"Inserted document with _id: %v\\n\", result.InsertedID)\n```\n\n```none\nInserted document with _id: ObjectID(\"...\")\n```\n\n### Modify InsertOne() Behavior\n\nYou can modify the behavior of `InsertOne()` by constructing and passing an optional `InsertOneOptions` struct. The available options to set with `InsertOneOptions` are:\n\n\n\n\n\n\n\n\n\n\n
\nOption\n\n\nDescription\n\n
\n`BypassDocumentValidation`\n\n\nIf `true`, allows the write to opt-out of document level validation.Default: `false`\n\n
Construct an `InsertOneOptions` as follows:\n\n```go\nopts := options.InsertOne().SetBypassDocumentValidation(true)\n```\n\n### Insert a Document Example: Full File\n\nThis example connects to an instance of MongoDB by using a connection URI. To learn more about connecting to your MongoDB instance, see Create a MongoClient. This example also uses the `restaurants` collection in the `sample_restaurants` database included in the Atlas sample datasets. You can load them into your database on a free cluster on MongoDB Atlas by following the steps in Get Started with Atlas.\n\nThe following example inserts a new document into the `restaurants` collection. Select the Struct or bson.D tab to see the corresponding code:\n\n\n\n\n\nThe following code uses a struct to insert a new document into the `restaurants` collection:\n\n```go\n// Inserts a single document describing a restaurant by using the Go driver\npackage main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com/joho/godotenv\"\n\t\"go.mongodb.org/mongo-driver/v2/mongo\"\n\t\"go.mongodb.org/mongo-driver/v2/mongo/options\"\n)\n\n// Defines the structure of a restaurant document\ntype Restaurant struct {\n\tName string\n\tRestaurantId string `bson:\"restaurant_id,omitempty\"`\n\tCuisine string `bson:\"cuisine,omitempty\"`\n\tAddress any `bson:\"address,omitempty\"`\n\tBorough string `bson:\"borough,omitempty\"`\n\tGrades []any `bson:\"grades,omitempty\"`\n}\n\nfunc main() {\n\tif err := godotenv.Load(); err != nil {\n\t\tlog.Println(\"No .env file found\")\n\t}\n\n\tvar uri string\n\tif uri = os.Getenv(\"MONGODB_URI\"); uri == \"\" {\n\t\tlog.Fatal(\"You must set your 'MONGODB_URI' environment variable. See\\n\\t https://www.mongodb.com/docs/drivers/go/current/connect/mongoclient/#environment-variable\")\n\t}\n\n\tclient, err := mongo.Connect(options.Client().ApplyURI(uri))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer func() {\n\t\tif err = client.Disconnect(context.TODO()); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}()\n\n\t// Inserts a sample document describing a restaurant into the collection\n\tcoll := client.Database(\"sample_restaurants\").Collection(\"restaurants\")\n\tnewRestaurant := Restaurant{Name: \"8282\", Cuisine: \"Korean\"}\n\n\tresult, err := coll.InsertOne(context.TODO(), newRestaurant)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Prints the ID of the inserted document\n\tfmt.Printf(\"Document inserted with ID: %s\\n\", result.InsertedID)\n\n\t// When you run this file for the first time, it should print output similar\n\t// to the following:\n\t// Document inserted with ID: ObjectID(\"...\")\n\n}\n\n```\n\n```none\nDocument inserted with ID: ObjectID(\"...\")\n```\n\n\n\n\n\nThe following code uses a `bson.D` type to insert a new document into the `restaurants` collection:\n\n```go\n// Inserts a single document describing a restaurant by using the Go driver with bson.D\npackage main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com/joho/godotenv\"\n\t\"go.mongodb.org/mongo-driver/v2/bson\"\n\t\"go.mongodb.org/mongo-driver/v2/mongo\"\n\t\"go.mongodb.org/mongo-driver/v2/mongo/options\"\n)\n\nfunc main() {\n\tif err := godotenv.Load(); err != nil {\n\t\tlog.Println(\"No .env file found\")\n\t}\n\n\tvar uri string\n\tif uri = os.Getenv(\"MONGODB_URI\"); uri == \"\" {\n\t\tlog.Fatal(\"You must set your 'MONGODB_URI' environment variable. See\\n\\t https://www.mongodb.com/docs/drivers/go/current/connect/mongoclient/#environment-variable\")\n\t}\n\n\tclient, err := mongo.Connect(options.Client().ApplyURI(uri))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer func() {\n\t\tif err = client.Disconnect(context.TODO()); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}()\n\n\t// Inserts a sample document describing a restaurant into the collection using bson.D\n\tcoll := client.Database(\"sample_restaurants\").Collection(\"restaurants\")\n\tnewRestaurant := bson.D{\n\t\tbson.E{Key: \"name\", Value: \"8282\"},\n\t\tbson.E{Key: \"cuisine\", Value: \"Korean\"},\n\t}\n\n\tresult, err := coll.InsertOne(context.TODO(), newRestaurant)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Prints the ID of the inserted document\n\tfmt.Printf(\"Document inserted with ID: %s\\n\", result.InsertedID)\n\n\t// When you run this file for the first time, it should print output similar\n\t// to the following:\n\t// Document inserted with ID: ObjectID(\"...\")\n}\n\n```\n\n```none\nDocument inserted with ID: ObjectID(\"...\")\n```\n\n\n\n\n\n## Insert Multiple Documents\n\nUse the `InsertMany()` method to insert multiple documents into a collection.\n\nUpon successful insertion, the `InsertMany()` method returns an `InsertManyResult` instance that contains the `_id` fields of the inserted documents."} -{"chunk_id": "699fe5cea6fa0684a38c2c74-1", "page_id": "699fe5cea6fa0684a38c2c74", "source_name": "golang", "product_name": "Go Driver", "url": "https://mongodb.com/docs/drivers/go/current/crud/insert", "title": "Insert Documents", "text": "### Example\n\nThe following example creates and inserts multiple documents into the `books` collection using the `InsertMany()` method:\n\n```go\ncoll := client.Database(\"myDB\").Collection(\"favorite_books\")\ndocs := []any{\n Book{Title: \"Cat's Cradle\", Author: \"Kurt Vonnegut Jr.\"},\n Book{Title: \"In Memory of Memory\", Author: \"Maria Stepanova\"},\n Book{Title: \"Pride and Prejudice\", Author: \"Jane Austen\"},\n}\n\nresult, err := coll.InsertMany(context.TODO(), docs)\nfmt.Printf(\"Documents inserted: %v\\n\", len(result.InsertedIDs))\n\nfor _, id := range result.InsertedIDs {\n fmt.Printf(\"Inserted document with _id: %v\\n\", id)\n}\n```\n\nAfter running the preceding code, your output resembles the following:\n\n```none\nDocuments inserted: 3\nInserted document with _id: ObjectID(\"...\")\nInserted document with _id: ObjectID(\"...\")\nInserted document with _id: ObjectID(\"...\")\n```\n\n### Modify InsertMany() Behavior\n\nYou can modify the behavior of `InsertMany()` by constructing and passing an optional `InsertManyOptions` struct. The available options to set with `InsertManyOptions` are:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nOption\n\n\nDescription\n\n
\n`BypassDocumentValidation`\n\n\nIf `true`, allows the write to opt-out of document level validation.Default: `false`\n\n
\n`Ordered`\n\n\nIf `true`, the driver sends documents to the server in the order provided. If an error occurs, the driver and server end all remaining insert operations. To learn more, see Ordered Behavior.Default: `false`\n\n
Construct an `InsertManyOptions` as follows:\n\n```go\nopts := options.InsertMany().SetBypassDocumentValidation(true).SetOrdered(false)\n```\n\n### Ordered Behavior\n\nAssume you want to insert the following documents:\n\n```json\n{ \"_id\": 1, \"title\": \"Where the Wild Things Are\" }\n{ \"_id\": 2, \"title\": \"The Very Hungry Caterpillar\" }\n{ \"_id\": 1, \"title\": \"Blueberries for Sal\" }\n{ \"_id\": 3, \"title\": \"Goodnight Moon\" }\n```\n\nIf you attempt to insert these documents with default `InsertManyOptions`, a `BulkWriteException` occurs at the third document because of the repeated `_id` value, but the documents before the error-producing document still get inserted into your collection.\n\nYou can get an acknowledgement of successful document insertion even if a BulkWriteException occurs:\n\n```go\ntype Book struct {\n ID int `bson:\"_id\"`\n Title string\n}\n\n...\n\ndocs := []any{\n Book{ID: 1, Title: \"Where the Wild Things Are\"},\n Book{ID: 2, Title: \"The Very Hungry Caterpillar\"},\n Book{ID: 1, Title: \"Blueberries for Sal\"},\n Book{ID: 3, Title: \"Goodnight Moon\"},\n}\n\nresult, err := coll.InsertMany(context.TODO(), docs)\nif err != nil {\n fmt.Printf(\"A bulk write error occurred, but %v documents were still inserted.\\n\", len(result.InsertedIDs))\n}\n\nfor _, id := range result.InsertedIDs {\n fmt.Printf(\"Inserted document with _id: %v\\n\", id)\n}\n```\n\n```none\nA bulk write error occurred, but 2 documents were still inserted.\nInserted document with _id: 1\nInserted document with _id: 2\n```\n\nAfter running the preceding code, your collection contains the following documents:\n\n```json\n{ \"_id\": 1, \"title\": \"Where the Wild Things Are\" }\n{ \"_id\": 2, \"title\": \"The Very Hungry Caterpillar\" }\n```"} -{"chunk_id": "699fe5cea6fa0684a38c2c74-2", "page_id": "699fe5cea6fa0684a38c2c74", "source_name": "golang", "product_name": "Go Driver", "url": "https://mongodb.com/docs/drivers/go/current/crud/insert", "title": "Insert Documents", "text": "### Insert Many Example: Full File\n\nThis example connects to an instance of MongoDB by using a connection URI. To learn more about connecting to your MongoDB instance, see Create a MongoClient. This example also uses the `restaurants` collection in the `sample_restaurants` database included in the Atlas sample datasets. You can load them into your database on a free cluster on MongoDB Atlas by following the steps in Get Started with Atlas.\n\nThe following example inserts multiple new documents into the `restaurants` collection. Select the Struct or bson.D tab to see the corresponding code:\n\n\n\n\n\nThe following code uses a struct to insert multiple new documents into the `restaurants` collection:\n\n```go\n// Inserts sample documents describing restaurants by using the Go driver\npackage main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com/joho/godotenv\"\n\t\"go.mongodb.org/mongo-driver/v2/mongo\"\n\t\"go.mongodb.org/mongo-driver/v2/mongo/options\"\n)\n\n// Defines the structure of a restaurant document\ntype Restaurant struct {\n\tName string\n\tRestaurantId string `bson:\"restaurant_id,omitempty\"`\n\tCuisine string `bson:\"cuisine,omitempty\"`\n\tAddress any `bson:\"address,omitempty\"`\n\tBorough string `bson:\"borough,omitempty\"`\n\tGrades []any `bson:\"grades,omitempty\"`\n}\n\nfunc main() {\n\tif err := godotenv.Load(); err != nil {\n\t\tlog.Println(\"No .env file found\")\n\t}\n\n\tvar uri string\n\tif uri = os.Getenv(\"MONGODB_URI\"); uri == \"\" {\n\t\tlog.Fatal(\"You must set your 'MONGODB_URI' environment variable. See\\n\\t https://www.mongodb.com/docs/drivers/go/current/connect/mongoclient/#environment-variable\")\n\t}\n\n\tclient, err := mongo.Connect(options.Client().ApplyURI(uri))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer func() {\n\t\tif err = client.Disconnect(context.TODO()); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}()\n\n\tcoll := client.Database(\"sample_restaurants\").Collection(\"restaurants\")\n\n\t// Creates two sample documents describing restaurants\n\tnewRestaurants := []any{\n\t\tRestaurant{Name: \"Rule of Thirds\", Cuisine: \"Japanese\"},\n\t\tRestaurant{Name: \"Madame Vo\", Cuisine: \"Vietnamese\"},\n\t}\n\n\t// Inserts sample documents into the collection\n\tresult, err := coll.InsertMany(context.TODO(), newRestaurants)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Prints the IDs of the inserted documents\n\tfmt.Printf(\"%d documents inserted with IDs:\\n\", len(result.InsertedIDs))\n\tfor _, id := range result.InsertedIDs {\n\t\tfmt.Printf(\"\\t%s\\n\", id)\n\t}\n\n\t// When you run this file for the first time, it should print output similar\n\t// to the following:\n\t// 2 documents inserted with IDs:\n\t// ObjectID(\"...\")\n\t// ObjectID(\"...\")\n}\n\n```\n\n```none\n2 documents inserted with IDs:\n ObjectID(\"...\")\n ObjectID(\"...\")\n```\n\n\n\n\n\nThe following code uses a `bson.D` type to insert multiple new documents into the `restaurants` collection:\n\n```go\n// Inserts sample documents describing restaurants by using the Go driver with bson.D\npackage main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com/joho/godotenv\"\n\t\"go.mongodb.org/mongo-driver/v2/bson\"\n\t\"go.mongodb.org/mongo-driver/v2/mongo\"\n\t\"go.mongodb.org/mongo-driver/v2/mongo/options\"\n)\n\nfunc main() {\n\tif err := godotenv.Load(); err != nil {\n\t\tlog.Println(\"No .env file found\")\n\t}\n\n\tvar uri string\n\tif uri = os.Getenv(\"MONGODB_URI\"); uri == \"\" {\n\t\tlog.Fatal(\"You must set your 'MONGODB_URI' environment variable. See\\n\\t https://www.mongodb.com/docs/drivers/go/current/connect/mongoclient/#environment-variable\")\n\t}\n\n\tclient, err := mongo.Connect(options.Client().ApplyURI(uri))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer func() {\n\t\tif err = client.Disconnect(context.TODO()); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}()\n\n\tcoll := client.Database(\"sample_restaurants\").Collection(\"restaurants\")\n\n\t// Creates two sample documents describing restaurants using bson.D\n\tnewRestaurants := []interface{}{\n\t\tbson.D{\n\t\t\tbson.E{Key: \"name\", Value: \"Rule of Thirds\"},\n\t\t\tbson.E{Key: \"cuisine\", Value: \"Japanese\"},\n\t\t},\n\t\tbson.D{\n\t\t\tbson.E{Key: \"name\", Value: \"Madame Vo\"},\n\t\t\tbson.E{Key: \"cuisine\", Value: \"Vietnamese\"},\n\t\t},\n\t}\n\n\t// Inserts sample documents into the collection\n\tresult, err := coll.InsertMany(context.TODO(), newRestaurants)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Prints the IDs of the inserted documents\n\tfmt.Printf(\"%d documents inserted with IDs:\\n\", len(result.InsertedIDs))\n\tfor _, id := range result.InsertedIDs {\n\t\tfmt.Printf(\"\\t%s\\n\", id)\n\t}\n\n\t// When you run this file for the first time, it should print output similar\n\t// to the following:\n\t// 2 documents inserted with IDs:\n\t// ObjectID(\"...\")\n\t// ObjectID(\"...\")\n}\n\n```\n\n```none\n2 documents inserted with IDs:\n ObjectID(\"...\")\n ObjectID(\"...\")\n```\n\n\n\n\n\n## Additional Information\n\nTo learn more about performing the operations mentioned, see the following guides:\n\n- Specify a Query\n\n- Bulk Operations\n\n### API Documentation\n\nTo learn more about any of the methods or types discussed in this guide, see the following API Documentation:\n\n- WriteError\n\n- InsertOne()\n\n- InsertOneResult\n\n- InsertMany()\n\n- InsertManyResult\n\n- BulkWriteException"} -{"chunk_id": "699fe5cda6fa0684a38c2afb-0", "page_id": "699fe5cda6fa0684a38c2afb", "source_name": "golang", "product_name": "Go Driver", "url": "https://mongodb.com/docs/drivers/go/current/crud/update", "title": "Update Documents", "text": "# Update Documents\n\n## Overview\n\nIn this guide, you can learn how to update documents in MongoDB by using **update** operations.\n\nUpdate operations change the fields that you specify while leaving other fields and values unchanged.\n\nIn MongoDB, all methods to modify documents follow the same pattern:\n\n`changeX` is a placeholder and not a real method.\n\nThe pattern expects you to:\n\n- Specify a query filter to match one or more documents to modify.\n\n- Specify the field and value changes.\n\n- Specify options, if you must modify the method behavior.\n\nThe driver provides the following methods to update documents:\n\n- `UpdateByID()`: Updates a single document based on its `_id`.\n\n- `UpdateOne()`: Updates a single document.\n\n- `UpdateMany()`: Updates multiple documents.\n\n### A Note About _id\n\nEach document in a MongoDB collection has a unique and immutable `_id` field. You cannot use update operations to change the `_id` field. If you attempt to change this field, the update methods return a `WriteError`.\n\n## Parameters\n\nEach method takes an **update document** that includes at least one **update operator**. The update operator specifies the type of update to perform. The update document also includes the fields and values that describe the change. Update documents use the following format:\n\n```go\nbson.D{{\"\", bson.D{{\"\", },\n {\"\", }, ... }},\n {\"\", ... }, ... }\n```\n\nSee the MongoDB server manual for a complete list of update operators and descriptions.\n\n`UpdateOne()` updates the first document that matches the query filter you provide. To ensure that you update the correct document, you can use the `sort` option to specify the order in which the operation finds documents. To learn more, see the UpdateOneOptions API documentation.\n\nYou can use aggregation pipelines made up of a subset of aggregation stages in update operations. To learn more about the aggregation stages MongoDB supports in aggregation pipelines, see the tutorial on performing Updates with Aggregation Pipeline tutorial in the Server Manual.\n\n## Return Values\n\n`UpdateOne()`, `UpdateByID()`, and `UpdateMany()` return an `UpdateResult` type that contains information about the update operation if the operation is successful. The `UpdateResult` type contains the following properties:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nProperty\n\n\nDescription\n\n
\n`MatchedCount`\n\n\nThe number of documents matched by the filter\n\n
\n`ModifiedCount`\n\n\nThe number of documents modified by the operation\n\n
\n`UpsertedCount`\n\n\nThe number of documents upserted by the operation\n\n
\n`UpsertedID`\n\n\nThe `_id` of the upserted document, or `nil` if there is none\n\n
If multiple documents match the query filter passed to `UpdateOne()`, the method selects and updates the first matched document. If no documents match the query filter, the update operation makes no changes.\n\nSee the upsert guide to learn how to insert a new document if no documents match the query filter.\n\n## UpdateOne() Example\n\nThe following example uses the `listingsAndReviews` collection in the `sample_airbnb` dataset from the Atlas sample datasets. The following document describes an airbnb listing:\n\n```json\n{\n \"_id\": \"10006546\",\n \"listing_url\": \"https://www.airbnb.com/rooms/10006546\",\n \"name\": \"Ribeira Charming Duplex\",\n \"summary\": \"Fantastic duplex apartment with three bedrooms, located in the historic area of Porto, Ribeira (Cube)...\",\n ...\n \"minimum_nights\": \"2\",\n \"maximum_nights\": \"30\",\n ...\n \"accommodates\": 8,\n ...\n}\n```\n\nThe following example uses the `UpdateOne()` method to:\n\n- Match the document where the `_id` value is `\"10006546\"`.\n\n- Set the `name` field to `\"Ribiera River View Duplex\"`.\n\n- Increment the value of the `accommodates` field by `1`.\n\n```go\nfilter := bson.D{{\"_id\", \"10006546\"}}\nupdate := bson.D{{\"$set\", bson.D{{\"name\", \"Ribiera River View Duplex\"}}},\n {\"$inc\", bson.D{{\"accomodates\", 1}}}}\n\nresult, err := collection.UpdateOne(context.TODO(), filter, update)\nfmt.Printf(\"Documents matched: %v\\n\", result.MatchedCount)\nfmt.Printf(\"Documents updated: %v\\n\", result.ModifiedCount)\n```\n\n```none\nDocuments matched: 1\nDocuments updated: 1\n```\n\nThe following shows the updated document resulting from the preceding update operation:\n\n```json\n{\n \"_id\": \"10006546\",\n \"listing_url\": \"https://www.airbnb.com/rooms/10006546\",\n \"name\": \"Ribeira River View Duplex\",\n \"summary\": \"Fantastic duplex apartment with three bedrooms, located in the historic area of Porto, Ribeira (Cube)...\",\n ...\n \"minimum_nights\": \"2\",\n \"maximum_nights\": \"30\",\n ...\n \"accommodates\": 9,\n ...\n}\n```\n\n### UpdateOne() Example: Full File\n\nThis example connects to an instance of MongoDB by using a connection URI. To learn more about connecting to your MongoDB instance, see Create a MongoClient. This example also uses the `restaurants` collection in the `sample_restaurants` database included in the Atlas sample datasets. You can load them into your database on a free cluster on MongoDB Atlas by following the steps in Get Started with Atlas.\n\nThe following example is a fully runnable file that performs the following actions on the `restaurants` collection:\n\n- Finds a document with a specific `_id`\n\n- Updates the `avg_rating` field value of the matched document\n\n```go\n// Updates the first document that matches a query filter by using the Go driver\npackage main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com/joho/godotenv\"\n\t\"go.mongodb.org/mongo-driver/v2/bson\"\n\t\"go.mongodb.org/mongo-driver/v2/mongo\"\n\t\"go.mongodb.org/mongo-driver/v2/mongo/options\"\n)\n\n// Defines a Restaurant struct as a model for documents in the \"restaurants\" collection\ntype Restaurant struct {\n\tID bson.ObjectID `bson:\"_id\"`\n\tName string `bson:\"name\"`\n\tAverageRating float64 `bson:\"avg_rating,omitempty\"`\n}\n\nfunc main() {\n\tif err := godotenv.Load(); err != nil {\n\t\tlog.Println(\"No .env file found\")\n\t}\n\n\tvar uri string\n\tif uri = os.Getenv(\"MONGODB_URI\"); uri == \"\" {\n\t\tlog.Fatal(\"You must set your 'MONGODB_URI' environment variable. See\\n\\t https://www.mongodb.com/docs/drivers/go/current/connect/mongoclient/#environment-variable\")\n\t}\n\n\tclient, err := mongo.Connect(options.Client().ApplyURI(uri))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer func() {\n\t\tif err = client.Disconnect(context.TODO()); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}()\n\n\tcoll := client.Database(\"sample_restaurants\").Collection(\"restaurants\")\n\n\tid, _ := bson.ObjectIDFromHex(\"5eb3d668b31de5d588f4292b\")\n\tfilter := bson.D{{\"_id\", id}}\n\n\t// Creates instructions to add the \"avg_rating\" field to documents\n\tupdate := bson.D{{\"$set\", bson.D{{\"avg_rating\", 4.4}}}}\n\n\t// Updates the first document that has the specified \"_id\" value\n\tresult, err := coll.UpdateOne(context.TODO(), filter, update)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Prints the number of updated documents\n\tfmt.Printf(\"Documents updated: %v\\n\", result.ModifiedCount)\n\n\t// When you run this file for the first time, it should print output similar to the following:\n\t// Documents updated: 1\n}\n\n```\n\n```none\nDocuments updated: 1\n```"} -{"chunk_id": "699fe5cda6fa0684a38c2afb-1", "page_id": "699fe5cda6fa0684a38c2afb", "source_name": "golang", "product_name": "Go Driver", "url": "https://mongodb.com/docs/drivers/go/current/crud/update", "title": "Update Documents", "text": "## UpdateMany() Example: Full File\n\nThis example connects to an instance of MongoDB by using a connection URI. To learn more about connecting to your MongoDB instance, see Create a MongoClient. This example also uses the `restaurants` collection in the `sample_restaurants` database included in the Atlas sample datasets. You can load them into your database on a free cluster on MongoDB Atlas by following the steps in Get Started with Atlas.\n\nThe following example is a fully runnable file that performs the following actions on the `restaurants` collection:\n\n- Finds documents with the `cuisine` field value of `\"Pizza\"` and the `borough` field value of `\"Brooklyn\"`\n\n- Updates the `avg_rating` field value of the matched documents\n\n```go\n// Updates documents that match a query filter by using the Go driver\npackage main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com/joho/godotenv\"\n\t\"go.mongodb.org/mongo-driver/v2/bson\"\n\t\"go.mongodb.org/mongo-driver/v2/mongo\"\n\t\"go.mongodb.org/mongo-driver/v2/mongo/options\"\n)\n\n// Defines a Restaurant struct as a model for documents in the \"restaurants\" collection\ntype Restaurant struct {\n\tID bson.ObjectID `bson:\"_id\"`\n\tName string `bson:\"name\"`\n\tCuisine string `bson:\"cuisine\"`\n\tAverageRating float64 `bson:\"avg_rating,omitempty\"`\n}\n\nfunc main() {\n\tif err := godotenv.Load(); err != nil {\n\t\tlog.Println(\"No .env file found\")\n\t}\n\n\tvar uri string\n\tif uri = os.Getenv(\"MONGODB_URI\"); uri == \"\" {\n\t\tlog.Fatal(\"You must set your 'MONGODB_URI' environment variable. See\\n\\t https://www.mongodb.com/docs/drivers/go/current/connect/mongoclient/#environment-variable\")\n\t}\n\n\tclient, err := mongo.Connect(options.Client().ApplyURI(uri))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer func() {\n\t\tif err = client.Disconnect(context.TODO()); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}()\n\n\tcoll := client.Database(\"sample_restaurants\").Collection(\"restaurants\")\n\tfilter := bson.D{{\"cuisine\", \"Pizza\"}, {\"borough\", \"Brooklyn\"}}\n\n\t// Creates instructions to update the values of the \"avg_rating\" field\n\tupdate := bson.D{{\"$set\", bson.D{{\"avg_rating\", 4.5}}}}\n\n\t// Updates documents in which the value of the \"Cuisine\"\n\t// field is \"Pizza\"\n\tresult, err := coll.UpdateMany(context.TODO(), filter, update)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Prints the number of updated documents\n\tfmt.Printf(\"Documents updated: %v\\n\", result.ModifiedCount)\n\t// end updatemany\n\n\t// When you run this file for the first time, it should print output similar to the following:\n\t// Documents updated: 296\n}\n\n```\n\n```none\nDocuments updated: 296\n```\n\n## Additional Information\n\nTo learn more about the operations mentioned, see the following guides:\n\n- Specify a Query\n\n- Find Documents\n\n- Compound Operations\n\n- Update Operators\n\nTo learn more about updating array elements, see Update Arrays in a Document.\n\n### API Documentation\n\nTo learn more about any of the methods or types discussed in this guide, see the following API Documentation:\n\n- WriteError\n\n- UpdateOne()\n\n- UpdateByID()\n\n- UpdateMany()\n\n- UpdateResult"} -{"chunk_id": "6ad1c488e2bd6bff87646f52-0", "page_id": "6ad1c488e2bd6bff87646f52", "source_name": "hibernate", "product_name": null, "url": "https://mongodb.com/docs/languages/java/mongodb-hibernate/current", "title": "MongoDB Extension for Hibernate ORM", "text": "# MongoDB Extension for Hibernate ORM\n\n## Introduction\n\nWelcome to the documentation site for the official MongoDB Extension for Hibernate ORM, an extension that integrates Hibernate with MongoDB.\n\nThe Hibernate ORM is an object-relational mapping framework for Java applications that maps Java classes to relational database tables. The MongoDB Extension for Hibernate ORM adds support for MongoDB, allowing you to represent and interact with MongoDB data by using Hibernate ORM's data mapping and querying capabilities.\n\n## Get Started\n\nLearn how to install the Hibernate ORM extension, establish a connection to MongoDB, and begin working with data in the Get Started with the Hibernate ORM Extension tutorial.\n\n## Spring Boot\n\nLearn how to use the Spring Boot starter to persist Java Persistence API (JPA) entities and Spring Data JPA repositories to MongoDB in the Spring Boot and Spring Data JPA Integration section.\n\n## Model Your Data\n\nLearn how to create Hibernate ORM models that represent MongoDB collections in the Model Your Data section.\n\n## Interact with Data\n\nLearn how to use the Hibernate ORM extension to perform operations on MongoDB data in the Interact with Data section.\n\nTo view a sample application that shows how to run create, read, update, and delete (CRUD) operations by using the Hibernate ORM extension, see the mongodb-hibernate-crud GitHub project.\n\n## Hibernate ORM Feature Compatibility\n\nLearn about the extension's support for Hibernate ORM and MongoDB features in the Feature Compatibility section.\n\n## Version Compatibility\n\nLearn about the versions of MongoDB Server, Java, and Hibernate ORM that are compatible with the Hibernate ORM extension on the Compatibility page.\n\n## Issues & Help\n\nLearn how to report bugs, contribute to the Hibernate ORM extension, and find more resources for receiving help in the Issues & Help section."} -{"chunk_id": "6ad1c488e2bd6bff87646f55-0", "page_id": "6ad1c488e2bd6bff87646f55", "source_name": "hibernate", "product_name": null, "url": "https://mongodb.com/docs/languages/java/mongodb-hibernate/current/interact-data/crud", "title": "Perform CRUD Operations", "text": "# Perform CRUD Operations\n\n## Overview\n\nIn this guide, you can learn how to use the MongoDB Extension for Hibernate ORM to run create, read, update, and delete (CRUD) operations on your MongoDB collections.\n\n### Sample Data\n\nThe examples in this guide use the `Movie` entity, which represents the `sample_mflix.movies` collection from the Atlas sample datasets. The `Movie` entity has the following definition:\n\n```java\nimport com.mongodb.hibernate.annotations.ObjectIdGenerator;\nimport org.bson.types.ObjectId;\nimport java.time.Instant;\nimport java.util.List;\nimport jakarta.persistence.Embedded;\n\nimport jakarta.persistence.Entity;\nimport jakarta.persistence.FetchType;\nimport jakarta.persistence.Id;\nimport jakarta.persistence.OneToMany;\nimport jakarta.persistence.Table;\n\n@Entity\n@Table(name = \"movies\")\npublic class Movie {\n @Id\n @ObjectIdGenerator\n private ObjectId id;\n private String title;\n private String plot;\n private int year;\n private List cast;\n private List directors;\n private Instant released;\n @Embedded\n private Awards awards;\n @OneToMany(mappedBy = \"movie\", fetch = FetchType.LAZY)\n private List comments;\n\n public Movie(String title, String plot, int year, List cast, List directors, Instant released, Awards awards) {\n this.title = title;\n this.plot = plot;\n this.year = year;\n this.cast = cast;\n this.directors = directors;\n this.released = released;\n this.awards = awards;\n }\n\n public Movie() {\n\n }\n\n public ObjectId getId() {\n return id;\n }\n\n public String getTitle() {\n return title;\n }\n\n public void setTitle(String title) {\n this.title = title;\n }\n\n public String getPlot() {\n return plot;\n }\n\n public void setPlot(String plot) {\n this.plot = plot;\n }\n\n public int getYear() {\n return year;\n }\n\n public void setYear(int year) {\n this.year = year;\n }\n\n public List getCast() {\n return cast;\n }\n\n public void setCast(List cast) {\n this.cast = cast;\n }\n\n public List getDirectors() {\n return directors;\n }\n\n public void setDirectors(List directors) {\n this.directors = directors;\n }\n\n public Awards getAwards() {\n return awards;\n }\n\n public void setAwards(Awards awards) {\n this.awards = awards;\n }\n\n public Instant getReleased() {\n return released;\n }\n\n public void setReleased(Instant released) {\n this.released = released;\n }\n\n public List getComments() {\n return comments;\n }\n\n public void setComments(List comments) {\n this.comments = comments;\n }\n}\n```\n\nTo learn how to create a Java application that uses the MongoDB Extension for Hibernate ORM to interact with this MongoDB sample collection, see the Get Started tutorial.\n\nYou also must run write operations inside a transaction to modify MongoDB data and maintain data integrity.\n\nTo enable Hibernate ORM to interact with the database, you must run operations inside a persistence context by using a Hibernate `Session` or a Jakarta Persistence `EntityManager`. You also must run write operations inside a transaction to modify MongoDB data and maintain data integrity.\n\nBefore running the examples in this guide, ensure that you add persistence context and transaction management code to your application that resembles the following code:\n\n\n\n\n\n```java\nvar sf = HibernateUtil.getSessionFactory();\nSession session = sf.openSession();\nTransaction tx = session.beginTransaction();\n\n// ... Perform CRUD operations here\n\ntx.commit();\nsession.close();\nsf.close();\n```\n\nTo use a session, you must create a `HibernateUtil.java` file that configures a `SessionFactory`. To learn more, see the Configure your Application step of the Get Started tutorial.\n\n\n\n\n\n```java\n // Replace with the name of your persistence unit in the persistence.xml file\n EntityManagerFactory emf = Persistence.createEntityManagerFactory(\"\");\n EntityManager entityManager = entityManagerFactory.createEntityManager();\n entityManager.getTransaction().begin();\n\n // ... Perform CRUD operations here\n\nentityManager.getTransaction().commit();\nentityManager.close();\nemf.close;\n```\n\nTo use an `EntityManager`, you must create a `persistence.xml` file that declares a persistence unit. To learn more, see the Tutorial using JPA-standard APIs in the Hibernate ORM documentation.\n\n\n\n\n\n## Insert Documents\n\nCreate a document by passing an entity instance to to the following methods, which insert the corresponding document into your collection:\n\n- `org.hibernate.Session.persist()`: Use the Hibernate API to apply your changes to the database\n\n- `jakarta.persistence.EntityManager.persist()`: Use the Jakarta Persistence API to apply your changes to the database\n\nTo learn more about creating entity instances and persisting them to your database, see Making entities persistent in the Hibernate ORM user guide.\n\n### Example\n\nThe following example creates a new `Movie` entity instance and uses the `persist()` method to insert a corresponding document into the `sample_mflix.movies` collection:\n\n\n\n\n\n```java\nvar myMovie = new Movie();\nmyMovie.setTitle(\"Knives Out\");\nmyMovie.setYear(2019);\nmyMovie.setCast(List.of(\"Ana de Armas\", \"Daniel Craig\", \"Chris Evans\"));\nmyMovie.setPlot(\"Detective Benoit Blanc investigates the mysterious death of crime novelist Harlan Thrombey, \" +\n \"unraveling lies as every Thrombey family member becomes a suspect.\");\nsession.persist(myMovie);\n```\n\n\n\n\n\n```java\nvar myMovie = new Movie();\nmyMovie.setTitle(\"Knives Out\");\nmyMovie.setYear(2019);\nmyMovie.setCast(List.of(\"Ana de Armas\", \"Daniel Craig\", \"Chris Evans\"));\nmyMovie.setPlot(\"Detective Benoit Blanc investigates the mysterious death of crime novelist Harlan Thrombey, \" +\n \"unraveling lies as every Thrombey family member becomes a suspect.\");\nentityManager.persist(myMovie);\n```\n\n\n\n\n\n## Read Documents\n\nTo retrieve documents from your collection, pass your query criteria to the `createQuery()` method. The following APIs both provide the `createQuery()` method:\n\n- Hibernate's `Session` API: Use Hibernate Query Language (HQL) syntax to define your queries\n\n- Jakarta Persistence's `EntityManager` API: Use Jakarta Persistence Query Language (JPQL) syntax, a subset of HQL, to define your queries\n\nTo learn more about retrieving data by using HQL and JPQL syntax, see Select statements in the Hibernate ORM query guide.\n\nThis section describes how to read documents by using HQL and JPQL, but you can also use the criteria builder or native queries to retrieve data. To learn more, see the following guides:\n\n- Specify a Query\n\n- Perform Native Database Queries"} -{"chunk_id": "6ad1c488e2bd6bff87646f55-1", "page_id": "6ad1c488e2bd6bff87646f55", "source_name": "hibernate", "product_name": null, "url": "https://mongodb.com/docs/languages/java/mongodb-hibernate/current/interact-data/crud", "title": "Perform CRUD Operations", "text": "### Return One Document Example\n\nTo retrieve only one document that matches your query criteria, chain the `getSingleResult()` method to the `createQuery()` method. The following example retrieves one document that has a `title` value of `\"Boyhood\"` from the `sample_mflix.movies` collection:\n\n\n\n\n\n```java\nvar singleResult = session.createQuery(\"from Movie where title = :t\", Movie.class)\n .setParameter(\"t\", \"Boyhood\")\n .getSingleResult();\nSystem.out.println(\"Title: \" + singleResult.getTitle() + \", Year: \" + singleResult.getYear());\n```\n\n```\nTitle: Boyhood, Year: 2014\n```\n\n\n\n\n\n```java\nvar singleResult = entityManager.createQuery(\"select m from Movie m where m.title = :t\", Movie.class)\n .setParameter(\"t\", \"Boyhood\")\n .getSingleResult();\nSystem.out.println(\"Title: \" + singleResult.getTitle() + \", Year: \" + singleResult.getYear());\n```\n\n```\nTitle: Boyhood, Year: 2014\n```\n\n\n\n\n\nTo learn more about HQL and JPQL syntax, see A Guide to Hibernate Query Language in the Hibernate ORM documentation.\n\n### Return Multiple Documents Example\n\nThe following example calls the `createQuery()` method on a session to retrieve documents from the `sample_mflix.movies` collection. The code uses HQL and JPQL to return documents that have a `year` value of `1920` and prints their `title` values:\n\n\n\n\n\n```java\nvar results = session.createQuery(\"from Movie where year = :y\", Movie.class)\n .setParameter(\"y\", 1920)\n .getResultList();\nresults.forEach(movie -> System.out.println(movie.getTitle()));\n```\n\n```\nHigh and Dizzy\nOne Week\nThe Saphead\nThe Daughter of Dawn\n```\n\n\n\n\n\n```java\nvar results = entityManager.createQuery(\"select m from Movie m where m.year = :y\", Movie.class)\n .setParameter(\"y\", 1920)\n .getResultList();\nresults.forEach(movie -> System.out.println(movie.getTitle()));\n```\n\n```\nHigh and Dizzy\nOne Week\nThe Saphead\nThe Daughter of Dawn\n```\n\n\n\n\n\n## Modify Documents\n\nYou can perform the following operations to modify documents in a collection:\n\n- Update one document: Call your entity's setter methods to change field values of one entity instance, and then use a session or entity manager to persist your changes.\n\n- Update multiple documents: Pass an update statement to the `createQuery()` or `createMutationQuery()` methods on a session or entity manager. Then, call the `executeUpdate()` method to apply your changes to the database.\n\nTo learn more about modifying data by using Hibernate ORM, see the following resources:\n\n- Modifying managed/persistent state in the Hibernate ORM user guide\n\n- Update statements in the Hibernate ORM query guide\n\n### Update One Example\n\nThe following example retrieves a document by its `ObjectId` value. Then, the example calls the `Movie` entity's `setTitle()` method to update the document's `title` value to `\"Jurassic Park I\"`:\n\n\n\n\n\n```java\n// Your ObjectId value might differ\nMovie movieById = session.get(Movie.class, new ObjectId(\"573a1399f29313caabcedc5d\"));\nmovieById.setTitle(\"Jurassic Park I\");\nsession.persist(movieById);\n```\n\n\n\n\n\n```java\n// Your ObjectId value might differ\nMovie movieById = entityManager.find(Movie.class, new ObjectId(\"573a1399f29313caabcedc5d\"));\nmovieById.setTitle(\"Jurassic Park I\");\nentityManager.persist(movieById);\n```\n\n\n\n\n\n### Update Multiple Example\n\nThe following example updates the `title` value of matching documents from `\"The Three Stooges\"` to `\"The 3 Stooges\"`. Then, the example calls the `executeUpdate()` method to apply the changes to the database:\n\n\n\n\n\n```java\nvar updateResult = session.createMutationQuery(\n \"update Movie set title = :new where title = :old\")\n .setParameter(\"new\", \"The 3 Stooges\")\n .setParameter(\"old\", \"The Three Stooges\")\n .executeUpdate();\nSystem.out.println(\"Number of movies updated: \" + updateResult);\n```\n\n```\nNumber of movies updated: 2\n```\n\n\n\n\n\n```java\nvar updateResult = entityManager.createQuery(\n \"update Movie m set m.title = :new where m.title = :old\")\n .setParameter(\"new\", \"The 3 Stooges\")\n .setParameter(\"old\", \"The Three Stooges\")\n .executeUpdate();\nSystem.out.println(\"Number of movies updated: \" + updateResult);\n```\n\n```\nNumber of movies updated: 2\n```\n\n\n\n\n\nThe `SET` clause of a bulk update statement can also use an expression instead of a literal value. The expression can reference the field being updated or another field on the entity.\n\nThe following example uses an arithmetic expression to increment the `year` value of documents that have a `title` value of `\"The 3 Stooges\"`:\n\n```java\nvar updateResult = session.createMutationQuery(\n \"update Movie m set m.year = m.year + 1 where m.title = :title\")\n .setParameter(\"title\", \"The 3 Stooges\")\n .executeUpdate();\nSystem.out.println(\"Number of movies updated: \" + updateResult);\n```\n\n```\nNumber of movies updated: 2\n```\n\nThe following example uses a field reference to set the `plot` value to match the `title` value for documents that have a `year` value of `1920`:\n\n```java\nvar updateResult = session.createMutationQuery(\n \"update Movie m set m.plot = m.title where m.year = :year\")\n .setParameter(\"year\", 1920)\n .executeUpdate();\nSystem.out.println(\"Number of movies updated: \" + updateResult);\n```\n\n```\nNumber of movies updated: 4\n```\n\n### Update Multiple Based On Conditional Logic Example\n\nThe following example uses a `CASE` expression to set the `plot` value depending on whether each document's `year` value is after the year `2000`. The Hibernate ORM extension translates the `CASE` expression to the MongoDB `$switch` operator and applies the update by using a `$set` pipeline stage:\n\n```java\nvar updateResult = session.createMutationQuery(\n \"update Movie m set m.plot = case when m.year > 2000 then 'Modern release' \"\n + \"else 'Classic release' end where m.title = :title\")\n .setParameter(\"title\", \"The 3 Stooges\")\n .executeUpdate();\nSystem.out.println(\"Number of movies updated: \" + updateResult);\n```\n\n```\nNumber of movies updated: 2\n```\n\nTo learn more about `CASE` expressions, see the Use Case Expressions for Conditional Logic section in the Specify a Query guide.\n\n## Upsert Documents\n\nAn upsert operation updates a document if a matching document exists, or inserts a new document if no match exists. To perform an upsert, use the `upsert()` or `upsertMultiple()` method. These methods are available only on Hibernate's `StatelessSession` API.\n\nA `StatelessSession` instance does not track changes to the entities it retrieves. To save changes to an entity, pass it to another write method. Use `StatelessSession` for bulk write workflows."} -{"chunk_id": "6ad1c488e2bd6bff87646f55-2", "page_id": "6ad1c488e2bd6bff87646f55", "source_name": "hibernate", "product_name": null, "url": "https://mongodb.com/docs/languages/java/mongodb-hibernate/current/interact-data/crud", "title": "Perform CRUD Operations", "text": "### Entity Requirements\n\nThe Hibernate ORM extension creates the filter for an upsert operation from your entity's identifier, so your application must assign the identifier value before you call `upsert()`.\n\nThe `upsert()` method does not generate identifier values, even if your entity uses the `@ObjectIdGenerator` annotation. If you do not assign an identifier value, the Hibernate ORM extension stores the document with a `null` `_id` value.\n\nYou can use the `@Column(updatable = false)` annotation to protect a field from updates during an upsert operation. The following `Movie` entity definition annotates the `released` field with `@Column(updatable = false)`, which instructs the Hibernate ORM extension to write to the field when it inserts a document but to omit the field when it updates an existing document:\n\n```java\n@Entity\n@Table(name = \"movies\")\npublic class Movie {\n @Id\n @ObjectIdGenerator\n private ObjectId id;\n\n private String title;\n private int year;\n\n @Column(updatable = false)\n private Instant released;\n\n // Getters and setters omitted\n}\n```\n\nThe Hibernate ORM extension sends fields that are both insertable and updatable in the `$set` operator of the generated update statement. It sends insertable-only fields, such as fields annotated with `@Column(updatable = false)`, in the `$setOnInsert` operator.\n\n### Upsert One Example\n\nThe following example creates a `Movie` entity instance and passes it to the `upsert()` method. If a document that has the specified `ObjectId` value exists, the Hibernate ORM extension updates the `title` and `year` values of that document. Otherwise, the Hibernate ORM extension inserts a new document:\n\n```java\ntry (StatelessSession statelessSession = sf.openStatelessSession()) {\n var movie = new Movie();\n movie.setId(new ObjectId(\"573a1398f29313caabce9682\"));\n movie.setTitle(\"The General\");\n movie.setYear(1926);\n movie.setReleased(Instant.parse(\"1927-02-24T00:00:00Z\"));\n\n statelessSession.upsert(movie);\n}\n```\n\n### Upsert Multiple Example\n\nTo upsert several entity instances in one operation, pass a list of instances to the `upsertMultiple()` method. The following example upserts two `Movie` entity instances:\n\n```java\ntry (StatelessSession statelessSession = sf.openStatelessSession()) {\n var firstMovie = new Movie();\n firstMovie.setId(new ObjectId(\"573a1398f29313caabce9682\"));\n firstMovie.setTitle(\"The General\");\n firstMovie.setYear(1926);\n\n var secondMovie = new Movie();\n secondMovie.setId(new ObjectId(\"573a1398f29313caabce9683\"));\n secondMovie.setTitle(\"Metropolis\");\n secondMovie.setYear(1927);\n\n statelessSession.upsertMultiple(List.of(firstMovie, secondMovie));\n}\n```\n\n### Upsert Limitations\n\nThe following entity mappings are unsupported in upsert operations. When you upsert an entity that uses one of these mappings, the Hibernate ORM extension throws a `FeatureNotSupportedException`:\n\n- Entities that have a field annotated with `@Version`.\n\n- Entities that have a field annotated with `@Column(insertable = false)`. MongoDB Query Language provides no way to write a field only when an operation matches an existing document.\n\n- Entities whose only persistent attribute is the identifier. An upsert on this type of entity has no fields to update, so the Hibernate ORM extension rejects the operation.\n\n## Delete Documents\n\nYou can perform the following operations to delete documents from a collection:\n\n- Delete one document: Call the `remove()` method on a session or entity manager, passing the entity instance that you want to delete as an argument.\n\n- Delete multiple documents: Pass a delete statement to the `createQuery()` or `createMutationQuery()` methods on a session or entity manager. Then, call the `executeUpdate()` method to apply your changes to the database.\n\nTo learn more about deleting data by using Hibernate ORM, see the following resources:\n\n- Deleting entities in the Hibernate ORM user guide\n\n- Delete statements in the Hibernate ORM query guide\n\n### Delete One Example\n\nThe following example retrieves a document by its `ObjectId` value. Then, the example calls the `remove()` method on a session to delete the corresponding document from the `sample_mflix.movies` collection:\n\n\n\n\n\n```java\n// Your ObjectId value might differ\nMovie movieToDelete = session.get(Movie.class, new ObjectId(\"573a1399f29313caabcedc5d\"));\nsession.remove(movieToDelete);\n```\n\n\n\n\n\n```java\n// Your ObjectId value might differ\nMovie movieToDelete = entityManager.find(Movie.class, new ObjectId(\"573a1399f29313caabcedc5d\"));\nentityManager.remove(movieToDelete);\n```\n\n\n\n\n\n### Delete Multiple Example\n\nThe following example deletes all documents that have a `year` value of `1920` from the `sample_mflix.movies` collection. The example passes a delete statement to the `createMutationQuery()` method, and then calls the `executeUpdate()` method to apply the changes to the database:\n\n\n\n\n\n```java\nvar deleteResult = session.createMutationQuery(\n \"delete Movie where year = :y\")\n .setParameter(\"y\", 1920)\n .executeUpdate();\nSystem.out.println(\"Number of movies deleted: \" + deleteResult);\n```\n\n```\nNumber of movies deleted: 4\n```\n\n\n\n\n\n```java\nvar deleteResult = entityManager.createQuery(\n \"delete Movie m where m.year = :y\")\n .setParameter(\"y\", 1920)\n .executeUpdate();\nSystem.out.println(\"Number of movies deleted: \" + deleteResult);\n```\n\n```\nNumber of movies deleted: 4\n```\n\n\n\n\n\n## Additional Information\n\nTo learn more about performing CRUD operations by using the Hibernate ORM, see the following resources:\n\n- Persistence Context in the Hibernate ORM user guide\n\n- Statement types in the Hibernate ORM query guide\n\nTo view more create, read, update, and delete examples, see the following sections of the Get Started tutorial:\n\n- Run a Sample Query\n\n- Write Data to MongoDB\n\nTo learn more about using the Hibernate ORM extension to run queries, see the following guides:\n\n- Specify a Query\n\n- Perform Native Database Queries"} -{"chunk_id": "6ad1c488e2bd6bff87646f5a-0", "page_id": "6ad1c488e2bd6bff87646f5a", "source_name": "hibernate", "product_name": null, "url": "https://mongodb.com/docs/languages/java/mongodb-hibernate/current/interact-data/transactions", "title": "Transactions and Sessions", "text": "# Transactions and Sessions\n\n## Overview\n\nIn this guide, you can learn how to use the MongoDB Extension for Hibernate ORM to perform **transactions**. Transactions allow you to run a series of operations that change data only if the entire transaction is committed.\n\nIn MongoDB, transactions run within logical sessions. A session is a grouping of related read or write operations that you want to run sequentially. Sessions enable causal consistency for a group of operations and allow you to run operations in an **ACID-compliant** transaction, which is a transaction that meets an expectation of atomicity, consistency, isolation, and durability.\n\nThe Hibernate ORM extension supports the following APIs for managing sessions and transactions:\n\n- Hibernate `Session`: Allows you to use the `org.hibernate.Transaction` API to group your database operations. To learn more, see Hibernate Transaction API in the Hibernate ORM user guide.\n\n- Jakarta Persistence `EntityManager`: Instructs the Hibernate ORM to manage a `Session` internally and allows you to use the `jakarta.persistence.EntityTransaction` API to group your database operations. To learn more, see the jakarta.persistence package in the Jakarta EE documentation.\n\n### Sample Data\n\nThe examples in this guide use the `Movie` entity, which represents the `sample_mflix.movies` collection from the Atlas sample datasets. The `Movie` entity has the following definition:\n\n```java\nimport com.mongodb.hibernate.annotations.ObjectIdGenerator;\nimport org.bson.types.ObjectId;\nimport java.time.Instant;\nimport java.util.List;\nimport jakarta.persistence.Embedded;\n\nimport jakarta.persistence.Entity;\nimport jakarta.persistence.FetchType;\nimport jakarta.persistence.Id;\nimport jakarta.persistence.OneToMany;\nimport jakarta.persistence.Table;\n\n@Entity\n@Table(name = \"movies\")\npublic class Movie {\n @Id\n @ObjectIdGenerator\n private ObjectId id;\n private String title;\n private String plot;\n private int year;\n private List cast;\n private List directors;\n private Instant released;\n @Embedded\n private Awards awards;\n @OneToMany(mappedBy = \"movie\", fetch = FetchType.LAZY)\n private List comments;\n\n public Movie(String title, String plot, int year, List cast, List directors, Instant released, Awards awards) {\n this.title = title;\n this.plot = plot;\n this.year = year;\n this.cast = cast;\n this.directors = directors;\n this.released = released;\n this.awards = awards;\n }\n\n public Movie() {\n\n }\n\n public ObjectId getId() {\n return id;\n }\n\n public String getTitle() {\n return title;\n }\n\n public void setTitle(String title) {\n this.title = title;\n }\n\n public String getPlot() {\n return plot;\n }\n\n public void setPlot(String plot) {\n this.plot = plot;\n }\n\n public int getYear() {\n return year;\n }\n\n public void setYear(int year) {\n this.year = year;\n }\n\n public List getCast() {\n return cast;\n }\n\n public void setCast(List cast) {\n this.cast = cast;\n }\n\n public List getDirectors() {\n return directors;\n }\n\n public void setDirectors(List directors) {\n this.directors = directors;\n }\n\n public Awards getAwards() {\n return awards;\n }\n\n public void setAwards(Awards awards) {\n this.awards = awards;\n }\n\n public Instant getReleased() {\n return released;\n }\n\n public void setReleased(Instant released) {\n this.released = released;\n }\n\n public List getComments() {\n return comments;\n }\n\n public void setComments(List comments) {\n this.comments = comments;\n }\n}\n```\n\nTo learn how to create a Java application that uses the MongoDB Extension for Hibernate ORM to interact with this MongoDB sample collection, see the Get Started tutorial.\n\n## Create a Session\n\nTo interact with MongoDB data, you must run all database operations in a session. This section shows how to manage a database session in the following ways:\n\n- Use a Hibernate Session: Use Hibernate's native API to create a `Session` from a `SessionFactory`\n\n- Use a JPA EntityManager: Use the Jakarta Persistence API to create an `EntityManager` from an `EntityManagerFactory`\n\n### Use a Hibernate Session\n\nBefore using a `Session`, you must create a `HibernateUtil.java` file that configures a `SessionFactory`. To learn more, see the Configure your Application step of the Get Started tutorial.\n\nTo start a Hibernate `Session`, perform the following steps:\n\n1. Retrieve a `SessionFactory` from your `HibernateUtil` utility class by using the `getSessionFactory()` method. The `SessionFactory` stores your MongoDB connection configuration and can open new database sessions.\n\n2. Create a `Session` by calling the `openSession()` method on your `SessionFactory` instance.\n\n3. After running database operations, close your `SessionFactory` and `Session` by using the `close()` method on both instances.\n\nThe following example runs a database query in a session and retrieves a document that has a `title` value of `\"Erin Brockovich\"` from the `sample_mflix.movies` collection:\n\n```java\nvar sf = HibernateUtil.getSessionFactory();\nSession session = sf.openSession();\n\nvar movie = session.createQuery(\"from Movie where title = :t\", Movie.class)\n .setParameter(\"t\", \"Erin Brockovich\")\n .getSingleResult();\nSystem.out.println(\"Title: \" + movie.getTitle() + \", Year: \" + movie.getYear());\n\nsession.close();\nsf.close();\n```\n\n```none\nTitle: Erin Brockovich, Year: 2000\n```\n\nYou can also use Java's try-with-resources statement to simplify the session management logic and automatically close the session, as shown in the following code:\n\n```java\nvar sf = HibernateUtil.getSessionFactory();\ntry (Session session = sf.openSession()) {\n var movie = session.createQuery(\"from Movie where title = :t\", Movie.class)\n .setParameter(\"t\", \"Erin Brockovich\")\n .getSingleResult();\n System.out.println(\"Title: \" + movie.getTitle() + \", Year: \" + movie.getYear());\n}\nsf.close();\n```\n\n### Use a JPA EntityManager\n\nBefore using an `EntityManager`, you must create a `persistence.xml` file that declares a persistence unit. To learn more, see the Tutorial using JPA-standard APIs in the Hibernate ORM documentation.\n\nTo start a Jakarta Persistence API (JPA) `EntityManager`, perform the following steps:\n\n1. Create an `EntityManagerFactory` from your `persistence.xml` file by calling the `createEntityManagerFactory()` method, which creates a `SessionFactory` internally.\n\n2. Create an `EntityManager` by calling the `createEntityManager()` method on your `EntityManagerFactory` instance, which creates a `Session` internally.\n\n3. After running database operations, close your `EntityManagerFactory` and `EntityManager` by calling the `close()` method on both instances.\n\nThe following example runs a database query in an entity manager and retrieves documents that have a `year` value of `1929` from the `sample_mflix.movies` collection:\n\n```java\n// Replace with the name of your persistence unit in the persistence.xml file\nEntityManagerFactory emf = Persistence.createEntityManagerFactory(\"\");\nEntityManager entityManager = emf.createEntityManager();\n\nvar results = entityManager.createQuery(\"select m from Movie m where m.year = :y\", Movie.class)\n .setParameter(\"y\", 1929)\n .getResultList();\nresults.forEach(movie -> System.out.println(movie.getTitle()));\n\nentityManager.close();\nemf.close();\n```\n\n```none\nThe Broadway Melody\nQueen Kelly\nAsphalt\nHallelujah\nDisraeli\nApplause\nLambchops\n```\n\nIn Jakarta Persistence v3.1 or later, you can use Java's try-with-resources statement to automatically close the `EntityManager`, as shown in the Hibernate Session section."} -{"chunk_id": "6ad1c488e2bd6bff87646f5a-1", "page_id": "6ad1c488e2bd6bff87646f5a", "source_name": "hibernate", "product_name": null, "url": "https://mongodb.com/docs/languages/java/mongodb-hibernate/current/interact-data/transactions", "title": "Transactions and Sessions", "text": "## Run a Transaction\n\nTo modify MongoDB data, you must run all write operations in a transaction. This section shows how to manage a transaction in the following ways:\n\n- Use a Hibernate Transaction: Use Hibernate's native `org.hibernate.Transaction` API to start a transaction from a `Session`\n\n- Use a JPA EntityTransaction: Use the `jakarta.persistence.EntityTransaction` API to start a transaction from an `EntityManager`\n\n### Use a Hibernate Transaction\n\nTo start a Hibernate `Transaction`, call the `beginTransaction()` method on a `Session` instance. After you run operations and use the `persist()` method to register your changes with the session, commit the transaction by calling the `commit()` method.\n\nThe following example uses a transaction to perform the following operations on the `sample_mflix.movies` collection:\n\n- Creates a new `Movie` entity and inserts it as a document into the collection\n\n- Updates the `cast` field of a document that has a `title` value of `\"Black Swan\"`\n\nThe highlighted lines begin and commit the transaction:\n\n```java\nvar sf = HibernateUtil.getSessionFactory();\nSession session = sf.openSession();\nTransaction tx = session.beginTransaction();\n\nvar newMovie = new Movie();\nnewMovie.setTitle(\"Lady Bird\");\nnewMovie.setYear(2017);\nsession.persist(newMovie);\n\nvar movie = session.createQuery(\"from Movie where title = :t\", Movie.class)\n .setParameter(\"t\", \"Black Swan\")\n .getSingleResult();\nvar currentCast = new ArrayList<>(movie.getCast());\ncurrentCast.add(\"Winona Ryder\");\nmovie.setCast(currentCast);\n\ntx.commit();\nsession.close();\nsf.close();\n```\n\n### Use a JPA EntityTransaction\n\nTo create a JPA `EntityTransaction`, call the `getTransaction()` method on your `EntityManager`. This method retrieves a `EntityTransaction`, which wraps the underlying Hibernate `Transaction`. Then, call the `begin()` method to start the transaction. After you run operations and use the `persist()` method to register your changes with the entity manager, commit the transaction by calling the `commit()` method.\n\nThe following example uses an `EntityTransaction` to delete a document from the `sample_mflix.movies` collection, and then inserts a new document that has a title value of `\"The Favourite\"`. The highlighted lines begin and commit the transaction:\n\n```java\n// Replace with the name of your persistence unit in the persistence.xml file\nEntityManagerFactory emf = Persistence.createEntityManagerFactory(\"\");\nEntityManager entityManager = emf.createEntityManager();\nentityManager.getTransaction().begin();\n\n// Your ObjectId value might differ\nMovie movieToDelete = entityManager.find(Movie.class, new ObjectId(\"573a1399f29313caabcedc5d\"));\nentityManager.remove(movieToDelete);\n\nvar addMovie = new Movie();\naddMovie.setTitle(\"The Favourite\");\naddMovie.setYear(2018);\nentityManager.persist(addMovie);\n\nentityManager.getTransaction().commit();\nentityManager.close();\nemf.close();\n```\n\n## Transaction Error Handling\n\nTo discard all data changes from a transaction, call the `rollback()` method on a Hibernate `Transaction` or a JPA `EntityTransaction`. After calling this method, the Hibernate ORM reverts the uncommitted changes and clears the persistence context.\n\nThe following example rolls back the transaction if the code throws an error. Select the Hibernate Transaction or JPA EntityTransaction tab to see the corresponding code:\n\n\n\n\n\n```java\nSession session = sessionFactory.openSession();\nTransaction tx = null;\n\ntry {\n tx = session.beginTransaction();\n\n Movie movie = new Movie();\n movie.setTitle(\"Control Alt Delete\");\n session.persist(movie);\n\n tx.commit();\n} catch (Exception e) {\n if (tx != null) {\n tx.rollback();\n }\n e.printStackTrace();\n} finally {\n session.close();\n}\n```\n\n\n\n\n\n```java\nEntityManager entityManager = emf.createEntityManager();\nEntityTransaction tx = entityManager.getTransaction();\n\ntry {\n tx.begin();\n\n Movie movie = new Movie();\n movie.setTitle(\"Control Alt Delete\");\n entityManager.persist(movie);\n\n tx.commit();\n} catch (Exception e) {\n if (tx != null && tx.isActive()) {\n tx.rollback();\n }\n e.printStackTrace();\n} finally {\n entityManager.close();\n}\n```\n\n\n\n\n\n## Additional Information\n\nTo learn more about sessions and entity managers, see Persistence Context in the Hibernate ORM documentation.\n\nTo learn more about transactions, see Transactions in the Hibernate ORM documentation."} -{"chunk_id": "6ad1c488e2bd6bff87646f65-0", "page_id": "6ad1c488e2bd6bff87646f65", "source_name": "hibernate", "product_name": null, "url": "https://mongodb.com/docs/languages/java/mongodb-hibernate/current/interact-data/optimistic-locking", "title": "Prevent Conflicting Updates with Optimistic Locking", "text": "# Prevent Conflicting Updates with Optimistic Locking\n\n## Overview\n\nIn this guide, you can learn how to use the MongoDB Extension for Hibernate ORM to perform **optimistic locking**. Optimistic locking allows concurrent sessions to read the same entity, then detects a conflict when more than one session tries to write to that entity.\n\nWhen you turn on optimistic locking, the Hibernate ORM extension generates a MongoDB Query Language (MQL) statement for each update or delete operation. The statement filters on the version value that the session read, in addition to the primary key. If another session modified the document first, the filter matches no document, and the Hibernate ORM throws an `OptimisticLockException`.\n\nThe Hibernate ORM extension does not support pessimistic locking. Pessimistic locking locks an entity when a session reads it, which blocks other sessions from modifying the entity until the session releases the lock.\n\n## Add a Version Field\n\nTo turn on optimistic locking for an entity, add a field annotated with `@Version` to the entity class.\n\nDefine a getter for the field if your application reads the version value, but don't define a setter. The Hibernate ORM assigns the value itself, and setting the field in your application code might cause the Hibernate ORM extension to generate a filter that doesn't match the stored document.\n\nThe examples in this guide use the following `Product` entity, which maps to the `products` collection. Don't initialize the `version` field, because the Hibernate ORM assigns its initial value when you first persist the entity:\n\n```java\n@Entity\n@Table(name = \"products\")\npublic class Product {\n @Id\n @ObjectIdGenerator\n private ObjectId id;\n private String name;\n private int quantity;\n\n @Version\n private Long version;\n\n public Product() {\n }\n\n public Product(String name, int quantity) {\n this.name = name;\n this.quantity = quantity;\n }\n\n public ObjectId getId() {\n return id;\n }\n\n public Long getVersion() {\n return version;\n }\n\n public void setQuantity(int quantity) {\n this.quantity = quantity;\n }\n}\n```\n\nThe Hibernate ORM extension supports the following types for a `@Version` field:\n\n- `int` and `Integer`\n\n- `long` and `Long`\n\n- `Instant`\n\nA numeric version field starts at `0` and increments by `1` on each write. An `Instant` version field stores the time of the write.\n\n## Update a Versioned Entity\n\nWhen you persist a new entity, the Hibernate ORM sets the version field to `0`. When you then modify the entity and commit the transaction, the Hibernate ORM extension generates an update statement that filters on both the primary key and the version value that the session read. The statement also sets the new version value.\n\nThe following example inserts a new `Product` entity, then updates its `quantity` field to increment the version:\n\n```java\nvar sf = HibernateUtil.getSessionFactory();\ntry (Session session = sf.openSession()) {\n // Insert a new product, which sets the version to 0\n session.beginTransaction();\n var product = new Product(\"notebook\", 100);\n session.persist(product);\n session.getTransaction().commit();\n System.out.println(\"Version after insert: \" + product.getVersion());\n\n // Update the same product, which increments the version to 1\n session.beginTransaction();\n product.setQuantity(75);\n session.getTransaction().commit();\n System.out.println(\"Version after update: \" + product.getVersion());\n}\nsf.close();\n```\n\n```none\nVersion after insert: 0\nVersion after update: 1\n```\n\nThe update in the preceding example generates a statement similar to the following MQL:\n\n```json\n{\n \"update\": \"products\",\n \"updates\": [\n {\n \"q\": { \"$and\": [ { \"_id\": { \"$eq\": \"...\" } }, { \"version\": { \"$eq\": 0 } } ] },\n \"u\": { \"$set\": { \"quantity\": 75, \"version\": 1 } }\n }\n ]\n}\n```\n\nDelete operations use the same filter. Because the version value is part of the filter, a write succeeds only if the document still holds the version that the session read.\n\n## Handle a Version Conflict\n\nIf another session modifies a document after your session reads it, the version value in your filter no longer matches the stored value, and the Hibernate ORM throws an `OptimisticLockException`. To recover, catch the exception and either reload the entity and retry the write, or return an error that notifies your application's user of the conflict.\n\nThe following example uses two sessions to read the same document. The second session commits first, so the commit in the first session throws an `OptimisticLockException`:\n\n```java\nvar sf = HibernateUtil.getSessionFactory();\nObjectId productId;\n\n// Insert a new product for two sessions to modify\ntry (Session session = sf.openSession()) {\n session.beginTransaction();\n var product = new Product(\"notebook\", 100);\n session.persist(product);\n session.getTransaction().commit();\n productId = product.getId();\n}\n\ntry (Session sessionA = sf.openSession(); Session sessionB = sf.openSession()) {\n // Both sessions load the product at version 0\n var productA = sessionA.find(Product.class, productId);\n var productB = sessionB.find(Product.class, productId);\n\n // Session B commits first and increments the version to 1\n sessionB.beginTransaction();\n productB.setQuantity(75);\n sessionB.getTransaction().commit();\n\n // Session A commits second, but still holds version 0\n try {\n sessionA.beginTransaction();\n productA.setQuantity(50);\n sessionA.getTransaction().commit();\n } catch (OptimisticLockException e) {\n System.out.println(\"Update failed: Another session modified this document\");\n // Reload the entity and retry, or report the conflict to the user\n }\n}\nsf.close();\n```\n\n```none\nUpdate failed: Another session modified this document\n```\n\nDepending on how your application loads the entity, the Hibernate ORM might throw a `StaleObjectStateException` instead. This exception is the Hibernate ORM native equivalent of `OptimisticLockException`.\n\n## Increment a Version Without Changing Data\n\nTo increment the version of an entity that your session did not modify, pass the entity and the `LockMode.OPTIMISTIC_FORCE_INCREMENT` lock mode to the `lock()` method on your `Session`. Use this lock mode when a change to related data must invalidate other sessions' copies of the entity.\n\nThe following example increments the version of a `Product` document:\n\n```java\nvar sf = HibernateUtil.getSessionFactory();\ntry (Session session = sf.openSession()) {\n session.beginTransaction();\n\n var product = session.createQuery(\"from Product where name = :n\", Product.class)\n .setParameter(\"n\", \"notebook\")\n .setMaxResults(1)\n .getSingleResult();\n session.lock(product, LockMode.OPTIMISTIC_FORCE_INCREMENT);\n\n session.getTransaction().commit();\n}\nsf.close();\n```\n\nIf another session incremented the version first, the commit throws an `OptimisticLockException`."} -{"chunk_id": "6ad1c488e2bd6bff87646f65-1", "page_id": "6ad1c488e2bd6bff87646f65", "source_name": "hibernate", "product_name": null, "url": "https://mongodb.com/docs/languages/java/mongodb-hibernate/current/interact-data/optimistic-locking", "title": "Prevent Conflicting Updates with Optimistic Locking", "text": "## Lock Without a Version Field\n\nYou can also detect conflicts without adding a version field. To do so, annotate your entity with `@OptimisticLocking` and specify one of the following types:\n\n- `OptimisticLockType.DIRTY`: The Hibernate ORM extension filters on the previous values of only the fields that the session modified.\n\n- `OptimisticLockType.ALL`: The Hibernate ORM extension filters on the previous values of all the entity's fields.\n\nBoth types require the `@DynamicUpdate` annotation.\n\nThe following example uses the `DIRTY` type:\n\n```java\n@Entity\n@Table(name = \"products\")\n@OptimisticLocking(type = OptimisticLockType.DIRTY)\n@DynamicUpdate\npublic class Product {\n @Id\n @ObjectIdGenerator\n private ObjectId id;\n private String name;\n private int quantity;\n\n // Constructors, getters, and setters\n}\n```\n\nTo exclude a field from optimistic locking in a versioned entity, annotate the field with `@OptimisticLock(excluded = true)`. Changes to an excluded field do not increment the version:\n\n```java\n@Entity\n@Table(name = \"products\")\npublic class Product {\n @Id\n @ObjectIdGenerator\n private ObjectId id;\n\n @OptimisticLock(excluded = true)\n private String name;\n\n private int quantity;\n\n @Version\n private Long version;\n\n // Constructors, getters, and setters\n}\n```\n\n## Limitations\n\nOptimistic locking has the following limitations:\n\n- The Hibernate ORM extension does not support pessimistic locking. To learn more about locking support, see the Transactions and Concurrency section of the Feature Compatibility page.\n\n- You cannot pass an entity that has a `@Version` field to the `StatelessSession.upsert()` method. The Hibernate ORM extension throws an `UnsupportedFeatureException` for this operation.\n\n## Additional Information\n\nTo learn more about optimistic locking, see Optimistic Locking in the Hibernate ORM documentation.\n\nTo learn more about running write operations in a transaction, see the Transactions and Sessions guide."} -{"chunk_id": "6ad1c488e2bd6bff87646f57-0", "page_id": "6ad1c488e2bd6bff87646f57", "source_name": "hibernate", "product_name": null, "url": "https://mongodb.com/docs/languages/java/mongodb-hibernate/current/interact-data/modify-query-results", "title": "Modify Query Results", "text": "# Modify Query Results\n\n## Overview\n\nIn this guide, you can learn how to sort, skip, limit, and group the results of a query by using the MongoDB Extension for Hibernate ORM.\n\n## Sort Results\n\nYou can sort query results by the value of a specified field by using the `order by` clause in your query statement. By default, the `order by` clause sorts documents in ascending order. To sort documents in descending order, append the `desc` keyword to the field name.\n\nThe following example retrieves matching documents from the `sample_mflix.movies` collection and sorts them by the `year` field in descending order:\n\n\n\n\n\n```java\nvar sortResult = session.createQuery(\"from Movie where title = :t order by year desc\", Movie.class)\n .setParameter(\"t\", \"Cinderella\")\n .getResultList();\nfor (var m : sortResult) {\n System.out.println(\"Title: \" + m.getTitle() + \", Year: \" + m.getYear());\n}\n```\n\n```\nTitle: Cinderella, Year: 2015\nTitle: Cinderella, Year: 1997\nTitle: Cinderella, Year: 1950\n```\n\n\n\n\n\n```java\nvar sortResult = entityManager.createQuery(\"select m from Movie m where m.title = :t order by m.year desc\", Movie.class)\n .setParameter(\"t\", \"Cinderella\")\n .getResultList();\nfor (var m : sortResult) {\n System.out.println(\"Title: \" + m.getTitle() + \", Year: \" + m.getYear());\n}\n```\n\n```\nTitle: Cinderella, Year: 2015\nTitle: Cinderella, Year: 1997\nTitle: Cinderella, Year: 1950\n```\n\n\n\n\n\n## Skip Results\n\nYou can skip a specified number of documents in your query results by chaining the `setFirstResult()` method to the query. Pass the number of initial documents to skip as an argument to this method.\n\nThe following example runs the same query as the preceding example but skips the first matching document in the results:\n\n\n\n\n\n```java\nvar skipResult = session.createQuery(\"from Movie where title = :t order by year desc\", Movie.class)\n .setParameter(\"t\", \"Cinderella\")\n .setFirstResult(1)\n .getResultList();\nfor (var m : skipResult) {\n System.out.println(\"Title: \" + m.getTitle() + \", Year: \" + m.getYear());\n}\n```\n\n```\nTitle: Cinderella, Year: 1997\nTitle: Cinderella, Year: 1950\n```\n\n\n\n\n\n```java\nvar skipResult = entityManager.createQuery(\"select m from Movie m where m.title = :t order by m.year desc\", Movie.class)\n .setParameter(\"t\", \"Cinderella\")\n .setFirstResult(1)\n .getResultList();\nfor (var m : skipResult) {\n System.out.println(\"Title: \" + m.getTitle() + \", Year: \" + m.getYear());\n}\n```\n\n```\nTitle: Cinderella, Year: 1997\nTitle: Cinderella, Year: 1950\n```\n\n\n\n\n\n## Limit Results\n\nYou can limit the number of documents that your query returns by chaining the `setMaxResults()` method to the query. Pass the maximum number of documents to return as an argument to this method.\n\nThe following example runs the same query as the sort example but returns up to two matching documents in the results:\n\n\n\n\n\n```java\nvar limitResult = session.createQuery(\"from Movie where title = :t order by year desc\", Movie.class)\n .setParameter(\"t\", \"Cinderella\")\n .setMaxResults(2)\n .getResultList();\nfor (var m : limitResult) {\n System.out.println(\"Title: \" + m.getTitle() + \", Year: \" + m.getYear());\n}\n```\n\n```\nTitle: Cinderella, Year: 2015\nTitle: Cinderella, Year: 1997\n```\n\n\n\n\n\n```java\nvar limitResult = entityManager.createQuery(\"select m from Movie m where m.title = :t order by m.year desc\", Movie.class)\n .setParameter(\"t\", \"Cinderella\")\n .setMaxResults(2)\n .getResultList();\nfor (var m : limitResult) {\n System.out.println(\"Title: \" + m.getTitle() + \", Year: \" + m.getYear());\n}\n```\n\n```\nTitle: Cinderella, Year: 2015\nTitle: Cinderella, Year: 1997\n```\n\n\n\n\n\nAlternatively, you can use a `limit` clause in your HQL or JPQL statement to restrict the number of documents that your query returns, as shown in the following code:\n\n\n\n\n\n```java\nvar limitClauseResult = session.createQuery(\"from Movie where title = :t order by year desc limit 2\", Movie.class)\n .setParameter(\"t\", \"Cinderella\")\n .getResultList();\n```\n\n\n\n\n\n```java\nvar limitClauseResult = entityManager.createQuery(\"select m from Movie m where m.title = :t order by m.year desc limit 2\", Movie.class)\n .setParameter(\"t\", \"Cinderella\")\n .getResultList();\n```\n\n\n\n\n\n## Group Results\n\nYou can collapse documents that share a value into a single result row by using the `group by` clause in your query statement. The Hibernate ORM extension translates the `group by` clause to a MongoDB $group stage, in which each grouping key becomes a sub-field of the `_id` field.\n\nEvery field that you reference in the `select`, `having`, or `order by` clause of a grouped query must be a grouping key or part of one. If you reference a field that the `$group` stage does not produce, the Hibernate ORM extension throws a `FeatureNotSupportedException`.\n\nA grouped query also cannot use the `distinct` keyword.\n\n### Group by Field Values\n\nTo group results by the value of one or more fields, list the fields in the `group by` clause. To group by multiple fields, separate the field names with commas.\n\nThis example performs the following operations:\n\n- Retrieves documents that have a `title` value of `\"Hairspray\"` from the `sample_mflix.movies` collection.\n\n- Groups the movies by the `year` field, which returns one row for each distinct release year.\n\n- Sorts the results by their `year` values in ascending order.\n\n\n\n\n\n```java\nvar groupResult = session.createQuery(\n \"select year from Movie where title = :title group by year order by year\",\n Integer.class)\n .setParameter(\"title\", \"Hairspray\")\n .getResultList();\nfor (var year : groupResult) {\n System.out.println(\"Year: \" + year);\n}\n```\n\n```\nYear: 1988\nYear: 2007\n```\n\n\n\n\n\n```java\nvar groupResult = entityManager.createQuery(\n \"select m.year from Movie m where m.title = :title group by m.year order by m.year\",\n Integer.class)\n .setParameter(\"title\", \"Hairspray\")\n .getResultList();\nfor (var year : groupResult) {\n System.out.println(\"Year: \" + year);\n}\n```\n\n```\nYear: 1988\nYear: 2007\n```\n\n\n\n\n\nThe Hibernate ORM extension translates this query to the following pipeline. The `where` clause becomes a `$match` stage that runs before the grouping. The `order by` clause becomes a `$sort` stage that sorts on the grouping key:\n\n```json\n[\n { \"$match\": { \"title\": { \"$eq\": \"Hairspray\" } } },\n { \"$group\": { \"_id\": { \"year\": \"$year\" } } },\n { \"$sort\": { \"_id.year\": 1 } },\n { \"$project\": { \"_id#year\": \"$_id.year\", \"_id\": 0 } }\n]\n```"} -{"chunk_id": "6ad1c488e2bd6bff87646f57-1", "page_id": "6ad1c488e2bd6bff87646f57", "source_name": "hibernate", "product_name": null, "url": "https://mongodb.com/docs/languages/java/mongodb-hibernate/current/interact-data/modify-query-results", "title": "Modify Query Results", "text": "### Group by a Computed Expression\n\nA grouping key can be a computed expression instead of a field reference. The Hibernate ORM extension stores the expression in a generated `_id` sub-field named `k`. When you write the same expression in the `select` or `having` clause, the Hibernate ORM extension resolves it to that sub-field rather than recomputing it.\n\nThe Hibernate ORM extension matches an expression to a grouping key only when you write the two identically. For example, a key of `year + 1` does not match an occurrence of `1 + year`.\n\nYou can also order by a computed expression key. Write the expression in the `order by` clause exactly as you write it in the `group by` clause.\n\nThe following example groups documents that have a `title` of `\"Hairspray\"` by the decade in which they were released and sorts the results in ascending order:\n\n\n\n\n\n```java\nvar groupExpressionResult = session.createQuery(\n \"select year / 10 * 10 from Movie where title = :title group by year / 10 * 10 order by year / 10 * 10\",\n Integer.class)\n .setParameter(\"title\", \"Hairspray\")\n .getResultList();\nfor (var decade : groupExpressionResult) {\n System.out.println(\"Decade: \" + decade);\n}\n```\n\n```\nDecade: 1980\nDecade: 2000\n```\n\n\n\n\n\n```java\nvar groupExpressionResult = entityManager.createQuery(\n \"select m.year / 10 * 10 from Movie m where m.title = :title group by m.year / 10 * 10 order by m.year / 10 * 10\",\n Integer.class)\n .setParameter(\"title\", \"Hairspray\")\n .getResultList();\nfor (var decade : groupExpressionResult) {\n System.out.println(\"Decade: \" + decade);\n}\n```\n\n```\nDecade: 1980\nDecade: 2000\n```\n\n\n\n\n\nThe Hibernate ORM extension translates this query to the following pipeline, in which the `$sort` and `$project` stages read the grouping key from `_id.k0` instead of recomputing the expression:\n\n```json\n[\n { \"$match\": { \"title\": { \"$eq\": \"Hairspray\" } } },\n {\n \"$group\": {\n \"_id\": {\n \"k0\": {\n \"$multiply\": [\n { \"$toInt\": { \"$divide\": [ \"$year\", 10 ] } },\n 10\n ]\n }\n }\n }\n },\n { \"$sort\": { \"_id.k0\": 1 } },\n { \"$project\": { \"#c_1\": \"$_id.k0\", \"_id\": 0 } }\n]\n```\n\nYou can also select a computed expression that contains a grouping key. In this case, the Hibernate ORM extension groups by the key and computes the expression from the key in the `$project` stage.\n\nTo learn more about computed expressions, see the Use Computed Expressions section in the Specify a Query guide.\n\n### Filter Grouped Results\n\nTo remove groups from the results, use the `having` clause. The Hibernate ORM extension uses the `having` clause to filter on the grouping key. You can combine multiple conditions by using the `and` and `or` operators.\n\nThis example performs the following operations:\n\n- Retrieves the `\"Hairspray\"` movies from the `sample_mflix.movies` collection.\n\n- Groups the movies by the `year` field, which returns one row for each distinct release year.\n\n- Filters the groups to only include `year` values greater than `2000`.\n\n- Sorts the results by year in ascending order.\n\n\n\n\n\n```java\nvar havingResult = session.createQuery(\n \"select year from Movie where title = :title group by year having year > 2000 order by year\",\n Integer.class)\n .setParameter(\"title\", \"Hairspray\")\n .getResultList();\nfor (var year : havingResult) {\n System.out.println(\"Year: \" + year);\n}\n```\n\n```\nYear: 2007\n```\n\n\n\n\n\n```java\nvar havingResult = entityManager.createQuery(\n \"select m.year from Movie m where m.title = :title group by m.year having m.year > 2000 order by m.year\",\n Integer.class)\n .setParameter(\"title\", \"Hairspray\")\n .getResultList();\nfor (var year : havingResult) {\n System.out.println(\"Year: \" + year);\n}\n```\n\n```\nYear: 2007\n```\n\n\n\n\n\nThe Hibernate ORM extension translates this query to the following pipeline. The `where` clause becomes a `$match` stage that runs before the grouping. The `having` clause becomes a second `$match` stage that runs after the grouping and filters on the grouping key:\n\n```json\n[\n { \"$match\": { \"title\": { \"$eq\": \"Hairspray\" } } },\n { \"$group\": { \"_id\": { \"year\": \"$year\" } } },\n { \"$match\": { \"_id.year\": { \"$gt\": 2000 } } },\n { \"$sort\": { \"_id.year\": 1 } },\n { \"$project\": { \"_id#year\": \"$_id.year\", \"_id\": 0 } }\n]\n```\n\n## Additional Information\n\nTo learn more about performing other operations on your MongoDB data, see the Perform CRUD Operations guide.\n\nTo learn more about using HQL and JPQL to run queries, see A Guide to Hibernate Query Language in the Hibernate ORM documentation."} -{"chunk_id": "6ad1c488e2bd6bff87646f64-0", "page_id": "6ad1c488e2bd6bff87646f64", "source_name": "hibernate", "product_name": null, "url": "https://mongodb.com/docs/languages/java/mongodb-hibernate/current/spring-boot/get-started", "title": "Get Started with the Spring Boot Starter", "text": "# Get Started with the Spring Boot Starter\n\n## Overview\n\nIn this tutorial, you can learn how to create a Spring Boot application that stores Java Persistence API (JPA) entities in MongoDB by using the Hibernate ORM extension. The application defines a `Movie` entity, a Spring Data JPA repository, and a query that runs at startup.\n\nBefore you begin, complete the Create a MongoDB Deployment and Create a Connection String steps of the Get Started with the Hibernate ORM Extension tutorial. Those steps create the Atlas deployment, sample data, and connection string that this tutorial uses.\n\n## Install the Application Starter\n\n### Create a Spring Boot project\n\nCreate a Spring Boot 4.x project named `MongoHibernateSpringQuickstart`. You can generate the project by using the Spring Initializr or create it in your IDE.\n\nThe Spring Initializr generates a main application class named after your project, such as `MongoHibernateSpringQuickstartApplication.java`. If you use the Spring Initializr to generate your project, delete the auto-generated main application class file. You will create a main application file for this project named `Movie Application` later in this tutorial. If your project contains two main application classes, your application fails to start with an `Unable to find a single main class` error.\n\n### Add the starter dependency\n\nFor Maven projects, add the following dependency to your `pom.xml` file:\n\n```xml\n\n \n org.mongodb\n mongodb-hibernate-spring-boot-starter\n 1.0.0\n \n\n```\n\nFor Gradle projects, add the following dependency to your `build.gradle` file:\n\n```groovy\ndependencies {\n implementation(\"org.mongodb:mongodb-hibernate-spring-boot-starter:1.0.0\")\n}\n```\n\n### Override the managed Hibernate ORM version\n\nThe starter requires Hibernate ORM 7.4 or later. Spring Boot manages the Hibernate ORM version through its bill of materials (BOM), and some Spring Boot 4.x releases manage an earlier version of Hibernate ORM than the version that the starter requires. If the managed version is earlier than 7.4, your application fails to start and the Hibernate ORM extension throws a `NoSuchMethodError`.\n\nTo override the managed version in a Maven project, add the following property to your `pom.xml` file:\n\n```xml\n\n 7.4.7.Final\n\n```\n\nTo override the managed version in a Gradle project, add the following line to your `build.gradle` file:\n\n```groovy\next['hibernate.version'] = '7.4.7.Final'\n```\n\nReload or sync your project to complete the installation.\n\n## Configure Your Application\n\n### Set your application properties\n\nIn your project's `src/main/resources` directory, open the `application.properties` file and add the following properties:\n\n```properties\nspring.jpa.database-platform=MongoDB\nspring.mongodb.uri=\nspring.jpa.properties.com.mongodb.hibernate.semantics.nulls=MQL\n\n```\n\nReplace the `` placeholder with the `sample_mflix` connection string that you created in the Create a Connection String step of the Get Started with the Hibernate ORM Extension tutorial. Your connection string should resemble the following example:\n\n```text\nmongodb+srv://:@/sample_mflix?\n```\n\nThe application properties you set do the following:\n\n- `spring.jpa.database-platform`: Activates the starter. The starter remains inactive unless you set this property to `MongoDB`.\n\n- `spring.mongodb.uri`: Configures the `MongoClient` instance that the starter reuses. The starter does not create a client of its own.\n\n- `spring.jpa.properties.com.mongodb.hibernate.semantics.nulls`: Declares the null-comparison semantics that queries use. This property is required and its only supported value is `MQL`.\n\n### Define your `Movie` entity\n\nIn your project's `src/main/java/org/example` directory, create a file called `Movie.java` and paste the following code into it:\n\n```java\npackage org.example;\n\nimport com.mongodb.hibernate.annotations.ObjectIdGenerator;\nimport org.bson.types.ObjectId;\n\nimport jakarta.persistence.Entity;\nimport jakarta.persistence.Id;\nimport jakarta.persistence.Table;\n\n@Entity\n@Table(name = \"movies\")\npublic class Movie {\n @Id\n @ObjectIdGenerator\n private ObjectId id;\n private String title;\n private int year;\n\n public Movie() {\n }\n\n public Movie(String title, int year) {\n this.title = title;\n this.year = year;\n }\n\n public ObjectId getId() {\n return id;\n }\n\n public String getTitle() {\n return title;\n }\n\n public void setTitle(String title) {\n this.title = title;\n }\n\n public int getYear() {\n return year;\n }\n\n public void setYear(int year) {\n this.year = year;\n }\n}\n\n```\n\nThis entity represents the `sample_mflix.movies` collection from the Atlas sample datasets. The starter scans your application's main package for entities, so you do not need to register the entity.\n\n### Define your repository\n\nIn the same directory, create a file called `MovieRepository.java` and paste the following code into it:\n\n```java\npackage org.example;\n\nimport org.bson.types.ObjectId;\nimport org.springframework.data.jpa.repository.JpaRepository;\n\nimport java.util.List;\n\npublic interface MovieRepository extends JpaRepository {\n List findByTitle(String title);\n}\n\n```\n\nThe starter enables Spring Data JPA repositories without a SQL `DataSource`, so Spring Boot implements the `MovieRepository` interface for you.\n\n### Define your application class\n\nIn the same directory, create a file called `MovieApplication.java` and paste the following code into it:\n\n```java\npackage org.example;\n\nimport org.springframework.boot.CommandLineRunner;\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.context.annotation.Bean;\n\n@SpringBootApplication\npublic class MovieApplication {\n\n public static void main(String[] args) {\n SpringApplication.run(MovieApplication.class, args);\n }\n\n @Bean\n CommandLineRunner run(MovieRepository repository) {\n return args -> {\n for (Movie movie : repository.findByTitle(\"Little Women\")) {\n System.out.println(\"Title: \" + movie.getTitle()\n + \", Year: \" + movie.getYear());\n }\n };\n }\n}\n\n```\n\nThis class runs a repository query at startup and prints each matching movie.\n\nAfter you complete these steps, your application has the following file structure:\n\n```text\nMongoHibernateSpringQuickstart\n\u251c\u2500\u2500 src\n\u2502 \u2514\u2500\u2500 main\n\u2502 \u251c\u2500\u2500 java\n\u2502 \u2502 \u2514\u2500\u2500 org/example\n\u2502 \u2502 \u251c\u2500\u2500 Movie.java\n\u2502 \u2502 \u251c\u2500\u2500 MovieApplication.java\n\u2502 \u2502 \u2514\u2500\u2500 MovieRepository.java\n\u2502 \u2514\u2500\u2500 resources\n\u2502 \u2514\u2500\u2500 application.properties\n\u251c\u2500\u2500 .gitignore\n\u251c\u2500\u2500 pom.xml (for Maven projects)\n\u2514\u2500\u2500 build.gradle (for Gradle projects)\n```\n\n## Run Your Application\n\nRun the `MovieApplication` class in your IDE. Your output resembles the following text:\n\n```none\nTitle: Little Women, Year: 1949\nTitle: Little Women, Year: 1994\n```\n\nIf your application does not start, see Troubleshoot Startup Errors for possible startup errors and troubleshooting tips.\n\n## Next Steps\n\nTo learn how to set JPA properties, change the field naming strategy, and customize the `MongoClient`, see Configure the Spring Boot Starter.\n\nTo learn how to model your data as entities, see Create Entities to Represent Collections.\n\nTo learn how to query your data, see the Interact with Data section."} -{"chunk_id": "6ad1c488e2bd6bff87646f62-0", "page_id": "6ad1c488e2bd6bff87646f62", "source_name": "hibernate", "product_name": null, "url": "https://mongodb.com/docs/languages/java/mongodb-hibernate/current/spring-boot/configure", "title": "Configure the Spring Boot Starter", "text": "# Configure the Spring Boot Starter\n\n## Overview\n\nIn this guide, you can learn how to configure the Spring Boot starter that the MongoDB Extension for Hibernate ORM provides. To learn how to install the starter and create an application that uses it, see Get Started with the Spring Boot Starter.\n\n## Activate the Starter\n\nTo activate the starter, set the `spring.jpa.database-platform` property to `MongoDB` in your application's `application.properties` file, as shown in the following example:\n\n```properties\nspring.jpa.database-platform=MongoDB\n```\n\nThe starter uses this standard Spring Boot property and requires no dedicated configuration of its own. When the property has any other value or is unset, the starter remains inactive. An inactive starter does not affect your application.\n\n## Configure the Connection\n\nThe starter reuses the `MongoClient` instance that Spring Boot creates from the `spring.mongodb.*` properties. The starter does not create a client of its own and does not manage the client's lifecycle, so your application uses one connection pool for Java Persistence API (JPA) persistence, health checks, metrics, and any other component that uses the client.\n\nThe starter uses the database name set in the `spring.mongodb.database` property. If you do not set that property, the starter uses the database name in the connection string that you set in the `spring.mongodb.uri` property.\n\nTo customize this client, declare a MongoClientSettingsBuilderCustomizer bean. This interface customizes the `MongoClientSettings.Builder` instance before Spring Boot creates the client.\n\n## Set JPA Properties\n\nThe starter uses the standard `spring.jpa.*` properties. The following table describes commonly used properties:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nProperty\n\n\nDescription\n\n
\n`spring.jpa.hibernate.ddl-auto`\n\n\nSpecifies the schema management action that Hibernate ORM performs at startup. The default value for MongoDB-backed persistence units is `none`.\n\n
\n`spring.jpa.show-sql`\n\n\nSpecifies whether Hibernate ORM logs the statements that it generates.\n\n
\n`spring.jpa.properties.*`\n\n\nPasses Hibernate ORM configuration properties directly to Hibernate ORM.\n\n
\n`spring.jpa.open-in-view`\n\n\nSpecifies whether the persistence context stays open for the duration of a web request. This property is enabled by default in servlet web applications.\n\n
\n`spring.data.jpa.repositories.enabled`\n\n\nSpecifies whether the starter enables Spring Data JPA repository scanning. This property is enabled by default.\n\n
You can also declare HibernatePropertiesCustomizer and EntityManagerFactoryBuilderCustomizer beans to modify the configuration that the starter builds. The `HibernatePropertiesCustomizer` interface customizes the Hibernate ORM properties that the starter passes to the `EntityManagerFactory`, and the `EntityManagerFactoryBuilderCustomizer` interface customizes the builder that creates it.\n\n## Scan for Entities and Repositories\n\nThe starter scans for entities in the packages that you register by using the @EntityScan annotation. If you register no packages, the starter scans the package of your `@SpringBootApplication` class and its subpackages.\n\nDeclare the `@EntityScan` annotation on your main application class, as shown in the following example:\n\n```java\n@SpringBootApplication\n@EntityScan(\"org.example.model\")\n\npublic class MovieApplication {\n // ...\n}\n```\n\nThe starter enables Spring Data JPA repositories in the same package scope. If you declare the `@EnableJpaRepositories` annotation yourself, your declaration takes precedence over the starter's.\n\nThe starter enables these repositories without a SQL `DataSource` and brings no SQL connection pool. A MongoDB-only application therefore requires no `spring.datasource.url` property, and Spring Boot does not use its `DataSourceAutoConfiguration` class.\n\n## Configure Field Naming\n\nUnlike a SQL Spring Boot application, which maps entity properties to `snake_case` column names by default, the starter maps each entity property to a document field of the same name. An entity that you bootstrap through the starter persists the same way as an entity that you bootstrap through Hibernate ORM directly.\n\nTo use a different naming strategy, set the strategy explicitly in your application's `application.properties` file, as shown in the following example:\n\n```properties\nspring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategySnakeCaseImpl\n```\n\nChanging the naming strategy affects only documents that your application writes after the strategy change. MongoDB does not migrate existing documents, so a collection can contain documents that use multiple types of field names. Migrate your existing documents before you change the naming strategy.\n\n## Troubleshoot Startup Errors\n\nWhen the starter is active but cannot configure a persistence unit, it reports the error at startup. The following table describes these errors:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nError\n\n\nResolution\n\n
\nNo `MongoClient` is available for the starter to use.\n\n\nAdd the `spring-boot-mongodb` dependency and set the `spring.mongodb.*` properties, or declare a `MongoClient` bean in your application.\n\n
\nNo database name is available.\n\n\nAdd the database name to the connection string in the `spring.mongodb.uri` property, set the `spring.mongodb.database` property, or set the name by using a `MongoConfigurationContributor` bean.\n\n
\n\n## Use a Dedicated Client\n\nTo connect through a client that only the starter uses, such as a client with different credentials, declare a `MongoConfigurationContributor` bean that sets the client and the database name. When you declare this bean, the starter uses your client instead of the Spring-managed client.\n\nIf you declare more than one `MongoConfigurationContributor` bean, the starter applies them in the order that you specify by using the `@Order` annotation, and the last bean that sets a value determines that value.\n\n## Limitations\n\nThe starter has the following limitations:\n\n- The `@DataJpaTest` annotation is not supported. To test against MongoDB, use the `@SpringBootTest` annotation, which loads your full application context.\n\n- The starter configures a single persistence unit. To use more than one persistence unit, configure the additional units yourself."} -{"chunk_id": "6ad1c488e2bd6bff87646f5e-0", "page_id": "6ad1c488e2bd6bff87646f5e", "source_name": "hibernate", "product_name": null, "url": "https://mongodb.com/docs/languages/java/mongodb-hibernate/current/security/validate-signatures", "title": "Validate Hibernate Extension Artifact Signatures", "text": "# Validate Hibernate Extension Artifact Signatures\n\n## Overview\n\nYou can validate the signature of a MongoDB Extension for Hibernate ORM artifact that MongoDB publishes to Maven Central. Validating an artifact signature helps you confirm that the artifact is authentic and unmodified.\n\n## Procedure\n\nThese steps describe how you can validate Hibernate ORM extension artifact signatures.\n\n### Install encryption software\n\nYou must install the GnuPG encryption suite to validate artifact signatures from the command line.\n\nOn macOS, you can install GnuPG by using Homebrew:\n\n```bash\nbrew install gnupg\n```\n\nYou can also install GPG Suite, which provides a graphical interface for GnuPG. There is a Homebrew installation for GPG Suite.\n\n### Download and import the MongoDB signing key\n\nDownload and import the public key that MongoDB uses to sign the release:\n\n```bash\ngpg --keyserver hkps://keyserver.ubuntu.com --recv-keys 1a75005e142192223d6a7c3b76e0008d166740a8\n```\n\nYou can also find release-specific instructions on the MongoDB Extension for Hibernate ORM releases page.\n\n### Download the signed artifact\n\nDownload the MongoDB Extension for Hibernate ORM artifact that you want to verify from Maven Central.\n\nThe following example downloads version 1.0.0 of the extension:\n\n```bash\ncurl -LO https://repo.maven.apache.org/maven2/org/mongodb/mongodb-hibernate/1.0.0/mongodb-hibernate-1.0.0.jar\n```\n\nTo verify a different version, replace 1.0.0 in the command with the version that you want to verify.\n\n### Download the artifact signature\n\nDownload the detached signature file for the same artifact and version:\n\n```bash\ncurl -LO https://repo.maven.apache.org/maven2/org/mongodb/mongodb-hibernate/1.0.0/mongodb-hibernate-1.0.0.jar.asc\n```\n\nThe `.asc` file must correspond to the artifact file that you downloaded.\n\n### Verify the signature\n\nRun the following command from the directory containing the artifact and its signature:\n\n```bash\ngpg --verify mongodb-hibernate-1.0.0.jar.asc mongodb-hibernate-1.0.0.jar\n```\n\nIf the signature is valid, GnuPG prints a message similar to the following:\n\n```text\ngpg: Signature made Wed Sep 16 19:15:35 2026 IST\ngpg: using RSA key 76E0008D166740A8\ngpg: Good signature from \"MongoDB Java Driver Release Signing Key \" [unknown]\ngpg: WARNING: This key is not certified with a trusted signature!\ngpg: There is no indication that the signature belongs to the owner.\nPrimary key fingerprint: 1A75 005E 1421 9222 3D6A 7C3B 76E0 008D 1667 40A8\n```\n\nA valid signature confirms that the artifact matches the signed release. Review the key fingerprint and signing identity before trusting the result.\n\n## Additional Information\n\nTo learn more about verifying signatures, see Verify Integrity of MongoDB Packages in the Server manual."} -{"chunk_id": "6ad1c488e2bd6bff87646f67-0", "page_id": "6ad1c488e2bd6bff87646f67", "source_name": "hibernate", "product_name": null, "url": "https://mongodb.com/docs/languages/java/mongodb-hibernate/current/feature-compatibility", "title": "Feature Compatibility", "text": "# Feature Compatibility\n\n## Overview\n\nOn this page, you can find information about supported and unsupported features in the Hibernate ORM extension. The Hibernate ORM extension supports only MongoDB replica sets. When you use an unsupported feature, the Hibernate ORM extension throws an `UnsupportedFeatureException`.\n\nYou can request support for a feature by creating an AHA idea. We prioritize upcoming features based on user demand.\n\n## MongoDB Features\n\nThis section indicates whether the Hibernate ORM extension supports various MongoDB features.\n\n### Data Type Support\n\nTo see a list of all BSON types supported in the Hibernate ORM extension, see the MongoDB BSON Fields section in the Create Entities guide.\n\n### Query Support\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nMongoDB Feature\n\n\nGeneral Availability (GA) Support\n\n
\nBulk Writes\n\n\n\u2713\n\n
\nDelete Operations\n\n\n\u2713\n\n
\nGeospatial Queries\n\n\n*Unsupported*. However, the `createNativeQuery()` method supports geospatial queries. Include the `$geoWithin` or `$near` pipeline stage in your MongoDB Query Language statement. To learn more about native queries, see the Perform Native Database Queries guide.\n\n
\nInsert Operations\n\n\n\u2713\n\n
\nMongoDB Search Queries\n\n\n*Unsupported*. However, the `createNativeQuery()` method supports Search queries. Include the `$search` pipeline stage in your MongoDB Query Language statement. To view an example, see the Run a MongoDB Search Query section in the Perform Native Database Queries guide.\n\n
\nMongoDB Vector Search Queries\n\n\n*Unsupported*. However, the `createNativeQuery()` method supports Vector Search queries. Include the `$vectorSearch` pipeline stage in your MongoDB Query Language statement. To learn more about native queries, see the Perform Native Database Queries guide.\n\n
\nNative Querying With MQL\n\n\n\u2713\n\n
\nProjections\n\n\n*Partially Supported*. Aggregation expressions within query projections are not supported, and you must include all entity fields in your projection.When the terminal `$project` stage does not specify `_id`, the Hibernate ORM extension excludes `_id` from the results instead of returning it implicitly. A native query that binds its results to an entity must project `_id` explicitly.\n\n
\nRead Operations\n\n\n\u2713\n\n
\nUpdate Operations\n\n\n\u2713\n\n
\nUpsert Operations\n\n\n*Partially Supported*. Upsert operations are supported on unversioned entities through the `StatelessSession` API. Does not support entities that have a field annotated with `@Version`. To learn more, see the Upsert Documents section in the Perform CRUD Operations guide.\n\n
\n\n### Database and Collection Support\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nMongoDB Feature\n\n\nGeneral Availability (GA) Support\n\n
\nChange Streams\n\n\n*Unsupported*. However, you can use a change stream through the MongoDB Java Driver. To learn more, see the Open Change Streams section in the Java Driver documentation.\n\n
\nClient-side Field Level Encryption (CSFLE) and Queryable Encryption (QE)\n\n\n*Unsupported*. We are considering this feature for future release. However, you can setup CSFLE/QE when you configure the MongoDB Java Driver. To learn more, see the CSFLE documentation in the MongoDB Server manual.\n\n
\nGridFS\n\n\n*Unsupported*. However, you can use GridFS through the MongoDB Java Driver. To learn more, see the Large File Storage with GridFS guide in the Java Driver documentation.\n\n
\nTime Series Data\n\n\n*Unsupported*. However, you can create a time series collection through the MongoDB Java Driver. To learn more, see the Time Series Collections guide in the Java Driver documentation.\n\n
\nStandalone `mongod` Instances\n\n\n*Unsupported*. We recommended that you convert any standalone instances to a replica set. To learn more, see Convert a Standalone Self-Managed mongod to a Replica Set in the MongoDB Server manual.\n\n
\nViews\n\n\n*Unsupported*. However, you can use the MongoDB Java Driver to define a `MongoClient` instance. Then, call the `createView()` method on your `MongoDatabase` instance to create a new view.\n\n
\n\n### Transactions and Concurrency\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nMongoDB Feature\n\n\nGeneral Availability (GA) Support\n\n
\nLocking\n\n\n*Partially Supported*. Optimistic locking is supported on entities that have a field annotated with `@Version`. The Hibernate ORM extension adds the current version value to the MQL filter for each update and delete, and throws an `OptimisticLockException` when the version no longer matches. To learn more, see the Prevent Conflicting Updates with Optimistic Locking guide.Does not support Pessimistic Locking.\n\n
\nTransactions\n\n\n\u2713\n\n
"} -{"chunk_id": "6ad1c488e2bd6bff87646f67-1", "page_id": "6ad1c488e2bd6bff87646f67", "source_name": "hibernate", "product_name": null, "url": "https://mongodb.com/docs/languages/java/mongodb-hibernate/current/feature-compatibility", "title": "Feature Compatibility", "text": "### Mapping and Model Support\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nMongoDB Feature\n\n\nGeneral Availability (GA) Support\n\n
\nAssociations\n\n\n*Partially Supported*. The `@OneToOne`, `@OneToMany`, `@ManyToOne`, `@ManyToMany`, and `@ElementCollection` annotations are supported. The `@SecondaryTable` and `@JoinFormula` annotations are not supported, and cause an error when the `SessionFactory` starts.\n\n
\nAutogenerating IDs\n\n\n*Partially Supported*. Autogenerating ObjectIds is supported. However, you can manually set `String` and `int` identifiers.The `@GeneratedValue` annotation supports sequence-style generation, which the Hibernate ORM extension backs with a counter collection named `hibernate_sequences`.Autogenerating `java.util.UUID` identifiers is supported through the `@UuidGenerator` annotation or the `@GeneratedValue(strategy = UUID)` annotation.Does not support the `IDENTITY` and `TABLE` strategies, `BigInteger` and `BigDecimal` identifiers, and a non-blank `@SequenceGenerator` `options` element.\n\n
\nComposite Primary Keys\n\n\n*Partially Supported*. Declare a composite key with `@EmbeddedId` on a standard `@Embeddable` class or record. The Hibernate ORM extension stores the key as an `_id` sub-document and never generates its value.Does not support the `@IdClass` annotation, multiple `@Id` attributes, a `@Struct` aggregate embeddable identifier, a non-scalar key component, and derived identity through `@MapsId`.To learn more, see the Composite Primary Keys section in the Create Entities guide.\n\n
\nInheritance Strategy\n\n\n*Partially Supported*. Single-table inheritance and mapped superclasses are supported. Does not support the `JOINED` and `TABLE_PER_CLASS` strategies. To learn more, see the Map an Entity Inheritance Hierarchy guide.\n\n
\n`@JdbcTypeCode` Annotation\n\n\n*Unsupported*.\n\n
\nLazy/Eager Fetching\n\n\n*Unsupported*.\n\n
\nOrdering\n\n\n\u2713\n\n
\n`@Table.catalog` Element\n\n\n*Unsupported*. The Hibernate ORM extension rejects the `@Table.catalog` element and the `hibernate.default_catalog` property at bootstrap because MongoDB does not support cross-database `$lookup` operations. Create one `SessionFactory` instance for each database instead.\n\n
\n`@Table.schema` Element\n\n\n\u2713Maps to a collection-name prefix within a single MongoDB database.\n\n
\nValidation\n\n\n\u2713\n\n
"} -{"chunk_id": "6ad1c488e2bd6bff87646f67-2", "page_id": "6ad1c488e2bd6bff87646f67", "source_name": "hibernate", "product_name": null, "url": "https://mongodb.com/docs/languages/java/mongodb-hibernate/current/feature-compatibility", "title": "Feature Compatibility", "text": "### Index Support\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nMongoDB Feature\n\n\nGeneral Availability (GA) Support\n\n
\nCapped Collections\n\n\n*Unsupported*. However, you can use the MongoDB Java Driver to define a `MongoClient` instance. Then, create a capped collection by specifying `CreateCollectionOptions.capped(true)` as a parameter in your `createCollection()` call.\n\n
\nClustered Collections\n\n\n*Unsupported*. However, you can use the MongoDB Java Driver to define a `MongoClient` instance. Then, create a document called `clusteredIndex` and define your clustered index. Use this clustered index as a part of the document you pass to the `MongoDatabase.runCommand()` method, which defines the clustered collection.\n\n
\nCompound Indexes\n\n\n\u2713\n\n
\nEmbedded Document Indexes\n\n\n*Unsupported*. However, you can use the MongoDB Java Driver to define a `MongoClient` instance. Then, call the nested method `MongoCollection.createIndex(Indexes.ascending(\"field.subfield\"))`. This method uses nested key paths \"field.subfield\" to create an embedded document index.\n\n
\nGeospatial Indexes\n\n\n*Unsupported*. However, you can use geospatial indexes through the MongoDB Java Driver. To learn more, see the Geospatial Indexes section of the Indexes guide in the Java Driver documentation.\n\n
\nMongoDB Search Indexes\n\n\n*Unsupported*. However, you can use MongoDB Search indexes through the MongoDB Java Driver. To learn more, see the MongoDB Search and Vector Search Indexes section of the Indexes guide in the Java Driver documentation.\n\n
\nMongoDB Vector Search Indexes\n\n\n*Unsupported*. However, you can use MongoDB Vector Search indexes through the MongoDB Java Driver. To learn more, see the MongoDB Search and Vector Search Indexes section of the Indexes guide in the Java Driver documentation.\n\n
\nMultikey Indexes\n\n\n*Unsupported*. However, you can use multikey indexes through the MongoDB Java Driver. To learn more, see the Multikey Indexes (Indexes on Array Fields) section of the Indexes guide in the Java Driver documentation.\n\n
\nPartial Indexes\n\n\n*Unsupported*. However, you can use the MongoDB Java Driver to define a `MongoClient` instance. Then, call the nested method `MongoCollection.createIndex(Indexes.partialFilterExpression())` to create a partial index.\n\n
\nSchema Validation\n\n\n*Unsupported*. However, you can use the MongoDB Java Driver to define a `MongoClient` instance. Then, create a validator by executing the `collMod` command through the `MongoDatabase.runCommand()` method.\n\n
\nSingle Field Indexes\n\n\n\u2713\n\n
\nSparse Indexes\n\n\n*Unsupported*. However, you can use the MongoDB Java Driver to define a `MongoClient` instance. Then, specify `IndexOptions().sparse(true)` as a parameter in your call to the `MongoCollection.createIndex()` method to create a sparse index.\n\n
\nUnique Indexes\n\n\n\u2713\n\n
\nUpdating Embedded Model Indexes After Model Creation\n\n\n*Unsupported*. However, you can drop and recreate the embedded model index manually.\n\n
To learn more about indexes, see the Indexes for Query Optimization guide.\n\n## Hibernate ORM Features\n\nThis section indicates whether the Hibernate ORM extension supports various Hibernate ORM Features.\n\n### Data Type Support\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nData Type\n\n\nGeneral Availability (GA) Support\n\n
\nCollection Types (List, Set, Maps, Arrays)\n\n\n\u2713`@ElementCollection` and `CollectionTable` are not supported. However, collections of embedded structs are supported through embeddable classes annotated with `@Embeddable` and `@Struct`.\n\n
\nEmbeddable Entities, Scalar Types\n\n\n*Partially Supported*. The `java.time.Instant`, `java.time.Duration`, `java.time.Year`, `java.time.ZoneId`, `java.time.ZoneOffset`, and `java.util.TimeZone` types are supported for top-level and nested entities.\n\n
\nEmbedded Entities, Binary\n\n\n\u2713\n\n
\nEmbedded Entities, Identifier Types\n\n\n*Partially Supported*. Manually set the ID of an entity before persisting an entity.\n\n
\nEmbedded Entities, JSON\n\n\n\u2713\n\n
\nEmbedded Entities, Null Semantics\n\n\n\u2713\n\n
\nTop-level Entities, Binary\n\n\n\u2713\n\n
\nTop-level Entities, Identifier Types\n\n\n\u2713Manually assign UUIDs before persisting an entity, or autogenerate them by using the `@UuidGenerator` annotation.\n\n
\nTop-level Entities, JSON\n\n\n\u2713\n\n
\nTop-level Entities, Null Semantics\n\n\n\u2713\n\n
\nTop-level Entities, Scalar Types\n\n\n\u2713\n\n
\nTop-level Entities, Temporal Types\n\n\n*Partially Supported*. The `java.time.Instant`, `java.time.Duration`, `java.time.Year`, `java.time.ZoneId`, `java.time.ZoneOffset`, and `java.util.TimeZone` types are supported for top-level and nested entities.\n\n
\nTernary Logic (True, False, or UNKNOWN)\n\n\n*Unsupported*.The Hibernate ORM extension requires you to set the `com.mongodb.hibernate.semantics.nulls` property, and `MQL` is the only supported value. Null comparisons follow MongoDB Query Language semantics rather than Hibernate ORM ternary logic. The Hibernate ORM extension throws an exception at startup when the property is not set.\n\n
"} -{"chunk_id": "6ad1c488e2bd6bff87646f67-3", "page_id": "6ad1c488e2bd6bff87646f67", "source_name": "hibernate", "product_name": null, "url": "https://mongodb.com/docs/languages/java/mongodb-hibernate/current/feature-compatibility", "title": "Feature Compatibility", "text": "### Query Support\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nHibernate ORM Feature\n\n\nGeneral Availability (GA) Support\n\n
\nHQL and JPQL Queries, Aggregate Operators\n\n\n\u2713\n\n
\nHQL and JPQL Queries, Arithmetic Operators\n\n\n*Partially Supported*. Supports the `+`, `-`, `*`, `/`, `div` operators, and unary `-` and `+` in the `SELECT` and `WHERE` clauses.Does not support function calls as operands, including the HQL `%` operator, which Hibernate ORM rewrites to a `mod()` function call.To learn more, see the Use Computed Expressions section in the Specify a Query guide.\n\n
\nHQL and JPQL Queries, Array Operators\n\n\n\u2713\n\n
\nHQL and JPQL Queries, Datetime Functions\n\n\n*Partially Supported*. Supports the `extract()` and `format()` functions on a datetime field in a `SELECT` clause, translating them to MongoDB date operators and the `$dateToString` operator. Each function supports a specific set of datetime fields and pattern codes. To learn more, see the Use Datetime Functions in Queries guide.\n\n
\nHQL and JPQL Queries, String Functions\n\n\n*Partially Supported*. Supports the `length()`, `upper()`, `lower()`, `concat()`, `substring()`, `locate()`, `replace()`, `trim()`, `pad()`, and `repeat()` functions and the `||` operator on a string field in a `SELECT` clause, translating them to MongoDB string operators. Does not support the `position()`, `overlay()`, `left()`, `right()`, or `collate()` functions. For more information and to view examples, see the Use String Functions in Queries guide.\n\n
\nHQL and JPQL Queries, Case Expressions\n\n\n*Partially Supported*.\n\n- Supports simple and searched `CASE` expressions in a `SELECT` clause, as an operand of a comparison in a `WHERE` clause, and in the `SET` clause of a bulk update statement. Translates them to the MongoDB `$switch` operator.\n\n- Does not support `CASE` expressions in an `ORDER BY` clause, unless the same `CASE` expression is a `GROUP BY` key. Additionally, does not support `CASE` expressions as the match expression of a `LIKE` predicate, as the test expression of an `IN` or `IS NULL` predicate, or as a `WHERE` clause predicate.\n\nFor more information and to view an example, see the Use Case Expressions for Conditional Logic section in the Specify a Query guide.\n\n
\nHQL and JPQL Queries, Comparison Operators\n\n\n- `>`, `>=`, `<`, `<=`, `=`, `<>`: *Supported*, including with computed operands. To learn more, see the Use Computed Expressions section in the Specify a Query guide.\n\n- `EXISTS`: *Partially Supported*. Supports an `EXISTS` subquery that filters on elements of a single field's embedded array, translating it to the MongoDB `$elemMatch` operator. Does not support certain `EXISTS` subqueries. To learn more, see the EXISTS section in the Specify a Query guide.\n\n- `BETWEEN`: *Supported*. Translates to the MongoDB `$gte` and `$lte` operators. To learn more, see the BETWEEN section in the Specify a Query guide.\n\n- `IS NULL` and `IS NOT NULL`: *Supported*. Matches explicitly null values and missing fields or the negation of those values, translating to the MongoDB `$match` operator. To learn more, see the IS NULL and IS NOT NULL sections in the Specify a Query guide.\n\n- `IN` and `NOT IN`: *Partially Supported*. Supports a list of literals or parameters tested against a field path, translating to the MongoDB `$in` and `$nin` operators. Does not support a subquery or an array-valued expression as the list. To learn more, see the IN and NOT IN sections in the Specify a Query guide.\n\n- Comparisons to `null`: *Supported*. Applies MongoDB Query Language null semantics rather than Hibernate ORM ternary logic, so a comparison to `null` matches explicitly null values and missing fields. To learn more, see the Compare Field Values to Null section in the Specify a Query guide.\n\n- Row-value predicates: *Partially Supported*. Supports the `=`, `<>`, `IN`, and `NOT IN` operators over a parenthesized list of fields, such as `where (title, year) = (:t, :y)`, translating each predicate to per-component MongoDB `$eq` comparisons. Does not support row-value predicates that use the `>`, `>=`, `<`, or `<=` operator. To learn more, see the Compare Multiple Fields at Once section in the Specify a Query guide.\n\n- `LIKE`: *Supported*. Translates to the MongoDB `$regex` operator.\n\n- `ANY`, `ALL`: *Unsupported*. You can use the `createNativeQuery()` method and pass comparison operators in your MongoDB Query Language statement. To learn more about native queries, see the Perform Native Database Queries guide.\n\n
\nHQL and JPQL Queries, Element Operators\n\n\n\u2713\n\n
\nHQL and JPQL Queries, Evaluation Operators\n\n\n*Partially Supported*. Supports the MongoDB `$regex` evaluation operator by translating the `LIKE`, `NOT LIKE`, `ILIKE`, and `NOT ILIKE` predicates to regular expression filters. For more information and to view examples, see the LIKE section in the Specify a Query guide.\n\n
\nHQL and JPQL Queries, Grouping\n\n\n*Partially Supported*. Supports the `GROUP BY` and `HAVING` clauses, which translate to the MongoDB `$group` and `$match` stages. A grouping key can be a field reference or a computed expression. For more information and to view examples, see the Group Results section in the Modify Query Results guide.\n\n- Field reference keys: *Supported*, including fields of `@Struct` aggregate embeddables and joined entities.\n\n- Aggregate functions over a `@Struct` aggregate embeddable: *Unsupported*. You can apply an aggregate function to a field of an embeddable, as in `count(a.intField)`, but not to the embeddable itself, as in `count(a)`.\n\n- Computed expression keys: *Supported*. An expression in the `SELECT` or `HAVING` clause resolves to a grouping key only when you write the two identically.\n\n- Stray columns: *Unsupported*. Every column in the `SELECT`, `HAVING`, or `ORDER BY` clause must be a grouping key or contained in one.\n\n- `ORDER BY` over a grouping key: *Supported*, for both field reference keys and computed expression keys.\n\n- `SELECT DISTINCT` with `GROUP BY`: *Unsupported*.\n\n
\nHQL and JPQL Queries, Joins\n\n\n*Partially Supported*. You can join entities by navigating a mapped association, as in `from Movie m join m.comments c`, or by naming an entity and supplying an `ON` clause, as in `from Movie m join Comment c on c.date > m.released`. Each join translates to a MongoDB `$lookup` and `$unwind` stage. To view examples, see the Join Entities Across Collections guide.\n\n- Inner and left outer joins: *Supported*.\n\n- `JOIN FETCH` clauses: *Supported*.\n\n- Chained joins: *Supported*. You can join across more than two entities."} -{"chunk_id": "6ad1c488e2bd6bff87646f67-4", "page_id": "6ad1c488e2bd6bff87646f67", "source_name": "hibernate", "product_name": null, "url": "https://mongodb.com/docs/languages/java/mongodb-hibernate/current/feature-compatibility", "title": "Feature Compatibility", "text": "- Composite key joins: *Partially Supported*. You can join a `@ManyToOne` or `@OneToOne` association whose target entity has an `@EmbeddedId` composite key. You can also compare whole composite identifiers with `=` in an `ON` condition.Does not support the `@JoinColumn` annotation on such an association, ordering comparisons between whole identifiers, and `@ManyToMany` associations that involve a composite key.To learn more, see the Composite Key Joins section in the Join Entities Across Collections guide.\n\n- `ON` conditions: *Partially Supported*. An `ON` condition supports the same comparison, logical, and predicate operators as a `WHERE` clause. This includes compound conditions that combine multiple field comparisons with `AND` or `OR`, and range and inequality conditions. An `ON` condition must compare columns. You cannot compare entity references, as in `on m = c.movie`, or navigate an association within the condition, as in `on c.movie.title = 'Blue Jasmine'`.\n\n- Right outer, full outer, cross, lateral, and subquery joins: *Unsupported*. You can use the `createNativeQuery()` method to run an aggregation operation that queries multiple collections. To learn more about native queries, see the Perform Native Database Queries guide.\n\n
\nHQL and JPQL Queries, Logical Operators\n\n\n\u2713\n\n
\nHQL and JPQL Queries, String Functions\n\n\n*Partially Supported*. Supports the `character_length()`, `length()`, `substring()`, `trim()`, `upper()`, `lower()`, `pad()`, `lpad()`, `rpad()`, `concat()`, `locate()`, and `repeat()` functions, and the `||` concatenation operator. Other Hibernate ORM string functions are unsupported.\n\n
\n\n### Database and Collection Support\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nHibernate ORM Feature\n\n\nGeneral Availability (GA) Support\n\n
\nFirst-Level Cache\n\n\n\u2713\n\n
\nSecond-Level Cache\n\n\n\u2713\n\n
\n\n## Framework and Library Support\n\nThis section indicates whether the Hibernate ORM extension supports various external frameworks or libraries.\n\n\n\n\n\n\n\n\n\n\n
\nFramework or Library\n\n\nGeneral Availability (GA) Support\n\n
\nSpring Boot and Spring Data JPA\n\n\n*Partially Supported*. The Hibernate ORM extension provides a Spring Boot starter that configures MongoDB-backed JPA and Spring Data JPA repositories. We do not guarantee support for all Spring Boot or Spring Data features. To learn more, see the Spring Boot and Spring Data JPA Integration section.\n\n
"} -{"chunk_id": "6ad1c488e2bd6bff87646f5f-0", "page_id": "6ad1c488e2bd6bff87646f5f", "source_name": "hibernate", "product_name": null, "url": "https://mongodb.com/docs/languages/java/mongodb-hibernate/current/spring-boot", "title": "Spring Boot and Spring Data JPA Integration", "text": "# Spring Boot and Spring Data JPA Integration\n\n## Overview\n\nThe MongoDB Extension for Hibernate ORM provides a Spring Boot starter that lets a Spring Boot application persist JPA entities to MongoDB. When you activate the starter, it configures the following components for you:\n\n- A JPA `EntityManagerFactory` backed by MongoDB\n\n- A `JpaTransactionManager`\n\n- Spring Data JPA repository support\n\nThe starter reuses the `MongoClient` that Spring Boot's MongoDB support creates, so your application maintains a single connection pool.\n\nThe Spring Boot starter is not Spring Data MongoDB, and you can use it without adding a SQL `DataSource` to your application.\n\n## Get Started\n\nLearn how to create a Spring Boot application that uses the starter to read and write MongoDB data in the Get Started with the Spring Boot Starter tutorial.\n\n## Configure the Starter\n\nLearn how to set connection, naming, and JPA properties, customize the `MongoClient`, and interpret startup errors in the Configure the Spring Boot Starter guide."} -{"chunk_id": "68a95c505e79d242619e3b3b-0", "page_id": "68a95c505e79d242619e3b3b", "source_name": "intellij", "product_name": "MongoDB IntelliJ Plugin", "url": "https://mongodb.com/docs/mongodb-intellij/submit-feedback", "title": "Submit Feedback", "text": "# Submit Feedback\n\nThe MongoDB for IntelliJ Plugin is currently in Public Preview. To learn more, see Preview Features.To report a bug, request a feature, or submit general feedback, follow the procedures on this page to open a ticket in the MongoDB for IntelliJ Plugin JIRA project.\n\n## Before You Begin\n\nTo submit feedback and vote on issues, you must be logged in to a JIRA account.\n\n## Steps\n\n### Open the ticket creation dialog.\n\nTo open a new ticket, click Create in the JIRA top navigation bar.\n\n### Specify the issue type.\n\nOpen the Issue Type drop-down menu and select the appropriate issue type:\n\n- If you encounter a bug, select Bug.\n\n- If you have a new feature request, select New Feature.\n\n### Provide a summary.\n\nIn the Summary field, provide a brief summary of the bug or feature request.\n\n### Provide a description.\n\nIn the Description field, you can provide more detailed information, including the exact steps needed to reproduce the issue.\n\n### Set the label field.\n\nIn the Labels field, include the `internal-preview` label.\n\n### (*Optional*) Add logs in the Attachment field.\n\nLogs can help navigate edge cases and diagnose issues in the IntelliJ Plugin. For more information, see Retrieve IntelliJ Logs.\n\n### Submit the ticket.\n\nClick Create to submit the ticket.\n\n## Vote on Submitted Tickets\n\nUnder the People section on the right side of the JIRA ticket, you can vote for tickets. Issues with more votes are more likely to be prioritized by the MongoDB development team."} -{"chunk_id": "68d634847a7e4b3c5a4f9f1d-0", "page_id": "68d634847a7e4b3c5a4f9f1d", "source_name": "intellij", "product_name": "MongoDB IntelliJ Plugin", "url": "https://mongodb.com/docs/mongodb-intellij/java-driver-methods-introspection", "title": "Java Driver Methods to Generate Insights", "text": "# Java Driver Methods to Generate Insights\n\nThe MongoDB for IntelliJ Plugin is currently in Public Preview. To learn more, see Preview Features.When you use the following Java Driver method calls in your queries, the MongoDB for IntelliJ Plugin generates insights for your workspace, including insights regarding index warnings, type validation, or database reference validation. If your query contains a combination of methods the IntelliJ Plugin can generate insights from and methods that the IntelliJ Plugin cannot generate insights from, the IntelliJ Plugin does not generate any insights.\n\n## Query Operation Methods\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nDescription\n\n
\nMongoCollection.find()\n\n\nFinds all documents in the collection.\n\n
\nMongoCollection.aggregate()\n\n\nAggregates documents according to the specified aggregation pipeline.\n\n
\n\n## Filtering Methods\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nDescription\n\n
\nFilters.eq()\n\n\nCreates a filter that matches all documents where the value of the field name equals the specified value.\n\n
\nFilters.gt()\n\n\nCreates a filter that matches all documents where the value of the given field is greater than the specified value.\n\n
\nFilters.gte()\n\n\nCreates a filter that matches all documents where the value of the given field is greater than or equal to the specified value.\n\n
\nFilters.lt()\n\n\nCreates a filter that matches all documents where the value of the given field is less than the specified value.\n\n
\nFilters.lte()\n\n\nCreates a filter that matches all documents where the value of the given field is less than or equal to the specified value.\n\n
\nFilters.ne()\n\n\nCreates a filter that matches all documents where the value of the field name does not equal the specified value.\n\n
\nFilters.in()\n\n\nCreates a filter that matches all documents where the value of a field equals any value in the list of specified values.\n\n
\nFilters.nin()\n\n\nCreates a filter that matches all documents where the value of a field does not equal any of the specified values or does not exist.\n\n
\nFilters.and()\n\n\nCreates a filter that performs a logical AND of the provided list of filters.\n\n
\nFilters.or()\n\n\nCreates a filter that preforms a logical OR of the provided list of filters.\n\n
\nFilters.nor()\n\n\nCreates a filter that performs a logical NOR operation on all the specified filters.\n\n
\nFilters.not()\n\n\nCreates a filter that matches all documents that do not match the passed in filter.\n\n
\nFilters.exists()\n\n\nCreates a filter that matches all documents that contain the given field.\n\n
\n\n## Aggregation Stage Methods\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nDescription\n\n
\nAggregates.match()\n\n\nCreates a $match pipeline stage that matches incoming documents against the specified query filter, filtering out documents that do not match.\n\n
\nAggregates.project()\n\n\nCreates a $project pipeline stage that project specified document fields.\n\n
\nAggregates.sort()\n\n\nCreates a $sort pipeline stage to sort by the specified criteria.\n\n
\nAggregates.group()\n\n\nCreates a $group pipeline stage to group documents by a specified expression and output a document for each distinct grouping.\n\n
\nAggregates.addFields()\n\n\nCreates an $addFields pipeline stage that adds new fields to documents.\n\n
\nAggregates.unwind()\n\n\nCreates an $unwind pipeline stage to deconstruct an array field from input documents, creating an output document for each array element.\n\n
\nAggregates.limit()\n\n\nCreates a $limit pipeline stage for the specified filter.\n\n
"} -{"chunk_id": "68d634847a7e4b3c5a4f9f1d-1", "page_id": "68d634847a7e4b3c5a4f9f1d", "source_name": "intellij", "product_name": "MongoDB IntelliJ Plugin", "url": "https://mongodb.com/docs/mongodb-intellij/java-driver-methods-introspection", "title": "Java Driver Methods to Generate Insights", "text": "## Accumulator Methods\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nDescription\n\n
\nAccumulators.sum()\n\n\nGets a field name for a $group operation representing the sum of the values of the given expression when applied to all members of the group.\n\n
\nAccumulators.avg()\n\n\nGets a field name for a $group operation representing the average of the values of the given expression when applied to all members of the group.\n\n
\nAccumulators.first()\n\n\nGets a field name for a $group operation representing the value of the given expression when applied to the first member of the group.\n\n
\nAccumulators.last()\n\n\nGets a field name for a $group operation representing the value of the given expression when applied to the last member of the group.\n\n
\nAccumulators.top()\n\n\nReturns a combination of a computed field and an accumulator that produces a value of the given outExpression computed for the top element within a group sorted according to the provided sortBy specification.\n\n
\nAccumulators.topN()\n\n\nReturns a combination of a computed field and an accumulator that produces a BSON Array of values of the given `outExpression` computed for the top N elements within a group sorted according to the provided `sortBy` specification, where N is the positive integral value of the `nExpression`.\n\n
\nAccumulators.bottom()\n\n\nReturns a combination of a computed field and an accumulator that produces a value of the given `outExpression` computed for the bottom element within a group sorted according to the provided `sortBy` specification.\n\n
\nAccumulators.bottomN()\n\n\nReturns a combination of a computed field and an accumulator that produces a BSON Array of values of the given `outExpression` computed for the bottom N elements within a group sorted according to the provided `sortBy` specification, where N is the positive integral value of the `nExpression`.\n\n
\nAccumulators.max()\n\n\nGets a field name for a $group operation representing the maximum of the values of the given expression when applied to all members of the group.\n\n
\nAccumulators.min()\n\n\nGets a field name for a $group operation representing the minimum of the values of the given expression when applied to all members of the group.\n\n
\nAccumulators.push()\n\n\nGets a field name for a $group operation representing an array of all values that results from applying an expression to each document in a group of documents that share the same group by key.\n\n
\nAccumulators.addToSet()\n\n\nGets a field name for a $group operation representing all unique values that results from applying the given expression to each document in a group of documents that share the same group by key.\n\n
\n\n## Projection Methods\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nDescription\n\n
\nProjections.include()\n\n\nCreates a projection that includes all of the given fields.\n\n
\nProjections.exclude()\n\n\nCreates a projection that excludes all of the given fields.\n\n
\nProjections.fields()\n\n\nCreates a projection that combines the list of projections into a single one. If there are duplicate keys, the last one takes precedence.\n\n
\n\n## Sorting Methods\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nDescription\n\n
\nSorts.ascending()\n\n\nCreate a sort specification for an ascending sort on the given fields.\n\n
\nSorts.descending()\n\n\nCreate a sort specification for a descending sort on the given fields.\n\n
\nSorts.orderBy()\n\n\nCombine multiple sort specifications. If any field names are repeated, the last one takes precedence.\n\n
\n\n## Learn More\n\n- IntelliJ Insights"} -{"chunk_id": "68a95c505e79d242619e3b28-0", "page_id": "68a95c505e79d242619e3b28", "source_name": "intellij", "product_name": "MongoDB IntelliJ Plugin", "url": "https://mongodb.com/docs/mongodb-intellij/autocomplete", "title": "Autocomplete", "text": "# Autocomplete\n\nThe MongoDB for IntelliJ Plugin is currently in Public Preview. To learn more, see Preview Features.The MongoDB for IntelliJ Plugin provides autocomplete suggestions for database, collection, or field names based on the connected data source. For example, when you start typing a field name in a query, the plugin analyzes the MongoDB collection and document schema to automatically suggest valid field names.\n\nTo use the autocomplete feature, start typing in a document field, collection, or database name. Then press Ctrl + Space to display a drop-down list that shows the available suggestions.\n\n## Database Name Autocompletion\n\nTo autocomplete database names, press Ctrl + Space inside the getDatabase() method of a `MongoClient` instance.\n\nThe IntelliJ Plugin displays a drop-down list of available database names, denoted by the `MongoDB Database` text and the database icon, as shown in the following image:\n\n## Collection Name Autocompletion\n\nTo autocomplete collection names, press Ctrl + Space inside the getCollection() method of a `MongoClient` instance.\n\nThe IntelliJ Plugin displays a drop-down list of available collection names, denoted by the `MongoDB Collection` text and the collection icon, as shown in the following image:\n\n## Document Field Name Autocompletion\n\nTo autocomplete document field names, press Ctrl + Space inside one of the following MongoCollection methods:\n\n- `countDocuments`\n\n- `deleteMany`\n\n- `deleteOne`\n\n- `distinct`\n\n- `find`\n\n- `findOneAndDelete`\n\n- `findOneAndReplace`\n\n- `findOneAndUpdate`\n\n- `replaceOne`\n\n- `updateMany`\n\n- `updateOne`\n\nThe IntelliJ Plugin displays a drop-down list of available field names, denoted by their data type and the document icon. For example, the following image shows autocomplete suggestions for fields that start with `rat` in the `sample_mflix.movies` collection:\n\n## Learn More\n\n- Connect to Your MongoDB Deployment\n\n- Database Reference Validation\n\n- Run Java Queries"} -{"chunk_id": "68a95c505e79d242619e3b35-0", "page_id": "68a95c505e79d242619e3b35", "source_name": "intellij", "product_name": "MongoDB IntelliJ Plugin", "url": "https://mongodb.com/docs/mongodb-intellij/logs", "title": "Retrieve IntelliJ Logs", "text": "# Retrieve IntelliJ Logs\n\nThe MongoDB for IntelliJ Plugin is currently in Public Preview. To learn more, see Preview Features.This page describes how to retrieve log files from IntelliJ IDEA.\n\n## About This Task\n\nLog files help the MongoDB development team diagnose bugs in the IntelliJ Plugin. When you retrieve logs, IntelliJ generates a zip file with the following contents:\n\n- General information about the IDE installation such as version, host OS, host CPU, available memory, and other plugins that might affect current functionality.\n\n- Thread dumps of the current state of IntelliJ.\n\n- Internal state of the UI.\n\n- OpenTelemetry metrics from IntelliJ.\n\n- Logs of all plugins, including the MongoDB for IntelliJ Plugin.\n\n## Steps\n\n### Open the Help menu.\n\nIn the IntelliJ top menu bar, click Help.\n\n### Click Collect Logs and Diagnostic Data.\n\nIn the drop-down menu, click Collect Logs and Diagnostic Data.\n\nA pop-up warning appears, mentioning that the collected information might contain sensitive data.\n\n### Download the log files.\n\nClick Show in Finder.\n\n## Learn More\n\n- Submit Feedback"} -{"chunk_id": "68a95c505e79d242619e3b2c-0", "page_id": "68a95c505e79d242619e3b2c", "source_name": "intellij", "product_name": "MongoDB IntelliJ Plugin", "url": "https://mongodb.com/docs/mongodb-intellij/connect", "title": "Connect to Your MongoDB Deployment", "text": "# Connect to Your MongoDB Deployment\n\nThe MongoDB for IntelliJ Plugin is currently in Public Preview. To learn more, see Preview Features.On this page, you'll learn how to connect to your MongoDB deployment using the MongoDB for IntelliJ Plugin.\n\nIf you need to create a MongoDB host, consider using MongoDB Atlas. Atlas is a cloud-hosted database-as-a-service which requires no installation, offers a free option to get started, and provides a copyable URI to easily connect the IntelliJ Plugin to your deployment.\n\n## Before You Begin\n\nEnsure that an instance of MongoDB is running and the IntelliJ Plugin is installed.\n\nIf you are using the MongoDB Java driver, use the Java driver version 5.0.0+. If you are using Spring Criteria MongoDB use Spring Data MongoDB version 4.3.0+.\n\n## Steps\n\n### Open the MongoDB side panel.\n\nTo open the MongoDB side panel, click the leaf icon on the IntelliJ far-right menu bar.\n\n### Add a MongoDB connection.\n\nTo open the Data Sources and Drivers modal, click Add a MongoDB Data Source.\n\nPaste your connection string directly in the URL field near the bottom of the Data Sources and Drivers tab.\n\nEnsure that your connection string specifies the port that your instance is running on.\n\nClick OK.\n\n### View insights for your MongoDB deployment.\n\nAfter you connect to your deployment, you can see all the generated insights for your workspace, which include index performance warnings and validation errors.\n\nThe IntelliJ Plugin includes four options to view your Insights:\n\n- All insights: Includes insights for all packages in your workspace.\n\n- Recommended Insights: Includes insights for the most common parent package of files opened in the IDE. This ensures that insights are relevant to all files and their shared context within the broader structure of your application.\n\n- Current File: Includes insights only from the currently open file.\n\n- Current Query: Includes insights for the query where the keyboard cursor is located.\n\n### (*Optional*) Connect to another MongoDB deployment.\n\nTo add another data source, click the + icon, click Data Source, and select MongoDB from the drop-down menu.\n\n### Select a data source in the side panel.\n\nYou can select a data source associated with your application from within MongoDB side panel.\n\nThe side panel has a Connected to drop-down menu that allows you to select a data source associated with your application.\n\nFor the best experience, the data source you select should contain the following:\n\n- All of the databases, collection, and fields your application code uses.\n\n- All of the indexes used by your queries.\n\n### (*Optional*) Launch Playgrounds.\n\nTo launch the Playgrounds, click the highlighted button in Database Explorer.\n\n## Next Steps\n\n- Autocomplete\n\n- Type Validation\n\n- Index Performance Warnings\n\n## Learn More\n\n- Connection Strings"} -{"chunk_id": "68a95c505e79d242619e3b30-0", "page_id": "68a95c505e79d242619e3b30", "source_name": "intellij", "product_name": "MongoDB IntelliJ Plugin", "url": "https://mongodb.com/docs/mongodb-intellij/run-java-queries", "title": "Run Java Queries", "text": "# Run Java Queries\n\nThe MongoDB for IntelliJ Plugin is currently in Public Preview. To learn more, see Preview Features.## Definition\n\nThe MongoDB for IntelliJ Plugin enables you to run queries written in Java directly in the Database Explorer Playgrounds.\n\nThe Run icon appears next to your MongoDB queries.\n\n## Behavior\n\nWhen you click the Run icon, the plugin automatically converts your Java query to `mongosh` syntax and opens a Playground file with the populated query.\n\nFor field values that are variables determined at runtime, the plugin creates a placeholder variable. You can populate this placeholder with a test value and run the query in the Playground.\n\n### Limitations\n\nThe IntelliJ Plugin does not generate insights in the side panel for the following Java and Spring queries:\n\n- Any query or aggregation that does not use a BSON builder exposed by the MongoDB Java Driver. This includes parts of queries and aggregations written using the following constructors:\n\n - Documents\n\n - BasicDBObjects\n\n - BasicDBLists\n\n - BasicDBObjectBuilders\n\n- Queries that use unsupported BSON builder methods provided by the MongoDB Java Driver. For a list of Java Driver methods that can be used for generating insights by the IntelliJ Plugin, see Java Driver Methods to Generate Insights.\n\n- Queries that use unsupported methods provided by Spring Data MongoDB. For a list of Spring Data methods that can be used for generating insights by the IntelliJ Plugin, see Spring Criteria Methods to Generate Insights.\n\n## Example\n\nIn this example, the Java query on the `production.trips` collection resembles the following:\n\n```java\npublic List findCompletedTripsByDriver(String driverId) {\n return trips.find(Filters.and(\n Filters.eq(fieldName: \"trip_status\", value: \"completed\"),\n Filters.eq(fieldName: \"driver_id\", driverId)\n )).into(new ArrayList<>());\n}\n```\n\nThe following code example shows the converted query from the Java code above:\n\n```javascript\nvar driver_id = \"\"\n\ndb.getSiblingsDB(\"production\")\n .getCollection(\"trips\")\n .find({\n \"$and\" : [\n { \"trip_status\" : \"completed\" },\n { \"driver_id\" : driver_id }\n ],\n })\n```\n\nIn this example, `driver_id` is a variable that holds a value determined at runtime. In order to test that your query outputs the results you expect, you must specify a test value by replacing `` with the driver ID. For example, `driver_id = \"1a2b3c4d5e\"`.\n\nOnce you are satisfied with the query, you can run it in the Playground and view the query results."} -{"chunk_id": "68a95c505e79d242619e3b3d-0", "page_id": "68a95c505e79d242619e3b3d", "source_name": "intellij", "product_name": "MongoDB IntelliJ Plugin", "url": "https://mongodb.com/docs/mongodb-intellij/index-warning", "title": "Index Performance Warnings", "text": "# Index Performance Warnings\n\nThe MongoDB for IntelliJ Plugin is currently in Public Preview. To learn more, see Preview Features.## Definition\n\nThe MongoDB for IntelliJ Plugin examines if application queries use indexes. If a query doesn't use an index or is only partially covered by an index, the plugin displays a warning for that query.\n\nTo resolve the warning, consider creating an index for the query.\n\nBefore you add an index, consider if:\n\n- The query runs often enough to justify reducing the write performance for faster reads.\n\n- You can change the query to use an existing index.\n\nYou can also disable index warnings.\n\nFor more information about indexes, see Indexes.\n\n## Examples\n\nIn the following example Java code snippet, the `awards` document field is used in a query, but the field isn't indexed in the database:\n\n```java\nclient.getDatabase( \"sample_mflix\" ).getCollection( \"movies\" ).find(\n Filters.ne( \"awards\", \"Comedy\" )\n)\n```\n\nThe side panel shows the following warning under Performance Warnings:\n\n### Create an Index\n\nTo create an index for the query:\n\n#### Click the Create an Index button displayed in the side panel warning.\n\nThe plugin displays the Database Explorer Playgrounds screen with template code for creating an index:\n\n```java\n// region Queries covered by this index\n// alt.mongodb.javadriver.JavaDriverRepository#getRatings at line 32\n// endregion\n// Learn about creating an index: https://www.mongodb.com/docs/v7.0/core/data-model-operations/#indexes\ndb.getSiblingDB(\"sample_mflix\").getCollection(\"movies\")\n.createIndex({ \"awards\": 1 })\n```\n\n#### Create an index on the awards field.\n\nSet `` to `awards` in the example code and then run the `createIndex()` method in the Database Explorer Playgrounds screen. For example:\n\n```java\ndb.getSiblingDB(\"sample_database\").getCollection(\"movies\").\ncreateIndex({\"awards\": 1})\n```\n\n## Learn More\n\n- Disable Warnings\n\n- Indexes\n\n- Operational Factors and Data Models"} -{"chunk_id": "68a95c505e79d242619e3b36-0", "page_id": "68a95c505e79d242619e3b36", "source_name": "intellij", "product_name": "MongoDB IntelliJ Plugin", "url": "https://mongodb.com/docs/mongodb-intellij/db-reference-validation", "title": "Database Reference Validation", "text": "# Database Reference Validation\n\nThe MongoDB for IntelliJ Plugin is currently in Public Preview. To learn more, see Preview Features.The MongoDB for IntelliJ Plugin validates database references in your Java driver or Spring Criteria code to ensure that the specified database, collection, or field exists in the server.\n\nIf you reference a field, collection, or database name that isn't in your data source, the plugin shows a warning that indicates the reference doesn't exist.\n\nTo resolve the warning:\n\n- Ensure that you're connected to the correct data source in the Connections Toolbar.\n\n- Check that you're referencing the correct database and collection in your code.\n\n- Verify that your database or collection contains the field you are trying to reference.\n\n## Non-existent Field Name\n\nIf you reference a field name that doesn't exist in the collection, the IntelliJ Plugin raises the following warning in the side panel under Correctness Warnings:\n\n```none\nField does not seem to exist in collection.\n```\n\n## Non-existent Collection Name\n\nIf you reference a collection name that doesn't exist in the database, the IntelliJ Plugin raises the following warning in the side panel under Environment Mismatch Warnings:\n\n```none\nCannot resolve collection in database in the\nconnected data source.\n```\n\nTo resolve the warning, ensure that the referenced collection exists in your database. Alternatively, you can click Choose a connection in the side panel to select a different data source that contains the referenced collection.\n\n## Non-existent Database Name\n\nIf you reference a database that doesn't exist in the data source, the IntelliJ Plugin raises the following warning in the side panel under Environment Mismatch Warnings:\n\n```none\nCannot resolve database reference in the connected data source.\n```\n\nTo resolve the warning, ensure that the referenced database exists in your deployment. Alternatively, you can click Choose a connection in the side panel to select a different data source that contains the referenced database.\n\n## Example\n\nThe following example references the `sample_mflix` database, which contains data on movies and movie theaters, from the Atlas sample datasets.\n\nThe sample code attempts to call a `restaurant_name` collection:\n\n```java\npublic List getHundredYearOldMovies() {\n return client.getDatabase(\"sample_mflix\")\n .getCollection(\"restaurant_name\")\n .find(Filters.eq(\"year\", 1924))\n .into(new ArrayList<>());\n }\n```\n\nBecause the collection doesn't exist in the `sample_mflix` database, the IntelliJ Plugin raises a warning that the collection cannot be resolved:\n\n```none\nCannot resolve \"restaurant_name\" collection in \"sample_mflix\" database in the\nconnected data source.``\n```\n\nTo resolve the warning, reference a collection that exists in the `sample_mflix` database:\n\n```java\npublic List getHundredYearOldMovies() {\n return client.getDatabase(\"sample_mflix\")\n .getCollection(\"movies\")\n .find(Filters.eq(\"year\", 1924))\n .into(new ArrayList<>());\n }\n```\n\n## Learn More\n\n- Connect to Your MongoDB Deployment\n\n- Autocomplete\n\n- Disable Warnings\n\n- Type Validation"} -{"chunk_id": "68d634847a7e4b3c5a4f9f19-0", "page_id": "68d634847a7e4b3c5a4f9f19", "source_name": "intellij", "product_name": "MongoDB IntelliJ Plugin", "url": "https://mongodb.com/docs/mongodb-intellij/disable-warnings", "title": "Disable Warnings", "text": "# Disable Warnings\n\nThe MongoDB for IntelliJ Plugin is currently in Public Preview. To learn more, see Preview Features.You can disable the following warnings in the IntelliJ Plugin side panel:\n\n- Database reference validation warnings\n\n- Index performance warnings\n\n- Type validation warnings\n\n## Steps\n\nTo disable the warnings in the IntelliJ Plugin side panel:\n\n### Click the icon next to the warning.\n\n### Click Disable Inspection.\n\nWhen you click Disable Inspection, the plugin disables all index warnings for the project.\n\n### Enable Hidden Warnings\n\nIf you previously disabled index warnings and want to re-enable the insight:\n\n#### Under Performance Warnings, click Show disabled inspections.\n\n#### Click the icon next to the hidden warning.\n\n#### Click Enable Inspection."} -{"chunk_id": "68d634847a7e4b3c5a4f9f0b-0", "page_id": "68d634847a7e4b3c5a4f9f0b", "source_name": "intellij", "product_name": "MongoDB IntelliJ Plugin", "url": "https://mongodb.com/docs/mongodb-intellij/spring-criteria-methods-introspection", "title": "Spring Criteria Methods to Generate Insights", "text": "# Spring Criteria Methods to Generate Insights\n\nThe MongoDB for IntelliJ Plugin is currently in Public Preview. To learn more, see Preview Features.When you use the following Spring Criteria method calls in your queries, the MongoDB for IntelliJ Plugin generates insights for your workspace, including insights regarding index warnings, type validation, or database reference validation. If your query contains a combination of methods the IntelliJ Plugin can generate insights from and methods that the IntelliJ Plugin cannot generate insights from, the IntelliJ Plugin does not generate any insights.\n\n## Query Operation Methods\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nDescription\n\n
\nMongoTemplate.count()\n\n\nReturns the number of documents for the given Query querying the given collection.\n\n
\nMongoTemplate.find()\n\n\nMaps the results of an ad-hoc query on the collection for the entity class to a List of the specified type.\n\n
\nMongoTemplate.findAll()\n\n\nQuery for a list of objects of type `T` from the collection used by the entity class.\n\n
\nMongoTemplate.findOne()\n\n\nMap the results of an ad-hoc query on the collection for the entity class to a single instance of an object of the specified type.\n\n
\nMongoTemplate.aggregate()\n\n\nExecute an aggregation operation. The raw results will be mapped to the given entity class.\n\n
\nMongoTemplate.aggregateStream()\n\n\nExecute an aggregation operation backed by a MongoDB `AggregateIterable`.\n\n
\n\n## Filtering Methods\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nDescription\n\n
\nQuery.with()\n\n\nSets the given cursor position on the Query instance.\n\n
\nQuery.query()\n\n\nCreates a new Query using the given `CriteriaDefinition`.\n\n
\nQuery.of()\n\n\nCreate an independent copy of the given Query. The resulting Query is not a binary equal to the given source but semantically equal in terms of creating the same result when executed.\n\n
\nCriteria.where()\n\n\nStatic factory method to create a Criteria using the provided key.\n\n
\nCriteria.in()\n\n\nCreates a criterion using the `$in` operator.\n\n
\nCriteria.nin()\n\n\nCreates a criterion using the `$nin` operator.\n\n
\nCriteria.not()\n\n\nCreates a criterion using the `$not` meta operator which affects the clause directly following\n\n
\nCriteria.is()\n\n\nCreates a criterion using equality.\n\n
\n\n## Aggregation Methods\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nDescription\n\n
\nAggregation.match()\n\n\nCreates a new `MatchOperation` using the given `AggregationExpression`.\n\n
\nAggregation.project()\n\n\nCreates a new `ProjectionOperation` including all top level fields of the given given `Class`.\n\n
\nAggregation.sort()\n\n\nFactory method to create a new `SortOperation` for the given `Sort`.\n\n
\nAggregation.group()\n\n\nCreates a new `GroupOperation` for the given `Fields`.\n\n
\nAggregation.addFields()\n\n\nObtain a `builder` instance to create a new `AddFieldsOperation`. MongoDB adds a new aggregation pipeline stage `$set` that is an alias for `$addFields`.\n\n
\nAggregation.unwind()\n\n\nFactory method to create a new `UnwindOperation` for the field with the given name.\n\n
\nAggregation.limit()\n\n\nLimits the result to the given number of elements.\n\n
\nProjection.andInclude()\n\n\nIncludes the given fields into the projection.\n\n
\nFields.fields()\n\n\nCreates a new `Fields` instance for `Fields` with the given names.\n\n
\nFields.field()\n\n\nCreates a `Field` with the given name.\n\n
\nFields.from()\n\n\nCreates a new `Fields` instance from the given `Fields`.\n\n
\nSorts.ascending()\n\n\nCreate a sort specification for an ascending sort on the given fields.\n\n
\nSorts.descending()\n\n\nCreate a sort specification for a descending sort on the given fields.\n\n
\nSorts.orderBy()\n\n\nCombine multiple sort specifications. If any field names are repeated, the last one takes precedence.\n\n
\n\n## Learn More\n\n- IntelliJ Insights"} -{"chunk_id": "68a95bf65e79d242619d9b92-0", "page_id": "68a95bf65e79d242619d9b92", "source_name": "java", "product_name": "Java Sync Driver", "url": "https://mongodb.com/docs/drivers/java/sync/current/crud/query-documents/count", "title": "Count Documents", "text": "# Count Documents\n\n## Overview\n\nIn this guide, you can learn how to count the number of documents in your MongoDB collections. There are two instance methods in the `MongoCollection` class that you can call to count the number of documents in a collection:\n\n- `countDocuments()` returns the number of documents in the collection that match a specified query. If you specify an empty query filter, the method returns the total number of documents in the collection.\n\n- `estimatedDocumentCount()` returns an **estimation** of the number of documents in the collection based on the collection metadata. You cannot specify a query when using this method.\n\nThe `estimatedDocumentCount()` method returns more quickly than the `countDocuments()` method because it uses the collection's metadata rather than scanning the entire collection. The `countDocuments()` method returns an **accurate** count of the number of documents and supports specifying a filter.\n\nWhen using `countDocuments()` to return the total number of documents in a collection, you can improve performance by avoiding a collection scan. To do this, use a hint to take advantage of the built-in index on the `_id` field. Use this technique only when calling `countDocuments()` with an empty query parameter.\n\n```java\nCountOptions opts = new CountOptions().hintString(\"_id_\");\nlong numDocuments = collection.countDocuments(new BsonDocument(), opts);\n```\n\nWhen you call the `countDocuments()` method, you can optionally pass a **query filter** parameter. You cannot pass any parameters when you call `estimatedDocumentCount()`.\n\nIf you are using the Stable API `V1` with the \"strict\" option and a MongoDB Server version between 5.0.0 and 5.0.8 inclusive, method calls to `estimatedDocumentCount()` might produce an error due to a server bug.\n\nUpgrade to MongoDB Server 5.0.9 or set the Stable API \"strict\" option to `false` to avoid this issue.\n\nYou can also pass an optional parameter to either of these methods to specify the behavior of the call:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nMethod\n\n\nOptional Parameter Class\n\n\nDescription\n\n
\n`countDocuments()`\n\n\n`CountOptions`\n\n\nYou can specify a maximum number of documents to count by using the `limit()` method or the maximum amount of execution time using the `maxTime()` method.\n\n
\n`estimatedDocumentCount()`\n\n\n`EstimatedDocumentCountOptions`\n\n\nYou can specify the maximum execution time using the `maxTime()` method.\n\n
Both methods return the number of matching documents as a `long` primitive.\n\n## Count Documents Example: Full File\n\nThis example connects to an instance of MongoDB by using a connection URI. To learn more about connecting to your MongoDB instance, see the Create a MongoClient guide. This example also uses the `movies` collection in the `sample_mflix` database included in the Atlas sample datasets. You can load them into your database on a free cluster in MongoDB Atlas by following the MongoDB Get Started.\n\nThe following example estimates the number of documents in the `movies` collection in the `sample_mflix` database, and then returns an accurate count of the number of documents in the `movies` collection with `Canada` in the `countries` field.\n\n```java\n/**\n * This file demonstrates how to open a change stream by using the Java driver.\n * It connects to a MongoDB deployment, accesses the \"sample_mflix\" database, and listens\n * to change events in the \"movies\" collection. The code uses a change stream with a pipeline\n * to only filter for \"insert\" and \"update\" events.\n */\n\npackage usage.examples;\n\nimport static com.mongodb.client.model.Filters.eq;\n\nimport org.bson.Document;\nimport org.bson.conversions.Bson;\n\nimport com.mongodb.MongoException;\nimport com.mongodb.client.MongoClient;\nimport com.mongodb.client.MongoClients;\nimport com.mongodb.client.MongoCollection;\nimport com.mongodb.client.MongoDatabase;\n\npublic class CountDocuments {\n public static void main(String[] args) {\n // Replace the uri string with your MongoDB deployment's connection string\n String uri = \"\";\n\n try (MongoClient mongoClient = MongoClients.create(uri)) {\n MongoDatabase database = mongoClient.getDatabase(\"sample_mflix\");\n MongoCollection collection = database.getCollection(\"movies\");\n\n Bson query = eq(\"countries\", \"Spain\");\n\n // Retrieves and prints the estimated number of documents in the collection\n long estimatedCount = collection.estimatedDocumentCount();\n System.out.println(\"Estimated number of documents in the movies collection: \" + estimatedCount);\n\n // Retrieves and prints the number of documents with a \"countries\" value of \"Spain\"\n long matchingCount = collection.countDocuments(query);\n System.out.println(\"Number of movies from Spain: \" + matchingCount);\n }\n }\n}\n```\n\nIf you run the preceding sample code, you should see output that looks something like this (exact numbers can vary depending on your data):\n\n```none\nEstimated number of documents in the movies collection: 23541\nNumber of movies from Spain: 755\n```\n\nIf you are using the legacy API, see the FAQ section of the Legacy API guide to learn what changes you need to make to this code example.\n\n## Additional Information\n\n### API Documentation\n\nFor more information about the classes and methods used to count documents, see the following API documentation:\n\n- countDocuments()\n\n- estimatedDocumentCount()\n\n- CountOptions\n\n- EstimatedDocumentCountOptions\n\n### Server Manual Entries\n\n- db.collection.countDocuments()\n\n- db.collection.estimatedDocumentCount()"} -{"chunk_id": "699fe5eca6fa0684a38c3321-0", "page_id": "699fe5eca6fa0684a38c3321", "source_name": "java", "product_name": "Java Sync Driver", "url": "https://mongodb.com/docs/drivers/java/sync/current/integrations/spring-microservice", "title": "Tutorial: Build a Microservices App With MongoDB", "text": "# Tutorial: Build a Microservices App With MongoDB\n\n## Overview\n\nThis tutorial shows how to build a microservices architecture by using Spring Boot, Spring Cloud, and MongoDB. Specifically, this tutorial walks you through creating multiple services that work together to form a complete application.\n\nYou can find the complete source code in the following GitHub repositories:\n\n- Microservices application\n\n- Configuration repository\n\n### Spring Boot\n\nSpring Boot is a framework built on top of the Spring Framework. It adds auto-configuration, defaults, and production-ready features to simplify building Spring-based Java applications, including integration with Spring Data MongoDB. For more information, see the Spring Boot documentation.\n\n### Spring Cloud\n\nSpring Cloud is a collection of tools for building distributed systems and microservices. It provides features for configuration management, service discovery, and intelligent routing. For more information, see the Spring Cloud documentation.\n\n## Tutorial\n\nThis tutorial shows how to perform the following actions:\n\n- Verify the prerequisites\n\n- Clone the example repositories\n\n- Set up a config server\n\n- Set up a service registry\n\n- Configure an API gateway\n\n- Create MongoDB microservices\n\n- Test the REST APIs\n\n### Verify the prerequisites.\n\nBefore you begin, ensure you have the following installed:\n\n- Java Development Kit (JDK) 21 or later. You can download the JDK from the Oracle website.\n\n- Git\n\n- MongoDB (two deployments for local development). To learn how to set up MongoDB locally, see the Create a Local Atlas Deployment with Docker guide.\n\n### Clone the example repositories.\n\nClone the microservices application and configuration repositories by running the following commands:\n\n```bash\ngit clone git@github.com:mongodb-developer/microservices-architecture-mongodb.git\ngit clone git@github.com:mongodb-developer/microservices-architecture-mongodb-config-repo.git\n```\n\nFollow the instructions in the README.md file of the `microservices-architecture-mongodb` repository to start each service.\n\n### Set up a config server.\n\nA config server stores all configuration files for your microservices within a single repository.\n\nThe config server configuration is defined in the `microservices-architecture-mongodb/config-server/src/main/resources/application.properties` file:\n\n```properties\nspring.application.name=config-server\nserver.port=8888\nspring.cloud.config.server.git.uri=${HOME}/Work/microservices-architecture-mongodb-config-repo\nspring.cloud.config.label=main\n```\n\nThis configuration specifies the location of the Git repository that stores your microservices configuration and the branch to use.\n\nThe config server application is defined in the following Java class located in the `microservices-architecture-mongodb/config-server/src/main/java/com/mongodb/configserver/` directory:\n\n```java\npackage com.mongodb.configserver;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.cloud.config.server.EnableConfigServer;\n\n@EnableConfigServer\n@SpringBootApplication\npublic class ConfigServerApplication {\n public static void main(String[] args) {\n SpringApplication.run(ConfigServerApplication.class, args);\n }\n}\n\n```\n\nThe `@EnableConfigServer` annotation enables the config server functionality in your Spring Boot application.\n\n### Set up a service registry.\n\nA service registry tracks which microservices are running and their locations. Other services use this information to communicate with the microservices they need.\n\nThe service registry configuration is defined in the following properties file:\n\n```properties\nspring.application.name=service-registry\nserver.port=8761\neureka.client.register-with-eureka=false\neureka.client.fetch-registry=false\n```\n\nThe last two properties prevent the service registry from registering to itself.\n\nThe service registry application is defined in the following Java class located in the `microservices-architecture-mongodb/service-registry/src/main/java/com/mongodb/serviceregistry/` directory:\n\n```java\npackage com.mongodb.serviceregistry;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;\n\n@SpringBootApplication\n@EnableEurekaServer\npublic class ServiceRegistryApplication {\n public static void main(String[] args) {\n SpringApplication.run(ServiceRegistryApplication.class, args);\n }\n}\n\n```\n\nThe `@EnableEurekaServer` annotation enables the service registry functionality in your Spring Boot application.\n\n### Configure an API gateway.\n\nAn API gateway provides a single entry point to access all your microservices. The gateway distributes requests across multiple microservices and handles security, monitoring, and other concerns.\n\nThe API gateway configuration is defined in the `microservices-architecture-mongodb/api-gateway/src/main/resources/application.yml` file:\n\n```yaml\nserver:\n port: 8080\n\nspring:\n application:\n name: api-gateway\n cloud:\n gateway:\n routes:\n - id: company-service\n uri: lb://company-service\n predicates:\n - Path=/api/company/**,/api/companies\n - id: employee-service\n uri: lb://employee-service\n predicates:\n - Path=/api/employee/**,/api/employees\n\neureka:\n client:\n register-with-eureka: true\n fetch-registry: true\n service-url:\n defaultZone: http://localhost:8761/eureka/\n instance:\n hostname: localhost\n```\n\nThis configuration defines routes for the company and employee services and registers the gateway with the service registry.\n\n### Create MongoDB microservices.\n\nThis application includes two microservices: a company service and an employee service. Each microservice connects to its own MongoDB instance to maintain independence.\n\nThe company service configuration is defined in the `microservices-architecture-mongodb-config-repo/company-service.properties` file:\n\n```properties\nspring.data.mongodb.uri=${MONGODB_URI_1:mongodb://localhost:27017}\nspring.threads.virtual.enabled=true\nmanagement.endpoints.web.exposure.include=*\nmanagement.info.env.enabled=true\ninfo.app.name=Company Microservice\ninfo.app.java.version=21\ninfo.app.type=Spring Boot\nserver.port=8081\neureka.client.register-with-eureka=true\neureka.client.fetch-registry=true\neureka.client.service-url.defaultZone=http://localhost:8761/eureka/\neureka.instance.hostname=localhost\n```\n\nThe employee service configuration is defined in the `microservices-architecture-mongodb-config-repo/employee-service.properties` file:\n\n```properties\nspring.data.mongodb.uri=${MONGODB_URI_2:mongodb://localhost:27018}\nspring.threads.virtual.enabled=true\nmanagement.endpoints.web.exposure.include=*\nmanagement.info.env.enabled=true\ninfo.app.name=Employee Microservice\ninfo.app.java.version=21\ninfo.app.type=Spring Boot\nserver.port=8082\neureka.client.register-with-eureka=true\neureka.client.fetch-registry=true\neureka.client.service-url.defaultZone=http://localhost:8761/eureka/\neureka.instance.hostname=localhost\n```\n\nFor local development, the company service connects to MongoDB on port 27017 and the employee service connects to MongoDB on port 27018. For production, use separate MongoDB Atlas clusters and set the connection strings by using the `MONGODB_URI_1` and `MONGODB_URI_2` environment variables."} -{"chunk_id": "699fe5eca6fa0684a38c3321-1", "page_id": "699fe5eca6fa0684a38c3321", "source_name": "java", "product_name": "Java Sync Driver", "url": "https://mongodb.com/docs/drivers/java/sync/current/integrations/spring-microservice", "title": "Tutorial: Build a Microservices App With MongoDB", "text": "### Test the REST APIs.\n\nAfter you start all services, verify that your microservices architecture works correctly by ensuring that the following services are running:\n\n- Config server on port 8888\n\n- Service registry on port 8761\n\n- API gateway on port 8080\n\n- Company service on port 8081\n\n- Employee service on port 8082\n\nAlso ensure you have two MongoDB instances running on ports 27017 and 27018, or two MongoDB Atlas clusters.\n\nRun the test script by running the following command:\n\n```bash\n./2_api-tests.sh\n```\n\nThe script creates companies and employees, then retrieves them by using the REST API. The output returned by the script resembles the following:\n\n```text\nDELETE Companies\n2\nDELETE Employees\n2\n\nPOST Company 'MongoDB'\nPOST Company 'Google'\n\nGET Company 'MongoDB' by 'id'\n{\n \"id\": \"661aac7904e1bf066ee8e214\",\n \"name\": \"MongoDB\",\n \"headquarters\": \"New York\",\n \"created\": \"2009-02-11T00:00:00.000+00:00\"\n}\n\nGET Company 'Google' by 'name'\n{\n \"id\": \"661aac7904e1bf066ee8e216\",\n \"name\": \"Google\",\n \"headquarters\": \"Mountain View\",\n \"created\": \"1998-09-04T00:00:00.000+00:00\"\n}\n\nGET Companies\n[\n {\n \"id\": \"661aac7904e1bf066ee8e214\",\n \"name\": \"MongoDB\",\n \"headquarters\": \"New York\",\n \"created\": \"2009-02-11T00:00:00.000+00:00\"\n },\n {\n \"id\": \"661aac7904e1bf066ee8e216\",\n \"name\": \"Google\",\n \"headquarters\": \"Mountain View\",\n \"created\": \"1998-09-04T00:00:00.000+00:00\"\n }\n]\n\nPOST Employee Maxime\nPOST Employee Tim\n\nGET Employee 'Maxime' by 'id'\n{\n \"id\": \"661aac79cf04401110c03516\",\n \"firstName\": \"Maxime\",\n \"lastName\": \"Beugnet\",\n \"company\": \"Google\",\n \"headquarters\": \"Mountain View\",\n \"created\": \"1998-09-04T00:00:00.000+00:00\",\n \"joined\": \"2018-02-12T00:00:00.000+00:00\",\n \"salary\": 2468\n}\n\nGET Employee 'Tim' by 'id'\n{\n \"id\": \"661aac79cf04401110c03518\",\n \"firstName\": \"Tim\",\n \"lastName\": \"Kelly\",\n \"company\": \"MongoDB\",\n \"headquarters\": \"New York\",\n \"created\": \"2009-02-11T00:00:00.000+00:00\",\n \"joined\": \"2023-08-23T00:00:00.000+00:00\",\n \"salary\": 13579\n}\n\nGET Employees\n[\n {\n \"id\": \"661aac79cf04401110c03516\",\n \"firstName\": \"Maxime\",\n \"lastName\": \"Beugnet\",\n \"company\": \"Google\",\n \"headquarters\": \"Mountain View\",\n \"created\": \"1998-09-04T00:00:00.000+00:00\",\n \"joined\": \"2018-02-12T00:00:00.000+00:00\",\n \"salary\": 2468\n },\n {\n \"id\": \"661aac79cf04401110c03518\",\n \"firstName\": \"Tim\",\n \"lastName\": \"Kelly\",\n \"company\": \"MongoDB\",\n \"headquarters\": \"New York\",\n \"created\": \"2009-02-11T00:00:00.000+00:00\",\n \"joined\": \"2023-08-23T00:00:00.000+00:00\",\n \"salary\": 13579\n }\n]\n```\n\nThe employee service queries the company service to retrieve company details. The following code shows how the employee service communicates with the company service through the service registry:\n\n```java\nprivate CompanyDTO getCompany(String company) {\n String url = \"http://company-service/api/company/name/\";\n CompanyDTO companyDTO = restTemplate.getForObject(url + company, CompanyDTO.class);\n if (companyDTO == null) {\n throw new EntityNotFoundException(\"Company not found: \", company);\n }\n return companyDTO;\n}\n\n```\n\nThe URL references the company service by name rather than by IP address and port, which confirms that the service registry works correctly.\n\n## Additional Resources\n\nTo learn more about building microservices with Spring and MongoDB, see the following resources:\n\n- Spring Cloud Circuit Breaker\n\n- Spring Cloud Sleuth"} -{"chunk_id": "68a95bf65e79d242619d9bd3-0", "page_id": "68a95bf65e79d242619d9bd3", "source_name": "java", "product_name": "Java Sync Driver", "url": "https://mongodb.com/docs/drivers/java/sync/current/reference/legacy", "title": "Migrate from the Legacy API", "text": "# Migrate from the Legacy API\n\n## Overview\n\nOn this page, you can identify the changes you must make to migrate from the legacy API to the current API. You can also learn about features unique to the current Java driver and the benefits of migrating to the new API.\n\nThe legacy API, packaged as the `mongodb-driver-legacy` JAR, contains the legacy synchronous Java driver and uses naming conventions used in earlier versions of the driver.\n\nThe current API, packaged as the `mongodb-driver-sync` JAR, contains the current synchronous Java driver. It features the `MongoCollection` interface as an entry point to CRUD operations. It does not contain the legacy API.\n\nTo perform a migration from the legacy API to the current API, ensure your code no longer references the legacy API, updating your code when necessary. Then, replace the legacy API and any uber JAR that contains it with the current API JAR in your application dependencies.\n\nIn addition to updating your application to handle any necessary changes, always check for any other differences in options and return values before moving it to production.\n\n## Current API Benefits\n\nYou can continue to use the legacy API with each new MongoDB Server release. However, the legacy API does not support any updates introduced in MongoDB Server 3.0 or later. Additionally, the legacy API lacks support for certain features of the current Java driver. Some features only available in the non-legacy API include:\n\n- **Change streams**, a MongoDB Server feature designed to monitor real-time changes to a single collection, database, or deployment\n\n- **Multi-document ACID transactions**, which ensure atomicity of reads and writes to multiple documents and allow for transactions across multiple operations, collections, databases, documents, and shards\n\n- **Time series collections**, which store sequences of measurements over a period of time and improve query efficiency for time series data\n\n- **Queryable Encryption**, which allows you to encrypt sensitive workloads and to query the encrypted data\n\n- **Java records**, or concise Java classes that separate business logic from data representation and reduce boilerplate code\n\n- **Native POJO support**, which provides automatic or custom mapping between MongoDB documents and Java objects\n\nTo learn about more features of the current API, see Release Notes.\n\n## API Changes\n\nThe following table shows the majority of the changes in class and method names between the legacy and current API.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nLegacy\n\n\nCurrent\n\n
\nMongoClientOptions\n\n\nMongoClientSettings\n\n
\nnew MongoClient()\n\n\nMongoClients.create()\n\n
\nMongoClient.getDB()\n\n\nMongoClient.getDatabase()\n\n
\nDB\n\n\nMongoDatabase\n\n
\nDBCollection\n\n\nMongoCollection<>\n\n
\nDBCursor\n\n\nMongoCursor\n\n
\nDBCollection.findOne()\n\n\n`MongoCollection.find().first()`See the following API documentation pages for these methods:- find()\n\n- first()\n\n
\nDBCollection.insert()\n\n\nUse one of the following methods:\n\n- MongoCollection.insertOne()\n\n- MongoCollection.insertMany()\n\n
\nDBCollection.update()\n\n\nUse one of the following methods:\n\n- MongoCollection.updateOne()\n\n- MongoCollection.updateMany()\n\n- MongoCollection.replaceOne()\n\n
\nDBCollection.remove()\n\n\nUse one of the following methods:\n\n- MongoCollection.deleteOne()\n\n- MongoCollection.deleteMany()\n\n
\nDBCollection.count()\n\n\nUse one of the following methods:\n\n- MongoCollection.countDocuments()\n\n- MongoCollection.estimatedDocumentCount()\n\n
\nDBCollection.findAndModify()\n\n\nUse one of the following methods:\n\n- MongoCollection.findOneAndUpdate()\n\n- MongoCollection.findOneAndReplace()\n\n- MongoCollection.findOneAndDelete()\n\n
\nQueryBuilder\n\n\nFilters\n\n
In addition to the preceding items, consider the following changes:\n\n- The current API uses `Options` classes and method chaining rather than overloaded methods.\n\n- The current API uses relaxed JSON format by default in driver versions 4.0 and later. If your application relies on the strict JSON format, use the strict mode when reading or writing data. Learn how to specify the JSON format in the current API in the Document Data Format: Extended JSON guide.\n\n- The default generic type for `MongoCollection` in the current API is org.bson.Document. You can specify BasicDBObject as a type parameter if it eases your migration.\n\n- In the current API, the aggregation pipeline you pass to the `aggregate()` method accepts a list of objects that extend the `Bson` interface. In the legacy API, it accepts a list of objects that extend the `DBObject` interface.\n\n The method signatures also differ between the APIs. See the following API documentation for more information:\n\n - aggregate() method in the current API\n\n - aggregate() method in the legacy API\n\n - Bson interface\n\n - DBObject interface\n\n## Frequently Asked Questions\n\nThis section answers questions that may arise about the legacy API.\n\n### How do I connect to my MongoDB instance by using the legacy API?\n\nImagine we are connecting to a collection that contains only the following document:\n\n```json\n{\"_id\": 1, \"val\": 1}\n```\n\nThe following example shows how to connect to this MongoDB collection by using the legacy API and the current API:\n\n\n\n\n\n```java\nMongoClient client = new MongoClient(URI);\nDB db = client.getDB(DATABASE);\nDBCollection col = db.getCollection(COLLECTION);\n\n// Retrieves one document in the collection and prints it\nDBObject doc = col.find().one();\nSystem.out.println(doc.toString());\n```\n\n\n\n\n\n```java\nMongoClient client = MongoClients.create(URI);\nMongoDatabase db = client.getDatabase(DATABASE);\nMongoCollection col = db.getCollection(COLLECTION);\n\n// Prints the first document retrieved from the collection as JSON\nDocument doc = col.find().first();\nSystem.out.println(doc.toJson());\n```\n\n\n\n\n\nThe output of the preceding code snippet resembles the following:\n\n```json\n{\"_id\": 1, \"val\": 1}\n```\n\nFor more information about the legacy classes and methods used in the preceding example, see the following API documentation pages:\n\n- MongoClient\n\n- DB\n\n- DBCollection\n\n- DBObject\n\n- getDB()\n\n- getCollection()\n\n- find()\n\n- one()\n\nSee the Migrate from the Legacy API page for a list of differences between the legacy and current API."} -{"chunk_id": "68a95bf65e79d242619d9bd3-1", "page_id": "68a95bf65e79d242619d9bd3", "source_name": "java", "product_name": "Java Sync Driver", "url": "https://mongodb.com/docs/drivers/java/sync/current/reference/legacy", "title": "Migrate from the Legacy API", "text": "### How do I use the legacy `MongoClientOptions` and `MongoClientURI` classes?\n\nThe following example shows how to use the legacy `MongoClientOptions` and `MongoClientURI` classes to set your write concern:\n\n\n\n\n\n```java\nMongoClientURI mongoURI = new MongoClientURI(URI,\n MongoClientOptions.builder()\n .writeConcern(WriteConcern.W1));\nMongoClient client = new MongoClient(mongoURI);\n```\n\n\n\n\n\n```java\nMongoClientSettings options = MongoClientSettings.builder()\n .applyConnectionString(new ConnectionString(URI))\n .writeConcern(WriteConcern.W1).build();\nMongoClient client = MongoClients.create(options);\n```\n\n\n\n\n\nFor more information about the legacy classes and methods used in the preceding example, see the following API documentation:\n\n- Legacy API documentation\n\n- MongoClient\n\n- MongoClientOptions\n\n- MongoClientURI\n\nSee the Migrate from the Legacy API page for a list of differences between the legacy and current API."} -{"chunk_id": "68a95bf65e79d242619d9bd7-0", "page_id": "68a95bf65e79d242619d9bd7", "source_name": "java", "product_name": "Java Sync Driver", "url": "https://mongodb.com/docs/drivers/java/sync/current/data-formats/document-data-format-pojo", "title": "Document Data Format: POJOs", "text": "# Document Data Format: POJOs\n\n## Overview\n\nIn this guide, you can learn how to store and retrieve data modeled by plain old Java objects, or POJOs. POJOs are often used for data encapsulation, which is the practice of separating business logic from data representation.\n\nTo learn more about POJOs, see the Plain old Java object Wikipedia article.\n\nThe example in this guide demonstrates how to perform the following tasks:\n\n- Configure the driver to serialize and deserialize POJOs\n\n- Perform CRUD operations that use data modeled by POJOs\n\n## Example POJO\n\nThe sections in this guide use the following sample POJO class, which describes the characteristics of flowers:\n\n```java\npublic class Flower {\n\n private ObjectId id;\n private String name;\n private List colors;\n private Boolean isBlooming;\n private Float height;\n\n // public empty constructor needed for retrieving the POJO\n public Flower() {\n }\n\n public Flower(String name, Boolean isBlooming, Float height, List colors) {\n this.name = name;\n this.isBlooming = isBlooming;\n this.height = height;\n this.colors = colors;\n }\n\n public ObjectId getId() {\n return id;\n }\n\n public void setId(ObjectId id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public Boolean getIsBlooming() {\n return isBlooming;\n }\n\n public void setIsBlooming(Boolean isBlooming) {\n this.isBlooming = isBlooming;\n }\n\n public Float getHeight() {\n return height;\n }\n\n public void setHeight(Float height) {\n this.height = height;\n }\n\n public List getColors() {\n return colors;\n }\n\n public void setColors(List colors) {\n this.colors = colors;\n }\n\n @Override\n public String toString() {\n return \"\\nFlower {\\n\\tid: \" + id + \"\\n\\tname: \" + name + \"\\n\\tcolors: \" + colors + \"\\n\\tisBlooming: \" + isBlooming + \"\\n\\theight: \" + height + \"\\n}\";\n }\n}\n```\n\nWhen defining a POJO to store and retrieve data within MongoDB, use the following guidelines:\n\n- The POJO class cannot implement interfaces or extend classes from a framework.\n\n- Include all the fields for which you want to store and retrieve data, and make sure they are not marked as `static` or `transient`.\n\n- If you include public getter or setter methods by using the JavaBean naming conventions in your POJO, the driver calls them when serializing or deserializing data. If you omit the getter or setter methods for a public property field, the driver accesses or assigns them directly.\n\n## Configure the Driver for POJOs\n\nTo configure the driver to use POJOs, you must specify the following components:\n\n- `PojoCodecProvider` instance that has codecs that define how to encode and decode the data between the POJO format and BSON. The provider also specifies which POJO classes or packages that the codecs apply to.\n\n- `CodecRegistry` instance that contains the codecs and other related information.\n\n- `MongoDatabase` or `MongoCollection` instance that is configured to use the `CodecRegistry`.\n\n- `MongoCollection` instance that is created with the POJO document class bound to the `TDocument` generic type.\n\nPerform the following steps to meet the configuration requirements defined in the preceding section:\n\n1. Configure the `PojoCodecProvider`. In this example, we use the `automatic(true)` setting of the `PojoCodecProvider.Builder` to apply the codecs to any class and its properties.\n\n ```java\n CodecProvider pojoCodecProvider = PojoCodecProvider.builder().automatic(true).build();\n ```\n\n Codec providers also contain other objects such as `ClassModel` and `Convention` instances that further define serialization behavior. For more information about codec providers and customization, see the guide on POJO Customization.\n\n2. Add the `PojoCodecProvider` instance to a `CodecRegistry`. The `CodecRegistry` allows you to specify one or more codec providers to encode the POJO data. In this example, we call the following methods:\n\n - `fromRegistries()` to combine multiple `CodecRegistry` instances into one instance\n\n - `getDefaultCodecRegistry()` to retrieve a `CodecRegistry` instance from a list of codec providers\n\n - `fromProviders()` to create a `CodecRegistry` instance from the `PojoCodecProvider`\n\n The following code shows how to instantiate the `CodecRegistry`:\n\n ```java\n // Include the following static imports before your class definition\n import static com.mongodb.MongoClientSettings.getDefaultCodecRegistry;\n import static org.bson.codecs.configuration.CodecRegistries.fromProviders;\n import static org.bson.codecs.configuration.CodecRegistries.fromRegistries;\n\n ...\n\n CodecRegistry pojoCodecRegistry = fromRegistries(getDefaultCodecRegistry(), fromProviders(pojoCodecProvider));\n ```\n\n3. Configure the `MongoDatabase` or `MongoCollection` instance to use the codecs in the `CodecRegistry`. You can configure either a database or collection to specify the codecs.\n\n In this example, we set the `CodecRegistry` on a `MongoDatabase` called `sample_pojos` by using the `withCodecRegistry()` method:\n\n ```java\n MongoClient mongoClient = MongoClients.create(uri);\n MongoDatabase database = mongoClient.getDatabase(\"sample_pojos\").withCodecRegistry(pojoCodecRegistry);\n ```\n\n4. Pass your POJO class to your call to `getCollection()` as the document class parameter and specify it as the type argument of your `MongoCollection` instance, as shown in the following code:\n\n ```java\n MongoCollection collection = database.getCollection(\"flowers\", Flower.class);\n ```\n\n### Perform CRUD Operations\n\nOnce you have configured the `MongoCollection` instance to use the `Flower` POJO, you can perform CRUD operations on data modeled by the POJO.\n\nThis example demonstrates how to perform the following operations by using the `Flower` POJO:\n\n- Insert instances of `Flower` into the `flowers` collection\n\n- Update a document in the collection\n\n- Delete a document in the collection\n\n- Find and print all documents in the collection\n\n```java\n// Insert three Flower instances\nFlower roseFlower = new Flower(\"rose\", false, 25.4f, Arrays.asList(new String[] {\"red\", \"pink\"}));\nFlower daisyFlower = new Flower(\"daisy\", true, 21.1f, Arrays.asList(new String[] {\"purple\", \"white\"}));\nFlower peonyFlower = new Flower(\"peony\", false, 19.2f, Arrays.asList(new String[] {\"red\", \"green\"}));\ncollection.insertMany(Arrays.asList(roseFlower, daisyFlower, peonyFlower));\n\n// Update a document\ncollection.updateOne(\n Filters.lte(\"height\", 22),\n Updates.addToSet(\"colors\", \"pink\")\n);\n\n// Delete a document\ncollection.deleteOne(Filters.eq(\"name\", \"rose\"));\n\n// Return and print all documents in the collection\nList flowers = new ArrayList<>();\ncollection.find().into(flowers);\nSystem.out.println(flowers);\n```\n\nThe example prints the following output:\n\n```none\n[\nFlower {\n id: 65b178ffa38ac42044ca1573\n name: daisy\n colors: [purple, white, pink]\n isBlooming: true\n height: 21.1\n},\nFlower {\n id: 65b178ffa38ac42044ca1574\n name: peony\n colors: [red, green]\n isBlooming: false\n height: 19.2\n}]\n```\n\nBy default, the `PojoCodecProvider` omits fields in your POJO that are set to `null`. For more information about how to specify this behavior, see the POJO Customization guide.\n\nFor more information about the methods and classes mentioned in this section, see the following API documentation:\n\n- CodecRegistry\n\n- TDocument\n\n- PojoCodecProvider\n\n- automatic(true)\n\n- PojoCodecProvider.Builder\n\n- fromRegistries()\n\n- getDefaultCodecRegistry()\n\n- fromProviders()\n\n## Frequently Asked Questions\n\nThis section answers questions that may arise when storing POJOs in MongoDB.\n\n### Do I have to specify an ID field value myself?\n\nNo, the `PojoCodecProvider` automatically generates an ObjectId."} -{"chunk_id": "68a95bf65e79d242619d9bd7-1", "page_id": "68a95bf65e79d242619d9bd7", "source_name": "java", "product_name": "Java Sync Driver", "url": "https://mongodb.com/docs/drivers/java/sync/current/data-formats/document-data-format-pojo", "title": "Document Data Format: POJOs", "text": "### Can the ID field be a compound key?\n\nYes. Annotate a field that holds multiple values with `@BsonId` to use it as the compound key. The following example defines an `EntityKey` class with `code` and `date` fields, then uses it as the `_id` field in an `Entity` POJO:\n\n```java\npublic static class EntityKey {\n\n @BsonCreator\n public EntityKey(@BsonProperty(\"code\") String code,\n @BsonProperty(\"date\") Date date) {\n this.code = code;\n this.date = date;\n }\n\n // getters\n}\n\npublic static class Entity {\n\n @BsonId\n private final EntityKey key;\n\n @BsonCreator\n public Entity(@BsonProperty(\"key\") EntityKey key) {\n this.key = key;\n }\n\n // getters and setters\n}\n```\n\n### Can I use polymorphism in a POJO accessor?\n\nYes, by using a discriminator. For more information, see the Discriminators section of the POJO Customization guide.\n\n### Can I mix private, protected, and public setters and getters?\n\nNo. The native POJO codec assumes that getters and setters have the same modifiers for each field.\n\nFor example, the following methods throws an exception during encoding:\n\n```java\nprivate String getField();\npublic String setField(String x);\n```\n\n### How do I fix: \"org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class X.\"?\n\nThis exception means you must register a codec for the class since none exist."} -{"chunk_id": "68a95bf65e79d242619d9b89-0", "page_id": "68a95bf65e79d242619d9b89", "source_name": "java", "product_name": "Java Sync Driver", "url": "https://mongodb.com/docs/drivers/java/sync/current/crud/collations", "title": "Collations", "text": "# Collations\n\n## Overview\n\nIn this guide, you can learn how to use **collations** with MongoDB to order your query or aggregation operation results by string values. A collation is a set of character ordering and matching rules that apply to a specific language and locale.\n\nYou can learn more about collations in the following sections in this guide:\n\n- Collations in MongoDB\n\n- How to Specify Collations\n\n- Collation Options\n\n- Collation Code Examples\n\n## Collations in MongoDB\n\nMongoDB sorts strings using **binary collation** by default. The binary collation uses the ASCII standard character values to compare and order strings. Certain languages and locales have specific character ordering conventions that differ from the ASCII character values.\n\nFor example, in Canadian French, the right-most accented character (diacritic) determines the ordering for strings when all preceding characters are the same. Consider the following Canadian French words:\n\n- cote\n\n- cot\u00e9\n\n- c\u00f4te\n\n- c\u00f4t\u00e9\n\nWhen using binary collation, MongoDB sorts them in the following order:\n\n```none\ncote\ncot\u00e9\nc\u00f4te\nc\u00f4t\u00e9\n```\n\nWhen using the Canadian French collation, MongoDB sorts them in a different order as shown below:\n\n```none\ncote\nc\u00f4te\ncot\u00e9\nc\u00f4t\u00e9\n```\n\n## How to Specify Collations\n\nMongoDB supports collations on most CRUD operations and aggregations. For a complete list of supported operations, see the Operations that Support Collations server manual page.\n\nYou can specify the locale code and optional variant in the following string format:\n\n```none\n\"@collation=\"\n```\n\nThe following example specifies the \"de\" locale code and \"phonebook\" variant code:\n\n```none\n\"de@collation=phonebook\"\n```\n\nIf you are not specifying a variant, omit everything after the locale code as follows:\n\n```none\n\"de\"\n```\n\nFor a complete list of supported locales, see our server manual page on Supported Languages and Locales.\n\nThe following sections show you different ways to apply collations in MongoDB:\n\n- Collection\n\n- Index\n\n- Operation\n\n### Collection\n\nYou can set a default collation when you create a collection. When you create a collection with a specified collation, all supported operations that scan that collection apply the rules of the collation.\n\nYou can only assign a default collation to a collection when you create that collection. However, you can specify a collation in a new index on an existing collection. See the Index section of this guide for more information.\n\nThe following snippet shows how to specify the \"en_US\" locale collation when creating a new collection called `items`:\n\n```java\ndatabase.createCollection(\n \"items\",\n new CreateCollectionOptions().collation(\n Collation.builder().locale(\"en_US\").build()));\n```\n\nTo check whether you created the collation successfully, retrieve a list of the indexes on that collection as follows:\n\n```java\nMongoCollection collection = database.getCollection(\"items\");\nList indexes = new ArrayList<>();\n\ncollection.listIndexes().into(indexes);\n\n// Prints the collection's indexes and any default collations\nindexes.forEach(idx -> System.out.println(idx.toJson()));\n```\n\nThe output of your code should contain the following:\n\n```none\n{ ...\n \"collation\": { \"locale\": \"en_US\", ... }\n ...\n}\n```\n\n### Index\n\nYou can specify a collation when you create a new index on a collection. The index stores an ordered representation of the documents in the collection so your operation does not perform the ordering in-memory. To use the index, your operation must meet the following criteria:\n\n- The operation uses the same collation as the one specified in the index.\n\n- The operation is covered by the index that contains the collation.\n\nThe following code snippet shows how you can create an index on the \"name\" field with the \"en_US\" locale collation in ascending order:\n\n```java\nMongoCollection collection = database.getCollection(\"items\");\nIndexOptions idxOptions = new IndexOptions();\n\n// Defines options that set a collation locale\nidxOptions.collation(Collation.builder().locale(\"en_US\").build());\n\n// Creates an index on the \"name\" field with the collation and ascending sort order\ncollection.createIndex(Indexes.ascending(\"name\"), idxOptions);\n```\n\nTo check whether you created the collation successfully, retrieve a list of the indexes on that collection as follows:\n\n```java\nMongoCollection collection = database.getCollection(\"items\");\nList indexes = new ArrayList<>();\n\ncollection.listIndexes().into(indexes);\n\n// Prints the collection's indexes and any default collations\nindexes.forEach(idx -> System.out.println(idx.toJson()));\n```\n\nThe output of the preceding code should contain the following:\n\n```none\n{ ...\n \"collation\": { \"locale\": \"en_US\", ... }\n ...\n}\n```\n\nThe following code snippet shows an example operation that specifies the same collation and is covered by the index we created in the preceding code snippet:\n\n```java\nFindIterable cursor = collection.find()\n .collation(Collation.builder().locale(\"en_US\").build())\n .sort(Sorts.ascending(\"name\"));\n```\n\n### Operation\n\nYou can override the default collation on a collection by passing the new collation as a parameter to one of the supported operations. However, since the operation does not use an index, the operation might not perform as well as one that is covered by an index. For more information about the disadvantages of sorting operations not covered by an index, see the server manual page on Use Indexes to Sort Query Results.\n\nThe following code snippet shows an example query operation with the following characteristics:\n\n- The referenced collection contains the default collation \"en_US\" similar to the one specified in the Collection section.\n\n- The query specifies the Icelandic (\"is\") collation which is not covered by the collection's default collation index.\n\n- Since the specified collation is not covered by an index, the sort operation is performed in-memory.\n\n```java\nFindIterable cursor = collection.find()\n .collation(Collation.builder().locale(\"is\").build())\n .sort(Sorts.ascending(\"name\"));\n```\n\n### Index Types That Do Not Support Collations\n\nWhile most MongoDB index types support collation, the following types support only binary comparison:\n\n- text\n\n- 2d"} -{"chunk_id": "68a95bf65e79d242619d9b89-1", "page_id": "68a95bf65e79d242619d9b89", "source_name": "java", "product_name": "Java Sync Driver", "url": "https://mongodb.com/docs/drivers/java/sync/current/crud/collations", "title": "Collations", "text": "## Collation Options\n\nThis section covers various collation options and how to specify them to further refine the ordering and matching behavior.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nCollation Option\n\n\nDescription\n\n
\nLocale\n\n\n**Required**. The ICU locale code for language and variant.locale() API Documentation\n\n
\nBackwards\n\n\nWhether to consider diacritics from the end of the string first.backwards() API Documentation\n\n
\nCase-sensitivity\n\n\nWhether to consider case (upper or lower) as different values.caseLevel() API Documentation\n\n
\nAlternate\n\n\nWhether to consider spaces and punctuation.collationAlternate() API Documentation\n\n
\nCase First\n\n\nWhether to consider uppercase or lowercase first.collationCaseFirst() API Documentation\n\n
\nMax Variable\n\n\nWhether to ignore whitespace or both whitespace and punctuation. This setting is only valid when the alternate setting is \"shifted\".collationMaxVariable() API Documentation\n\n
\nStrength\n\n\nICU level of comparison. The default value is \"tertiary\". For more information about each level, see the ICU Comparison Levels.collationStrength() API Documentation\n\n
\nNormalization\n\n\nWhether to perform unicode normalization on the text as needed. For more information about unicode normalization, see Unicode Normalization Forms.normalization() API Documentation\n\n
\nNumeric Ordering\n\n\nWhether to order numbers according to numeric value rather than collation order.numericOrdering() API Documentation\n\n
You can use the `Collation.Builder` class to specify values for the preceding collation options. You can call the `build()` method to construct a `Collation` object as shown in the following code snippet:\n\n```java\nCollation.builder()\n.caseLevel(true)\n.collationAlternate(CollationAlternate.SHIFTED)\n.collationCaseFirst(CollationCaseFirst.UPPER)\n.collationMaxVariable(CollationMaxVariable.SPACE)\n.collationStrength(CollationStrength.SECONDARY)\n.locale(\"en_US\")\n.normalization(false)\n.numericOrdering(true)\n.build();\n```\n\nFor more information about the corresponding methods and parameters they take, see the API Documentation for Collation.Builder.\n\n## Collation Examples\n\nThis section contains examples that demonstrate how to use a selection of MongoDB operations that support collations. For each example, assume that you start with the following collection of documents:\n\n```json\n{ \"_id\" : 1, \"first_name\" : \"Klara\" }\n{ \"_id\" : 2, \"first_name\" : \"Gunter\" }\n{ \"_id\" : 3, \"first_name\" : \"G\u00fcnter\" }\n{ \"_id\" : 4, \"first_name\" : \"J\u00fcrgen\" }\n{ \"_id\" : 5, \"first_name\" : \"Hannah\" }\n```\n\nIn the following examples, we specify the \"de@collation=phonebook\" locale and variant collation. The \"de\" part of the collation specifies the German locale and the \"collation=phonebook\" part specifies a variant. The \"de\" locale collation contains rules for prioritizing proper nouns, identified by capitalization of the first letter. In the \"collation=phonebook\" variant, characters with umlauts are ordered before the same characters without them in an ascending sort.\n\n### find() and sort() Example\n\nThe following example demonstrates how you can apply a collation when retrieving sorted results from a collection. To perform this operation, call `find()` on the example collection and chain the `collation()` and `sort()` methods to specify the order in which you want to receive the results.\n\nThe following code example uses imports from the `import com.mongodb.client.model` package for convenience.\n\n```java\nList results = new ArrayList<>();\n\n// Retrieves all documents and applies a \"de@collation-phonebook\" collation and ascending sort to the results\ncollection.find()\n .collation(Collation.builder().locale(\"de@collation=phonebook\").build())\n .sort(Sorts.ascending(\"first_name\")).into(results);\n\n// Prints the JSON representation of the results\nif (results != null) {\n results.forEach(doc -> System.out.println(doc.toJson()));\n}\n```\n\nWhen you perform this operation on the example collection, the output resembles the following:\n\n```json\n{\"_id\": 3, \"first_name\": \"G\u00fcnter\"}\n{\"_id\": 2, \"first_name\": \"Gunter\"}\n{\"_id\": 5, \"first_name\": \"Hannah\"}\n{\"_id\": 4, \"first_name\": \"J\u00fcrgen\"}\n{\"_id\": 1, \"first_name\": \"Klara\"}\n```\n\nFor more information about the methods and classes mentioned in this section, see the following API Documentation:\n\n- find()\n\n- sort()\n\n- Sorts\n\n### findOneAndUpdate() Example\n\nThis section demonstrates how you can specify a collation in an operation that updates the first match from your query. To specify the collation for this operation, instantiate a `FindOneAndUpdateOptions` object, set a collation on it, and pass it as a parameter to your call to the `findOneAndUpdate()` method.\n\nIn this example, we demonstrate the following:\n\n- Retrieve the first document in our example collection that precedes \"Gunter\" in an ascending order.\n\n- Set options for operation including the \"de@collation=phonebook\" collation.\n\n- Add a new field \"verified\" with the value \"true\".\n\n- Retrieve and print the updated document.\n\nThe following code example uses imports from the `import com.mongodb.client.model` package for convenience.\n\n```java\nDocument result = collection.findOneAndUpdate(\n Filters.gt(\"first_name\", \"Gunter\"),\n Updates.set(\"verified\", true),\n new FindOneAndUpdateOptions()\n .collation(Collation.builder().locale(\"de@collation=phonebook\").build())\n .sort(Sorts.ascending(\"first_name\"))\n .returnDocument(ReturnDocument.AFTER));\n\n// Prints the JSON representation of the updated document if an update occurred\nif (result != null) {\n System.out.println(\"Updated document: \" + result.toJson());\n}\n```\n\nSince \"G\u00fcnter\" is lexically before \"Gunter\" using the `de@collation=phonebook` collation in ascending order, the preceding operation returns the following update document:\n\n```none\n{\n lastErrorObject: { updatedExisting: true, n: 1 },\n value: { _id: 3, first_name: 'G\u00fcnter' },\n ok: 1\n}\n```\n\nFor more information about the methods and classes mentioned in this section, see the following API Documentation:\n\n- findOneAndUpdate\n\n- findOneAndUpdateOptions\n\n- Filters\n\n- Updates\n\n- Sorts"} -{"chunk_id": "68a95bf65e79d242619d9b89-2", "page_id": "68a95bf65e79d242619d9b89", "source_name": "java", "product_name": "Java Sync Driver", "url": "https://mongodb.com/docs/drivers/java/sync/current/crud/collations", "title": "Collations", "text": "### findOneAndDelete() Example\n\nThis section demonstrates how you can specify a numerical ordering of strings in a collation in an operation that deletes the first match from your query. To specify the collation for this operation, instantiate a `FindOneAndDeleteOptions` object, set a numeric ordering collation on it, and pass it as a parameter to your call to the `findOneAndDelete()` method.\n\nThis example calls the `findOneAndDelete()` operation on a collection that contains the following documents:\n\n```json\n{ \"_id\" : 1, \"a\" : \"16 apples\" }\n{ \"_id\" : 2, \"a\" : \"84 oranges\" }\n{ \"_id\" : 3, \"a\" : \"179 bananas\" }\n```\n\nIn the collation, we set the `locale` option to \"en\" and the `numericOrdering` option to \"true\" in order to sort strings based on their numerical order.\n\nThe following code example uses imports from the `import com.mongodb.client.model` package for convenience.\n\n```java\nDocument result = collection.findOneAndDelete(\n Filters.gt(\"a\", \"100\"),\n new FindOneAndDeleteOptions()\n .collation(\n Collation.builder()\n .locale(\"en\")\n .numericOrdering(true)\n .build())\n .sort(Sorts.ascending(\"a\")));\n\n// Prints the JSON representation of the deleted document\nif (result != null) {\n System.out.println(\"Deleted document: \" + result.toJson());\n}\n```\n\nAfter you run the preceding operation, your output resembles the following:\n\n```none\nDeleted document: {\"_id\": 3, \"a\": \"179 bananas\"}\n```\n\nThe numeric value of the string \"179\" is greater than the number 100, so the preceding document is the only match.\n\nIf we perform the same operation without the numerical ordering collation on the original collection of three documents, the filter matches all of our documents since \"100\" comes before \"16\", \"84\", and \"179\" when ordering by binary collation.\n\nFor more information about the methods and classes mentioned in this section, see the following API Documentation:\n\n- findOneAndDelete\n\n- FindOneAndDeleteOptions\n\n- Filters\n\n- Sorts\n\n### Aggregation Example\n\nThis section demonstrates how you can specify a collation in an aggregation operation. In an aggregation operation, you can specify a series of aggregation stages which is collectively called the aggregation pipeline. To perform an aggregation, call the `aggregate()` method on a `MongoCollection` object.\n\nTo specify a collation for an aggregation operation, call the `collation()` method on the `AggregateIterable` returned by the aggregation operation. Make sure to specify a sort aggregation stage on which to apply the collation in your aggregation pipeline.\n\nThe following example shows how we can construct an aggregation pipeline on the example collection and apply a collation by specifying the following:\n\n- A group aggregation stage using the `Aggregates.group()` helper to identify each document by the `first_name` field and use that value as the `_id` of the result.\n\n- An accumulator in the group aggregation stage to sum the number of instances of matching values in the `first_name` field.\n\n- Apply an ascending sort to the `_id` field of the output documents of the prior aggregation stage.\n\n- Construct a collation object, specifying the German locale and a collation strength that ignores accents and umlauts.\n\n```java\nBson groupStage = Aggregates.group(\"$first_name\", Accumulators.sum(\"nameCount\", 1));\nBson sortStage = Aggregates.sort(Sorts.ascending(\"_id\"));\n\nAggregateIterable results = collection\n // Runs the aggregation pipeline that includes tallying \"first_name\" frequencies\n .aggregate(Arrays.asList(groupStage, sortStage))\n\n // Applies a collation to sort documents alphabetically by using the German locale, ignoring accents\n .collation(Collation.builder().locale(\"de\").collationStrength(CollationStrength.PRIMARY).build());\n\n// Prints the JSON representation of the results\nif (results != null) {\n results.forEach(doc -> System.out.println(doc.toJson()));\n}\n```\n\nThe preceding code outputs the following documents:\n\n```json\n{\"_id\": \"Gunter\", \"nameCount\": 2}\n{\"_id\": \"Hannah\", \"nameCount\": 1}\n{\"_id\": \"J\u00fcrgen\", \"nameCount\": 1}\n{\"_id\": \"Klara\", \"nameCount\": 1}\n```\n\nFor more information about the methods and classes mentioned in this section, see the following API Documentation:\n\n- aggregate()\n\n- AggregateIterable\n\n- CollationStrength\n\n- Accumulators\n\n- Aggregates\n\n- Sorts"} -{"chunk_id": "695ca90b2d5be1431b31759c-0", "page_id": "695ca90b2d5be1431b31759c", "source_name": "java", "product_name": "Java Sync Driver", "url": "https://mongodb.com/docs/drivers/java/sync/current/integrations/spring-session", "title": "Spring Session MongoDB Integration", "text": "# Spring Session MongoDB Integration\n\n## Overview\n\n**Spring Session MongoDB** is a library that allows Spring-based applications to store HTTP session data in MongoDB. This integration between Spring Session and MongoDB provides reliable and scalable sessions for applications that run on multiple servers or containers, because any instance can access the same session data. When using MongoDB for session storage, you can maintain sessions after your application restarts and share sessions across a cluster with minimal configuration.\n\nSpring Session 4.0 introduces the first MongoDB-maintained release of the Spring Session MongoDB integration. When working with the integration, you can now receive direct support from the MongoDB engineers who develop the MongoDB Java Driver. This change ensures that Spring Session MongoDB aligns with the latest Java driver releases and API improvements.\n\n## Getting Started\n\nYou can use the MongoDB-maintained Spring Session integration in your application by creating a new Spring Boot application, or by updating an existing application that uses an earlier version of Spring Session MongoDB.\n\n### Create a New Application\n\nTo learn how to create a Spring Boot application that uses Spring Session MongoDB to manage user session information, follow the Get Started with Spring Session MongoDB tutorial.\n\n### Migrate Your Application\n\nIf you have an existing application that uses the Spring Session MongoDB integration maintained by Spring, migrate to the MongoDB-maintained integration by performing the following updates:\n\n- Update your Maven artifact from `org.springframework.session:spring-session-data-mongodb` to `org.mongodb:mongodb-spring-session`. To learn more about the new artifact, see mongodb-spring-session in Maven Central.\n\n- Change the API namespace from `org.springframework.session.data.mongo` to `org.mongodb.spring.session`. Ensure that your import statements use the new namespace.\n\n- Because Jackson 2 support is now deprecated, update your application to use `JacksonMongoSessionConverter`. This is the Jackson 3 session converter.\n\n## Issues & Help\n\n### Bugs / Feature Requests\n\nIf you have feedback about Spring Session MongoDB, visit the Frameworks section of the MongoDB Feedback Engine. You can propose improvements, report issues, and provide other types of feedback by using this site.\n\nYou can also open a case in Jira, our issue management tool, to identify bugs or propose improvements. The following steps describe how to create a Jira issue:\n\n1. Visit the MongoDB Jira issue tracker and click the signup link. Create an account, and then log in to Jira.\n\n2. Navigate to the JAVAF Jira project.\n\n3. Click Create to create a ticket. Provide as much information as possible about the issue or request in the ticket.\n\nBug reports in the JAVAF Jira project are publicly viewable.\n\nIf you\u2019ve identified a security vulnerability in any official MongoDB product, you can report it according to the instructions found in the Create a Vulnerability Report page.\n\n### Pull Requests\n\nWe are happy to accept contributions to help improve Spring Session MongoDB. We will guide user contributions to ensure they meet the standards of the codebase. Ensure that any pull requests include documentation, tests, and pass the **gradle** checks.\n\nTo contribute to the integration, run the following commands to check out the source repository and work on a branch:\n\n```bash\ngit clone https://github.com/mongodb/mongo-spring-session.git\ncd mongo-spring-session\ngit checkout -b myNewFeature\n```\n\nThen, ensure that the code passes gradle checks by running the following command:\n\n```bash\n./gradlew clean check\n```\n\n## Compatibility\n\nTo view compatibility information for the MongoDB-maintained Spring Session module, see the compatibility page.\n\n## Additional Information\n\nTo learn more about Spring Session MongoDB, see the following resources:\n\n- Spring Session MongoDB source code\n\n- Spring Session documentation"} -{"chunk_id": "68a95bf65e79d242619d9c27-0", "page_id": "68a95bf65e79d242619d9c27", "source_name": "java", "product_name": "Java Sync Driver", "url": "https://mongodb.com/docs/drivers/java/sync/current/security/socks", "title": "Connect to MongoDB by Using a SOCKS5 Proxy", "text": "# Connect to MongoDB by Using a SOCKS5 Proxy\n\n## Overview\n\nIn this guide, you can learn how to connect to MongoDB by using a SOCKS5 proxy. SOCKS5 is a standardized protocol for communicating with network services through a proxy server.\n\nTo learn more about the SOCKS5 protocol, see the Wikipedia entry on SOCKS.\n\n## SOCKS5 Proxy Settings\n\nThe proxy settings specify the SOCKS5 proxy server address and your authentication credentials. You can specify your settings in an instance of MongoClientSettings or in your connection string.\n\nThe driver ignores the proxy settings if either of the following are true:\n\n- A Unix domain socket handles the communication. For more information, see the UnixServerAddress documentation.\n\n- `TransportSettings` are configured. For more information, see the TransportSettings documentation.\n\nThe following table describes the SOCKS5 client options:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nAccepted Values\n\n\nDescription\n\n
\n**proxyHost**\n\n\nString\n\n\nSpecifies the SOCKS5 proxy IPv4 address, IPv6 address, or hostname. You must provide this value to connect to a SOCKS5 proxy. | | **Default**: `null`\n\n
\n**proxyPort**\n\n\nnon-negative Integer\n\n\nSpecifies the TCP port number of the SOCKS5 proxy server.**Default**: `1080` when you set `proxyHost`\n\n
\n**proxyUsername**\n\n\nString\n\n\nSpecifies the username for authentication to the SOCKS5 proxy server. The driver ignores `null` and empty string values for this setting. The driver requires that you pass values for both `proxyUsername` and `proxyPassword` or that you omit both values. | | **Default**: `null`\n\n
\n**proxyPassword**\n\n\nString\n\n\nSpecifies the password for authentication to the SOCKS5 proxy server. The driver ignores `null` and empty string values for this setting. The driver requires that you pass values for both `proxyUsername` and `proxyPassword` or that you omit both values.\n\n**Default**: `null`\n\n
\n\n## Examples\n\nThe following examples show how to instantiate a `MongoClient` that connects to MongoDB by using a SOCKS5 proxy. The proxy settings can be specified in a `MongoClientSettings` instance or a connection string. These examples use the placeholder values described in the SOCKS5 Proxy Settings section. Replace the placeholders with your proxy settings.\n\n### Specify Proxy Settings in the MongoClientSettings\n\nThe following code example shows how to specify your SOCKS5 proxy settings by using the `MongoClientSettings` builder:\n\n```java\nMongoClient mongoClient = MongoClients.create(\n MongoClientSettings.builder()\n .applyConnectionString(\n new ConnectionString(\"mongodb+srv://myDatabaseUser:myPassword@example.org/\"))\n .applyToSocketSettings(builder ->\n builder.applyToProxySettings(proxyBuilder ->\n proxyBuilder\n .host(\"\")\n .port()\n .username(\"\")\n .password(\"\")\n )\n ).build());\n```\n\n### Specify Proxy Settings in the Connection String\n\nThe following code example shows how to specify your SOCKS5 proxy settings in your connection string:\n\n```java\nString connectionString = \"mongodb+srv://myDatabaseUser:myPassword@example.org/\" +\n \"?proxyHost=\" +\n \"&proxyPort=\" +\n \"&proxyUsername=\" +\n \"&proxyPassword=\";\n\nMongoClient mongoClient = MongoClients.create(connectionString);\n```\n\n### API Documentation\n\nTo learn more about the methods and types discussed in this guide, see the following API documentation:\n\n- MongoClientSettings.Builder\n\n- SocketSettings.Builder\n\n- MongoClients.create()\n\n- ProxySettings.Builder"} -{"chunk_id": "68a95bf65e79d242619d9bd5-0", "page_id": "68a95bf65e79d242619d9bd5", "source_name": "java", "product_name": "Java Sync Driver", "url": "https://mongodb.com/docs/drivers/java/sync/current/connection/specify-connection-options/stable-api", "title": "Stable API", "text": "# Stable API\n\nThe Stable API feature requires MongoDB Server 5.0 or later.\n\nYou should only use the Stable API feature if all the MongoDB servers you are connecting to support this feature.\n\n## Overview\n\nIn this guide, you can learn how to specify the **Stable API** when connecting to a MongoDB instance or replica set. You can use the Stable API feature to force the server to run operations with behavior compatible with the specified **API version**. An API version defines the expected behavior of the operations it covers and the format of server responses. If you change to a different API version, the operations are not guaranteed to be compatible and the server responses are not guaranteed to be similar.\n\nWhen you use the Stable API feature with an official MongoDB driver, you can update your driver or server without worrying about backward compatibility issues of the commands covered by the Stable API.\n\nSee the MongoDB reference page on the Stable API for more information including a list of commands it covers.\n\nThe following sections describe how you can enable the Stable API for your MongoDB client and the options that you can specify.\n\n## Enable the Stable API on a MongoDB Client\n\nTo enable the Stable API, you must specify an API version in the settings of your MongoDB client. Once you instantiate a `MongoClient` instance with a specified API version, all commands you run with that client use that version of the Stable API.\n\nTo run commands that use more than one version of the Stable API, instantiate a separate client with that version.\n\nTo run commands not covered by the Stable API, make sure the \"strict\" option is disabled. See the section on Stable API Options for more information.\n\nThe following example shows how you can instantiate a `MongoClient` that sets the Stable API version and connects to a server by performing the following operations:\n\n- Construct a `ServerApi` instance using the `ServerApi.Builder` helper class.\n\n- Specify a Stable API version using a constant from the `ServerApiVersion` class.\n\n- Construct a `MongoClientSettings` instance using the `MongoClientSettings.Builder` class.\n\n- Specify a server to connect to using a `ServerAddress` instance.\n\n- Instantiate a `MongoClient` using the `MongoClients.create()` method and pass your `MongoClientSettings` instance as a parameter.\n\n```java\nServerApi serverApi = ServerApi.builder()\n .version(ServerApiVersion.V1)\n .build();\n\n// Replace the uri string with your MongoDB deployment's connection string\nString uri = \"\";\n\nMongoClientSettings settings = MongoClientSettings.builder()\n .applyConnectionString(new ConnectionString(uri))\n .serverApi(serverApi)\n .build();\n\nMongoClient client = MongoClients.create(settings);\n```\n\nIf you specify an API version and connect to a MongoDB deployment that does not support the Stable API, your application might raise an exception when executing a command on your MongoDB deployment. If you use a `MongoClient` that specifies the API version to query a server that does not support it, your query can fail with an exception message that includes the following text:\n\n```none\n'Unrecognized field 'apiVersion' on server...\n```\n\nFor more information about the methods and classes referenced in this section, see the following API Documentation:\n\n- ServerApi\n\n- ServerApi.Builder\n\n- ServerApiVersion\n\n- ServerAddress\n\n- MongoClientSettings\n\n- MongoClientSettings.Builder\n\n- MongoClients.create()\n\n- MongoClient\n\n## Stable API Options\n\nYou can enable or disable optional behavior related to the Stable API as described in the following table.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nOption Name\n\n\nDescription\n\n
\nStrict\n\n\n**Optional**. When set, if you call a command that is not part of the declared API version, the driver raises an exception.\n\nDefault: **false**\n\n
\nDeprecationErrors\n\n\n**Optional**. When set, if you call a command that is deprecated in the declared API version, the driver raises an exception.\n\nDefault: **false**\n\n
The following example shows how you can set the two options on an instance of `ServerApi` by chaining methods on the `ServerApi.Builder`:\n\n```java\nServerApi serverApi = ServerApi.builder()\n .version(ServerApiVersion.V1)\n .strict(true)\n .deprecationErrors(true)\n .build();\n```\n\nFor more information about the options in this section, see the following API Documentation:\n\n- strict()\n\n- deprecationErrors()"} -{"chunk_id": "68a95bf65e79d242619d9ba2-0", "page_id": "68a95bf65e79d242619d9ba2", "source_name": "java", "product_name": "Java Sync Driver", "url": "https://mongodb.com/docs/drivers/java/sync/current/crud/query-documents/project", "title": "Specify Which Fields to Return", "text": "# Specify Which Fields to Return\n\n## Overview\n\nIn this guide, you can learn how to control which fields appear in documents returned from read operations with the MongoDB Java driver.\n\nMany read requests require only a subset of fields in a document. For example, when logging a user in you might only need their username, and not all of their profile information. By default, queries in MongoDB return all fields in matching documents. You can use a **projection** to return only the data you need.\n\nA projection is a document that instructs MongoDB which fields of a document to return. Use the Projections class to construct a projection document.\n\n## Behavior\n\nProjections work in two ways:\n\n- Explicitly including fields. This has the side-effect of implicitly excluding all unspecified fields.\n\n- Implicitly excluding fields. This has the side-effect of implicitly including all unspecified fields.\n\nThese two methods of projection are mutually exclusive: if you explicitly include fields, you cannot explicitly exclude fields, and vice versa.\n\nThe `_id` field is **not** subject to these mechanics. You must explicitly exclude the `_id` field if you do not want it returned. You can exclude the `_id` field even if you have specified certain fields to include.\n\n## Explanation\n\nConsider the following collection containing documents that describe varieties of fruit:\n\n```json\n{ \"_id\": 1, \"name\": \"apples\", \"qty\": 5, \"rating\": 3 },\n{ \"_id\": 2, \"name\": \"bananas\", \"qty\": 7, \"rating\": 1 },\n{ \"_id\": 3, \"name\": \"oranges\", \"qty\": 6, \"rating\": 2 },\n{ \"_id\": 4, \"name\": \"avocados\", \"qty\": 3, \"rating\": 5 },\n```\n\nIn the following query, pass the projection to return the `name` field of each document:\n\n```java\n// return all documents with *only* the name field\nBson filter = Filters.empty();\nBson projection = Projections.fields(Projections.include(\"name\"));\ncollection.find(filter).projection(projection).forEach(doc -> System.out.println(doc));\n```\n\nThe projection document specifies that the read operation result should *include* the `name` field of each returned document. As a result, this projection implicitly excludes the `qty` and `rating` fields. Chaining this projection to `find()` with an empty query filter yields the following results:\n\n```json\n{ \"_id\": 1, \"name\": \"apples\" }\n{ \"_id\": 2, \"name\": \"bananas\" }\n{ \"_id\": 3, \"name\": \"oranges\" }\n{ \"_id\": 4, \"name\": \"avocados\" }\n```\n\nDespite the fact that this projection only explicitly included the `name` field, the query returned the `_id` field as well.\n\nThe `_id` field is a special case: it is always included in every query result unless explicitly excluded. That's because the `_id` field is a unique identifier for each document, a property that can be useful when constructing queries.\n\nA `movies` collection is a good example of why this property is useful: because remakes and even separate works sometimes reuse movie titles, you need a unique `_id` value to refer to any specific movie.\n\nThe `_id` is the only exception to the mutually exclusive include-exclude behavior in projections: you *can* explicitly exclude the `_id` field even when explicitly including other fields if you do not want `_id` to be present in returned documents.\n\n```java\n// return all documents with only the name field\nBson filter = Filters.empty();\nBson projection = Projections.fields(Projections.include(\"name\"), Projections.excludeId());\ncollection.find(filter).projection(projection).forEach(doc -> System.out.println(doc));\n```\n\nThe projection document specifies that the read operation result should *include* the `name` field of each returned document, and specifies to *exclude* the `_id` field. As a result, this projection implicitly excludes the `qty` and `rating` fields. Chaining this projection to `find()` with an empty query filter yields the following results:\n\n```javascript\n{ \"name\": \"apples\" }\n{ \"name\": \"bananas\" }\n{ \"name\": \"oranges\" }\n{ \"name\": \"avocados\" }\n```\n\nYou can also specify multiple fields to include in your projection.\n\nThe order in which you specify the fields in the projection does not alter the order in which they are returned.\n\n```java\nBson filter = Filters.empty();\nBson projection = Projections.fields(Projections.include(\"name\", \"rating\"), Projections.excludeId());\ncollection.find(filter).projection(projection).forEach(doc -> System.out.println(doc));\n```\n\nThis example that identifies two fields to include in the projection yields the following results:\n\n```json\n { \"name\": \"apples\", \"rating\": 3 }\n { \"name\": \"bananas\", \"rating\": 1 }\n { \"name\": \"oranges\", \"rating\": 2 }\n { \"name\": \"avocados\", \"rating\": 5 }\n```\n\nFor additional projection examples, see the MongoDB Manual page on Project Fields to Return from Query."} -{"chunk_id": "68a95bf65e79d242619d9bb5-0", "page_id": "68a95bf65e79d242619d9bb5", "source_name": "java", "product_name": "Java Sync Driver", "url": "https://mongodb.com/docs/drivers/java/sync/current/data-formats/codecs", "title": "Encode Data with Type Codecs", "text": "# Encode Data with Type Codecs\n\n## Overview\n\nIn this guide, you can learn about **Codecs** and the supporting classes that handle the encoding and decoding of Java objects to and from BSON data in the MongoDB Java driver. The `Codec` abstraction allows you to map any Java type to a corresponding BSON type. You can use this to map your domain objects directly to and from BSON instead of using an intermediate map-based object such as `Document` or `BsonDocument`.\n\nYou can learn how to specify custom encoding and decoding logic using the `Codec` abstraction and view example implementations in the following sections:\n\n- Codec\n\n- CodecRegistry\n\n- CodecProvider\n\n- Custom Codec Example\n\nIf you are customizing encoding and decoding logic for plain old Java objects (POJOs), read our guide on POJO Customization.\n\n## Codec\n\nThe `Codec` interface contains abstract methods for serializing and deserializing Java objects to BSON data. You can define your conversion logic between BSON and your Java object in your implementation of this interface.\n\nTo implement the `Codec` interface, override the `encode()`, `decode()`, and `getEncoderClass()` abstract methods.\n\nThe `encode()` method requires the following parameters:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nParameter Type\n\n\nDescription\n\n
\n`writer`\n\n\nAn instance of a class that implements `BsonWriter`, an interface type that exposes methods for writing a BSON document. For example, the `BsonBinaryWriter` implementation writes to a binary stream of data. Use this instance to write your BSON value using the appropriate write method.\n\n
\n`value`\n\n\nThe data that your implementation encodes. The type must match the type variable assigned to your implementation.\n\n
\n`encoderContext`\n\n\nContains meta information about the Java object data that it encodes to BSON including whether to store the current value in a MongoDB collection.\n\n
This method uses the `BsonWriter` instance to send the encoded value to MongoDB and does not return a value.\n\nThe `decode()` method returns your Java object instance populated with the value from the BSON data. This method requires the following parameters:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nParameter Type\n\n\nDescription\n\n
\n`bsonReader`\n\n\nAn instance of a class that implements `BsonReader`, an interface type that exposes methods for reading a BSON document. For example, the `BsonBinaryReader` implementation reads from a binary stream of data.\n\n
\n`decoderContext`\n\n\nContains information about the BSON data that it decodes to a Java object.\n\n
The `getEncoderClass()` method returns a class instance of the Java class since Java cannot infer the type due to type erasure.\n\nSee the following code examples that show how you can implement a custom `Codec`.\n\nThe `PowerStatus` enum contains the values \"ON\" and \"OFF\" to represent the states of an electrical switch.\n\n```java\npublic enum PowerStatus {\n ON,\n OFF\n}\n```\n\nThe `PowerStatusCodec` class implements `Codec` in order to convert the Java `enum` values to corresponding BSON boolean values. The `encode()` method converts a `PowerStatus` to a BSON boolean and the `decode()` method performs the conversion in the opposite direction.\n\n```java\npublic class PowerStatusCodec implements Codec {\n\n @Override\n public void encode(BsonWriter writer, PowerStatus value, EncoderContext encoderContext) {\n if (value != null) {\n writer.writeBoolean(value.equals(PowerStatus.ON) ? Boolean.TRUE : Boolean.FALSE);\n }\n }\n\n @Override\n public PowerStatus decode(BsonReader reader, DecoderContext decoderContext) {\n return reader.readBoolean() ? PowerStatus.ON : PowerStatus.OFF;\n }\n\n @Override\n public Class getEncoderClass() {\n return PowerStatus.class;\n }\n}\n```\n\nYou can add an instance of the `PowerStatusCodec` to your `CodecRegistry` which contains a mapping between your `Codec` and the Java object type to which it applies. Continue to the CodecRegistry section of this page to see how you can include your `Codec`.\n\nFor more information about the classes and interfaces in this section, see the following API Documentation:\n\n- Codec\n\n- BsonWriter\n\n- BsonBinaryWriter\n\n- EncoderContext\n\n- BsonReader\n\n- DecoderContext\n\n- BsonBinaryReader\n\n## CodecRegistry\n\nA `CodecRegistry` is an immutable collection of `Codec` instances that encode and decode the Java classes they specify. You can use any of the following `CodecRegistries` class static factory methods to construct a `CodecRegistry` from the `Codec` instances contained in the associated types:\n\n- `fromCodecs()`\n\n- `fromProviders()`\n\n- `fromRegistries()`\n\nThe following code snippet shows how to construct a `CodecRegistry` using the `fromCodecs()` method:\n\n```java\nCodecRegistry codecRegistry = CodecRegistries.fromCodecs(new IntegerCodec(), new PowerStatusCodec());\n```\n\nIn the preceding example, we assign the `CodecRegistry` the following `Codec` implementations:\n\n- `IntegerCodec`, a `Codec` that converts `Integers` and is part of the BSON package.\n\n- PowerStatusCodec, our sample `Codec` that converts certain Java strings to BSON booleans.\n\nYou can retrieve the `Codec` instances from the `CodecRegistry` instance from the prior example using the following code:\n\n```java\nCodec powerStatusCodec = codecRegistry.get(PowerStatus.class);\nCodec integerCodec = codecRegistry.get(Integer.class);\n```\n\nIf you attempt to retrieve a `Codec` instance for a class that is not registered, the `get()` method throws a `CodecConfigurationException` exception.\n\nFor more information about the classes and interfaces in this section, see the following API Documentation:\n\n- CodecRegistries\n\n- IntegerCodec\n\n## CodecProvider\n\nA `CodecProvider` is an interface that contains abstract methods that create `Codec` instances and assign them to a `CodecRegistry` instance. Similar to the `CodecRegistry`, the BSON library uses the `Codec` instances retrieved by the `get()` method to convert between Java and BSON data types.\n\nHowever, in cases in which you add a class that contains fields that require corresponding `Codec` objects, you need to ensure that you instantiate the `Codec` objects for the class fields before you instantiate the `Codec` for the class. You can use the `CodecRegistry` parameter in the `get()` method to pass any of the `Codec` instances that the `Codec` relies on.\n\nThe following code example shows how you can implement `CodecProvider` to pass the `MonolightCodec` any `Codec` instances it needs in a `CodecRegistry` instance such as the `PowerStatusCodec` from our prior example:\n\n```java\npublic class MonolightCodecProvider implements CodecProvider {\n\n public MonolightCodecProvider() {}\n\n @Override\n @SuppressWarnings(\"unchecked\")\n public Codec get(Class clazz, CodecRegistry registry) {\n if (clazz == Monolight.class) {\n return (Codec) new MonolightCodec(registry);\n }\n\n // return null when not a provider for the requested class\n return null;\n }\n\n}\n```\n\nTo see a runnable example that demonstrates read and write operations using these `Codec` classes, see the Custom Codec Example section of this guide.\n\nWhen working with POJOs, consider using the `PojoCodecProvider` to minimize duplicate code to convert commonly-used data types and customize their behavior. See our POJO Customization guide for more information."} -{"chunk_id": "68a95bf65e79d242619d9bb5-1", "page_id": "68a95bf65e79d242619d9bb5", "source_name": "java", "product_name": "Java Sync Driver", "url": "https://mongodb.com/docs/drivers/java/sync/current/data-formats/codecs", "title": "Encode Data with Type Codecs", "text": "### Default Codec Registry\n\nThe default codec registry is a set of `CodecProvider` classes that specify conversion between commonly-used Java and MongoDB types. The driver automatically uses the default codec registry unless you specify a different one.\n\nIf you need to override the behavior of one or more `Codec` classes, but keep the behavior from the default codec registry for the other classes, you can specify all of the registries in order of precedence. For example, suppose you wanted to override the default provider behavior of a `Codec` for enum types with your custom `MyEnumCodec`, you must add it to the registry list prior to the default codec registry as shown in the example below:\n\n```java\nCodecRegistry newRegistry = CodecRegistries.fromRegistries(\n CodecRegistries.fromCodecs(new MyEnumCodec()),\n MongoClientSettings.getDefaultCodecRegistry());\n```\n\nFor more information about the classes and interfaces in this section, see the following API documentation sections:\n\n- CodecProvider\n\n- Default codec registry\n\n## BsonTypeClassMap\n\nThe `BsonTypeClassMap` class contains a recommended mapping between BSON and Java types. You can use this class in your custom `Codec` or `CodecProvider` to help you manage which Java types to decode your BSON types to container classes that implement `Iterable` or `Map` such as the `Document` class.\n\nYou can add or modify the `BsonTypeClassMap` default mapping by passing a `Map` containing new or replacement entries.\n\nThe following code snippet shows how you can retrieve the Java class type that corresponds to the BSON type in the default `BsonTypeClassMap` instance:\n\n```java\nBsonTypeClassMap bsonTypeClassMap = new BsonTypeClassMap();\nClass clazz = bsonTypeClassMap.get(BsonType.ARRAY);\nSystem.out.println(\"Java type: \" + clazz.getName());\n```\n\nThis code outputs the following:\n\n```none\nJava type: java.util.List\n```\n\nYou can modify these mappings in your instance by specifying replacements in the `BsonTypeClassMap` constructor. The following code snippet shows how you can replace the mapping for `ARRAY` in your `BsonTypeClassMap` instance with the `Set` class:\n\n```java\nMap> replacements = new HashMap>();\nreplacements.put(BsonType.ARRAY, Set.class);\nBsonTypeClassMap bsonTypeClassMap = new BsonTypeClassMap(replacements);\n\nClass clazz = bsonTypeClassMap.get(BsonType.ARRAY);\nSystem.out.println(\"Java type: \" + clazz.getName());\n```\n\nThis code outputs the following:\n\n```none\nJava type: java.util.Set\n```\n\nFor a complete list of the default mappings, see the BsonTypeClassMap API Documentation.\n\nFor an example of how the `Document` class uses `BsonTypeClassMap`, see the driver source code for the following classes:\n\n- DocumentCodecProvider\n\n- DocumentCodec"} -{"chunk_id": "68a95bf65e79d242619d9bb5-2", "page_id": "68a95bf65e79d242619d9bb5", "source_name": "java", "product_name": "Java Sync Driver", "url": "https://mongodb.com/docs/drivers/java/sync/current/data-formats/codecs", "title": "Encode Data with Type Codecs", "text": "## Custom Codec Example\n\nIn this section, we show how you can implement `Codec` and `CodecProvider` to define the encoding and decoding logic for a custom Java class. We also show how you can specify and use your custom implementations to perform insert and retrieve operations.\n\nThe following code snippet shows our example custom class called `Monolight` and its fields that we want to store and retrieve from a MongoDB collection:\n\n```java\npublic class Monolight {\n private PowerStatus powerStatus = PowerStatus.OFF;\n private Integer colorTemperature;\n\n public Monolight() {}\n\n // ...\n```\n\nThis class contains the following fields, each of which we need to assign a `Codec`:\n\n- `powerStatus` describes whether the light is switched \"on\" or \"off\" for which we use the PowerStatusCodec that converts specific enum values to BSON booleans.\n\n- `colorTemperature` describes the color of the light and contains an `Integer` value for which we use the `IntegerCodec` included in the BSON library.\n\nThe following code example shows how we can implement a `Codec` for the `Monolight` class. Note that the constructor expects an instance of `CodecRegistry` from which it retrieves the `Codec` instances it needs to encode and decode its fields:\n\n```java\npublic class MonolightCodec implements Codec{\n\n private Codec powerStatusCodec;\n private Codec integerCodec;\n\n public MonolightCodec(CodecRegistry registry) {\n this.powerStatusCodec = registry.get(PowerStatus.class);\n this.integerCodec = registry.get(Integer.class);\n }\n\n // Defines an encode() method to convert Monolight enum values to BSON values\n @Override\n public void encode(BsonWriter writer, Monolight value, EncoderContext encoderContext) {\n writer.writeStartDocument();\n writer.writeName(\"powerStatus\");\n powerStatusCodec.encode(writer, value.getPowerStatus(), encoderContext);\n writer.writeName(\"colorTemperature\");\n integerCodec.encode(writer, value.getColorTemperature(), encoderContext);\n writer.writeEndDocument();\n }\n\n // Defines a decode() method to convert BSON values to Monolight enum values\n @Override\n public Monolight decode(BsonReader reader, DecoderContext decoderContext) {\n Monolight monolight = new Monolight();\n\n reader.readStartDocument();\n while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) {\n String fieldName = reader.readName();\n if (fieldName.equals(\"powerStatus\")) {\n monolight.setPowerStatus(powerStatusCodec.decode(reader, decoderContext));\n } else if (fieldName.equals(\"colorTemperature\")) {\n monolight.setColorTemperature(integerCodec.decode(reader, decoderContext));\n } else if (fieldName.equals(\"_id\")){\n reader.readObjectId();\n }\n }\n reader.readEndDocument();\n\n return monolight;\n }\n\n // Returns an instance of the Monolight class, since Java cannot infer the class type\n @Override\n public Class getEncoderClass() {\n return Monolight.class;\n }\n\n}\n```\n\nTo ensure we make the `Codec` instances for the fields available for `Monolight`, we implement a custom `CodecProvider` shown in the following code example:\n\n```java\npublic class MonolightCodecProvider implements CodecProvider {\n\n public MonolightCodecProvider() {}\n\n @Override\n @SuppressWarnings(\"unchecked\")\n public Codec get(Class clazz, CodecRegistry registry) {\n if (clazz == Monolight.class) {\n return (Codec) new MonolightCodec(registry);\n }\n\n // return null when not a provider for the requested class\n return null;\n }\n\n}\n```\n\nAfter defining the conversion logic, we can perform the following:\n\n- Store data from instances of `Monolight` into MongoDB\n\n- Retrieve data from MongoDB into instances of `Monolight`\n\nThe following example class contains code that assigns the `MonolightCodecProvider` to the `MongoCollection` instance by passing it to the `withCodecRegistry()` method. The example class also inserts and retrieves data using the `Monolight` class and associated codecs:\n\n```java\npublic class MonolightCodecExample {\n\n public static void main(String[] args) {\n\n String uri = \"\";\n\n try (MongoClient mongoClient = MongoClients.create(uri)) {\n CodecRegistry codecRegistry = CodecRegistries.fromRegistries(\n CodecRegistries.fromCodecs(new IntegerCodec(), new PowerStatusCodec()),\n CodecRegistries.fromProviders(new MonolightCodecProvider()),\n MongoClientSettings.getDefaultCodecRegistry());\n\n MongoDatabase database = mongoClient.getDatabase(\"codecs_example_products\");\n MongoCollection collection = database.getCollection(\"monolights\", Monolight.class).withCodecRegistry(codecRegistry);\n\n // construct and insert an instance of Monolight\n Monolight myMonolight = new Monolight();\n myMonolight.setPowerStatus(PowerStatus.ON);\n myMonolight.setColorTemperature(5200);\n collection.insertOne(myMonolight);\n\n // retrieve one or more instances of Monolight\n List lights = new ArrayList<>();\n collection.find().into(lights);\n System.out.println(lights);\n }\n }\n\n}\n```\n\nIf you run the preceding example, you should see the following output:\n\n```none\n[Monolight [powerStatus=ON, colorTemperature=5200]]\n```\n\nFor more information about the methods and classes mentioned in this section, see the following API Documentation:\n\n- withCodecRegistry()\n\n- MongoClientSettings.getDefaultCodecRegistry()\n\n- Codec\n\n- CodecProvider"} -{"chunk_id": "68a95c375e79d242619e0f19-0", "page_id": "68a95c375e79d242619e0f19", "source_name": "java-rs", "product_name": "Java Reactive Streams Driver", "url": "https://mongodb.com/docs/languages/java/reactive-streams-driver/current/getting-started", "title": "Get Started", "text": "# Get Started\n\n## Overview\n\nThe Java Reactive Streams driver is an asynchronous API that you can use to connect to and communicate with MongoDB. This guide shows you how to create an application that uses the Java Reactive Streams driver to connect to a MongoDB cluster hosted on MongoDB Atlas.\n\nMongoDB Atlas is a fully managed cloud database service that hosts your MongoDB deployments. You can create your own free (no credit card required) MongoDB Atlas deployment by following the steps in this guide.\n\nFollow this guide to connect a sample Java Reactive Streams application to a MongoDB Atlas deployment. If you prefer to connect to MongoDB using a different driver or programming language, see our list of official drivers."} -{"chunk_id": "6a514d65d727379c91b9d7df-0", "page_id": "6a514d65d727379c91b9d7df", "source_name": "java-rs", "product_name": "Java Reactive Streams Driver", "url": "https://mongodb.com/docs/languages/java/reactive-streams-driver/current/reference/release-notes", "title": "Release Notes", "text": "# Release Notes\n\nLearn about new features, improvements, and fixes introduced in the following versions of the MongoDB Java Reactive Streams Driver:\n\n- Version 5.13\n\n- Version 5.12\n\n- Version 5.11.1\n\n- Version 5.11\n\n- Version 5.10\n\n- Version 5.9.2\n\n- Version 5.9\n\n- Version 5.8.1\n\n- Version 5.8\n\n- Version 5.7.1\n\n- Version 5.7\n\n- Version 5.6\n\n- Version 5.5.1\n\n- Version 5.5\n\n- Version 5.4\n\n- Version 5.3\n\n- Version 5.2\n\n- Version 5.1.3\n\n- Version 5.1.2\n\n- Version 5.1.1\n\n- Version 5.1\n\n## What's New in 5.13\n\nThe 5.13 driver release includes the following changes, fixes, and features:\n\nSpecify Connection URI Options\n\n- Adds the `srvAllowedHostsSuffix` option, which you can set in your connection string or by using the `ClusterSettings.Builder.srvAllowedHostsSuffix()` method. This option sets the hostname suffix that the driver uses to validate hosts returned by an SRV lookup. To learn more about this option, see Specify Connection URI Options.\n\nTo learn more about this release, see the v5.13 Release Notes on GitHub.\n\n## What's New in 5.12\n\nThe 5.12 driver release includes the following changes, fixes, and features:\n\n- Adds support for MongoDB 9.0's Intelligent Workload Management (IWM). The driver now gracefully handles write-blocking scenarios and optimizes connection establishment during high-load conditions to maintain application availability. This feature includes the following changes:\n\n - Adds the `MongoClientSettings.Builder.maxAdaptiveRetries()` method and the `maxAdaptiveRetries` connection string option, which configure the maximum number of retry attempts for commands that fail with a retryable overload error.\n\n - Adds the `MongoClientSettings.Builder.enableOverloadRetargeting()` method and the `enableOverloadRetargeting` connection string option, which control whether retries of commands that fail with an error that has the `SystemOverloadedError` label attempt to use a different server. The default value is `false`. This setting has no effect on sharded clusters.\n\n - Adds the `MongoException.SYSTEM_OVERLOADED_ERROR_LABEL` and `MongoException.RETRYABLE_ERROR_LABEL` constants. A retryable overload error carries both labels. If you don't upgrade your driver version, or if you implement custom retry logic, you might need to update error-handling code to account for new errors related to overloaded servers. Use these constants to identify and handle those errors.\n\n This feature requires MongoDB 9.0 or later. To learn more about IWM, see Write-Blocking in the Atlas documentation.\n\nTo learn more about this release, see the v5.12 Release Notes on GitHub.\n\n## What's New in 5.11.1\n\nThe Java Reactive Streams driver 5.11.1 includes fixes for the following CVEs:\n\n- CVE-2026-88032\n\n- CVE-2026-88033\n\nFor the latest information about MongoDB security updates, see MongoDB Security Bulletins.\n\nTo learn more about this release, see the v5.11.1 Release Notes on GitHub.\n\n## What's New in 5.11\n\nThe 5.11 driver release does not include any changes, fixes, or features that apply to the Java Reactive Streams driver.\n\nTo learn more about this release, see the v5.11 Release Notes on GitHub.\n\n## What's New in 5.10\n\nThe 5.10 driver release includes the following changes, fixes, and features:\n\n- Adds the `$scoreFusion` aggregation stage, which combines and normalizes the scores of multiple search pipelines. This stage requires MongoDB 8.2 or later.\n\n- Adds a fluent builder API for the `$score` aggregation stage. Use this API to configure score normalization, weighting, and score details. This feature requires MongoDB 8.2 or later.\n\n- Adds the `parentFilter` and `nestedOptions` options, which allow nested embeddings and arrays of embeddings in `$vectorSearch` queries.\n\nTo learn more about this release, see the v5.10 Release Notes on GitHub.\n\n## What's New in 5.9.2\n\nThe 5.9.2 driver patch release includes the following changes:\n\n- Fixes an issue where `ProxySettings.toString()` included the SOCKS5 proxy username and password, which caused these credentials to appear in application logs. This issue affects driver versions 4.11.0 through 5.9.1. To learn more, see JAVA-6266 and CVE-2026-18710.\n\nIf you use SOCKS5 proxy authentication and can't upgrade to v5.9.2, set the `org.mongodb.driver.client` logger to `WARN` or higher to suppress the client-construction message. We don't recommend this as a long-term measure, because it silences diagnostic information that is valuable for support and it doesn't remove credentials that are already written to existing logs.\n\nTo learn more about this release, see the v5.9.2 Release Notes on GitHub.\n\n## What's New in 5.9\n\nThe 5.9 driver release includes the following changes, fixes, and features:\n\n- Fixes a bug where the `MongoClient.getTimeout()` method always returned `null`.\n\nIn-Use Encryption\n\n- Promotes Queryable Encryption (QE) prefix, suffix, and substring queries to general availability (GA). These query types are supported on MongoDB 9.0 and later. To learn more about QE, see In-Use Encryption.\n\n- Renames the explicit encryption API for QE string queries from `Text` to `String`. To perform a QE string query, make the following changes:\n\n - Use the `StringOptions` class instead of `TextOptions`.\n\n - Use the `EncryptOptions.stringOptions()` method instead of `textOptions()`.\n\n - Use the `EncryptOptions.getStringOptions()` method instead of `getTextOptions()`.\n\n - Set the encryption algorithm to `\"String\"`.\n\n- Upgrades the `libmongocrypt` version to 1.20.0.\n\nTo learn more about this release, see the v5.9 Release Notes on GitHub.\n\n## What's New in 5.8.1\n\nThe 5.8.1 driver patch release includes the following changes:\n\n- Fixes a bug where the `MongoClient.getTimeout()` method always returned `null`.\n\nTo learn more about this release, see the v5.8.1 Release Notes on GitHub.\n\n## What's New in 5.8\n\nThe 5.8 driver release includes the following changes, fixes, and features:\n\n- Adds a typed builder API for vector search index definitions.\n\n- Adds support for the `$rerank` aggregation stage. When connected to an Atlas cluster running MongoDB 8.3 or later, you can use the `Aggregates.rerank()` builder method to create this stage.\n\n- Adds support for the `vectorSearch` operator in a `$search` pipeline stage. You can use the `SearchOperator.vectorSearch()` builder method to perform approximate nearest neighbor (ANN) vector search, or `SearchOperator.vectorSearchExact()` for exact nearest neighbor (ENN) search. The returned `VectorSearchOperator` supports a `filter()` method to apply lexical prefilters.\n\n- Adds support for configuring stored source on vector search index definitions by using the `storedSource()` method in the `VectorSearchIndexDefinition` class.\n\n- Adds support for requesting stored source fields in `$vectorSearch` results by using the `returnStoredSource()` method in the `VectorSearchOptions` class.\n\n- Optimizes `RawBsonDocument` encode and decode performance by eliminating intermediate allocations.\n\n- Fixes an OSGi bundle resolution failure when Micrometer is not present.\n\n- Adds Javadoc documentation to the `MongodbObservation` and `MongodbObservationContext` classes.\n\n- Upgrades the `libmongocrypt` version to 1.18.1.\n\nTo learn more about this release, see the v5.8 Release Notes on GitHub.\n\n## What's New in 5.7.1\n\nThe 5.7.1 driver patch release includes the following changes:\n\n- Fixes Javadoc warnings in the Micrometer integration.\n\n- Marks Micrometer OSGi imports as optional to resolve bundle resolution issues in OSGi runtime environments.\n\nTo learn more about this release, see the v5.7.1 Release Notes on GitHub."} -{"chunk_id": "6a514d65d727379c91b9d7df-1", "page_id": "6a514d65d727379c91b9d7df", "source_name": "java-rs", "product_name": "Java Reactive Streams Driver", "url": "https://mongodb.com/docs/languages/java/reactive-streams-driver/current/reference/release-notes", "title": "Release Notes", "text": "## What's New in 5.7\n\nThe 5.7 driver release includes the following changes, fixes, and features:\n\n- Updates the `commitTransaction()` and `abortTransaction()` methods to return cold publishers. As a result, these methods do not run until you subscribe to the returned publisher.\n\n- Important: An upcoming minor release will drop support for MongoDB Server version 4.2 and raise the minimum supported version to 4.4. This change aligns with the MongoDB Software Lifecycle Schedules.\n\n We recommend making changes to your application to accommodate breaking changes. To learn more about upgrading your server version, see the Release Notes section in the MongoDB Server manual.\n\n- Adds Scala 3 support.\n\n- Adds auto-embedding support as part of vector search APIs.\n\n- Adds Micrometer/OpenTelemetry tracing support to the reactive-streams driver, and includes general Micrometer support improvements.\n\n- Adds stack-safe async loop support with trampoline pattern to prevent stack overflow errors.\n\n- Improves client-side timeout handling to better account for round-trip time (RTT) variations, along with various small timeout-related improvements.\n\n- Reuses `ConnectionSource` to avoid extra server selection.\n\n- Restores the optimized codec path for `RawBsonDocument` encoding, fixing a performance regression.\n\n- Releases the connection between empty `getMore` responses in `AsyncCommandCursor`, preventing connection pool exhaustion when idle change streams reach `maxPoolSize`.\n\n- The encryption client now uses `writeConcern` majority.\n\n- Handles unexpected end-of-stream errors from KMS.\n\n- Fixes `JsonBsonEncoder` parsing of `JsonPrimitive` numbers, where scientifically formatted numbers were parsed as plain Ints or Longs.\n\n- Simplifies `ServerMonitor` thread names and removes the `=` character, which some monitoring systems cannot process.\n\n- Fixes Kotlin BSON decoding of optionals.\n\n- Upgrades `libmongocrypt` to 1.17.3.\n\n- Uses `ZstdInputStreamNoFinalizer` for Zstandard decompression.\n\n- Updates Netty to the latest version.\n\n- Updates Snappy for the latest security fixes.\n\n- Updates JUnit 5 to the latest version.\n\n- Aligns the log level to warning when removing a server from the cluster.\n\n## What's New in 5.6\n\nThe 5.6 driver release includes the following changes, fixes, and features:\n\nIn-Use Encryption\n\n- Adds experimental support for Queryable Encryption prefix, suffix, and substring queries. To learn more about QE, see In-Use Encryption.\n\n Queryable Encryption prefix, suffix, and substring queries are unstable, and their security is not guaranteed until they're generally available (GA). Use them in experimental workloads only.\n\n- Adds an `nsType` field to `ChangeStreamDocument` objects. This field contains the namespace type (`COLLECTION`, `TIMESERIES`, or `VIEW`) of the change event.\n\n- Adds experimental client-side operation timeout (CSOT) support for OIDC authentication.\n\n The CSOT feature is experimental and might change in future driver releases.\n\n- When `timeoutMS` is set for CSOT, the driver ignores the value of the `maxWaitTime` connection setting.\n\n- Adds an `appendMetadata()` method to the `MongoClient` class. You can use this method to append metadata to an existing client's metadata. The maximum metadata size is 512 MB.\n\n- Adds a public constructor to the `RewrapManyDataKeyOptions` class.\n\n- Merges the `AsyncReadOperation` and `AsyncWriteOperation` interfaces into the `ReadOperation` and `WriteOperation` interfaces. You can create read and write operations by using builder methods in the `Operations` class.\n\n- Deprecates the `MongoNamespace.COMMAND_COLLECTION_NAME` constant.\n\n- Fixes a bug that prevented OIDC reauthentication within a session.\n\n- When serializing a POJO annotated with `@BsonDiscriminator`, if the property's `readName` matches the discriminator key, the driver serializes the field only once.\n\n- After you call the `next()` or `tryNext()` method on a `CommandCursorResult` instance, the driver clears the `CommandCursorResult.results` property to free memory.\n\n- The `PojoBuilderHelper` class creates property models that include properties from abstract classes and interfaces.\n\n- The driver publishes and logs the following events when the cluster topology changes:\n\n - `ClusterOpeningEvent`: Published when the topology opens\n\n - `ClusterDescriptionChangedEvent`: Published when the topology description changes\n\n - `ClusterClosedEvent`: Published when the topology closes\n\n- The driver throws a `MongoStalePrimaryException` when the primary replica set member becomes stale for one of the following reasons:\n\n - A new primary member is elected or discovered.\n\n - The value of the `electionId` or `setVersion` field in the primary member doesn't match the values of these fields in the other replica set members.\n\n To learn more about replica sets, see Replication in the MongoDB Server manual.\n\n## What's New in 5.5.1\n\nThe 5.5.1 driver patch release includes the following changes:\n\n- Fixes an issue where OIDC reauthentication failed when triggered by an operation run in a session, including operations run in a transaction.\n\n## What's New in 5.5\n\nJava Reactive Streams driver v5.5 removes support for MongoDB Server 4.0. To learn more about compatible versions of the server, see Compatibility.\n\nThe 5.5 driver release includes the following changes, fixes, and features:\n\n- Adds support for the `connectTimeoutMS` option when using the default Java Reactive Streams TLS transport layer.\n\n- Introduces performance improvements that are reflected in the driver performance benchmarks. To view the results of the performance benchmark tests, see the following Performance Improvements section."} -{"chunk_id": "6a514d65d727379c91b9d7df-2", "page_id": "6a514d65d727379c91b9d7df", "source_name": "java-rs", "product_name": "Java Reactive Streams Driver", "url": "https://mongodb.com/docs/languages/java/reactive-streams-driver/current/reference/release-notes", "title": "Release Notes", "text": "### Performance Improvements\n\nThe tables in this section show the results of performance tests for the synchronous Java driver. The tests were conducted on a MongoDB Server 8.0 deployment with the following configuration:\n\n- Running on `localhost` with negligible network latency. In higher-latency environments, you might see less significant performance improvements.\n\n- Authentication disabled.\n\n- TLS disabled.\n\nWe expect similar performance increases for all MongoDB Java drivers because they share the improved `driver-core` API.\n\n#### Standard Transport Settings\n\nThe following table shows the results of performance tests for v5.5 of the driver configured with standard transport settings. Each row includes the feature tested, the percent improvement in performance, and the z-score.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nFeature\n\n\nPercent Improvement\n\n\nZ-score\n\n
\nDeep BSON decoding\n\n\n19.44%\n\n\n5.4\n\n
\nDeep BSON encoding\n\n\n102%\n\n\n22.8\n\n
\nFind many and empty the cursor\n\n\n25.08%\n\n\n13.72\n\n
\nFind one by ID\n\n\n2.7%\n\n\n3.16\n\n
\nFlat BSON decoding\n\n\n31.2%\n\n\n9.38\n\n
\nFlat BSON encoding\n\n\n199.5%\n\n\n12.34\n\n
\nFull BSON decoding\n\n\n16.5%\n\n\n7.23\n\n
\nFull BSON encoding\n\n\n147.3%\n\n\n10.39\n\n
\nJSON-LD multi-file import\n\n\n21.8%\n\n\n8.21\n\n
\nClient bulk insert with large documents\n\n\n91.3%\n\n\n24.44\n\n
\nCollection bulk insert with large documents\n\n\n96.5%\n\n\n8.79\n\n
\nBulk insert with large documents\n\n\n93.3%\n\n\n8.11\n\n
\nBulk insert with small documents\n\n\n39.3%\n\n\n5.72\n\n
\nInsert one with large documents\n\n\n82.4%\n\n\n7.28\n\n
\nClient bulk insert with small documents\n\n\n49.5%\n\n\n17.99\n\n
\nCollection bulk insert with small documents\n\n\n47.8%\n\n\n6.44\n\n
\n\n#### Netty Transport Settings\n\nThe following table shows the results of performance tests for v5.5 of the driver configured with Netty transport settings. Each row includes the feature tested, the percent improvement in performance, and the z-score.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nFeature\n\n\nPercent Improvement\n\n\nZ-score\n\n
\nFind many and empty the cursor\n\n\n40.3%\n\n\n14.81\n\n
\nFind one by ID\n\n\n4.4%\n\n\n4.12\n\n
\nJSON-LD multi-file import\n\n\n16.9%\n\n\n3.77\n\n
\nClient bulk insert with large documents\n\n\n54.8%\n\n\n14.49\n\n
\nCollection bulk insert with large documents\n\n\n104.9%\n\n\n38.72\n\n
\nBulk insert with large documents\n\n\n74.6%\n\n\n65.55\n\n
\nInsert one with large documents\n\n\n66.6%\n\n\n58.65\n\n
\nClient bulk insert with small documents\n\n\n36.1%\n\n\n15.41\n\n
\nCollection bulk insert with small documents\n\n\n39.3%\n\n\n37.38\n\n
\nBulk insert with small documents\n\n\n35.1%\n\n\n41.51\n\n
To learn more about how we conduct driver performance benchmark tests, see the Performance Benchmarking specification.\n\n## What's New in 5.4\n\nThe 5.4 driver release includes the following changes, fixes, and features:\n\nthe Add the Driver Bill of Materials step of the Download and Install tutorial\n\nthe Update Operations and Replace Operations sections of the Bulk Write Operations guide\n\nthe MONGODB-OIDC: Kubernetes section of the Enterprise Authentication Mechanisms guide\n\nthe MongoDB Search section of the Aggregation guide\n\n- Supports `$lookup` operations for CSFLE and QE. To learn more, see the following references in the Server manual:\n\n - $lookup and $graphLookup Behavior for CSFLE\n\n - $lookup and $graphLookup Behavior for QE\n\n- Introduces a Bill of Materials (BOM) to manage versions of MongoDB JVM artifacts that you might use in your application. To view instructions on adding the BOM to your application, see the Add the Driver Bill of Materials step of the Download and Install tutorial.\n\n- Updates AWS SDK dependencies to 2.30.31 and 1.12.782 for testing the `MONGODB-AWS` authentication mechanism.\n\n- Adds a sort option to the `ClientUpdateOneOptions` and `ClientReplaceOneOptions` classes. This change allows you to set a sort order for update and replace operations in client bulk writes. To learn more, see the Update Operations and Replace Operations sections of the Bulk Write Operations guide.\n\n- Adds Kubernetes support for OIDC authentication. To learn more, see the MONGODB-OIDC: Kubernetes section of the Enterprise Authentication Mechanisms guide.\n\n- Adds first class support for the following MongoDB Search query operators:\n\n - `phrase`\n\n - `regex`\n\n - `queryString`\n\n - `equals`\n\n - `moreLikeThis`\n\n - `in`\n\n - `wildcard`\n\n To learn more, see the MongoDB Search section of the Aggregation guide.\n\n- Updates cursors to refresh the `timeoutMS` setting when you call `close()` without affecting the operation timeout.\n\n- Enables you to use an index when calling the `distinct()` method by specifying a `hint` option.\n\nTo view a full list of changes in this release, see the v5.4 release notes on GitHub."} -{"chunk_id": "6a514d65d727379c91b9d7df-3", "page_id": "6a514d65d727379c91b9d7df", "source_name": "java-rs", "product_name": "Java Reactive Streams Driver", "url": "https://mongodb.com/docs/languages/java/reactive-streams-driver/current/reference/release-notes", "title": "Release Notes", "text": "## What's New in 5.3\n\nThe 5.3 driver release includes the following changes, fixes, and features:\n\nTo learn about this type, see the BinaryVector API documentation.\n\nthe Update Documents, Replace Documents, and Bulk Write Operations guides\n\n- Important: The next minor release will drop support for MongoDB Server version 4.0 and raise the minimum supported version to 4.2. We recommend making changes to your application to accommodate breaking changes. See the Release Notes section in the Server manual to learn more about upgrading.\n\n- Adds the `BinaryVector` class to implement BSON Binary Subtype 9 for vector storage and retrieval. This class provides more effective storage of values compared a list of `Double` instances. You can create the following vector types based on the type of elements your vector contains:\n\n - `Int8BinaryVector`: Vector of 8-bit signed integers\n\n - `Float32BinaryVector`: Vector of floating-point numbers\n\n - `PackedBitBinaryVector`: Binary quantized vector *(In beta and subject to change before becoming generally available)*\n\n To learn more about this feature, see Vector Quantization in the Atlas documentation. To learn about this type, see the BinaryVector API documentation.\n\n- Removes explicit fairness from the connection pool implementation. This change might contribute to better throughput when you use a `MongoClient` instance in many application threads. However, this change might cause increased tail latency.\n\n- Adds a sort option to the `updateOne()` and `replaceOne()` methods. This change also allows you to set a sort as an option when creating `ReplaceOneModel` and `UpdateOneModel` instances. To learn more, see the Update Documents, Replace Documents, and Bulk Write Operations guides.\n\n- Implements a *client* bulk write API that allows you to perform write operations on multiple databases and collections in the same call. To learn more about this feature, see the Client Bulk Write section of the Bulk Operations guide.\n\n## What's New in 5.2\n\nJava Reactive Streams driver v5.2 removes support for MongoDB Server 3.6. To learn more about compatible versions of the server, see Compatibility.\n\nThe 5.2 driver release includes the following changes, fixes, and features:\n\nthe SearchIndexModel API documentation\n\nthe In-Use Encryption guide\n\nthe MongoDB Vector Search Quick Start\n\nthe Limit Server Execution Time guide\n\n- Enables setting a client-side operations timeout (CSOT). This feature allows you to set a single timeout on your `MongoClient` instance that applies to all operations performed with that client. To learn more, see the Limit Server Execution Time guide.\n\n If, and only if, the CSOT feature is enabled, the following timeout options are ignored by the driver:\n\n - `waitQueueTimeoutMS`\n\n - `socketTimeoutMS`\n\n - `wTimeoutMS`\n\n - `maxTimeMS`\n\n - `maxCommitTimeMS`\n\n CSOT is an **experimental** feature and not yet production ready. This feature is optional in the current release and existing timeout options remain functional.\n\n- Adds the `SearchIndexType` class, which you can pass when constructing a `SearchIndexModel` instance. This change allows you to specify the index type when creating an Atlas Search or Vector Search index. To learn more, see the SearchIndexModel API documentation.\n\n- Delegates the implementation of the algorithms that implement the `SCRAM-SHA-1` and `SCRAM-SHA-256` authentication mechanisms to the configured JCA provider. This change means that your application can use a configured FIPS-compliant JCA provider to provide a higher level of security.\n\n- Revises the mongodb-crypt dependency versioning to match the versioning for the JVM drivers. Future versions of `mongodb-crypt` will be released alongside the driver and will share the same version number. You must upgrade your `mongodb-crypt` dependency to v5.2.0 when upgrading your driver for this release. To learn more, see the In-Use Encryption guide.\n\n- Performance improvements due to implementation of native cryptography on all supported platforms. The following list describes the actions needed to implement this improvement depending on your operating system:\n\n - **Windows**: Upgrade your `mongodb-crypt` version to v5.2.0.\n\n - **Mac**: Upgrade your `mongodb-crypt` version to v5.2.0.\n\n - **Linux**: Install `libmongocrypt.so` directly on the file system, instead of using the file that is bundled within the `mongodb-crypt` JAR file. You can find Linux instructions to install `libmongocrypt` in the Server manual. If you use a package manager to install `libmongocrypt`, Java Native Access (JNA) will find it there without further configuration. Alternatively, you can specify the search path by setting the `LD_LIBRARY_PATH` environment variable to the file path of the `libmongocrypt` package.\n\n We recommend direct installation because the bundled shared library does not link with OpenSSL due to the potential for OpenSSL binary incompatibilities.\n\n The shared library loading is handled by JNA. You can view the rules for library loading search path order in the NativeLibrary class documentation.\n\n- Fixes an issue that caused the `InsertOneResult.getInsertedId()` and `InsertManyResult.getInsertedIds()` methods to return incorrect document IDs in some situations. This change is backported to Java Reactive Streams driver v5.1.4 and v4.11.4.\n\n- When a sharded cluster operation is unsuccessful, the driver avoids selecting the same `mongos` server for operation retry attempts if other `mongos` servers are available.\n\n- Adds reachability metadata needed when your application uses GraalVM Native Image. This metadata replaces the need for collecting reachability metadata when using the driver libraries. To learn more, see Reachability Metadata in the GraalVM documentation.\n\n This change does not add the `libjnidispatch` and `libmongocrypt` resource entries, because adding entries for all supported platforms (targets) significantly affects the size of native executables built using GraalVM Native Image. View this sample resource-config.json file in the driver GitHub repository to see how to specify these entries explicitly if your application depends on the `org.mongodb:mongodb-crypt` library.\n\n- Enables exact vector search by extending the `VectorSearchOptions` API to introduce the following specific option subtypes:\n\n - `ExactVectorSearchOptions`: Use this options type to enable precise matching, ensuring that results are the closest vectors to a given query vector.\n\n - `ApproximateVectorSearchOptions`: Use this options type to enable searches that might not return the exact closest vectors. You can pass a `numCandidates` parameter when instantiating this type to specify the number of nearest neighbors to consider.\n\n To learn more about using the MongoDB Vector Search feature, see the MongoDB Vector Search Quick Start.\n\n## What's New in 5.1.3\n\nThe 5.1.3 driver patch release includes the following changes:\n\n- Fixes an issue that could cause assertion errors when using `Cursor` types.\n\n## What's New in 5.1.2\n\nThe 5.1.2 driver patch release includes the following changes:\n\n- Fixes an issue that prevents the driver from encoding and decoding concrete classes that extend generic base classes, in cases that you specify the base class as the generic type of the `MongoCollection` instance.\n\n## What's New in 5.1.1\n\nThe 5.1.1 driver patch release includes the following changes:\n\n- When using the `MONGODB-OIDC` authentication mechanism, you must not include comma characters in the `authMechanismProperties` connection string value.\n\n## What's New in 5.1\n\nSupport for MongoDB Server v3.6 is deprecated in this release and will be removed in the v5.2 release of the driver.\n\nTo learn about other changes introduced in v5.1, see the What's New guide in the Java Sync Driver documentation."} -{"chunk_id": "68a95c375e79d242619e0f63-0", "page_id": "68a95c375e79d242619e0f63", "source_name": "java-rs", "product_name": "Java Reactive Streams Driver", "url": "https://mongodb.com/docs/languages/java/reactive-streams-driver/current/security/encrypt", "title": "In-Use Encryption", "text": "Version 8.2.0 of `mongocryptd` might not run on Windows. This bug affects In-Use Encryption with the driver if you specify the `--logpath NUL` argument when starting `mongocryptd`.\n\nTo learn more about this issue and how to resolve it, see Known Issues in the MongoDB 8.2 Release Notes.\n\nThe Java Reactive Streams driver uses the mongodb-crypt encryption library for in-use encryption. This driver version is compatible with `mongodb-crypt` v5.13.0.\n\nAdd the Driver Bill of Materials step of the Download and Install guide.\n\nWe recommend adding the JVM driver Bill of Materials (BOM) to your application to manage the versions of driver artifacts. This removes the need to specify a version for any individual package covered by the BOM, simplifying dependency management. To learn more, see the Add the Driver Bill of Materials step of the Download and Install guide.\n\nSelect from the following Maven and Gradle tabs to see how to add the `mongodb-crypt` dependency to your project by using the specified manager:\n\n\n\n\n\n```xml\n\n \n org.mongodb\n mongodb-crypt\n \n\n```\n\n\n\n\n\n```groovy\ndependencies {\n implementation 'org.mongodb:mongodb-crypt'\n}\n```\n\n\n\n\n\n# In-Use Encryption\n\n## Overview\n\nYou can use the Java Reactive Streams driver to encrypt specific document fields by using a set of features called **in-use encryption**. In-use encryption allows your application to encrypt data *before* sending it to MongoDB and query documents with encrypted fields.\n\nVersion 8.2.0 of `mongocryptd` might not run on Windows. This bug affects In-Use Encryption with the driver if you specify the `--logpath NUL` argument when starting `mongocryptd`.\n\nTo learn more about this issue and how to resolve it, see Known Issues in the MongoDB 8.2 Release Notes.\n\nThe Java Reactive Streams driver uses the mongodb-crypt encryption library for in-use encryption. This driver version is compatible with `mongodb-crypt` v5.13.0.\n\nAdd the Driver Bill of Materials step of the Download and Install guide.\n\nWe recommend adding the JVM driver Bill of Materials (BOM) to your application to manage the versions of driver artifacts. This removes the need to specify a version for any individual package covered by the BOM, simplifying dependency management. To learn more, see the Add the Driver Bill of Materials step of the Download and Install guide.\n\nSelect from the following Maven and Gradle tabs to see how to add the `mongodb-crypt` dependency to your project by using the specified manager:\n\n\n\n\n\n```xml\n\n \n org.mongodb\n mongodb-crypt\n \n\n```\n\n\n\n\n\n```groovy\ndependencies {\n implementation 'org.mongodb:mongodb-crypt'\n}\n```\n\n\n\n\n\nIn-use encryption prevents unauthorized users from viewing plaintext data as it is sent to MongoDB or while it is in an encrypted database. To enable in-use encryption in an application and authorize it to decrypt data, you must create encryption keys that only your application can access. Only applications that have access to your encryption keys can access the decrypted, plaintext data. If an attacker gains access to the database, they can only see the encrypted ciphertext data because they lack access to the encryption keys.\n\nYou might use in-use encryption to encrypt fields in your MongoDB documents that contain the following types of sensitive data:\n\n- Credit card numbers\n\n- Addresses\n\n- Health information\n\n- Financial information\n\n- Any other sensitive or personally identifiable information (PII)\n\nMongoDB offers the following features to enable in-use encryption:\n\n- Queryable Encryption\n\n- Client-side Field Level Encryption\n\n### Queryable Encryption\n\nQueryable Encryption (QE) is an in-use encryption feature that supports querying uniquely encrypted field values, including equality, range, prefix, suffix, and substring queries. Range query support requires MongoDB Server 8.0 or later. Prefix, suffix, and substring query support requires MongoDB Server 9.0 or later.\n\nTo learn more about Queryable Encryption, see Queryable Encryption in the Server manual.\n\n### Client-side Field Level Encryption\n\nClient-side Field Level Encryption (CSFLE) supports searching encrypted fields for equality. MongoDB Server version 4.2 introduced CSFLE.\n\nUnlike QE, CSFLE requires you to select an encryption algorithm for each field, and that choice determines whether you can query the field. Deterministic encryption always produces the same output value for the same input value. Because matching values look the same after encryption, you can run equality queries on these fields. Randomized encryption produces a different output value each time it encrypts the same input value. Drivers can decrypt these fields, but you cannot query them.\n\nDeterministic encryption trades some confidentiality for query support. When an encrypted field has low cardinality, an attacker can compare how often each encrypted value appears and infer the original values. This technique is called frequency analysis. To protect fields that you do not query, use randomized encryption.\n\nTo learn more about these concepts, see the following Wikipedia entries:\n\n- Cardinality\n\n- Frequency Analysis\n\nTo learn more about CSFLE, see CSFLE in the Server manual."} -{"chunk_id": "6a514d65d727379c91b9d7db-0", "page_id": "6a514d65d727379c91b9d7db", "source_name": "java-rs", "product_name": "Java Reactive Streams Driver", "url": "https://mongodb.com/docs/languages/java/reactive-streams-driver/current/reference/upgrade", "title": "Upgrade Driver Versions", "text": "# Upgrade Driver Versions\n\n## Overview\n\nIn this section, you can identify the changes you must make to your application to upgrade your driver to a new version.\n\nBefore you upgrade, perform the following actions:\n\n- Ensure the new version is compatible with the MongoDB Server versions your application connects to and the Java Runtime Environment (JRE) your application runs on. See the Compatibility page to find this information.\n\n- Address any breaking changes between the current version of the driver your application is using and your planned upgrade version in the Breaking Changes section. To learn more about the MongoDB Server release compatibility changes, see the Server Release Compatibility Changes section.\n\nTo minimize the amount of changes your application might require when upgrading driver versions in the future, use the Stable API.\n\n## Breaking Changes\n\nA breaking change is a modification in a convention or behavior in a specific version of the driver that might prevent your application from working properly if not addressed before upgrading.\n\nThe breaking changes in this section are categorized by the driver version that introduced them. When upgrading driver versions, address all the breaking changes between the current and upgrade versions. For example, if you are upgrading the driver from v4.0 to v4.5, address all breaking changes from the version after v4.0 including any listed under v4.5.\n\n### Version 5.5 Breaking Changes\n\n- The driver is no longer compatible with MongoDB Server version v4.0. To learn more about this change, see the Driver Version 5.5 Server Support Changes section.\n\n### Version 5.2 Breaking Changes\n\n- The driver is no longer compatible with MongoDB Server version v3.6. To learn more about this change, see the Driver Version 5.2 Server Support Changes section."} -{"chunk_id": "6a514d65d727379c91b9d7db-1", "page_id": "6a514d65d727379c91b9d7db", "source_name": "java-rs", "product_name": "Java Reactive Streams Driver", "url": "https://mongodb.com/docs/languages/java/reactive-streams-driver/current/reference/upgrade", "title": "Upgrade Driver Versions", "text": "### Version 5.0 Breaking Changes\n\nThis driver version introduces the following breaking changes:\n\n- Introduces the following changes to the `ConnectionId` class:\n\n - The `ConnectionId` constructor now accepts a value of type `long` as its second parameter instead of type `int`. Similarly, the constructor now accepts a value of type `Long` as its third parameter instead of type `Integer`. Because this change breaks binary compatibility, recompile any existing code that calls the `ConnectionId` constructor.\n\n - The `withServerValue()` method now accepts a parameter of type `long` rather than type `int`. This change breaks binary compatibility, so you must recompile any code that calls the `withServerValue()` method.\n\n - The `getServerValue()` method now returns a value of type `Long` instead of type `Integer`. Similarly, the `getLocalValue()` method returns a value of type `long` instead of type `int`. Because this change breaks both binary and source compatibility, update any source code that uses these methods and rebuild your binary.\n\n- Replaces the following record annotations from the `org.bson.codecs.record.annotations` package with annotations of the same name from the `org.bson.codecs.pojo.annotations` package:\n\n - `BsonId`\n\n - `BsonProperty`\n\n - `BsonRepresentation`\n\n- Changes the data type of the timeout duration parameter in the `SocketSettings.Builder.connectTimeout()` and `SocketSettings.Builder.readTimeout()` methods. The data type of this parameter is now `long` instead of `int`.\n\n In earlier versions, this parameter is of type `int` for both methods. This change breaks binary compatibility and requires recompiling, but does not require code changes.\n\n- Removes the `Filters.eqFull()` method, released exclusively in `Beta`, which allowed you to construct an equality filter when performing a vector search. You can use the `Filters.eq()` method when instantiating a `VectorSearchOptions` type, as shown in the following code:\n\n ```java\n VectorSearchOptions opts = vectorSearchOptions().filter(eq(\"x\", 8));\n ```\n\n- Removes the `org.mongodb.scala.ObservableImplicits.ToSingleObservableVoid` implicit class. This means the `org.reactivestreams.Publisher[Void]` type no longer converts automatically to `org.mongodb.scala.SingleObservable[Void]`. The API also exposes `org.mongodb.scala.Observable[Unit]` instead of `org.mongodb.scala.Observable[Void]`.\n\n For more information, see the Observable trait in the Scala API documentation.\n\n- Changes how `ClusterSettings` computes `ClusterConnectionMode`, making it more consistent by using the specified replica set name, regardless of how it is configured. Previously, replica set name was only considered if it was set by the connection string.\n\n For example, the following two code samples both return the value `ClusterConnectionMode.MULTIPLE`, while previously the second one returned `ClusterConnectionMode.SINGLE`.\n\n ```java\n ClusterSettings.builder()\n .applyConnectionString(new ConnectionString(\"mongodb://127.0.0.1:27017/?replicaSet=replset\"))\n .build()\n .getMode()\n ```\n\n ```java\n ClusterSettings.builder()\n .hosts(Collections.singletonList(\n new ServerAddress(\"127.0.0.1\", 27017)\n ))\n .requiredReplicaSetName(\"replset\")\n .build()\n .getMode()\n ```\n\n- Changes how `BsonDecimal128` values respond to method calls, by responding in the same way as `Decimal128` values. In particular, `BsonDecimal128.isNumber()` now returns `true`, and `BsonDecimal128.asNumber()` returns the equivalent `BsonNumber`.\n\n- Removes the ServerAddress methods `getSocketAddress()` and `getSocketAddresses()`.\n\n Instead of `getSocketAddress()`, use the `getByName()` instance method of `java.net.InetAddress`.\n\n Instead of `getSocketAddresses()`, use the `getAllByName()` instance method of `java.net.InetAddress`.\n\n- Removes the `Parameterizable` interface. Instead of implementing this interface on a custom `Codec` type, override the `CodecProvider.get()` method on the codec's `CodecProvider` if the codec is intended for a parameterized type.\n\n- Removes the `isSlaveOk()` method from the `ReadPreference` and `TaggableReadPreference` classes. To check whether a read preference allows reading from a secondary member of a replica set, use the `isSecondaryOk()` methods from these classes instead.\n\n- Removes the `DBCollection.getStats()` and `DBCollection.isCapped()` helper methods for the `collStats` command. Instead of these methods, you can use the `$collStats` aggregation pipeline stage.\n\n- Removes the `MapCodec` and `IterableCodec` classes. Instead of `MapCodec`, use `MapCodecProvider`. Instead of `IterableCodec`, use `CollectionCodecProvider`, or `IterableCodecProvider` for `Iterable` types that aren't `Collection` types.\n\n- Removes the `sharded()` and `nonAtomic()` methods from the `MapReducePublisher` and `MapReduceIterable` classes.\n\n- Removes the following methods for use with `geoHaystack` indexes:\n\n - `Indexes.geoHaystack()`\n\n - `IndexOptions.getBucketSize()`\n\n - `IndexOptions.bucketSize()`\n\n Instead, you can use the `$geoNear` aggregation pipeline stage or a geospatial query operator on a 2d index. For more information, see the Geospatial Queries page in the MongoDB Server manual.\n\n- Removes the `oplogReplay` option from find operations. This includes the following methods:\n\n - `DBCursor.oplogReplay()`\n\n - `DBCollectionFindOptions.isOplogReplay()`\n\n - `DBCollectionFindOptions.oplogReplay()`\n\n - `FindPublisher.oplogReplay()`\n\n - `FindIterable.oplogReplay()`\n\n- Removes the following `Exception` constructors:\n\n - `MongoBulkWriteException(BulkWriteResult, List, WriteConcernError, ServerAddress)`\n\n - `MongoCursorNotFoundException(long, ServerAddress)`\n\n - `MongoQueryException(ServerAddress, int, String)`\n\n - `MongoQueryException(ServerAddress, int, String, String)`\n\n - `MongoQueryException(MongoCommandException)`\n\n- Removes the following overloads for the `BulkWriteResult.acknowledged()` method:\n\n - `acknowledged(Type, int, List)`\n\n - `acknowledged(Type, int, Integer, List)`\n\n - `acknowledged(int, int, int, Integer, List)`\n\n- Removes the following `ChangeStreamDocument` constructors:\n\n - `ChangeStreamDocument(String, BsonDocument, BsonDocument, BsonDocument, TDocument, TDocument, BsonDocument, ...)`\n\n - `ChangeStreamDocument(String, BsonDocument, BsonDocument, BsonDocument, TDocument, BsonDocument, BsonTimestamp, ...)`\n\n - `ChangeStreamDocument(OperationType, BsonDocument, BsonDocument, BsonDocument, TDocument, BsonDocument, BsonTimestamp, ...)`\n\n- Removes the following constructors for events:\n\n - `CommandEvent(RequestContext, int, ConnectionDescription, String)`\n\n - `CommandEvent(int, ConnectionDescription, String)`\n\n - `CommandEvent(RequestContext, long, int, ConnectionDescription, String)`\n\n - `CommandFailedEvent(RequestContext, int, ConnectionDescription, String, long, Throwable)`\n\n - `CommandFailedEvent(int, ConnectionDescription, String, long, Throwable)`\n\n - `CommandStartedEvent(RequestContext, int, ConnectionDescription, String, String, BsonDocument)`\n\n - `CommandStartedEvent(int, ConnectionDescription, String, String, BsonDocument)`\n\n - `CommandSucceededEvent(RequestContext, int, ConnectionDescription, String, BsonDocument, long)`\n\n - `CommandSucceededEvent(int, ConnectionDescription, String, BsonDocument, long)`\n\n - `ConnectionCheckedInEvent(ConnectionId)`\n\n - `ConnectionCheckedOutEvent(ConnectionId, long)`\n\n - `ConnectionCheckedOutEvent(ConnectionId)`\n\n - `ConnectionCheckOutFailedEvent(ServerId, long, Reason)`\n\n - `ConnectionCheckOutFailedEvent(ServerId, Reason)`\n\n - `ConnectionCheckOutStartedEvent(ServerId)`\n\n - `ConnectionReadyEvent(ConnectionId)`\n\n - `ServerHeartbeatFailedEvent(ConnectionId, long, Throwable)`\n\n - `ServerHeartbeatSucceededEvent(ConnectionId, BsonDocument, long)`"} -{"chunk_id": "6a514d65d727379c91b9d7db-2", "page_id": "6a514d65d727379c91b9d7db", "source_name": "java-rs", "product_name": "Java Reactive Streams Driver", "url": "https://mongodb.com/docs/languages/java/reactive-streams-driver/current/reference/upgrade", "title": "Upgrade Driver Versions", "text": "- Removes the `errorLabels` option from the `WriteConcernError` class. This includes the `addLabel()` and `getErrorLabels()` methods and the constructor that includes an `errorLabels` parameter. Instead, you can use the error labels included in the `MongoException` object that contains the `WriteConcernError`.\n\n- Removes the following classes from the `com.mongodb.event` package:\n\n - `ConnectionAddedEvent`\n\n - `ConnectionPoolOpenedEvent`\n\n - `ConnectionRemovedEvent`\n\n - `ClusterListenerAdapter`\n\n - `ConnectionPoolListenerAdapter`\n\n - `ServerListenerAdapter`\n\n - `ServerMonitorListenerAdapter`\n\n Because of these removals, the following methods were also removed from the `ConnectionPoolListener` interface:\n\n - `connectionAdded`\n\n - `connectionPoolOpened`\n\n - `connectionRemoved`\n\n For more information about the events package, see the com.mongodb.event package documentation\n\n- Adds support for a new `authorizedCollection` option of the `listCollections` command. This introduces a breaking binary change in the `MongoDatabase.listCollectionNames()` methods, meaning any code using these methods must be recompiled. This change does not require any changes to source code.\n\n- Removes the following methods and types related to the Stream interface:\n\n - `streamFactoryFactory()` method from `MongoClientSettings.Builder`. Use the `MongoClientSettings.Builder.transportSettings()` method instead.\n\n - `getStreamFactoryFactory()` method from `MongoClientSettings`. Use the `MongoClientSettings.getTransportSettings()` method instead.\n\n - `NettyStreamFactoryFactory` class. Use the `NettyTransportSettings`, creatable by `TransportSettings.nettyBuilder()` and applied through `MongoClientSettings.Builder.transportSettings()`.\n\n - `NettyStreamFactory` class\n\n - `AsynchronousSocketChannelStreamFactory` class\n\n - `AsynchronousSocketChannelStreamFactoryFactory` class\n\n - `BufferProvider` interface\n\n - `SocketStreamFactory` class\n\n - `Stream` interface\n\n - `StreamFactory` interface\n\n - `StreamFactoryFactory` interface\n\n - `TlsChannelStreamFactoryFactory` class\n\n### Version 4.8 Breaking Changes\n\n- The driver ends support for connecting to MongoDB Server versions v3.4 and earlier. To learn more about this change, see the Driver Version 4.8 Server Support Changes section.\n\n- You must add an explicit dependency on the `org.bson.codecs.record` module if your application deploys the driver in an OSGi container and relies on the driver for encoding and decoding Java records.\n\n- The `RecordCodec`, implemented in v4.6, deserialized POJOs and record classes that are specified as type parameters of `List` or `Map` fields of a record as `Document` values instead of their respective classes. This version now deserializes them to the proper record and POJO types.\n\n For example, the following record class definitions show a `Book` record that contains a `List` that receives a `Chapter` type parameter:\n\n ```java\n public record Book(String title, List chapters) {}\n public record Chapter(Integer number, String text) {}\n ```\n\n Starting in this version, the codec deserializes data in the `List` into `Chapter` record classes instead of `Document` values.\n\n### Version 4.7 Breaking Changes\n\n- The `setWindowFields` builder API is no longer beta. The new builder breaks binary and source compatibility. See the Aggregates API documentation for information the new `setWindowFields()` method signatures.\n\n If your application uses this builder in a version earlier than v4.7, update your source code to use the new method signature and rebuild your binary.\n\n### Version 4.2 Breaking Changes\n\n- The `ObjectId` class and its `serialVersionUID` field were updated to use a new format that minimizes serialization compatibility issues across different versions of the driver.\n\n If an application using this version or later of the driver attempts to perform Java Object Serialization on any objects that contain an `ObjectId` and were serialized by a prior version of the driver, Java throws an `InvalidClassException`.\n\n To learn more about Java Object Serialization, see the Java Documentation on Serializable Objects.\n\n### Version 4.0 Breaking Changes\n\n- Several classes and methods marked as deprecated in the 3.12 release were removed in this version.\n\n- The insert helper methods return an insert result object instead of `void`.\n\n- The `toJson()` methods on `BsonDocument`, `Document`, and `DbObject` return a relaxed JSON format instead of a strict JSON format. This makes the JSON documents more readable, but can make it more difficult to identify the BSON type information, such as the difference between a 32-bit and 64-bit integer. If your application relies on the strict JSON format, use the strict mode when reading or writing data.\n\n- The default BSON representation of `java.util.UUID` value was changed from `JAVA_LEGACY` to `UNSPECIFIED`. Applications that store or retrieve UUID values must explicitly specify which representation to use. You can specify the representation in the `uuidRepresentation` property of `MongoClientSettings`.\n\n The UUID representation that you specify strictly controls how the driver decodes UUIDs. In previous versions of the driver, if you specified the `JAVA_LEGACY` representation, the driver would decode binary objects of subtypes 3 and 4 as UUIDs. In version 4.0, the `JAVA_LEGACY` representation works only with subtype 3.\n\n For a list of members in the `UuidRepresentation` enum, see the v4.0 API documentation.\n\n- The connection pool no longer restricts the number of wait queue threads or asynchronous tasks that require a connection to MongoDB. The application will throttle requests as necessary rather than depend on the driver to throw a `MongoWaitQueueFullException`.\n\n- The driver no longer logs using the `java.util.logging` (JUL) package and only supports the SLF4J logging framework.\n\n- The embedded and Android drivers were removed. If your application relies on these drivers, you must continue to use a 3.x Java driver version.\n\n- The uber JARs, `mongo-java-driver` and `mongodb-driver`, are no longer published. If your application relies on one of these, you must switch to either `mongodb-driver-sync` or `mongodb-driver-legacy` depending on which API the application uses. Make sure you remove the uber JARs from your dependencies.\n\n- Updates to several classes introduced binary compatibility breaks, such as the method signature change to the insert helper methods. Recompile any classes that link to the driver against this version or later to ensure that they continue to work.\n\n## Server Release Compatibility Changes\n\nA server release compatibility change is a modification to the MongoDB Java Reactive Streams Driver that discontinues support for a set of MongoDB Server versions.\n\nThe driver discontinues support for a MongoDB Server version after it reaches end-of-life (EOL).\n\nTo learn more about the MongoDB support for EOL products, see the Legacy Support Policy.\n\n### Driver Version 5.5 Server Support Changes\n\nThe v5.5 driver drops support for MongoDB Server 4.0. To use the v5.5 driver, you must connect to MongoDB Server 4.2 or later. To learn how to upgrade your MongoDB Server deployment, see Release Notes in the MongoDB Server manual.\n\n### Driver Version 5.2 Server Support Changes\n\nThe v5.2 driver drops support for MongoDB Server 3.6. To use the v5.2 driver, you must connect to MongoDB Server 4.0 or later. To learn how to upgrade your MongoDB Server deployment, see Release Notes in the MongoDB Server manual.\n\n### Server Version 8.1 Support Changes\n\nYou cannot use a 3.x version of the Java Reactive Streams driver to connect to a deployment running MongoDB Server v8.1. Starting in MongoDB Server v8.1, the `buildinfo` command requires authentication, causing an incompatibility with the v3.x driver."} -{"chunk_id": "6a514d65d727379c91b9d7db-3", "page_id": "6a514d65d727379c91b9d7db", "source_name": "java-rs", "product_name": "Java Reactive Streams Driver", "url": "https://mongodb.com/docs/languages/java/reactive-streams-driver/current/reference/upgrade", "title": "Upgrade Driver Versions", "text": "### Driver Version 4.8 Server Support Changes\n\nThe v4.8 driver drops support for MongoDB Server 3.4 and earlier. To use the v4.8 driver, you must connect to MongoDB Server 3.6 or later. To learn how to upgrade your MongoDB Server deployment, see Release Notes in the MongoDB Server manual."} -{"chunk_id": "6a514d65d727379c91b9d79a-0", "page_id": "6a514d65d727379c91b9d79a", "source_name": "java-rs", "product_name": "Java Reactive Streams Driver", "url": "https://mongodb.com/docs/languages/java/reactive-streams-driver/current/connect/specify-connection-options/network-compression", "title": "Compress Network Traffic", "text": "# Compress Network Traffic\n\n## Overview\n\nMongoDB drivers can compress the messages sent to and received from MongoDB Server. This reduces the amount of data transferred for each operation. Compression can improve performance over constrained networks and lower the data transfer costs associated with running MongoDB Atlas.\n\nCompression operates at the wire protocol level, so it applies to every operation that your application performs. If you specify more than one algorithm, the driver uses the first algorithm in your list that MongoDB Server also supports.\n\n### Compression Algorithms\n\nMongoDB drivers support the following compression algorithms:\n\n- Snappy\n\n- Zlib\n\n- Zstandard\n\n## Network Compression Benefits\n\nMongoDB Atlas charges for data transferred across cloud regions, cloud providers, and between your infrastructure and MongoDB Atlas. Network compression reduces the amount of data that your application sends and receives, which can lower these data transfer costs. To learn more about pricing, see Data Transfer Costs.\n\nNetwork compression also has productivity benefits. Compressed messages take less time to transfer across the network, which can improve your application's response times. Compression also reduces the bandwidth that your MongoDB traffic uses, which leaves more bandwidth available for other applications on the same network.\n\nWhen you choose a compression algorithm, consider the following guidelines:\n\n- Use **Zstandard** for a balance of compression efficiency and resource usage. Zstandard is a good default choice for most applications.\n\n- Use **Snappy** for latency-sensitive applications that require minimal computational overhead.\n\n- Use **Zlib** for broad compatibility across MongoDB drivers and environments.\n\nCompression trades network bandwidth for CPU usage. After you enable network compression, monitor your application's CPU utilization to confirm that the trade-off benefits your workload. To learn more about these trade-offs, see the CPU Utilization and Network Compression in MongoDB blog post.\n\n## Version Compatibility\n\nThe following table lists the minimum supported driver and MongoDB Server version for each compression algorithm:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nCompression Algorithm\n\n\nMinimum Driver Version\n\n\nMinimum Server Version\n\n
\nSnappy\n\n\n3.6\n\n\n4.2\n\n
\nZlib\n\n\n3.6\n\n\n4.2\n\n
\nZstandard\n\n\n3.11\n\n\n4.2\n\n
\n\n## Enable Network Compression\n\nTo enable network compression for your MongoDB connection, install the required dependencies and specify the compression algorithms that you want to use.\n\n### Compression Algorithm Dependencies\n\nThe following table lists each algorithm and the dependency it requires, if any:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nCompression Algorithm\n\n\nDependency\n\n
\nSnappy\n\n\nDownload `snappy-java`, a Java JNI wrapper for the Snappy library. To install, see snappy-java in Maven Central.\n\n
\nZlib\n\n\nNone. The driver natively supports Zlib compression.\n\n
\nZstandard\n\n\nDownload `zstd-jni`, a Java JNI wrapper for the Zstandard library. To install, see zstd-jni in Maven Central.\n\n
\n\n### Specify Compression Algorithms\n\nYou can enable compression for the connection to your MongoDB instance by specifying the algorithms in one of two ways. Select the Connection String or MongoClientSettings tab to see the corresponding syntax:\n\n- In the `compressors` parameter of your connection string\n\n- In the `compressorList` method chained to the `MongoClientSettings.builder()` method\n\nThe following example shows how to specify all compression algorithms:\n\n\n\n\n\n```java\nConnectionString connectionString = new ConnectionString(\n \"mongodb+srv://:@/?compressors=snappy,zlib,zstd\");\n\nMongoClient client = MongoClients.create(connectionString);\n```\n\n\n\n\n\n```java\nMongoClientSettings settings = MongoClientSettings.builder()\n .compressorList(Arrays.asList(MongoCompressor.createSnappyCompressor(),\n MongoCompressor.createZlibCompressor(),\n MongoCompressor.createZstdCompressor()))\n .build();\n\nMongoClient client = MongoClients.create(settings);\n```\n\n\n\n\n\n## API Documentation\n\nTo learn more about any of the methods or types discussed in this guide, see the following API documentation:\n\n- MongoClient\n\n- createSnappyCompressor()\n\n- createZlibCompressor()\n\n- createZstdCompressor()"} -{"chunk_id": "6a514d65d727379c91b9d7b9-0", "page_id": "6a514d65d727379c91b9d7b9", "source_name": "java-rs", "product_name": "Java Reactive Streams Driver", "url": "https://mongodb.com/docs/languages/java/reactive-streams-driver/current/crud/query-documents/text-search", "title": "Text Query", "text": "# Text Query\n\nMongoDB supports query operations that perform a text query on string content in documents. To perform a text query, MongoDB uses a text index and the `$text` query operator.\n\nTo learn more about other text search options, like full-text search and vector search, see the Text Search overview in the MongoDB Server manual.\n\nThe driver provides the `Filters.text()` helper method to facilitate the creation of text query filters.\n\n## Prerequisites\n\nYou must set up the following components to run the code examples in this guide:\n\n- A `test.restaurants` collection populated with documents from the `restaurants.json` file in the documentation assets GitHub.\n\n- The following import statements:\n\n```java\nimport com.mongodb.client.MongoClients;\nimport com.mongodb.client.MongoClient;\nimport com.mongodb.client.MongoCollection;\nimport com.mongodb.client.MongoDatabase;\n\nimport com.mongodb.client.model.Indexes;\nimport com.mongodb.client.model.Filters;\nimport com.mongodb.client.model.Sorts;\nimport com.mongodb.client.model.TextSearchOptions;\nimport com.mongodb.client.model.Projections;\nimport org.bson.Document;\n```\n\nThis guide uses custom `Subscriber` implementations, which are described in the Sample Custom Subscriber Implementations guide.\n\n## Connect to a MongoDB Deployment\n\nFirst, connect to a MongoDB deployment and declare and define `MongoDatabase` and `MongoCollection` instances.\n\nThe following code connects to a standalone MongoDB deployment running on `localhost` on port `27017`. Then, it defines the `database` variable to refer to the `test` database and the `collection` variable to refer to the `restaurants` collection:\n\n```java\nMongoClient mongoClient = MongoClients.create();\nMongoDatabase database = mongoClient.getDatabase(\"test\");\nMongoCollection collection = database.getCollection(\"restaurants\");\n```\n\nTo learn more about connecting to MongoDB deployments, see the Connect to MongoDB tutorial.\n\n## Create the Text Index\n\nTo create a text index, use the `Indexes.text()` static helper to create a specification for a text index and pass the specification to the `MongoCollection.createIndex()` method to create the index.\n\nThe following example creates a text index on the `name` field for the `restaurants` collection:\n\n```java\nMongoCollection collection = database.getCollection(\"restaurants\");\ncollection.createIndex(Indexes.text(\"name\")).subscribe(new PrintToStringSubscriber());\n```\n\n## Perform a Text Query\n\nTo perform a text query, use the `Filters.text()` helper method to specify the text query filter.\n\nFor example, the following code performs a text query on the `name` field to match the strings `\"bakery\"` or `\"coffee\"`:\n\n```java\ncollection\n .countDocuments(Filters.text(\"bakery coffee\"))\n .subscribe(new PrintSubscriber(\"Text query matches: %s\"));\n```\n\n```none\nText query matches: [2]\n```\n\n### Text Score\n\nFor each matching document, a text query assigns a score that represents the relevance of a document to the specified text query filter. To return and sort by score, use the `$meta` operator in the projection document and the sort expression:\n\n```java\ncollection.find(Filters.text(\"bakery cafe\"))\n .projection(Projections.metaTextScore(\"score\"))\n .sort(Sorts.metaTextScore(\"score\"))\n .subscribe(new PrintDocumentSubscriber());\n```\n\n### Specify a Text Query Option\n\nThe `Filters.text()` helper can accept various text query options. The driver provides the `TextSearchOptions` class to specify these options.\n\nFor example, the following text query specifies the text query language option when performing a text query for the word `\"cafe\"`:\n\n```java\ncollection.countDocuments(\n Filters.text(\"cafe\", new TextSearchOptions().language(\"english\"))\n).subscribe(new PrintSubscriber(\"Text query matches (English): %s\"));\n```\n\n```none\nText query matches (English): [1]\n```\n\nTo learn more about text queries, see the following sections in the MongoDB Server manual:\n\n- $text\n\n- Text Indexes\n\n- Specify the Default Language for a Text Index"} -{"chunk_id": "6a514d65d727379c91b9d7b1-0", "page_id": "6a514d65d727379c91b9d7b1", "source_name": "java-rs", "product_name": "Java Reactive Streams Driver", "url": "https://mongodb.com/docs/languages/java/reactive-streams-driver/current/crud/query-documents/specify-a-query", "title": "Specify a Query", "text": "# Specify a Query\n\n## Overview\n\nIn this guide, you can learn how to specify a query by using the Java Reactive Streams driver.\n\nThis guide uses the Project Reactor library to consume `Publisher` instances returned by the Java Reactive Streams driver methods. To learn more about the Project Reactor library and how to use it, see Getting Started in the Reactor documentation. To learn more about how we use Project Reactor library methods in this guide, see the Write Data to MongoDB guide.\n\nThis guide uses the `Flux Publisher`, which is a `Publisher` implementation from the Project Reactor library. In Java Reactive Streams, you must use `Publisher` implementations to control how data is transmitted in your application. To learn more about the `Flux` class, see Flux in the Project Reactor documentation.\n\nYou can refine the set of documents that a query returns by creating a **query filter**. A query filter is an expression that specifies the search criteria MongoDB uses to match documents in a read or write operation. In a query filter, you can prompt the driver to search for documents with an exact match to your query, or you can compose query filters to express more complex matching criteria.\n\n### Sample Data\n\nThe examples in this guide run operations on a collection called `fruits` that contains the following documents:\n\n```json\n{ \"_id\": 1, \"name\": \"apples\", \"qty\": 5, \"rating\": 3, \"color\": \"red\", \"type\": [\"fuji\", \"honeycrisp\"] },\n{ \"_id\": 2, \"name\": \"bananas\", \"qty\": 7, \"rating\": 4, \"color\": \"yellow\", \"type\": [\"cavendish\"] },\n{ \"_id\": 3, \"name\": \"oranges\", \"qty\": 6, \"rating\": 2, \"type\": [\"naval\", \"mandarin\"] },\n{ \"_id\": 4, \"name\": \"pineapple\", \"qty\": 3, \"rating\": 5, \"color\": \"yellow\" },\n```\n\nThe following code example shows how to create a database and collection, then insert the sample documents into your collection:\n\n```java\nimport com.mongodb.ConnectionString;\nimport com.mongodb.MongoClientSettings;\nimport com.mongodb.ServerApi;\nimport com.mongodb.ServerApiVersion;\nimport com.mongodb.client.result.InsertManyResult;\nimport org.bson.Document;\n\nimport org.reactivestreams.Publisher;\nimport reactor.core.publisher.Mono;\n\nimport com.mongodb.reactivestreams.client.MongoClient;\nimport com.mongodb.reactivestreams.client.MongoClients;\nimport com.mongodb.reactivestreams.client.MongoDatabase;\nimport com.mongodb.reactivestreams.client.MongoCollection;\n\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class QueryDatabase {\n public static void main(String[] args) {\n // Replace the placeholder with your Atlas connection string\n String uri = \"\";\n\n // Construct a ServerApi instance using the ServerApi.builder() method\n ServerApi serverApi = ServerApi.builder()\n .version(ServerApiVersion.V1)\n .build();\n\n MongoClientSettings settings = MongoClientSettings.builder()\n .applyConnectionString(new ConnectionString(uri))\n .serverApi(serverApi)\n .build();\n\n // Create a new client and connect to the server\n try (MongoClient mongoClient = MongoClients.create(settings)) {\n MongoDatabase database = mongoClient.getDatabase(\"sample_fruits\");\n MongoCollection fruits = database.getCollection(\"fruits\");\n\n Document document1 = new Document(\"_id\", \"1\")\n .append(\"name\", \"apples\")\n .append(\"qty\", 5)\n .append(\"rating\", 3)\n .append(\"color\", \"red\")\n .append(\"type\", Arrays.asList(\"fuji\", \"honeycrisp\"));\n Document document2 = new Document(\"_id\", \"2\")\n .append(\"name\", \"bananas\")\n .append(\"qty\", 7)\n .append(\"rating\", 4)\n .append(\"color\", \"yellow\")\n .append(\"type\", Arrays.asList(\"cavendish\"));\n Document document3 = new Document(\"_id\", \"3\")\n .append(\"name\", \"oranges\")\n .append(\"qty\", 6)\n .append(\"rating\", 2)\n .append(\"type\", Arrays.asList(\"naval\", \"mandarin\"));\n Document document4 = new Document(\"_id\", \"4\")\n .append(\"name\", \"pineapple\")\n .append(\"qty\", 3)\n .append(\"rating\", 5)\n .append(\"color\", \"yellow\");\n\n List documents = Arrays.asList(document1, document2, document3, document4);\n\n Publisher insertPublisher = fruits.insertMany(documents);\n Mono.from(insertPublisher).block();\n }\n }\n}\n```\n\n## Exact Match\n\nLiteral value queries return documents with an exact match to your query filter. To return documents with an exact match, use the `eq()` comparison operator method.\n\nThe following example specifies an `eq()` comparison operator method as the query filter parameter in the `find()` method. The code returns all documents with a `color` field value of `\"yellow\"`.\n\n```java\nFindPublisher findDocPublisher = fruits.find(eq(\"color\", \"yellow\"));\nDocument findResults = Flux.from(findDocPublisher)\n .doOnNext(System.out::println)\n .blockLast();\n```\n\n```\n{'_id': 2, 'name': 'bananas', 'qty': 7, 'rating': 4, 'color': 'yellow', 'type': ['cavendish']}\n{'_id': 4, 'name': 'pineapple', 'qty': 3, 'rating': 5, 'color': 'yellow'}\n```\n\nTo find all documents in a collection, call the `find()` method without specifying any parameters. The following example finds all documents in a collection:\n\n```java\nFindPublisher findDocPublisher = fruits.find();\nDocument findResults = Flux.from(findDocPublisher)\n .doOnNext(System.out::println)\n .blockLast();\n```\n\n## Comparison Operators\n\nComparison operators evaluate a document field value against a specified value in your query filter. The following is a list of common comparison operator methods:\n\n- `gt()`: Greater than\n\n- `lte()`: Less than or Equal\n\n- `ne()`: Not equal\n\nTo view a full list of comparison operators, see the Comparison Query Operators guide in the MongoDB Server manual.\n\nThe following example specifies a `gt()` comparison operator method in a query filter as a parameter to the `find()` method. The code returns all documents with a `rating` field value greater than `2`.\n\n```java\nFindPublisher findDocPublisher = fruits.find(gt(\"rating\", 2));\nDocument findResults = Flux.from(findDocPublisher)\n .doOnNext(System.out::println)\n .blockLast();\n```\n\n```\n{'_id': 1, 'name': 'apples', 'qty': 5, 'rating': 3, 'color': 'red', 'type': ['fuji', 'honeycrisp']}\n{'_id': 2, 'name': 'bananas', 'qty': 7, 'rating': 4, 'color': 'yellow', 'type': ['cavendish']}\n{'_id': 4, 'name': 'pineapple', 'qty': 3, 'rating': 5, 'color': 'yellow'}\n```"} -{"chunk_id": "6a514d65d727379c91b9d7b1-1", "page_id": "6a514d65d727379c91b9d7b1", "source_name": "java-rs", "product_name": "Java Reactive Streams Driver", "url": "https://mongodb.com/docs/languages/java/reactive-streams-driver/current/crud/query-documents/specify-a-query", "title": "Specify a Query", "text": "## Logical Operators\n\nLogical operators match documents by using logic applied to the results of two or more sets of expressions. The following is a list of logical operator methods:\n\n- `and()`, which returns all documents that match the conditions of *all* clauses\n\n- `or()`, which returns all documents that match the conditions of *one* clause\n\n- `nor()`, which returns all documents that *do not* match the conditions of any clause\n\n- `not()`, which returns all documents that *do not* match the expression\n\nTo learn more about logical operators, see the Logical Query Operators guide in the MongoDB Server manual.\n\nThe following example specifies an `or()` logical operator method in a query filter as a parameter to the `find()` method. The code returns all documents with a `qty` field value greater than `5` **or** a `color` field value of `\"yellow\"`.\n\n```java\nFindPublisher findDocPublisher = fruits.find(\n or(gt(\"qty\", 5), eq(\"color\", \"yellow\")));\nDocument findResults = Flux.from(findDocPublisher)\n .doOnNext(System.out::println)\n .blockLast();\n```\n\n```\n{'_id': 2, 'name': 'bananas', 'qty': 7, 'rating': 4, 'color': 'yellow', 'type': ['cavendish']}\n{'_id': 3, 'name': 'oranges', 'qty': 6, 'rating': 2, 'type': ['naval', 'mandarin']}\n{'_id': 4, 'name': 'pineapple', 'qty': 3, 'rating': 5, 'color': 'yellow'}\n```\n\n## Array Operators\n\nArray operators match documents based on the value or quantity of elements in an array field. The following is a list of available array operator methods:\n\n- `all()`, which returns documents with arrays that contain all elements in the query\n\n- `elemMatch()`, which returns documents if an element in their array field matches all conditions in the query\n\n- `size()`, which returns all documents with arrays of a specified size\n\nTo learn more about array operators, see the Array Query Operators guide in the MongoDB Server manual.\n\nThe following example specifies a `size()` array operator method in a query filter as a parameter to the `find()` method. The code returns all documents with a `type` array field containing `2` elements.\n\n```java\nFindPublisher findDocPublisher = fruits.find(size(\"type\", 2));\nDocument findResults = Flux.from(findDocPublisher)\n .doOnNext(System.out::println)\n .blockLast();\n```\n\n```\n{'_id': 1, 'name': 'apples', 'qty': 5, 'rating': 3, 'color': 'red', 'type': ['fuji', 'honeycrisp']}\n{'_id': 3, 'name': 'oranges', 'qty': 6, 'rating': 2, 'type': ['naval', 'mandarin']}\n```\n\n## Element Operators\n\nElement operators query data based on the presence or type of a field. The following is a list of available element operator methods:\n\n- `exists()`, which returns documents with the specified field\n\n- `type()`, which returns documents if a field is of the specified type\n\nTo learn more about element operators, see the Element Query Operators guide in the MongoDB Server manual.\n\nThe following example specifies an `exists()` element operator method in a query filter as a parameter to the `find()` method. The code returns all documents that have a `color` field.\n\n```java\nFindPublisher findDocPublisher = fruits.find(exists(\"color\", true));\nDocument findResults = Flux.from(findDocPublisher)\n .doOnNext(System.out::println)\n .blockLast();\n```\n\n```\n{'_id': 1, 'name': 'apples', 'qty': 5, 'rating': 3, 'color': 'red', 'type': ['fuji', 'honeycrisp']}\n{'_id': 2, 'name': 'bananas', 'qty': 7, 'rating': 4, 'color': 'yellow', 'type': ['cavendish']}\n{'_id': 4, 'name': 'pineapple', 'qty': 3, 'rating': 5, 'color': 'yellow'}\n```\n\n## Evaluation Operators\n\nEvaluation operators return data based on evaluations of either individual fields or the entire collection's documents. The following is a list of common evaluation operator methods:\n\n- `text()`, which performs a text query on the documents\n\n- `regex()`, which returns documents that match a specified regular expression\n\n- `mod()`, which performs a modulo operation on the value of a field and returns documents where the remainder is a specified value\n\nTo view a full list of evaluation operators, see the Evaluation Query Operators guide in the MongoDB Server manual.\n\nThe following example specifies a `regex()` evaluation operator method in a query filter as a parameter to the `find()` method. The code uses a regular expression to return all documents with a `name` field value that has at least two consecutive `\"p\"` characters.\n\n```java\nFindPublisher findDocPublisher = fruits.find(regex(\"name\", \"p{2,}\"));\nDocument findResults = Flux.from(findDocPublisher)\n .doOnNext(System.out::println)\n .blockLast();\n```\n\n```\n{'_id': 1, 'name': 'apples', 'qty': 5, 'rating': 3, 'color': 'red', 'type': ['fuji', 'honeycrisp']}\n{'_id': 4, 'name': 'pineapple', 'qty': 3, 'rating': 5, 'color': 'yellow'}\n```\n\n## Additional Information\n\nTo learn more about querying documents, see the Query Documents guide in the MongoDB Server manual.\n\n### API Documentation\n\nTo learn more about any of the methods or types discussed in this guide, see the following API documentation:\n\n- find()\n\n- FindPublisher"} -{"chunk_id": "6a514d65d727379c91b9d78a-0", "page_id": "6a514d65d727379c91b9d78a", "source_name": "java-rs", "product_name": "Java Reactive Streams Driver", "url": "https://mongodb.com/docs/languages/java/reactive-streams-driver/current/builders/filters", "title": "Filters Builders", "text": "# Filters Builders\n\n## Overview\n\nIn this guide, you can learn how to use **builders** to specify **filters** for your queries in the Java Reactive Streams driver.\n\nBuilders are classes provided by the Java Reactive Streams driver that help you construct BSON objects. To learn more, see the builders guide.\n\nFilters are operations used to limit the results of a query based on specified conditions. Filters are a helpful tool to locate information that matches search conditions in a collection.\n\nYou can use filters in the following places:\n\n- As a parameter to the `find()` method\n\n- In a match stage of an aggregation pipeline\n\n- As a parameter to the `deleteOne()` or `deleteMany()` method\n\n- As a parameter to the `updateOne()` or `updateMany()` method\n\nSome examples of results from queries with filters are:\n\n- Items that cost more than $0 but less than $25\n\n- Foods that are both gluten-free and less than 500 calories\n\n- Food critic reviews that mention \"spicy\"\n\nThis guide shows you how to use builders with examples of the following types of operators:\n\n- Comparison\n\n- Logical\n\n- Arrays\n\n- Elements\n\n- Evaluation\n\n- Bitwise\n\n- Geospatial\n\nThe `Filters` class provides static factory methods for all the MongoDB query operators. Each method returns an instance of the BSON type, which you can pass to any method that expects a query filter.\n\nFor brevity, you may choose to import all methods of the Filters class statically:\n\n```java\nimport static com.mongodb.client.model.Filters.*;\n```\n\nThe following examples assume this static import.\n\n## Sample Data\n\nThe examples in this guide use the following sample collections:\n\nCollection: `paint_purchases`\n\n```json\n{ \"_id\": 1, \"color\": \"red\", \"qty\": 5, \"vendor\": [\"A\"] }\n{ \"_id\": 2, \"color\": \"purple\", \"qty\": 10, \"vendor\": [\"C\", \"D\"] }\n{ \"_id\": 3, \"color\": \"blue\", \"qty\": 8, \"vendor\": [\"B\", \"A\"] }\n{ \"_id\": 4, \"color\": \"white\", \"qty\": 6, \"vendor\": [\"D\"] }\n{ \"_id\": 5, \"color\": \"yellow\", \"qty\": 11, \"vendor\": [\"A\", \"B\"] }\n{ \"_id\": 6, \"color\": \"pink\", \"qty\": 5, \"vendor\": [\"C\"] }\n{ \"_id\": 7, \"color\": \"green\", \"qty\": 8,\"vendor\": [\"B\", \"C\"] }\n{ \"_id\": 8, \"color\": \"orange\", \"qty\": 7, \"vendor\": [\"A\", \"D\"] }\n```\n\nCollection: `binary_numbers`\n\n```json\n{ \"_id\": 9, \"a\": 54, \"binaryValue\": \"00110110\" }\n{ \"_id\": 10, \"a\": 20, \"binaryValue\": \"00010100\" }\n{ \"_id\": 11, \"a\": 68, \"binaryValue\": \"1000100\" }\n{ \"_id\": 12, \"a\": 102, \"binaryValue\": \"01100110\" }\n```\n\nCollection: `geo_points`\n\n```json\n{ \"_id\": 13, \"coordinates\": { \"type\": \"Point\", \"coordinates\": [2.0, 2.0] } }\n{ \"_id\": 14, \"coordinates\": { \"type\": \"Point\", \"coordinates\": [5.0, 6.0] } }\n{ \"_id\": 15, \"coordinates\": { \"type\": \"Point\", \"coordinates\": [1.0, 3.0] } }\n{ \"_id\": 16, \"coordinates\": { \"type\": \"Point\", \"coordinates\": [4.0, 7.0] } }\n```\n\n## Comparison\n\nThe comparison filters include all operators that compare the value in a document to a specified value.\n\nThe comparison operator methods include:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nComparison Method\n\n\nMatches\n\n
\neq()\n\n\nvalues equal to a specified value.\n\n
\ngt()\n\n\nvalues greater than a specified value.\n\n
\ngte()\n\n\nvalues greater than or equal to a specified value.\n\n
\nlt()\n\n\nvalues less than a specified value.\n\n
\nlte()\n\n\nvalues less than or equal to a specified value.\n\n
\nne()\n\n\nvalues not equal to a specified value.\n\n
\nin()\n\n\nany of the values specified in an array.\n\n
\nnin()\n\n\nnone of the values specified in an array.\n\n
\nempty()\n\n\nall the documents.\n\n
The following example creates a filter that matches all documents where the value of the `qty` field equals \"5\" in the `paint_purchases` collection:\n\n```java\nBson equalComparison = eq(\"qty\", 5);\nFindPublisher findPublisher = collection.find(equalComparison);\nFlux.from(findPublisher)\n .doOnNext(doc -> System.out.println(doc.toJson()))\n .blockLast();\n```\n\n```json\n{ \"_id\": 1, \"color\": \"red\", \"qty\": 5, \"vendor\": [\"A\"] }\n{ \"_id\": 6, \"color\": \"pink\", \"qty\": 5, \"vendor\": [\"C\"] }\n```\n\nThe following example creates a filter that matches all documents where the value of the `qty` field is greater than or equal to \"10\" in the `paint_purchases` collection:\n\n```java\nBson gteComparison = gte(\"qty\", 10);\nFindPublisher findPublisher = collection.find(gteComparison);\nFlux.from(findPublisher)\n .doOnNext(doc -> System.out.println(doc.toJson()))\n .blockLast();\n```\n\n```json\n{ \"_id\": 2, \"color\": \"purple\", \"qty\": 10, \"vendor\": [\"C\", \"D\"] }\n{ \"_id\": 5, \"color\": \"yellow\", \"qty\": 11, \"vendor\": [\"A\", \"B\"] }\n```\n\nThe following example creates a filter that matches all documents in the `paint_purchases` collection because the predicate is empty:\n\n```java\nBson emptyComparison = empty();\nFindPublisher findPublisher = collection.find(emptyComparison);\nFlux.from(findPublisher)\n .doOnNext(doc -> System.out.println(doc.toJson()))\n .blockLast();\n```\n\n```json\n{ \"_id\": 1, \"color\": \"red\", \"qty\": 5, \"vendor\": [\"A\"] }\n{ \"_id\": 2, \"color\": \"purple\", \"qty\": 10, \"vendor\": [\"C\", \"D\"] }\n{ \"_id\": 3, \"color\": \"blue\", \"qty\": 8, \"vendor\": [\"B\", \"A\"] }\n...\n```\n\n## Logical\n\nThe logical operators perform logical operations based on the conditions of the specified method.\n\nThe logical operator methods include:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nLogical Method\n\n\nMatches\n\n
\nand()\n\n\ndocuments with the conditions of all the filters. This operator joins filters with a logical `AND`.\n\n
\nor()\n\n\ndocuments with the conditions of either filter. This operator joins filters with a logical `OR`.\n\n
\nnot()\n\n\ndocuments that do not match the filter.\n\n
\nnor()\n\n\ndocuments that fail to match both filters. This operator joins filters with a logical `NOR`.\n\n
The following example creates a filter that matches documents where the value of the `qty` field is greater than \"8\" or the value of the `color` field equals \"pink\" in the `paint_purchases` collection:\n\n```java\nBson orComparison = or(gt(\"qty\", 8), eq(\"color\", \"pink\"));\nFindPublisher findPublisher = collection.find(orComparison);\nFlux.from(findPublisher)\n .doOnNext(doc -> System.out.println(doc.toJson()))\n .blockLast();\n```\n\n```json\n{ \"_id\": 2, \"color\": \"purple\", \"qty\": 10, \"vendor\": [\"C\", \"D\"] }\n{ \"_id\": 5, \"color\": \"yellow\", \"qty\": 11, \"vendor\": [\"A\", \"B\"] }\n{ \"_id\": 6, \"color\": \"pink\", \"qty\": 5, \"vendor\": [\"C\"] }\n```"} -{"chunk_id": "6a514d65d727379c91b9d78a-1", "page_id": "6a514d65d727379c91b9d78a", "source_name": "java-rs", "product_name": "Java Reactive Streams Driver", "url": "https://mongodb.com/docs/languages/java/reactive-streams-driver/current/builders/filters", "title": "Filters Builders", "text": "## Arrays\n\nThe array operators evaluate the array field in a document.\n\nThe array operator methods include:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nArray Method\n\n\nMatches\n\n
\nall()\n\n\ndocuments if the array field contains every element specified in the query.\n\n
\nelemMatch()\n\n\ndocuments if an element in the array field matches all the specified conditions.\n\n
\nsize()\n\n\ndocuments if the array field is a specified number of elements.\n\n
The following example matches documents with a `vendor` array containing both \"A\" and \"D\" in the `paint_purchases` collection:\n\n```java\nList search = Arrays.asList(\"A\", \"D\");\nBson allComparison = all(\"vendor\", search);\nFindPublisher findPublisher = collection.find(allComparison);\nFlux.from(findPublisher)\n .doOnNext(doc -> System.out.println(doc.toJson()))\n .blockLast();\n```\n\n```json\n{ \"_id\": 8, \"color\": \"orange\", \"qty\": 7, \"vendor\": [\"A\", \"D\"] }\n```\n\n## Elements\n\nThe elements operators evaluate the nature of a specified field.\n\nThe elements operator methods include:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nElements Method\n\n\nMatches\n\n
\nexists()\n\n\ndocuments that have the specified field.\n\n
\ntype()\n\n\ndocuments if a field is of the specified type.\n\n
The following example matches documents that have a `qty` field and a value not equal to \"5\" or \"8\" in the `paint_purchases` collection:\n\n```java\nBson existsComparison = and(exists(\"qty\"), nin(\"qty\", 5, 8));\nFindPublisher findPublisher = collection.find(existsComparison);\nFlux.from(findPublisher)\n .doOnNext(doc -> System.out.println(doc.toJson()))\n .blockLast();\n```\n\n```json\n{ \"_id\": 2, \"color\": \"purple\", \"qty\": 10, \"vendor\": [\"C\", \"D\"] }\n{ \"_id\": 4, \"color\": \"white\", \"qty\": 6, \"vendor\": [\"D\"]}\n{ \"_id\": 5, \"color\": \"yellow\", \"qty\": 11, \"vendor\": [\"A\", \"B\"] }\n{ \"_id\": 8, \"color\": \"orange\", \"qty\": 7, \"vendor\": [\"A\", \"D\"] }\n```\n\n## Evaluation\n\nThe evaluation operators evaluate the value of any field in a document.\n\nThe evaluation operator methods include:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nEvaluation Method\n\n\nMatches\n\n
\nmod()\n\n\ndocuments where a modulo operation on a field value produces a specified result.\n\n
\nregex()\n\n\ndocuments where values contain a specified regular expression.\n\n
\ntext()\n\n\ndocuments which contain a specified full-text search expression.\n\n
\nwhere()\n\n\ndocuments which contain a specified JavaScript expression.\n\n
The following example matches documents that have a `color` field starting with the letter \"p\" in the `paint_purchases` collection:\n\n```java\nBson regexComparison = regex(\"color\", \"^p\");\nFindPublisher findPublisher = collection.find(regexComparison);\nFlux.from(findPublisher)\n .doOnNext(doc -> System.out.println(doc.toJson()))\n .blockLast();\n```\n\n```json\n{ \"_id\": 2, \"color\": \"purple\", \"qty\": 10, \"vendor\": [\"C\", \"D\"] }\n{ \"_id\": 6, \"color\": \"pink\", \"qty\": 5, \"vendor\": [\"C\"] }\n```\n\n## Bitwise\n\nThe bitwise operators convert a number into its binary value to evaluate its bits.\n\nThe bitwise operator methods include:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nBitwise Method\n\n\nMatches\n\n
\nbitsAllSet()\n\n\ndocuments where the specified bits of a field are set (i.e. \"1\").\n\n
\nbitsAllClear()\n\n\ndocuments where the specified bits of a field are clear (i.e. \"0\").\n\n
\nbitsAnySet()\n\n\ndocuments where at least one of the specified bits of a field are set (i.e. \"1\").\n\n
\nbitsAnyClear()\n\n\ndocuments where at least one of the specified bits of a field are clear (i.e. \"0\").\n\n
The following example matches documents that have an `a` field with bits set at positions of the corresponding bitmask \"34\" (i.e. \"00100010\") in the `binary_numbers` collection:\n\n```java\nBson bitsComparison = bitsAllSet(\"a\", 34);\nFindPublisher findPublisher = collection.find(bitsComparison);\nFlux.from(findPublisher)\n .doOnNext(doc -> System.out.println(doc.toJson()))\n .blockLast();\n```\n\n```json\n{ \"_id\": 9, \"a\": 54, \"binaryValue\": \"00110110\" }\n{ \"_id\": 12, \"a\": 102, \"binaryValue\": \"01100110\" }\n```\n\n## Geospatial\n\nThe geospatial operators evaluate a specified coordinate and its relation to a shape or location.\n\nThe geospatial operator methods include:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nGeospatial Method\n\n\nMatches\n\n
\ngeoWithin()\n\n\ndocuments containing a GeoJSON geometry value that falls within a bounding GeoJSON geometry.\n\n
\ngeoWithinBox()\n\n\ndocuments containing a coordinates value that exist within the specified box.\n\n
\ngeoWithinPolygon()\n\n\ndocuments containing a coordinates value that exist within the specified polygon.\n\n
\ngeoWithinCenter()\n\n\ndocuments containing a coordinates value that exist within the specified circle.\n\n
\ngeoWithinCenterSphere()\n\n\ngeometries containing a geospatial data value (GeoJSON or legacy coordinate pairs) that exist within the specified circle, using spherical geometry.\n\n
\ngeoIntersects()\n\n\ngeometries that intersect with a GeoJSON geometry. The `2dsphere` index supports `$geoIntersects`.\n\n
\nnear()\n\n\ngeospatial objects in proximity to a point. Requires a geospatial index. The `2dsphere` and `2d` indexes support `$near`.\n\n
\nnearSphere()\n\n\ngeospatial objects in proximity to a point on a sphere. Requires a geospatial index. The `2dsphere` and `2d` indexes support `$nearSphere`.\n\n
The following example creates a filter that matches documents in which the `point` field contains a GeoJSON geometry that falls within the given Polygon in the `geo_points` collection:\n\n```java\nPolygon square = new Polygon(Arrays.asList(\n new Position(0, 0),\n new Position(4, 0),\n new Position(4, 4),\n new Position(0, 4),\n new Position(0, 0)));\nBson geoWithinComparison = geoWithin(\"coordinates\", square);\nFindPublisher findPublisher = collection.find(geoWithinComparison);\nFlux.from(findPublisher)\n .doOnNext(doc -> System.out.println(doc.toJson()))\n .blockLast();\n```\n\n```json\n{ \"_id\": 13, \"coordinates\": {\"type\": \"Point\", \"coordinates\": [2.0, 2.0]} }\n{ \"_id\": 15, \"coordinates\": {\"type\": \"Point\", \"coordinates\": [1.0, 3.0]} }\n```"} -{"chunk_id": "6a514d65d727379c91b9d7a5-0", "page_id": "6a514d65d727379c91b9d7a5", "source_name": "java-rs", "product_name": "Java Reactive Streams Driver", "url": "https://mongodb.com/docs/languages/java/reactive-streams-driver/current/crud/insert-documents", "title": "Insert Documents", "text": "# Insert Documents\n\n## Overview\n\nIn this guide, you can learn how to use the Java Reactive Streams driver to add documents to a MongoDB collection by performing insert operations.\n\nAn insert operation inserts one or more documents into a MongoDB collection. You can perform an insert operation by using the `insertOne()` or `insertMany()` methods.\n\n### Sample Data\n\nThe examples in this guide use the `sample_restaurants.restaurants` collection from the Atlas sample datasets.\n\nTo learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the Get Started tutorial.\n\nThis guide uses the Project Reactor library to consume `Publisher` instances returned by the Java Reactive Streams driver methods. To learn more about the Project Reactor library and how to use it, see Getting Started in the Reactor documentation. To learn more about how we use Project Reactor library methods in this guide, see the Write Data to MongoDB guide.\n\n## The `_id` Field\n\nIn a MongoDB collection, each document *must* contain an `_id` field with a unique field value.\n\nMongoDB allows you to manage this field in two ways:\n\n- You can set this field for each document yourself, ensuring each `_id` field value is unique.\n\n- You can let the driver automatically generate unique `ObjectId` values for each document `_id`. If you do not manually set an `_id` value for a document, the driver populates the field with an `ObjectId`.\n\nUnless you can guarantee uniqueness, we recommend letting the driver automatically generate `_id` values.\n\nDuplicate `_id` values violate unique index constraints, which causes the driver to return a `WriteError` from `insertOne()` or a `BulkWriteError` from `insertMany()`.\n\nTo learn more about the `_id` field, see the Unique Indexes guide in the MongoDB Server manual.\n\nTo learn more about document structure and rules, see the Documents guide in the MongoDB Server manual.\n\n## Insert One Document\n\nTo add a single document to a MongoDB collection, call the `insertOne()` method and pass the document you want to add. Then, pass the `insertOne()` result to the static `Mono.from()` method from `Mono`. `Mono` is a class from the Project Reactor library. In Java Reactive Streams, the driver methods return cold `Publisher` instances, which means that the corresponding operation does not happen unless you subscribe to the returned `Publisher`. This guide uses the Project Reactor library to consume them. To learn more about `Mono`, see Mono in the Project Reactor documentation.\n\nThe following example uses the `insertOne()` method to insert a document in which the `name` value is `\"Mongo's Burgers\"` into the `restaurants` collection:\n\n```java\n Document document = new Document(\"name\", \"Mongo's Burgers\");\n Publisher insertPublisher = restaurants.insertOne(document);\n Mono.from(insertPublisher).block();\n```\n\n## Insert Multiple Documents\n\nTo add multiple documents to a MongoDB collection, call the `insertMany()` method and pass a list of documents you want to add. Then, pass the `insertMany()` result to the static `Mono.from()` method from `Mono`. `Mono` is a class from the Project Reactor library. In Java Reactive Streams, the driver methods return cold `Publisher` instances, which means that the corresponding operation does not happen unless you subscribe to the returned `Publisher`. This guide uses the Project Reactor library to consume them. To learn more about `Mono`, see Mono in the Project Reactor documentation.\n\nThe following example uses the `insertMany()` method to insert a list of documents into the `restaurants` collection:\n\n```java\n Document doc1 = new Document(\"name\", \"Mongo's Pizza\");\n Document doc2 = new Document(\"name\", \"Mongo's Coffee\");\n\n List documents = Arrays.asList(doc1, doc2);\n\n Publisher insertPublisher = restaurants.insertMany(documents);\n Mono.from(insertPublisher).block();\n```\n\n## Modify Insert Behavior\n\nThe `InsertOneOptions` class contains methods that modify the behavior of the `insertOne()` method. To use the `InsertOneOptions` class, construct a new instance of the class, then call one or more of its methods to modify the insert operation. You can chain these method calls together. To modify the behavior of the insert operation, pass the class instance and chained method calls as the second argument to the `insertOne()` method.\n\nYou can similarly modify the `insertMany()` method by using the `InsertManyOptions` class.\n\nYou can use the following methods in the `InsertOneOptions` class to modify the `insertOne()` method. All methods are optional.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nMethod\n\n\nDescription\n\n
\n`bypassDocumentValidation (Boolean bypassDocumentValidation)`\n\n\nIf set to `True`, allows the write to opt out of document-level validation.Defaults to `False`.\n\n
\n`toString()`\n\n\nIf used, returns a string representation of the object.\n\n
\n`comment(BsonValue comment)`\n\n\nA comment to attach to the operation. For more information, see the insert command fields guide in the MongoDB Server manual.\n\n
The `InsertManyOptions` class contains the previous methods, as well as the following `ordered()` method:\n\n\n\n\n\n\n\n\n\n\n
\nMethod\n\n\nDescription\n\n
\n`ordered(Boolean ordered)`\n\n\nIf set to `True`, the driver sends documents to the server in the order provided. If an error occurs, the driver and server cancel all remaining insert operations.Defaults to `True`.\n\n
### Example\n\nThe following code uses the `insertMany()` method to insert new documents into the `restaurants` collection. It also sets the `bypassDocumentValidation(true)` option to bypass document-level validation.\n\n```java\n Document doc1 = new Document(\"name\", \"Mongo's Burgers\");\n Document doc2 = new Document(\"name\", \"Mongo's Pizza\");\n Document doc3 = new Document(\"name\", \"Mongo's Coffee\");\n\n List documents = Arrays.asList(doc1, doc2, doc3);\n\nPublisher insertPublisher =\n restaurants.insertMany(documents,\n new InsertManyOptions().bypassDocumentValidation(true));\n\n Mono.from(insertPublisher).block();\n```\n\n## Additional Information\n\nFor runnable code examples of inserting documents with the Java Reactive Streams driver, see the CRUD Operations guide.\n\n### API Documentation\n\nTo learn more about any of the methods or types discussed in this guide, see the following API documentation:\n\n- insertOne()\n\n- insertMany()\n\n- InsertOneOptions\n\n- InsertManyOptions\n\n- BsonValue"} -{"chunk_id": "68a95c375e79d242619e0ed2-0", "page_id": "68a95c375e79d242619e0ed2", "source_name": "java-rs", "product_name": "Java Reactive Streams Driver", "url": "https://mongodb.com/docs/languages/java/reactive-streams-driver/current/aggregation", "title": "Aggregation Framework", "text": "# Aggregation Framework\n\nThe aggregation pipeline is a framework for data aggregation, modeled on the concept of data processing pipelines.\n\nTo learn more about aggregation, see Aggregation Pipeline in the Server manual.\n\n## Prerequisites\n\nYou must set up the following components to run the code examples in this guide:\n\n- A `test.restaurants` collection populated with documents from the `restaurants.json` file in the documentation assets GitHub.\n\n- The following import statements:\n\n```java\nimport com.mongodb.reactivestreams.client.MongoClients;\nimport com.mongodb.reactivestreams.client.MongoClient;\nimport com.mongodb.reactivestreams.client.MongoCollection;\nimport com.mongodb.reactivestreams.client.MongoDatabase;\nimport com.mongodb.client.model.Aggregates;\nimport com.mongodb.client.model.Accumulators;\nimport com.mongodb.client.model.Projections;\nimport com.mongodb.client.model.Filters;\n\nimport org.bson.Document;\n```\n\nThis guide uses custom `Subscriber` implementations, which are described in the Sample Custom Subscriber Implementations guide.\n\n## Connect to a MongoDB Deployment\n\nFirst, connect to a MongoDB deployment, then declare and define `MongoDatabase` and `MongoCollection` instances.\n\nThe following code connects to a standalone MongoDB deployment running on `localhost` on port `27017`. Then, it defines the `database` variable to refer to the `test` database and the `collection` variable to refer to the `restaurants` collection:\n\n```java\nMongoClient mongoClient = MongoClients.create();\nMongoDatabase database = mongoClient.getDatabase(\"test\");\nMongoCollection collection = database.getCollection(\"restaurants\");\n```\n\nTo learn more about connecting to MongoDB deployments, see the Connect to MongoDB tutorial.\n\n## Perform Aggregation\n\nTo perform aggregation, pass a list of aggregation stages to the `MongoCollection.aggregate()` method. The driver provides the `Aggregates` helper class that contains builders for aggregation stages.\n\nIn this example, the aggregation pipeline performs the following tasks:\n\n- Uses a `$match` stage to filter for documents in which the `categories` array field contains the element `\"Bakery\"`. The example uses `Aggregates.match()` to build the `$match` stage.\n\n- Uses a `$group` stage to group the matching documents by the `stars` field, accumulating a count of documents for each distinct value of `stars`. The example uses `Aggregates.group()` to build the `$group` stage and `Accumulators.sum()` to build the accumulator expression. For the accumulator expressions for use within the `$group` stage, the driver provides `Accumulators` helper class.\n\n```java\ncollection.aggregate(\n Arrays.asList(\n Aggregates.match(Filters.eq(\"categories\", \"Bakery\")),\n Aggregates.group(\"$stars\", Accumulators.sum(\"count\", 1))\n )\n).subscribe(new PrintDocumentSubscriber());\n```\n\n### Use Aggregation Expressions\n\nFor `$group` accumulator expressions, the driver provides the `Accumulators` helper class. For other aggregation expressions, manually build the expression by using the `Document` class.\n\nIn the following example, the aggregation pipeline uses a `$project` stage to return only the `name` field and the calculated field `firstCategory` whose value is the first element in the `categories` array. The example uses `Aggregates.project()` and various `Projections` class methods to build the `$project` stage:\n\n```java\ncollection.aggregate(\n Arrays.asList(\n Aggregates.project(\n Projections.fields(\n Projections.excludeId(),\n Projections.include(\"name\"),\n Projections.computed(\n \"firstCategory\",\n new Document(\"$arrayElemAt\", Arrays.asList(\"$categories\", 0))\n )\n )\n )\n )\n).subscribe(new PrintDocumentSubscriber());\n```\n\n### Explain an Aggregation\n\nTo `$explain` an aggregation pipeline, call the `AggregatePublisher.explain()` method:\n\n```java\ncollection.aggregate(\n Arrays.asList(\n Aggregates.match(Filters.eq(\"categories\", \"Bakery\")),\n Aggregates.group(\"$stars\", Accumulators.sum(\"count\", 1))))\n .explain()\n .subscribe(new PrintDocumentSubscriber());\n```\n\n## MongoDB Search\n\nYou can perform a MongoDB Search query by creating and running an aggregation pipeline that contains one of the following pipeline stages:\n\n- `$search`\n\n- `$searchMeta`\n\nThe Java Reactive Streams driver provides the Aggregates.search() and Aggregates.searchMeta() methods to perform MongoDB Search queries.\n\nTo learn more about MongoDB Search pipeline stages, see Choose the Aggregation Pipeline Stage in the Atlas documentation.\n\nThe `$search` aggregation-pipeline operator is available only for collections hosted on MongoDB Atlas clusters running MongoDB v4.2 or later, or on MongoDB Community Edition clusters running MongoDB v8.2 or later. Collections must be covered by a MongoDB Search index. To learn more about the required setup and the functionality of this operator, see the MongoDB Search documentation."} -{"chunk_id": "68a95c375e79d242619e0ed2-1", "page_id": "68a95c375e79d242619e0ed2", "source_name": "java-rs", "product_name": "Java Reactive Streams Driver", "url": "https://mongodb.com/docs/languages/java/reactive-streams-driver/current/aggregation", "title": "Aggregation Framework", "text": "### Create Pipeline Search Stages\n\nYou can create the search criteria in your MongoDB Search pipeline stage by using Search operators.\n\nthe MongoDB Search Index Management section of the Indexes guide\n\n```java\nBson searchStageFilters = Aggregates.search(\n SearchOperator.compound()\n .filter(\n List.of(\n SearchOperator.in(fieldPath(\"genres\"), List.of(\"Comedy\")),\n SearchOperator.phrase(fieldPath(\"fullplot\"), \"new york\"),\n SearchOperator.numberRange(fieldPath(\"year\")).gtLt(1950, 2000),\n SearchOperator.wildcard(fieldPath(\"title\"), \"Love *\")\n )));\n\nBson projection = Aggregates.project(Projections.fields(\n Projections.include(\"title\", \"year\", \"genres\")\n));\n\nList aggregateStages = List.of(searchStageFilters, projection);\n\nPublisher publisher = movies.aggregate(aggregateStages);\npublisher.subscribe(new SubscriberHelpers.PrintDocumentSubscriber());\nMono.from(publisher).block();\n```\n\n```console\n{\"_id\": ..., \"genres\": [\"Comedy\", \"Romance\"], \"title\": \"Love at First Bite\", \"year\": 1979}\n{\"_id\": ..., \"genres\": [\"Comedy\", \"Drama\"], \"title\": \"Love Affair\", \"year\": 1994}\n```\n\nThe Java Reactive Streams driver provides helper methods for the following operators:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nOperator\n\n\nDescription\n\n
\nautocomplete\n\n\nPerforms a search for a word or phrase that contains a sequence of characters from an incomplete input string.\n\n
\ncompound\n\n\nCombines two or more operators into a single query.\n\n
\nequals\n\n\nChecks whether a field matches a value you specify. Maps to the `equals()` and `equalsNull()` methods.\n\n
\nexists\n\n\nTests if a path to a specified indexed field name exists in a document.\n\n
\nin\n\n\nPerforms a search for an array of BSON number, date, boolean, objectId, uuid, or string values at the given path and returns documents where the value of the field equals any value in the specified array.\n\n
\nmoreLikeThis\n\n\nReturns documents similar to input documents.\n\n
\nnear\n\n\nSupports querying and scoring numeric, date, and GeoJSON point values.\n\n
\nphrase\n\n\nPerforms a search for documents containing an ordered sequence of terms using the analyzer specified in the index configuration.\n\n
\nqueryString\n\n\nSupports querying a combination of indexed fields and values.\n\n
\nrange\n\n\nSupports querying and scoring numeric, date, and string values. Maps to the `numberRange()` and `dateRange()` methods.\n\n
\nregex\n\n\nInterprets the query field as a regular expression.\n\n
\ntext\n\n\nPerforms a full-text search using the analyzer that you specify in the index configuration.\n\n
\nwildcard\n\n\nEnables queries which use special characters in the search string that can match any character.\n\n
#### Example Pipeline Search Stage\n\nBefore you can run this example, you must create a MongoDB Search index on the `movies` collection that has the following definition:\n\n```json\n{\n \"mappings\": {\n \"dynamic\": true,\n \"fields\": {\n \"title\": {\n \"analyzer\": \"lucene.keyword\",\n \"type\": \"string\"\n },\n \"genres\": {\n \"normalizer\": \"lowercase\",\n \"type\": \"token\"\n }\n }\n }\n}\n```\n\nTo learn more about creating MongoDB Search indexes, see the MongoDB Search Index Management section of the Indexes guide.\n\nThe following code creates a `$search` stage that has the following specifications:\n\n- Checks that the `genres` array includes `\"Comedy\"`\n\n- Searches the `fullplot` field for the phrase `\"new york\"`\n\n- Matches `year` values between `1950` and `2000`, inclusive\n\n- Searches for `title` values that begins with the term `\"Love\"`\n\n```java\nBson searchStageFilters = Aggregates.search(\n SearchOperator.compound()\n .filter(\n List.of(\n SearchOperator.in(fieldPath(\"genres\"), List.of(\"Comedy\")),\n SearchOperator.phrase(fieldPath(\"fullplot\"), \"new york\"),\n SearchOperator.numberRange(fieldPath(\"year\")).gtLt(1950, 2000),\n SearchOperator.wildcard(fieldPath(\"title\"), \"Love *\")\n )));\n\nBson projection = Aggregates.project(Projections.fields(\n Projections.include(\"title\", \"year\", \"genres\")\n));\n\nList aggregateStages = List.of(searchStageFilters, projection);\n\nPublisher publisher = movies.aggregate(aggregateStages);\npublisher.subscribe(new SubscriberHelpers.PrintDocumentSubscriber());\nMono.from(publisher).block();\n```\n\n```console\n{\"_id\": ..., \"genres\": [\"Comedy\", \"Romance\"], \"title\": \"Love at First Bite\", \"year\": 1979}\n{\"_id\": ..., \"genres\": [\"Comedy\", \"Drama\"], \"title\": \"Love Affair\", \"year\": 1994}\n```\n\nTo learn more about the MongoDB Search helper methods, see the SearchOperator interface reference in the Driver Core API documentation.\n\n## Additional Information\n\nFor a full list of aggregation stages, see Aggregation Stages in the MongoDB Server manual.\n\nTo learn about assembling an aggregation pipeline and view examples, see Aggregation Pipeline in the MongoDB Server manual.\n\nTo learn more about explaining MongoDB operations, see Explain Output and Query Plans in the MongoDB Server manual.\n\n### API Documentation\n\nTo learn more about the classes and methods mentioned in this guide, see the following API documentation:\n\n- aggregate()\n\n- Aggregates\n\n- AggregatePublisher\n\n- search()\n\n- project()"} -{"chunk_id": "68a95c115e79d242619dbb92-0", "page_id": "68a95c115e79d242619dbb92", "source_name": "kafka-connector", "product_name": "MongoDB Kafka Connector", "url": "https://mongodb.com/docs/kafka-connector/current/sink-connector/configuration-properties/time-series", "title": "Kafka Time Series Properties", "text": "# Kafka Time Series Properties\n\n## Overview\n\nUse the following configuration settings to specify how the MongoDB Kafka sink connector should sink data to a MongoDB time series collection.\n\nFor a list of sink connector configuration settings organized by category, see the guide on Sink Connector Configuration Properties.\n\n## Settings\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nDescription\n\n
\n**timeseries.timefield**\n\n\n**Type:** string**Description:**The name of the top-level field in the source data that contains time information that you want to associate with the new document in the time series collection.**Default**: `\"\"`**Accepted Values**: An empty string or the name of a field that contains a BSON `DateTime` value\n\n
\n**timeseries.timefield.auto.convert.date.format**\n\n\n**Type:** string**Description:**The date format pattern the connector should use to convert the source data contained in the field specified by the `timeseries.timefield` setting.The connector passes the date format pattern to the Java DateTimeFormatter.ofPattern(pattern, locale) method to perform date and time conversions on the time field.If the date value from the source data only contains date information, the connector sets the time information to the start of the specified day. If the date value does not contain the timezone offset, the connector sets the offset to UTC.**Default**:```none\nyyyy-MM-dd[['T'][ ]][HH:mm:ss[[.][SSSSSS][SSS]][ ]VV[ ]'['VV']'][HH:mm:ss[[.][SSSSSS][SSS]][ ]X][HH:mm:ss[[.][SSSSSS][SSS]]]\n```\n\n**Accepted Values**: A valid `DateTimeFormatter` format\n\n
\n**timeseries.timefield.auto.convert**\n\n\n**Type:** boolean**Description:**Whether to convert the data in the field into the BSON `Date` format.When set to `true`, the connector uses the milliseconds after epoch and discards fractional parts if the value is a number. If the value is a string, the connector uses the setting in the following configuration to parse the date:```none\ntimeseries.timefield.auto.convert.date.format\n```\n\nIf the connector fails to convert the value, it sends the original value to the time series collection.**Default**: `false`**Accepted Values**: `true` or `false`\n\n
\n**timeseries.timefield.auto.convert.locale.language.tag**\n\n\n**Type:** string**Description:**Which `DateTimeFormatter` locale language tag to use with the date format pattern (e.g. `\"en-US\"`).To learn more about locales, see the Java SE documentation of Locale.**Default**: `ROOT`**Accepted Values**: A valid `Locale` language tag format\n\n
\n**timeseries.metafield**\n\n\n**Type:** string**Description:**Which top-level field to read from the source data to describe a group of related time series documents.IMPORTANT: This field must not be the `_id` field nor the field you specified in the `timeseries.timefield` setting.**Default**: `\"\"`**Accepted Values**: An empty string or the name of a field that contains any BSON type except `BsonArray`.\n\n
\n**timeseries.expire.after.seconds**\n\n\n**Type:** int**Description:**The number of seconds MongoDB should wait before automatically removing the time series collection data. The connector disables timed expiry when the setting value is less than `1`.To learn more, see Set up Automatic Removal for Time Series Collections in the MongoDB manual.**Default**: `0`**Accepted Values**: An integer\n\n
\n**timeseries.granularity**\n\n\n**Type:** string**Description:**The expected interval between subsequent measurements of your source data.To learn more, see Set Granularity for Time Series Data in the MongoDB manual.*Optional***Default**: `\"\"`**Accepted Values**: `\"\"`, `\"seconds\"`, `\"minutes\"`, `\"hours\"`\n\n
For an example on how to convert an existing collection to a time series collection, see the tutorial on how to Migrate an Existing Collection to a Time Series Collection."} -{"chunk_id": "68a95c115e79d242619dbbda-0", "page_id": "68a95c115e79d242619dbbda", "source_name": "kafka-connector", "product_name": "MongoDB Kafka Connector", "url": "https://mongodb.com/docs/kafka-connector/current/sink-connector/configuration-properties/post-processors", "title": "Sink Connector Post-processor Properties", "text": "# Sink Connector Post-processor Properties\n\n## Overview\n\nUse the following configuration settings to specify how the MongoDB Kafka sink connector should transform Kafka data before inserting it into MongoDB.\n\nFor a list of sink connector configuration settings organized by category, see the guide on Sink Connector Configuration Properties.\n\n## Settings\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nDescription\n\n
\n**post.processor.chain**\n\n\n**Type:** list**Description:**A list of post-processor classes the connector should apply to process the data before saving it to MongoDB.To learn more about post-processors and see examples oftheir usage, seeSink Connector Post Processors.**Default**:```none\ncom.mongodb.kafka.connect.sink.processor.DocumentIdAdder\n```\n\n**Accepted Values**: A comma-separated list of fully qualified Java class names\n\n
\n**field.renamer.mapping**\n\n\n**Type:** string**Description:**A list of field name mappings for key and value fields. Define the mappings in an inline JSON array in the following format:```none\n[ { \"oldName\":\"key.fieldA\", \"newName\":\"field1\" }, { \"oldName\":\"value.xyz\", \"newName\":\"abc\" } ]\n```\n\n**Default**: `[]`**Accepted Values**: A valid JSON array\n\n
\n**field.renamer.regexp**\n\n\n**Type:** string**Description:**A list of field name mappings for key and value fields using regular expressions. Define the mappings in an inline JSON array in the following format:```none\n[ {\"regexp\":\"^key\\\\\\\\..*my.*$\", \"pattern\":\"my\", \"replace\":\"\"}, {\"regexp\":\"^value\\\\\\\\..*$\", \"pattern\":\"\\\\\\\\.\", \"replace\":\"_\"} ]\n```\n\n**Default**: `[]`**Accepted Values**: A valid JSON array\n\n
\n**field.value.transformer**\n\n\n**Type:** string**Description:**Fully qualified class name of a `FieldValueTransformer` implementation. When configured, the connector applies the specified transformer to the fields listed in `field.value.transformer.fields` before writing to MongoDB. The class must implement `com.mongodb.kafka.connect.sink.processor.field.transform.FieldValueTransformer` and have a public no-arg constructor.**Default**: `\"\"`**Accepted Values**: A fully qualified Java class name\n\n
\n**field.value.transformer.fields**\n\n\n**Type:** string**Description:**Comma-separated list of field names to which the connector applies the configured `FieldValueTransformer`. The connector also transforms nested fields in sub-documents with matching names.**Default**: `\"\"`**Accepted Values**: A comma-separated list of field names\n\n
\n**key.projection.list**\n\n\n**Type:** string**Description:**A list of field names the connector should include in the key projection.**Default**: `\"\"`**Accepted Values**: A comma-separated list of field names\n\n
\n**key.projection.type**\n\n\n**Type:** string**Description:**The key projection type the connector should use.**Default**: `none`**Accepted Values**: `none`, `BlockList`, or `AllowList` (*Deprecated: blacklist, whitelist*)\n\n
\n**value.projection.list**\n\n\n**Type:** string**Description:**A list of field names the connector should include in the value projection.**Default**: `\"\"`**Accepted Values**: A comma-separated list of field names\n\n
\n**value.projection.type**\n\n\n**Type:** string**Description:**The type of value projection the connector should use.**Default**: `none`**Accepted Values**: `none`, `BlockList`, or `AllowList` (*Deprecated: blacklist, whitelist*)\n\n
\n**writemodel.strategy**\n\n\n**Type:** string**Description:**The class that specifies the `WriteModelStrategy` the connector should use for Bulk Writes.To learn more about how to create your own strategy, seeCustom Write Model Strategies.**Default**:```none\ncom.mongodb.kafka.connect.sink.writemodel.strategy.DefaultWriteModelStrategy\n```\n\n**Accepted Values**: A fully qualified Java class name\n\n
"} -{"chunk_id": "68a95c115e79d242619dbb14-0", "page_id": "68a95c115e79d242619dbb14", "source_name": "kafka-connector", "product_name": "MongoDB Kafka Connector", "url": "https://mongodb.com/docs/kafka-connector/current", "title": "MongoDB Kafka Connector", "text": "# MongoDB Kafka Connector\n\n## Overview\n\nThe MongoDB Connector for Apache Kafka is a Confluent-verified connector that persists data from Apache Kafka topics as a data sink into MongoDB and publishes changes from MongoDB into Kafka topics as a data source.\n\nWe recommend that you use one of the following MongoDB partner service offerings to host your Apache Kafka cluster and MongoDB Kafka Connector:\n\n- Confluent Cloud\n\n - Register to learn more about the MongoDB Source Connector, or read the documentation.\n\n - Register to learn more about the MongoDB Sink Connector, or read the documentation.\n\n- Amazon Managed Streaming for Apache Kafka (MSK)\n\n- Redpanda Cloud\n\n - To learn more about the MongoDB Source Connector, read the documentation.\n\n - To learn more about the MongoDB Sink Connector, read the documentation.\n\nAtlas Stream Processing provides MongoDB-native tooling to continuously process streaming data, validate schemas, and materialize views into either Atlas database collections or Apache Kafka topics.\n\nTo learn more about Atlas Stream Processing, see Atlas Stream Processing.\n\n## What's New\n\nFor a list of new features and changes in each version, see the What's New section.\n\n## Quick Start\n\nLearn how to get started with the MongoDB Kafka Connector and begin working with data in the Kafka Connector Quick Start section.\n\n## Introduction\n\nLearn about and how the MongoDB Kafka Connector passes data between Apache Kafka and MongoDB in the Introduction section. In this section, you can also learn about how to install the connector and configure it to connect to your MongoDB deployment.\n\n## Tutorials\n\nFollow tutorials to learn how to set up the MongoDB Kafka Connector to read and write data for several use cases.\n\n## Sink Connector\n\nLearn how to configure how the MongoDB Kafka sink connector writes data from Apache Kafka into MongoDB in the Sink Connector section.\n\n## Source Connector\n\nLearn how to configure how the MongoDB Kafka source connector writes data from MongoDB into Apache Kafka in the Source Connector section.\n\n## Security and Authentication\n\nLearn how to secure communications between MongoDB and the MongoDB Kafka Connector in the Security and Authentication section. In this section, you can also learn how to configure the MongoDB Kafka Connector to authenticate to MongoDB with your AWS Identity and IAM credentials.\n\n## Monitoring\n\nLearn how to monitor your MongoDB Kafka source and sink connectors in the Monitoring section.\n\n## Migrate from the Community Connector\n\nLearn how to to migrate from the legacy Kafka Connect MongoDB sink connector to the official MongoDB Kafka Connector in the Migration Guide.\n\n## Troubleshooting\n\nLearn how to resolve issues you may encounter while running the MongoDB Kafka Connector in the Troubleshooting section.\n\n## How to Contribute\n\nLearn how to contribute to the MongoDB Kafka Connector codebase in the How to Contribute section.\n\n## Issues & Help\n\nLearn how to report bugs and request features in the Issues & Help section.\n\n## Compatibility\n\nFor information about compatibility between the MongoDB Kafka Connector and MongoDB, see the Compatibility section. In this section, you can also learn about compatibility between the MongoDB Kafka Connector and Confluent Kafka Connect."} -{"chunk_id": "68a95c115e79d242619dbb22-0", "page_id": "68a95c115e79d242619dbb22", "source_name": "kafka-connector", "product_name": "MongoDB Kafka Connector", "url": "https://mongodb.com/docs/kafka-connector/current/issues-and-help", "title": "Issues & Help", "text": "# Issues & Help\n\nOften, the quickest way to get support for general questions is through the MongoDB communities on Reddit or Stack Overflow.\n\nRefer to our support channels documentation for more information.\n\n## Bugs / Feature Requests\n\nIf you think you've found a bug or want to see a new feature in the MongoDB Kafka Connector, please open a case in our issue management tool, JIRA:\n\n- Create an account and login.\n\n- Navigate to the KAFKA project.\n\n- Click **Create**. Please provide as much information as possible about the issue and the steps to reproduce it.\n\nBug reports in JIRA for the Kafka Connector project are **public**.\n\nIf you've identified a security vulnerability in the connector or any other MongoDB project, please report it according to the instructions found in the Create a Vulnerability Report."} -{"chunk_id": "68a95c115e79d242619dbb79-0", "page_id": "68a95c115e79d242619dbb79", "source_name": "kafka-connector", "product_name": "MongoDB Kafka Connector", "url": "https://mongodb.com/docs/kafka-connector/current/source-connector/configuration-properties/startup", "title": "Startup Properties", "text": "# Startup Properties\n\n## Overview\n\nUse the following configuration settings to configure startup of the MongoDB Kafka source connector to convert MongoDB collections into Change Stream events.\n\nFor an example using the copy existing feature, see the Copy Existing Data Usage Example.\n\nFor a list of source connector configuration settings organized by category, see the guide on Source Connector Configuration Properties.\n\n## Settings\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nDescription\n\n
\n**startup.mode**\n\n\n**Type:** string**Description:**Specifies how the connector should start up when there is no source offset available. Resuming a change stream requires a resume token, which the connector gets from the source offset. If no source offset is available, the connector may either ignore all or some of the existing source data, or may at first copy all existing source data and then continue with processing new data.If `startup.mode=latest`, the connector ignores all existing source data.If `startup.mode=timestamp`, the connector actuates `startup.mode.timestamp.*` properties. If no properties are configured, `timestamp` is equivalent to `latest`.If `startup.mode=copy_existing`, the connector copies all existing source data to Change Stream events. This setting is equivalent to the deprecated setting `copy.existing=true`.If any system changes the data in the database while the source connector converts existing data from it, MongoDB may produce duplicate change stream events to reflect the latest changes. Since the change stream events on which the data copy relies are idempotent, the copied data is eventually consistent, conformant to an \"at-least-once\" delivery guarantee.\n\n**Default**:`latest`**Accepted Values**: `latest`, `timestamp`, `copy_existing`\n\n
\n**startup.mode.timestamp.start.at.operation.time**\n\n\n**Type:** string**Description:**Actuated only if `startup.mode=timestamp`. Specifies the starting point for the change stream.To learn more about Change Stream parameters, see $changeStream (aggregation) in the MongoDB manual.**Default**: `\"\"`**Accepted Values**:- An integer number of seconds since the Epoch in decimal format (for example, `30`)\n\n- An instant in the ISO-8601 format with one second precision (for example, `1970-01-01T00:00:30Z`)\n\n- A BSON Timestamp in the canonical extended JSON (v2) format (for example, `{\"$timestamp\": {\"t\": 30, \"i\": 0}}`)\n\n
\n**startup.mode.copy.existing.namespace.regex**\n\n\n**Type:** string**Description:**Regular expression the connector uses to match namespaces from which to copy data. A namespace describes the MongoDB database name and collection separated by a period (for example, `databaseName.collectionName`).For example, the following regular-expression setting matches collections that start with \"page\" in the `stats` database:```none\nstartup.mode.copy.existing.namespace.regex=stats\\.page.*\n```\n\nThe `\\` character in the example above escapes the `.` character that follows it in the regular expression. For more information on how to build regular expressions, see Patterns in the Java API documentation.**Default**: `\"\"`**Accepted Values**: A valid regular expression\n\n
\n**startup.mode.copy.existing.pipeline**\n\n\n**Type:** string**Description:**An inline array of pipeline operations the connector runs when copying existing data. You can use this setting to filter the source collection and improve the use of indexes in the copying process.For example, the following setting uses the $match aggregation operator to instruct the connector to copy only documents that contain a `closed` field with a value of `false`.```none\nstartup.mode.copy.existing.pipeline=[ { \"$match\": { \"closed\": \"false\" } } ]\n```\n\n**Default**: `\"\"`**Accepted Values**: Valid aggregation pipeline stages\n\n
\n**startup.mode.copy.existing.max.threads**\n\n\n**Type:** int**Description:**The maximum number of threads the connector can use to copy data.**Default**: number of processors available in the environment**Accepted Values**: An integer\n\n
\n**startup.mode.copy.existing.queue.size**\n\n\n**Type:** int**Description:**The size of the queue the connector can use when copying data.**Default**: `16000`**Accepted Values**: An integer\n\n
\n**startup.mode.copy.existing.allow.disk.use**\n\n\n**Type:** boolean**Description:**When set to `true`, the connector uses temporary disk storage for the copy existing aggregation.**Default**: `true`**Accepted Values**: `true` or `false`\n\n
"} -{"chunk_id": "68a95c115e79d242619dbb5f-0", "page_id": "68a95c115e79d242619dbb5f", "source_name": "kafka-connector", "product_name": "MongoDB Kafka Connector", "url": "https://mongodb.com/docs/kafka-connector/current/source-connector/configuration-properties/change-stream", "title": "Change Stream Properties", "text": "# Change Stream Properties\n\n## Overview\n\nUse the following configuration settings to specify aggregation pipelines for change streams and read preferences for change stream cursors when working with the MongoDB Kafka source connector.\n\nFor a list of source connector configuration settings organized by category, see the guide on Source Connector Configuration Properties.\n\n## Settings\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nDescription\n\n
\n**pipeline**\n\n\n**Type:** string**Description:**An array of aggregation pipelines to run in your change stream. You must configure this setting for the change stream event document, not the `fullDocument` field.For example:```none\n[{\"$match\": { \"$and\": [{\"operationType\": \"insert\"}, {\"fullDocument.eventId\": 1404 }] } }]\n```\n\nFor more examples, see:- Customize a Pipeline to Filter Change Events\n\n- Listen for Changes on Multiple Sources\n\n**Default**: `\"[]\"`**Accepted Values**: Valid aggregation pipeline stage\n\n
\n**change.stream.full.document**\n\n\n**Type:** string**Description:**Determines what values your change stream returns on update operations.The default setting returns the differences between the original document and the updated document.The `updateLookup` setting returns the differences between the original document and updated document as well as a copy of the entire updated document at a *point in time* after the update.The `whenAvailable` setting returns the updated document, if available.The `required` setting returns the updated document and raises an error if it is not available.For more information on how this change stream option works, see Lookup Full Document for Update Operations in the MongoDB manual.**Default**: `\"\"`**Accepted Values**: `\"\"`, `\"updateLookup\"`, `\"whenAvailable\"`, or `\"required\"`\n\n
\n**change.stream.show.expanded.events**\n\n\n**Type:** boolean**Description:**Determines if change streams notifies for DDL events such ascreateIndexes anddropIndexesevents. To learn more, see showExpandedEvents.This setting is **required** to show`updateDescription.disambiguatedPaths` in update events, whichclarifies changes that involve ambiguous fields. To learn more,see disambiguatedPaths.**Default**: `false`**Accepted Values**: `true` or `false`\n\n
\n**change.stream.full.document.before.change**\n\n\n**Type:** string**Description:**Configures the document pre-image your change stream returns on update operations. The pre-image is not available for source records published while copying existing data, and the pre-image configuration has no effect on copying.To learn how to configure a collection to enable pre-images, see Change Streams with Document Pre- and Post-Images in the MongoDB manual.The default setting suppresses the document pre-image.The `whenAvailable` setting returns the document pre-image if it's available, before it was replaced, updated, or deleted.The `required` setting returns the document pre-image and raises an error if it is not available.**Default**: `\"\"`**Accepted Values**: `\"\"` or `\"whenAvailable\"` or `\"required\"`\n\n
\n**publish.full.document.only**\n\n\n**Type:** boolean**Description:**Whether to return only the `fullDocument` field from the change stream event document produced by any update event. The `fullDocument` field contains the most current version of the updated document. To learn more about the `fullDocument` field, see the update Event in the Server manual.When set to `true`, the connector overrides the `change.stream.full.document` setting and sets it to `updateLookup` so that the `fullDocument` field contains updated documents.**Default**: `false`**Accepted Values**: `true` or `false`\n\n
\n**publish.full.document.only.tombstone.on.delete**\n\n\n**Type:** boolean**Description:**Whether to return tombstone events when documents are deleted. Tombstone events contain the keys of deleted documents with `null` values. This setting applies only when `publish.full.document.only` is `true`.**Default**: `false`**Accepted Values**: `true` or `false`\n\n
\n**change.stream.document.key.as.key**\n\n\n**Type:** boolean**Description:**Whether to use the document key for the source record key if the document key is present.When set to `true`, the connector adds keys of the deleted documents to the tombstone events. When set to `false`, the connector uses the resume token as the source key for the tombstone events.**Default**: `true`**Accepted Values**: `true` or `false`\n\n
\n**collation**\n\n\n**Type:** string**Description:**A JSON collation document that specifies language-specific ordering rules that MongoDB applies to the documents returned by the change stream.**Default**: `\"\"`**Accepted Values**: A valid collation JSON document\n\n
\n**batch.size**\n\n\n**Type:** int**Description:**The change stream cursor batch size.**Default**: `0`**Accepted Values**: An integer\n\n
\n**poll.await.time.ms**\n\n\n**Type:** long**Description:**The maximum amount of time in milliseconds that the server waits for new data changes to report to the change stream cursor before returning an empty batch.**Default**: `5000`**Accepted Values**: An integer\n\n
\n**poll.max.batch.size**\n\n\n**Type:** int**Description:**Maximum number of documents to read in a single batch when polling a change stream cursor for new data. You can use this setting to limit the amount of data buffered internally in the connector.**Default**: `1000`**Accepted Values**: An integer\n\n
"} -{"chunk_id": "68a95c115e79d242619dbb1f-0", "page_id": "68a95c115e79d242619dbb1f", "source_name": "kafka-connector", "product_name": "MongoDB Kafka Connector", "url": "https://mongodb.com/docs/kafka-connector/current/introduction", "title": "Introduction", "text": "# Introduction\n\nRead the following sections to learn about the MongoDB Kafka Connector, Kafka Connect, and Apache Kafka:\n\n- Kafka and Kafka Connect\n\n- Install the MongoDB Kafka Connector\n\n- Connect to MongoDB\n\n- Data Formats\n\n- Converters\n\nAtlas Stream Processing provides MongoDB-native tooling to continuously process streaming data, validate schemas, and materialize views into either Atlas database collections or Apache Kafka topics.\n\nTo learn more about Atlas Stream Processing, see Atlas Stream Processing."} -{"chunk_id": "68a95c115e79d242619dbb2f-0", "page_id": "68a95c115e79d242619dbb2f", "source_name": "kafka-connector", "product_name": "MongoDB Kafka Connector", "url": "https://mongodb.com/docs/kafka-connector/current/security-and-authentication", "title": "Security and Authentication", "text": "# Security and Authentication\n\nRead the following sections to learn how to secure communications between MongoDB and the MongoDB Kafka Connector:\n\n- Encrypt the Messages Your Connector Sends with SSL/TLS\n\n- Authenticate Your Connector with MongoDB using Amazon Web Services\n\n- Implement a Custom Authentication Provider"} -{"chunk_id": "68a95c115e79d242619dbb27-0", "page_id": "68a95c115e79d242619dbb27", "source_name": "kafka-connector", "product_name": "MongoDB Kafka Connector", "url": "https://mongodb.com/docs/kafka-connector/current/introduction/connect", "title": "Connect to MongoDB", "text": "# Connect to MongoDB\n\n## Overview\n\nLearn how to connect the MongoDB Kafka Connector to MongoDB using a **connection Uniform Resource Identifier (URI)**. A connection URI is a string that contains the following information:\n\n- The address of your MongoDB deployment *required*\n\n- Connection settings *optional*\n\n- Authentication settings *optional*\n\n- Authentication credentials *optional*\n\nThe following is an example of a connection URI for a MongoDB replica set:\n\n```text\nmongodb://mongodb0.example.com:27017,mongodb1.example.com:27017,mongodb2.example.com:27017/?replicaSet=myRepl\n```\n\nTo learn more about the connection URI format, see Connection String URI Format in the MongoDB Manual.\n\n## Prerequisites\n\nTo connect the MongoDB Kafka Connector to MongoDB, you must grant the database user either of the following:\n\n- the `readWrite` role\n\n- both the `readAnyDatabase` and `clusterMonitor` roles\n\n## How to Connect\n\nSpecify a connection URI with the following configuration option in both a source and sink connector:\n\n```properties\nconnection.uri=\n```\n\nTo learn more about this configuration option, see the following resources:\n\n- Source connector configuration options\n\n- Sink connector configuration options\n\n## How to Configure Your Connection\n\nThe MongoDB Kafka Connector uses the **MongoDB Java driver** to parse your connection URI. The MongoDB Java driver is an artifact that enables Java applications like Kafka Connect to interact with MongoDB.\n\nVersion 3.0 of the MongoDB Kafka Connector uses version 4.7 of the MongoDB Java driver.\n\nTo learn what connection URI options are available in the connector, see the MongoDB Java driver Connection guide.\n\n### Authentication\n\nAll authentication mechanisms available in the MongoDB Java driver are available in the MongoDB Kafka Connector.\n\nThe following is an example of a connection URI that authenticates with MongoDB using `SCRAM-SHA-256` authentication:\n\n```text\nmongodb://:@:/?authSource=&authMechanism=SCRAM-SHA-256\n```\n\nTo avoid storing your authentication secrets as plain text in your `connection.uri` setting, load your secrets from a secure location as your connector starts. To learn how to load your secrets as your connector starts, see the Externalize Secrets guide from Confluent.\n\nTo learn what authentication mechanisms are available, see the MongoDB Java driver Authentication Mechanisms guide.\n\nTo learn more about authentication in the connector, see the Security and Authentication guide."} -{"chunk_id": "68a95c115e79d242619dbb81-0", "page_id": "68a95c115e79d242619dbb81", "source_name": "kafka-connector", "product_name": "MongoDB Kafka Connector", "url": "https://mongodb.com/docs/kafka-connector/current/troubleshooting/recover-from-invalid-resume-token", "title": "Invalid Resume Token", "text": "# Invalid Resume Token\n\n## Overview\n\nLearn how to recover from an invalid resume token in a MongoDB Kafka source connector.\n\n### Stack Trace\n\nThe following stack trace indicates that the source connector has an invalid resume token:\n\n```text\n...\norg.apache.kafka.connect.errors.ConnectException: ResumeToken not found.\nCannot create a change stream cursor\n...\nCommand failed with error 286 (ChangeStreamHistoryLost): 'PlanExecutor\nerror during aggregation :: caused by :: Resume of change stream was not\npossible, as the resume point may no longer be in the oplog\n...\n```\n\n## Cause\n\nWhen the ID of your source connector's resume token does not correspond to any entry in your MongoDB deployment's oplog, your connector has no way to determine where to begin to process your MongoDB change stream. Click the following tabs to see scenarios in which you can experience this issue:\n\n\n\n\n\nIn this scenario, you pause your source connector and you fill your MongoDB deployment's oplog:\n\n1. You start a Kafka deployment with a MongoDB Kafka source connector.\n\n2. You produce a change event in your source MongoDB namespace, and your connector stores a resume token corresponding to this event.\n\n3. You pause your source connector.\n\n4. While your connector pauses, you fill your MongoDB oplog such that MongoDB deletes the oplog entry corresponding to your resume token.\n\n5. You restart your source connector and it is unable to resume processing as its resume token does not exist in your MongoDB oplog.\n\n\n\n\n\nIn this scenario, your source connector listens for changes on an infrequently updated MongoDB namespace and the heartbeat feature is not enabled:\n\n1. You start a Kafka deployment with a MongoDB Kafka source connector.\n\n2. You produce a change event in your source MongoDB namespace, and your connector stores a resume token corresponding to this event.\n\n3. Your source MongoDB namespace is not updated in the time it takes for your MongoDB deployment to rotate the change event corresponding to your resume token out of its oplog.\n\n4. You produce a change event in your source MongoDB namespace and your source connector is unable to resume processing as its resume token does not exist in your MongoDB oplog.\n\n\n\n\n\nFor more information on the oplog, see the MongoDB Manual.\n\nFor more information on change streams, see the Change Streams guide.\n\n## Solutions\n\nYou can recover from an invalid resume token using one of the following strategies:\n\n- Temporarily Tolerate Errors\n\n- Reset Stored Offsets\n\n### Temporarily Tolerate Errors\n\nYou can configure your source connector to tolerate errors while you produce a change stream event that updates the connector's resume token. This recovery strategy is the simplest, but there is a risk that your connector briefly ignores errors unrelated to the invalid resume token. If you aren't comfortable briefly tolerating errors in your deployment, you can delete stored offsets instead.\n\nTo configure your source connector to temporarily tolerate errors:\n\n1. Set the `errors.tolerance` option to tolerate all errors:\n\n ```java\n errors.tolerance=all\n ```\n\n2. Insert, update, or delete a document in the collection referenced by your source connector to produce a change stream event that updates your connector's resume token.\n\n3. Once you produce a change stream event, set the `errors.tolerance` option to no longer tolerate errors:\n\n ```java\n errors.tolerance=none\n ```\n\nFor more information on the `errors.tolerance` option, see the Error Handling and Resuming from Interruption Properties page.\n\n### Reset Stored Offsets\n\nYou can reset your Kafka Connect offset data, which contains your resume token, to allow your connector to resume processing your change stream.\n\nTo reset your offset data, change the value of the `offset.partition.name` configuration property to a partition name that does not exist on your Kafka deployment. You can set your `offset.partition.name` property like this:\n\n```properties\noffset.partition.name=\n```\n\nConsider using the following pattern to name your offset partitions:\n\n```properties\noffset.partition.name=.\n```\n\nThis pattern provides the following benefits:\n\n- Records the number of times you reset your connector\n\n- Documents to which connector an offset partition belongs\n\nFor example, if you named your source connector `\"source-values\"` and you are setting the `offset.partition.name` property for the first time, configure your connector as follows:\n\n```properties\noffset.partition.name=source-values.1\n```\n\nThe next time you reset your connector's offset data, configure your connector as follows:\n\n```properties\noffset.partition.name=source-values.2\n```\n\nTo learn more about the `offset.partition.name` configuration property, see the Error Handling and Resuming from Interruption Properties page.\n\nTo learn about naming your connector, see the official Apache Kafka documentation.\n\n## Prevention\n\nTo prevent invalid resume token errors caused by an infrequently updated namespace, enable **heartbeats**. Heartbeats is a feature of your source connector that causes your connector to update its resume token at regular intervals as well as when the contents of your source MongoDB namespace changes.\n\nSpecify the following option in your source connector configuration to enable heartbeats:\n\n```properties\nheartbeat.interval.ms=\n```\n\nTo learn more about heartbeats, see the Error Handling and Resuming from Interruption Properties guide."} -{"chunk_id": "695ca9502d5be1431b31836e-0", "page_id": "695ca9502d5be1431b31836e", "source_name": "kotlin", "product_name": "Kotlin Coroutine Driver", "url": "https://mongodb.com/docs/drivers/kotlin/coroutine/current/builders", "title": "Builders", "text": "# Builders\n\n## Overview\n\nThis section includes guides on how to use each of the available builders and demonstrates the utility that the Kotlin driver builder classes provide.\n\nThe Kotlin driver provides classes to simplify the process of performing CRUD operations and using the Aggregation API. The static utility methods allow you to build queries and other kinds of documents more efficiently.\n\nThe builder classes pass input values to the underlying MongoDB operation and do not sanitize those values. Validate input in your application before you pass it to a builder method.\n\n## Why Use Builders?\n\nWhen you use builders classes, you leverage the following products:\n\n- The Kotlin compiler to find errors during development\n\n- The IDE for discovery, debugging, and code completion\n\nWhen using builders, the Kotlin compiler and the IDE catch errors such as misspelled operators or missing parameters early on. If you use the MongoDB shell or plain Kotlin instead, you write operators as strings and get no visual indication of a problem, which pushes these errors to runtime instead of compile time.\n\nBy using builder classes, you can write operators as methods, so that your IDE instantly indicates whether your code has errors. While developing, your IDE can also show you methods that you can use and can complete your code with placeholder parameters.\n\n## Example Scenario\n\nSuppose you want to send a marketing email to all users in the `users` collection that meet the following criteria:\n\n- Users in which the value of the `gender` field is `\"female\"`\n\n- Users in which the value of the `age` field is greater than `29`\n\nYou also need your query to return only their email addresses.\n\nThe documents in the `users` collection are modeled by the following data class:\n\n```kotlin\ndata class User(\n @BsonId\n val id: BsonObjectId = BsonObjectId(),\n val gender: String,\n val age: Int,\n val email: String,\n)\n\n```\n\n### Using the MongoDB Shell\n\nThe following code provides the command you use in the MongoDB Shell to perform the query:\n\n```js\ncollection.find({ \"gender\": \"female\", \"age\" : { \"$gt\": 29 }}, { \"_id\": 0, \"email\": 1 })\n```\n\n### Without Using Builders\n\nThe following code provides the find operation you create without builders in the Kotlin driver:\n\n```kotlin\ndata class Results(val email: String)\n\nval filter = Document().append(\"gender\", \"female\").append(\"age\", Document().append(\"\\$gt\", 29))\nval projection = Document().append(\"_id\", 0).append(\"email\", 1)\nval results = collection.find(filter).projection(projection)\n\n```\n\nIn this case, you might easily include an error when writing the `\"\\$gt\"` operator in the filter, but your IDE returns the relevant error only at runtime.\n\n### Using Builders\n\nThe following code provides the find operation you create by using builders in the Kotlin driver:\n\n```kotlin\nimport com.mongodb.client.model.Filters\nimport com.mongodb.client.model.Projections\n```\n\n```kotlin\ndata class Results(val email: String)\n\nval filter = Filters.and(Filters.eq(User::gender.name, \"female\"), Filters.gt(User::age.name, 29))\nval projection = Projections.fields(Projections.excludeId(), Projections.include(\"email\"))\nval results = collection.find(filter).projection(projection)\n\n```\n\n## Available Builders\n\n- Aggregates: Build aggregation pipelines\n\n - See the MongoDB Vector Search to learn more about the `Aggregates.vectorSearch()` method\n\n- Filters: Build query filters\n\n- Indexes: Build index keys\n\n- Projections: Build projections\n\n- Sorts: Build sort criteria\n\n- Updates: Build update documents\n\nThe Use Builders with Data Classes guide provides examples on how to use the preceding builders classes directly with data class properties. This guide might help to make your application more type-safe and improve Kotlin interoperability."} -{"chunk_id": "695ca9502d5be1431b3183f0-0", "page_id": "695ca9502d5be1431b3183f0", "source_name": "kotlin", "product_name": "Kotlin Coroutine Driver", "url": "https://mongodb.com/docs/drivers/kotlin/coroutine/current/crud/update", "title": "Update Documents", "text": "# Update Documents\n\nUpdate One Update Many \n\n## Overview\n\nIn this guide, you can learn how to update documents in a MongoDB collection by using the `updateOne()` and `updateMany()` methods.\n\n### Sample Data\n\nThe examples in this guide run operations on the `paint_inventory` collection, which stores documents that represent paint colors in a store's inventory. This collection contains the following sample documents:\n\n```json\n{ \"_id\": 1, \"color\": \"red\", \"qty\": 5, \"prices\": [15.99, 19.99] }\n{ \"_id\": 2, \"color\": \"purple\", \"qty\": 8, \"prices\": [18.99, 22.99] }\n{ \"_id\": 3, \"color\": \"yellow\", \"qty\": 0, \"prices\": [14.99, 17.99] }\n{ \"_id\": 4, \"color\": \"green\", \"qty\": 6, \"prices\": [19.99, 24.99] }\n{ \"_id\": 5, \"color\": \"blue\", \"qty\": 3, \"prices\": [17.99, 21.99] }\n```\n\nThe following Kotlin data class models the collection's documents:\n\n```kotlin\ndata class PaintOrder(\n @BsonId val id: Int,\n val color: String,\n val qty: Int,\n val prices: List\n)\n```\n\n## Run an Update Operation\n\nYou can update documents in MongoDB by using the following methods:\n\n- `updateOne()`, which updates *the first document* that matches the search criteria\n\n- `updateMany()`, which updates *all documents* that match the search criteria\n\nEach update method requires the following parameters:\n\n- **Query filter**, which matches which documents to update. To learn more about query filters, see the Specify a Query guide.\n\n- **Update document**, which specifies the update operator, or the kind of update to perform, and the fields and values to be updated. For a list of update operators and their usages, see the Field Update Operators in the MongoDB server manual.\n\nThe examples in this guide use the `Updates` builder, a factory class that provides helper methods to construct update documents. To learn more about the `Updates` builder, see the Updates Builders guide.\n\n### Update One Document\n\nThis example uses the `updateOne()` method to perform the following actions:\n\n- Matches a document in which the `color` field value is `\"yellow\"`\n\n- Uses the `Updates` builder to increment the matching document's `qty` field value by `1`\n\n```kotlin\nval filter = Filters.eq(PaintOrder::color.name, \"yellow\")\nval update = Updates.inc(PaintOrder::qty.name, 1)\nval result = collection.updateOne(filter, update)\nprintln(\"Matched document count: ${result.matchedCount}\")\nprintln(\"Modified document count: ${result.modifiedCount}\")\n```\n\n```\nMatched document count: 1\nModified document count: 1\n```\n\nIf multiple documents match the query filter passed to the `updateOne()` method, the operation updates only the first result. To control which document the operation matches, you can specify a sort order. To learn more about the `sort` option, see the Sort Results page.\n\n### Update Many Documents\n\nThe following example uses the `updateMany()` method to perform the following actions:\n\n- Matches all documents by using an empty query filter\n\n- Uses the `Updates` builder to increase the `qty` field value by `20` in all matching documents\n\n```kotlin\nval filterMany = Filters.empty()\nval updateMany = Updates.inc(PaintOrder::qty.name, 20)\nval resultMany = collection.updateMany(filterMany, updateMany)\nprintln(\"Matched document count: ${resultMany.matchedCount}\")\nprintln(\"Modified document count: ${resultMany.modifiedCount}\")\n```\n\n```\nMatched document count: 5\nModified document count: 5\n```\n\nAfter the update operation, the documents in `paint_inventory` collection have the following values:\n\n```json\n{ \"_id\": 1, \"color\": \"red\", \"qty\": 25, \"prices\": [15.99, 19.99] }\n{ \"_id\": 2, \"color\": \"purple\", \"qty\": 28, \"prices\": [18.99, 22.99] }\n{ \"_id\": 3, \"color\": \"yellow\", \"qty\": 20, \"prices\": [14.99, 17.99] }\n{ \"_id\": 4, \"color\": \"green\", \"qty\": 26, \"prices\": [19.99, 24.99] }\n{ \"_id\": 5, \"color\": \"blue\", \"qty\": 23, \"prices\": [17.99, 21.99] }\n```\n\nIf the query filter does not match any documents, the `updateMany()` method makes no changes to documents in the collection. You can use the `upsert` option to insert a new document if none match. To view an example that uses this option, see Insert or Update in a Single Operation.\n\nThe `updateOne()` and `updateMany()` methods cannot make changes to a document that violates unique index constraints on the collection. To learn more, see Unique Indexes in the MongoDB server manual.\n\n### Update Array Elements\n\nTo update a document's array values, use the `Updates` builder to specify the update you want to perform and the array elements to update. Then, call the `updateOne()` or `updateMany()` method to run the update operation.\n\nYou can specify which array elements to update by using the following positional operators:\n\n- `$`: Updates the first array element that matches the query filter.\n\n- `$[]`: Updates all elements in an array.\n\n- `$[]`: Updates array elements that match a filter.\n\nThe examples in this section show how to use each positional operator.\n\n#### Update First Matching Element\n\nTo update the first array element that matches your query filter, use the positional (`$`) operator and specify the array field to update in your query filter.\n\nThis example performs the following actions:\n\n- Matches a document that has a `prices` array containing the value `15.99`\n\n- Uses the `$` positional operator to increase the first value in the matching document's `prices` array by `2`\n\n```kotlin\nval filterArrayFirst = Filters.eq(PaintOrder::prices.name, 15.99)\nval updateArrayFirst = Updates.inc(\"${PaintOrder::prices.name}.$\", 2)\nval resultArrayFirst = collection.updateOne(filterArrayFirst, updateArrayFirst)\nprintln(\"Modified document count: ${resultArrayFirst.modifiedCount}\")\n```\n\n```\nModified document count: 1\n```\n\n#### Update All Elements\n\nTo update all elements in an array, use the all positional (`$[]`) operator.\n\nThis example performs the following actions:\n\n- Matches a document that has a `color` value of `\"green\"`\n\n- Uses the `$[]` positional operator to multiply all values in the matching document's `prices` array by `1.1`\n\n```kotlin\nval filterArrayAll = Filters.eq(PaintOrder::color.name, \"green\")\nval update = Updates.mul(\"${PaintOrder::prices.name}.$[]\", 1.1)\nval resultArrayAll = collection.updateOne(filterArrayAll, update)\nprintln(\"Modified document count: ${resultArrayAll.modifiedCount}\")\n```\n\n```console\nModified document count: 1\n```\n\nThe `updateOne()` and `updateMany()` methods cannot make changes to a document that violate unique index constraints on the collection. See the MongoDB server manual for more information on unique indexes."} -{"chunk_id": "695ca9502d5be1431b318386-0", "page_id": "695ca9502d5be1431b318386", "source_name": "kotlin", "product_name": "Kotlin Coroutine Driver", "url": "https://mongodb.com/docs/drivers/kotlin/coroutine/current/builders/projections", "title": "Projections Builders", "text": "# Projections Builders\n\n## Overview\n\nIn this guide, you can learn how to specify **projections** using builders in the MongoDB Kotlin driver.\n\nMongoDB supports **field projection**, specifying which fields to include and exclude when returning results from a query. Projection in MongoDB follows some basic rules:\n\n- The `_id` field is *always* included unless explicitly excluded\n\n- Specifying a field for inclusion implicitly excludes all other fields **except** the `_id` field\n\n- Specifying a field for exclusion removes **only** that field in a query result\n\nFind more information about projection mechanics in the Project Fields to Return from Query guide in the MongoDB Server documentation.\n\nThe `Projections` class provides static factory methods for all the MongoDB projection operators. Each method returns an instance of the BSON type which you can pass to any method that expects a projection.\n\nFor brevity, you may choose to import the methods of the Projections class:\n\n```kotlin\nimport com.mongodb.client.model.Projections.*\n```\n\n### Sample Documents and Examples\n\nThe following sections feature examples that run query and projection operations on a sample collection called `projection_builders`. Each section uses a variable named `collection` to refer to the `MongoCollection` instance of the `projection_builders` collection.\n\nThe collection contains the following documents, representing the monthly average temperatures in Celsius for the years 2018 and 2019:\n\n```json\n{\n \"year\" : 2018,\n \"type\" : \"even number but not a leap year\",\n \"temperatures\" : [\n { \"month\" : \"January\", \"avg\" : 9.765 },\n { \"month\" : \"February\", \"avg\" : 9.675 },\n { \"month\" : \"March\", \"avg\" : 10.004 },\n { \"month\" : \"April\", \"avg\" : 9.983 },\n { \"month\" : \"May\", \"avg\" : 9.747 },\n { \"month\" : \"June\", \"avg\" : 9.65 },\n { \"month\" : \"July\", \"avg\" : 9.786 },\n { \"month\" : \"August\", \"avg\" : 9.617 },\n { \"month\" : \"September\", \"avg\" : 9.51 },\n { \"month\" : \"October\", \"avg\" : 10.042 },\n { \"month\" : \"November\", \"avg\" : 9.452 },\n { \"month\" : \"December\", \"avg\" : 9.86 }\n ]\n},\n{\n \"year\" : 2019,\n \"type\" : \"odd number, can't be a leap year\",\n \"temperatures\" : [\n { \"month\" : \"January\", \"avg\" : 10.023 },\n { \"month\" : \"February\", \"avg\" : 9.808 },\n { \"month\" : \"March\", \"avg\" : 10.43 },\n { \"month\" : \"April\", \"avg\" : 10.175 },\n { \"month\" : \"May\", \"avg\" : 9.648 },\n { \"month\" : \"June\", \"avg\" : 9.686 },\n { \"month\" : \"July\", \"avg\" : 9.794 },\n { \"month\" : \"August\", \"avg\" : 9.741 },\n { \"month\" : \"September\", \"avg\" : 9.84 },\n { \"month\" : \"October\", \"avg\" : 10.15 },\n { \"month\" : \"November\", \"avg\" : 9.84 },\n { \"month\" : \"December\", \"avg\" : 10.366 }\n ]\n}\n```\n\nThe following data class is used to represent the documents in the collection:\n\n```kotlin\ndata class YearlyTemperature(\n @BsonId val id: ObjectId,\n val year: Int,\n val type: String,\n val temperatures: List\n) {\n data class MonthlyTemperature(\n val month: String,\n val avg: Double\n )\n}\n\n```\n\nYou can use the methods from builder classes directly with data class properties by adding the optional Kotlin driver extensions dependency to your application. To learn more and view examples, see the Use Builders with Data Classes guide.\n\n## Projection Operations\n\nThe following sections contain information on the available projection operations and how to construct them using the `Projections` class.\n\n### Inclusion\n\nUse the `include()` method to specify the inclusion of one or more fields.\n\nThe following example includes the `year` field and implicitly the `_id` field:\n\n```kotlin\ndata class Results(@BsonId val id: ObjectId, val year: Int)\n\nval filter = Filters.empty()\nval projection = Projections.include(YearlyTemperature::year.name)\nval resultsFlow = collection.find(filter).projection(projection)\nresultsFlow.collect { println(it) }\n\n```\n\n```console\nResults(id=6467808db5003e6354a1ee22, year=2018)\nResults(id=6467808db5003e6354a1ee23, year=2019)\n```\n\nThe following example includes the `year` and `type` fields and implicitly the `_id` field:\n\n```kotlin\ndata class Results(@BsonId val id: ObjectId, val year: Int, val type: String)\n\nval filter = Filters.empty()\nval projection = Projections.include(YearlyTemperature::year.name, YearlyTemperature::type.name)\nval resultsFlow = collection.find(filter).projection(projection)\nresultsFlow.collect { println(it) }\n\n```\n\n```console\nResults(id=646780e3311323724f69a907, year=2018, type=even number but not a leap year)\nResults(id=646780e3311323724f69a908, year=2019, type=odd number, can't be a leap year)\n```\n\n### Exclusion\n\nUse the `exclude()` method to specify the exclusion of one or more fields.\n\nThe following example excludes the `temperatures` field:\n\n```kotlin\ndata class Results(@BsonId val id: ObjectId, val year: Int, val type: String)\nval filter = Filters.empty()\nval projection = Projections.exclude(YearlyTemperature::temperatures.name)\nval resultsFlow = collection.find(filter).projection(projection)\nresultsFlow.collect { println(it) }\n\n```\n\n```console\nResults(id=6462976102c85b29a7bfc9d5, year=2018, type=even number but not a leap year)\nResults(id=6462976102c85b29a7bfc9d6, year=2019, type=odd number, can't be a leap year)\n```\n\nThe following example excludes the `temperatures` and `type` fields:\n\n```kotlin\ndata class Results(@BsonId val id: ObjectId, val year: Int)\n\nval filter = Filters.empty()\nval projection = Projections.exclude(YearlyTemperature::temperatures.name, YearlyTemperature::type.name)\nval resultsFlow = collection.find(filter).projection(projection)\nresultsFlow.collect { println(it) }\n\n```\n\n```console\nResults(id=64629783d7760d2365215147, year=2018)\nResults(id=64629783d7760d2365215148, year=2019)\n```\n\n### Combining Projections\n\nUse the `fields()` method to combine multiple projections.\n\nThe following example includes the `year` and `type` fields and excludes the `_id` field:\n\n```kotlin\ndata class Results(val year: Int, val type: String)\n\nval filter = Filters.empty()\nval projection = Projections.fields(\n Projections.include(YearlyTemperature::year.name, YearlyTemperature::type.name),\n Projections.excludeId()\n)\nval resultsFlow = collection.find(filter).projection(projection)\nresultsFlow.collect { println(it) }\n\n```\n\n```console\nResults(year=2018, type=even number but not a leap year)\nResults(year=2019, type=odd number, can't be a leap year)\n```"} -{"chunk_id": "695ca9502d5be1431b318386-1", "page_id": "695ca9502d5be1431b318386", "source_name": "kotlin", "product_name": "Kotlin Coroutine Driver", "url": "https://mongodb.com/docs/drivers/kotlin/coroutine/current/builders/projections", "title": "Projections Builders", "text": "### Exclusion of `_id`\n\nUse the `excludeId()` convenience method to specify the exclusion of the `_id` field:\n\n```kotlin\ndata class Results(val year: Int, val type: String, val temperatures: List)\nval filter = Filters.empty()\nval projection = Projections.excludeId()\nval resultsFlow = collection.find(filter).projection(projection)\nresultsFlow.collect { println(it) }\n\n```\n\n```console\nResults(year=2018, type=even number but not a leap year, temperatures=[MonthlyTemperature(month=January, avg=9.765), MonthlyTemperature(month=February, avg=9.675), MonthlyTemperature(month=March, avg=10.004), MonthlyTemperature(month=April, avg=9.983), MonthlyTemperature(month=May, avg=9.747), MonthlyTemperature(month=June, avg=9.65), MonthlyTemperature(month=July, avg=9.786), MonthlyTemperature(month=August, avg=9.617), MonthlyTemperature(month=September, avg=9.51), MonthlyTemperature(month=October, avg=10.042), MonthlyTemperature(month=November, avg=9.452), MonthlyTemperature(month=December, avg=9.86)])\nResults(year=2019, type=odd number, can't be a leap year, temperatures=[MonthlyTemperature(month=January, avg=10.023), MonthlyTemperature(month=February, avg=9.808), MonthlyTemperature(month=March, avg=10.43), MonthlyTemperature(month=April, avg=10.175), MonthlyTemperature(month=May, avg=9.648), MonthlyTemperature(month=June, avg=9.686), MonthlyTemperature(month=July, avg=9.794), MonthlyTemperature(month=August, avg=9.741), MonthlyTemperature(month=September, avg=9.84), MonthlyTemperature(month=October, avg=10.15), MonthlyTemperature(month=November, avg=9.84), MonthlyTemperature(month=December, avg=10.366)])\n```\n\n### Project an Array Element Match\n\nUse the `elemMatch(String, Bson)` method variant to specify an array projection that will include the first element of an array that matches a supplied query filter. This filtering occurs *after* all documents matching the query filter (if supplied) are retrieved.\n\nOnly the first element that matches the specified query filter will be included, regardless of how many matches there may be.\n\nThe following example projects the first element of the `temperatures` array where the `avg` field is greater that `10.1`:\n\n```kotlin\ndata class Results(\n val year: Int,\n val temperatures: List?\n)\n\nval filter = Filters.empty()\nval projection = Projections.fields(\n Projections.include(YearlyTemperature::year.name),\n Projections.elemMatch(\n YearlyTemperature::temperatures.name,\n Filters.gt(YearlyTemperature.MonthlyTemperature::avg.name, 10.1)\n )\n)\nval resultsFlow = collection.find(filter).projection(projection)\nresultsFlow.collect { println(it) }\n\n```\n\n```console\nResults(year=2018, temperatures=null)\nResults(year=2019, temperatures=[MonthlyTemperature(month=March, avg=10.43)])\n```\n\nWhen you've specified matching criteria in the **query** portion of your operation, use the `elemMatch(String)` method variant to specify a positional projection to include the first element of an array. Only documents that match the query filter will be retrieved.\n\nIn MongoDB versions earlier than 4.4, the specified array field must appear in the query filter. Beginning in MongoDB 4.4, you can use a positional project on an array field that does not appear in the query filter.\n\nThe following example projects the first element of the `temperatures` array:\n\n```kotlin\ndata class Results(\n val year: Int,\n val temperatures: List\n)\n\nval filter = Filters.gt(\n \"${YearlyTemperature::temperatures.name}.${YearlyTemperature.MonthlyTemperature::avg.name}\",\n 10.1\n)\nval projection = Projections.fields(\n Projections.include(YearlyTemperature::year.name),\n Projections.elemMatch(YearlyTemperature::temperatures.name)\n)\nval resultsFlow = collection.find(filter).projection(projection)\nresultsFlow.collect { println(it) }\n\n```\n\n```console\nResults(year=2019, temperatures=[MonthlyTemperature(month=March, avg=10.43)])\n```\n\n### Project an Array Slice\n\nUse the `slice()` method to project a slice of an array.\n\nThe following example projects the first 6 elements of the `temperatures` array:\n\n```kotlin\ndata class Results(val temperatures: List)\n\nval filter = Filters.empty()\n// First half of the year\nval projection = Projections.fields(\n Projections.slice(YearlyTemperature::temperatures.name, 6),\n Projections.excludeId()\n)\nval resultsFlow = collection.find(filter)\n .projection(projection)\nresultsFlow.collect { println(it) }\n\n```\n\n```console\nResults(temperatures=[MonthlyTemperature(month=January, avg=9.765), MonthlyTemperature(month=February, avg=9.675), MonthlyTemperature(month=March, avg=10.004), MonthlyTemperature(month=April, avg=9.983), MonthlyTemperature(month=May, avg=9.747), MonthlyTemperature(month=June, avg=9.65)])\nResults(temperatures=[MonthlyTemperature(month=January, avg=10.023), MonthlyTemperature(month=February, avg=9.808), MonthlyTemperature(month=March, avg=10.43), MonthlyTemperature(month=April, avg=10.175), MonthlyTemperature(month=May, avg=9.648), MonthlyTemperature(month=June, avg=9.686)])\n```\n\nThe following example skips the first 6 elements of the `temperatures` array and projects the next **6**:\n\n```kotlin\ndata class Results(val temperatures: List)\n\nval filter = Filters.empty()\n// Second half of the year\nval projection = Projections.fields(\n Projections.slice(YearlyTemperature::temperatures.name, 6, 6),\n Projections.excludeId()\n)\nval resultsFlow = collection.find(filter)\n .projection(projection)\nresultsFlow.collect { println(it) }\n\n```\n\n```console\nResults(temperatures=[MonthlyTemperature(month=July, avg=9.786), MonthlyTemperature(month=August, avg=9.617), MonthlyTemperature(month=September, avg=9.51), MonthlyTemperature(month=October, avg=10.042), MonthlyTemperature(month=November, avg=9.452), MonthlyTemperature(month=December, avg=9.86)])\nResults(temperatures=[MonthlyTemperature(month=July, avg=9.794), MonthlyTemperature(month=August, avg=9.741), MonthlyTemperature(month=September, avg=9.84), MonthlyTemperature(month=October, avg=10.15), MonthlyTemperature(month=November, avg=9.84), MonthlyTemperature(month=December, avg=10.366)])\n```\n\n### Project a Text Score\n\nUse the `metaTextScore()` method to specify a projection of the score of a text query.\n\nThe following example projects the text score as the value of the `score` field:\n\n```kotlin\ndata class Results(val year: Int, val score: Double)\n\nval filter = Filters.text(\"even number\")\nval projection = Projections.fields(\n Projections.include(YearlyTemperature::year.name),\n Projections.metaTextScore(\"score\")\n)\nval resultsFlow = collection.find(filter).projection(projection)\nresultsFlow.collect { println(it) }\n\n```\n\n```console\nResults(year=2018, score=1.25)\nResults(year=2019, score=0.625)\n```"} -{"chunk_id": "697858c65a54ba504970a80b-0", "page_id": "697858c65a54ba504970a80b", "source_name": "kotlin", "product_name": "Kotlin Coroutine Driver", "url": "https://mongodb.com/docs/drivers/kotlin/coroutine/current/security/auth/kerberos", "title": "Kerberos (GSSAPI) Authentication", "text": "# Kerberos (GSSAPI) Authentication\n\n## Overview\n\nThe Generic Security Services API (`GSSAPI`) authentication mechanism allows the user to authenticate to a Kerberos service using the user's principal name.\n\nThe method refers to the `GSSAPI` authentication mechanism instead of `Kerberos` because the driver authenticates using the GSSAPI RFC-4652 SASL mechanism.\n\n### Code Placeholders\n\nThe code examples on this page use the following placeholders:\n\n- `Kerberos principal` - your URL-encoded principal name, e.g. \"username%40REALM.ME\"\n\n- `hostname` - network address of your MongoDB server, accessible by your client\n\n- `port` - port number of your MongoDB server\n\n## Authenticate with GSSAPI\n\n\n\n\n\nTo specify the GSSAPI authentication mechanism by using a connection string, assign the `authMechanism` URL parameter to the value `GSSAPI` Then, optionally assign the `authSource` URL parameter to the value `$external`.\n\nIf you specify the `GSSAPI` mechanism, you cannot assign `authSource` to any value other than `$external`.\n\nYour code to instantiate a `MongoClient` should resemble the following:\n\n```kotlin\nval connectionString = ConnectionString(\"@:/?authSource=$external&authMechanism=GSSAPI\")\nval mongoClient = MongoClient.create(connectionString)\n\n```\n\n\n\n\n\nTo specify the GSSAPI authentication mechanism by using the `MongoCredential` class, use the `createGSSAPICredential()` method. Your code to instantiate a `MongoClient` should resemble the following:\n\n```kotlin\nval credential = MongoCredential.createGSSAPICredential(\"\")\n\nval settings = MongoClientSettings.builder()\n .applyToClusterSettings { builder ->\n builder.hosts(listOf(ServerAddress(\"\", )))\n }\n .credential(credential)\n .build()\n\nval mongoClient = MongoClient.create(settings)\n\n```\n\n\n\n\n\nIn order to acquire a Kerberos ticket, the GSSAPI Java libraries require you to specify the realm and Key Distribution Center (KDC) system properties. See the sample settings in the following example:\n\n```none\njava.security.krb5.realm=MYREALM.ME\njava.security.krb5.kdc=mykdc.myrealm.me\n```\n\nYou might need to specify one or more of the following additional `MongoCredential` mechanism properties depending on your Kerberos setup:\n\n- `SERVICE_NAME`\n\n- `CANONICALIZE_HOST_NAME`\n\n- `JAVA_SUBJECT`\n\n- `JAVA_SASL_CLIENT_PROPERTIES`\n\n- `JAVA_SUBJECT_PROVIDER`\n\nYou can specify the following GSSAPI properties only by using the `MongoCredential`:\n\n- `JAVA_SUBJECT`\n\n- `JAVA_SASL_CLIENT_PROPERTIES`\n\n- `JAVA_SUBJECT_PROVIDER`\n\nThe following example shows how to specify the additional properties:\n\n\n\n\n\nTo specify one of the GSSAPI additional properties, include it in the connection string as a URL parameter using the format: `:`.\n\nYour code to instantiate a `MongoClient` using GSSAPI and additional properties might resemble the following:\n\n```kotlin\nval connectionString = ConnectionString(\"@:/?authSource=$external&authMechanism=GSSAPI&authMechanismProperties=SERVICE_NAME:myService\")\nval mongoClient = MongoClient.create(connectionString)\n\n```\n\n\n\n\n\nTo specify one of the GSSAPI additional properties, call the `withMechanismProperty()` method on your `MongoCredential` instance and pass the property name and value as parameters. Use the property name constants defined in the `MongoCredential` class:\n\n- SERVICE_NAME_KEY\n\n- CANONICALIZE_HOST_NAME_KEY\n\n- JAVA_SUBJECT_KEY\n\n- JAVA_SASL_CLIENT_PROPERTIES_KEY\n\n- JAVA_SUBJECT_PROVIDER_KEY\n\nThe following example instantiates a `MongoCredential` that uses GSSAPI and the the `SERVICE_NAME_KEY`:\n\n```kotlin\nval credential = MongoCredential.createGSSAPICredential(\"\")\n .withMechanismProperty(MongoCredential.SERVICE_NAME_KEY, \"myService\")\n\n```\n\n\n\n\n\nBy default, the Kotlin driver caches Kerberos tickets by `MongoClient` instance. If your deployment needs to frequently create and destroy `MongoClient` instances, you can change the default Kerberos ticket caching behavior to cache by process to improve performance.\n\nTo cache Kerberos tickets by process, you must specify the `JAVA_SUBJECT_PROVIDER` mechanism property and provide a KerberosSubjectProvider in your `MongoCredential` instance. The code to configure the Kotlin driver to cache Kerberos tickets by process should resemble the following:\n\n```kotlin\n/* All MongoClient instances sharing this instance of KerberosSubjectProvider\nwill share a Kerberos ticket cache */\nval myLoginContext = \"myContext\"\n/* Login context defaults to \"com.sun.security.jgss.krb5.initiate\"\nif unspecified in KerberosSubjectProvider */\nval credential = MongoCredential.createGSSAPICredential(\"\")\n .withMechanismProperty(\n MongoCredential.JAVA_SUBJECT_PROVIDER_KEY,\n KerberosSubjectProvider(myLoginContext)\n )\n\n```\n\nOn Windows, Oracle's JRE uses LSA rather than SSPI in its implementation of GSSAPI which limits interoperability with Windows Active Directory and implementations of single sign-on. See the following articles for more information:\n\n- JDK-8054026\n\n- JDK-6722928\n\n- SO 23427343"} -{"chunk_id": "695ca9502d5be1431b3183c5-0", "page_id": "695ca9502d5be1431b3183c5", "source_name": "kotlin", "product_name": "Kotlin Coroutine Driver", "url": "https://mongodb.com/docs/drivers/kotlin/coroutine/current/crud/read-operations/distinct", "title": "Retrieve Distinct Values of a Field", "text": "# Retrieve Distinct Values of a Field\n\nYou can retrieve a list of distinct values for a field across a collection by calling the `distinct()` method on a `MongoCollection` object. Pass the document field name as the first parameter and the class you want to cast the results to as the type parameter.\n\nThe following snippets demonstrate the `distinct()` method using the `movies` collection in the `sample_mflix` sample database. Documents are modeled with the following Kotlin data class:\n\n```kotlin\ndata class Movie(\n val type: String,\n val languages: List,\n val countries: List,\n val awards: Awards){\n data class Awards(val wins: Int)\n }\n\n```\n\nThe following method call returns each distinct value of the `countries` field in the `movies` collection:\n\n```kotlin\ncollection.distinct(Movie::countries.name)\n\n```\n\nYou can specify a field on the document or one within an **embedded document** using **dot notation**. The following method call returns each distinct value of the `wins` field in the `awards` embedded document:\n\n```kotlin\ncollection.distinct(\"${Movie::awards.name}.${Movie.Awards::wins.name}\")\n\n```\n\nYou can also limit the set of documents from which your MongoDB instance retrieves distinct values with a query filter as a second parameter, as follows:\n\n```kotlin\ncollection.distinct(Movie::type.name, Filters.eq(Movie::languages.name, \"French\"))\n\n```\n\nThe `distinct()` method returns an object that implements the `DistinctFlow` class, which contains methods to access, organize, and traverse the results. `DistinctFlow` delegates to the `Flow` interface from the Kotlin Coroutines library, allowing access to methods such as `first()` and `firstOrNull()`.\n\nFor more information, see our guide on Accessing Data From a Flow.\n\n## Example\n\nThe following example retrieves a list of distinct values for the `year` document field from the `movies` collection. It uses a query filter to match movies that include \"Carl Franklin\" as one of the values in the `directors` array.\n\nWhen you run the example, you should see output that reports each distinct year for all the movies that Carl Franklin was included as a director.\n\nThis example connects to an instance of MongoDB by using a connection URI. To learn more about connecting to your MongoDB instance, see the connection guide.\n\n```kotlin\nimport com.mongodb.MongoException\nimport com.mongodb.client.model.Filters\nimport com.mongodb.kotlin.client.coroutine.MongoClient\nimport kotlinx.coroutines.runBlocking\n\ndata class Movie(val year: Int, val directors: List)\n\nfun main() = runBlocking {\n // Replace the uri string with your MongoDB deployment's connection string\n val uri = \"\"\n val mongoClient = MongoClient.create(uri)\n val database = mongoClient.getDatabase(\"sample_mflix\")\n val collection = database.getCollection(\"movies\")\n\n try {\n val resultsFlow = collection.distinct(\n Movie::year.name, Filters.eq(Movie::directors.name, \"Carl Franklin\")\n )\n resultsFlow.collect { println(it) }\n } catch (e: MongoException) {\n System.err.println(\"An error occurred: $e\")\n }\n\n mongoClient.close()\n}\n\n```\n\n```console\n1992\n1995\n1998\n...\n```\n\nFor additional information on the classes and methods mentioned on this page, see the following resources:\n\n- distinct() API Documentation\n\n- distinctFlow API Documentation\n\n- Dot Notation Server Manual Entry"} -{"chunk_id": "695ca9502d5be1431b3183d3-0", "page_id": "695ca9502d5be1431b3183d3", "source_name": "kotlin", "product_name": "Kotlin Coroutine Driver", "url": "https://mongodb.com/docs/drivers/kotlin/coroutine/current/crud/read-operations/query-document", "title": "Specify a Query", "text": "# Specify a Query\n\n## Overview\n\nIn this guide, you can learn how to specify a query in the MongoDB Kotlin driver.\n\nMost CRUD operations allow you to narrow the set of matched documents by specifying matching criteria in a **query filter**. Query filters contain one or more query operators that apply to specific fields which determine which documents to include in the result set.\n\nIn this page, we cover the following query operators with examples on how to use them:\n\n- Comparison Operators\n\n- Logical Operators\n\n- Array Operators\n\n- Element Operators\n\n- Evaluation Operators\n\nThe examples in this guide use the following documents in the `paint_purchases` collection:\n\n```json\n{ \"_id\": 1, \"color\": \"red\", \"qty\": 9, \"vendor\": [\"A\", \"E\"] }\n{ \"_id\": 2, \"color\": \"purple\", \"qty\": 8, \"vendor\": [\"B\", \"D\", \"F\"], \"rating\": 5 }\n{ \"_id\": 3, \"color\": \"blue\", \"qty\": 5, \"vendor\": [\"A\", \"E\"] }\n{ \"_id\": 4, \"color\": \"white\", \"qty\": 6, \"vendor\": [\"D\"], \"rating\": 9 }\n{ \"_id\": 5, \"color\": \"yellow\", \"qty\": 4, \"vendor\": [\"A\", \"B\"] }\n{ \"_id\": 6, \"color\": \"pink\", \"qty\": 3, \"vendor\": [\"C\"] }\n{ \"_id\": 7, \"color\": \"green\", \"qty\": 8, \"vendor\": [\"C\", \"E\"], \"rating\": 7 }\n{ \"_id\": 8, \"color\": \"black\", \"qty\": 7, \"vendor\": [\"A\", \"C\", \"D\"] }\n```\n\nThis data is modeled with the following Kotlin data class:\n\n```kotlin\ndata class PaintOrder(\n @BsonId val id: Int,\n val qty: Int,\n val color: String,\n val vendor: List,\n val rating: Int? = null\n)\n\n```\n\nThe examples in this guide use the Filters class from the `com.mongodb.client.model` package to create query filters. Alternatively, you can use the Filters class from the Kotlin driver's `mongodb-driver-kotlin-extensions` extension library, which allows you to create query filters that recognize serialization annotations.\n\nTo view an example that uses the extension library's `Filters` class, see Query Annotated Classes in the Kotlin Serialization guide.\n\n## Comparison Operators\n\nComparison operators query data based on comparisons with values in a collection. Common comparison operators include `gt()` for \"greater than\" comparisons, `lte()` for \"less than or equal to\" comparisons, and `ne()` for \"not equal to \" comparisons.\n\nThe following example uses the `Filters.gt()` method to match all documents where the value of `qty` is greater than `7` in the `paint_purchases` collection:\n\n```kotlin\nval filter = Filters.gt(\"qty\", 7)\nval findFlow = collection.find(filter)\nfindFlow.collect { println(it) }\n\n```\n\n```console\nPaintOrder(id=1, qty=9, color=red, vendor=[A, E], rating=null)\nPaintOrder(id=2, qty=8, color=purple, vendor=[B, D, F], rating=5)\nPaintOrder(id=7, qty=8, color=green, vendor=[C, E], rating=7)\n```\n\n## Logical Operators\n\nLogical operators query data using logic applied to the results of field-level operators. Common logical operators include `and()` where all operators must be true, and `or()` where at least one of the operators must be true.\n\nThe following example uses the `Filters.and()` method to match documents where the value of `qty` is less than or equal to `5` and the value of `color` is not `\"pink\"` in the `paint_purchases` collection:\n\n```kotlin\nval filter = Filters.and(Filters.lte(\"qty\", 5), Filters.ne(\"color\", \"pink\"))\nval findFlow = collection.find(filter)\nfindFlow.collect { println(it) }\n\n```\n\n```console\nPaintOrder(id=3, qty=5, color=blue, vendor=[A, E], rating=null)\nPaintOrder(id=5, qty=4, color=yellow, vendor=[A, B], rating=null)\n```\n\n## Array Operators\n\nArray operators query data based on the value or quantity of elements in an array field.\n\nThe following example uses the `Filters.size()` method to match documents where the size of the `vendor` list is `3` in the `paint_purchases` collection:\n\n```kotlin\nval filter = Filters.size(\"vendor\", 3)\nval findFlow = collection.find(filter)\nfindFlow.collect { println(it) }\n\n```\n\n```console\nPaintOrder(id=2, qty=8, color=purple, vendor=[B, D, F], rating=5)\nPaintOrder(id=8, qty=7, color=black, vendor=[A, C, D], rating=null)\n```\n\n## Element Operators\n\nElement operators query data based on the presence or type of a field.\n\nThe following example uses the `Filters.exists()` method to match documents that have a `rating` in the `paint_purchases` collection:\n\n```kotlin\nval filter = Filters.exists(\"rating\")\nval findFlow = collection.find(filter)\nfindFlow.collect { println(it) }\n\n```\n\n```console\nPaintOrder(id=2, qty=8, color=purple, vendor=[B, D, F], rating=5)\nPaintOrder(id=4, qty=6, color=white, vendor=[D], rating=9)\nPaintOrder(id=7, qty=8, color=green, vendor=[C, E], rating=7)\n```\n\n## Evaluation Operators\n\nEvaluation operators query data on higher level logic, like regex and text queries.\n\nThe following example uses the `Filters.regex()` method to match documents that have a `color` ending with the letter `\"k\"` in the `paint_purchases` collection:\n\n```kotlin\nval filter = Filters.regex(\"color\", \"k$\")\nval findFlow = collection.find(filter)\nfindFlow.collect { println(it) }\n\n```\n\n```console\nPaintOrder(id=6, qty=3, color=pink, vendor=[C], rating=null)\nPaintOrder(id=8, qty=7, color=black, vendor=[A, C, D], rating=null)\n```\n\nFor more information about the operators mentioned in this guide, see the following Server Manual Entries:\n\n- Query Operators\n\n- Comparison Operators\n\n- Logical Operators\n\n- Array Operators\n\n- Element Operators\n\n- Evaluation Operators"} -{"chunk_id": "695ca9502d5be1431b31844d-0", "page_id": "695ca9502d5be1431b31844d", "source_name": "kotlin", "product_name": "Kotlin Coroutine Driver", "url": "https://mongodb.com/docs/drivers/kotlin/coroutine/current/reference/release-notes", "title": "Release Notes", "text": "# Release Notes\n\nLearn what's new in:\n\n- Version 5.13\n\n- Version 5.12\n\n- Version 5.11.1\n\n- Version 5.11\n\n- Version 5.10\n\n- Version 5.9.2\n\n- Version 5.9\n\n- Version 5.8\n\n- Version 5.7.1\n\n- Version 5.7\n\n- Version 5.6\n\n- Version 5.5.1\n\n- Version 5.5\n\n- Version 5.4\n\n- Version 5.3\n\n- Version 5.2\n\n- Version 5.1.3\n\n- Version 5.1.2\n\n- Version 5.1.1\n\n- Version 5.1\n\n- Version 5.0\n\n- Version 4.11\n\n- Version 4.10\n\n## What's New in 5.13\n\nThe 5.13 driver release includes the following changes, fixes, and features:\n\nConnection Options\n\n- Adds the `srvAllowedHostsSuffix` option, which you can set in your connection string or by using the `ClusterSettings.Builder.srvAllowedHostsSuffix()` method. This option sets the hostname suffix that the driver uses to validate hosts returned by an SRV lookup. To learn more about this option, see Connection Options.\n\nTo learn more about this release, see the v5.13 Release Notes on GitHub.\n\n## What's New in 5.12\n\nThe 5.12 driver release includes the following changes, fixes, and features:\n\n- Adds support for MongoDB 9.0's Intelligent Workload Management (IWM). The driver now gracefully handles write-blocking scenarios and optimizes connection establishment during high-load conditions to maintain application availability. This feature includes the following changes:\n\n - Adds the `MongoClientSettings.Builder.maxAdaptiveRetries()` method and the `maxAdaptiveRetries` connection string option, which configure the maximum number of retry attempts for commands that fail with a retryable overload error.\n\n - Adds the `MongoClientSettings.Builder.enableOverloadRetargeting()` method and the `enableOverloadRetargeting` connection string option, which control whether retries of commands that fail with an error that has the `SystemOverloadedError` label attempt to use a different server. The default value is `false`. This setting has no effect on sharded clusters.\n\n - Adds the `MongoException.SYSTEM_OVERLOADED_ERROR_LABEL` and `MongoException.RETRYABLE_ERROR_LABEL` constants. A retryable overload error carries both labels. If you don't upgrade your driver version, or if you implement custom retry logic, you might need to update error-handling code to account for new errors related to overloaded servers. Use these constants to identify and handle those errors.\n\n This feature requires MongoDB 9.0 or later. To learn more about IWM, see Write-Blocking in the Atlas documentation.\n\nTo learn more about this release, see the v5.12 Release Notes on GitHub.\n\n## What's New in 5.11.1\n\nThe Kotlin driver 5.11.1 includes fixes for the following CVEs:\n\n- CVE-2026-88032\n\n- CVE-2026-88033\n\nFor the latest information about MongoDB security updates, see MongoDB Security Bulletins.\n\nTo learn more about this release, see the v5.11.1 Release Notes on GitHub.\n\n## What's New in 5.11\n\nThe 5.11 driver release does not include any changes, fixes, or features that apply to the Kotlin driver.\n\nTo learn more about this release, see the v5.11 Release Notes on GitHub.\n\n## What's New in 5.10\n\nThe 5.10 driver release includes the following changes, fixes, and features:\n\n- Fixes an issue where a `ByteArray` field in a Kotlin data class was encoded as a BSON array of `Int32` values instead of BSON Binary, which could significantly increase document size. This release restores BSON Binary encoding, matching the behavior before v5.1.3. The driver still decodes data written in the array format, but any non-driver consumers of this data might require updates to handle the new encoding.\n\n- Adds the `$scoreFusion` aggregation stage, which combines and normalizes the scores of multiple search pipelines. This stage requires MongoDB 8.2 or later.\n\n- Adds a fluent builder API for the `$score` aggregation stage. Use this API to configure score normalization, weighting, and score details. This feature requires MongoDB 8.2 or later.\n\n- Adds the `parentFilter` and `nestedOptions` options, which allow nested embeddings and arrays of embeddings in `$vectorSearch` queries.\n\nTo learn more about this release, see the v5.10 Release Notes on GitHub.\n\n## What's New in 5.9.2\n\nThe 5.9.2 driver patch release includes the following changes:\n\n- Fixes an issue where `ProxySettings.toString()` included the SOCKS5 proxy username and password, which caused these credentials to appear in application logs. This issue affects driver versions 4.11.0 through 5.9.1. To learn more, see JAVA-6266 and CVE-2026-18710.\n\nIf you use SOCKS5 proxy authentication and can't upgrade to v5.9.2, set the `org.mongodb.driver.client` logger to `WARN` or higher to suppress the client-construction message. We don't recommend this as a long-term measure, because it silences diagnostic information that is valuable for support and it doesn't remove credentials that are already written to existing logs.\n\nTo learn more about this release, see the v5.9.2 Release Notes on GitHub.\n\n## What's New in 5.9\n\nThe 5.9 driver release includes the following changes, fixes, and features:\n\nIn-Use Encryption\n\n- Promotes Queryable Encryption (QE) prefix, suffix, and substring queries to general availability (GA). These query types are supported on MongoDB 9.0 and later. To learn more about QE, see In-Use Encryption.\n\n- Renames the explicit encryption API for QE string queries from `Text` to `String`. To perform a QE string query, make the following changes:\n\n - Use the `StringOptions` class instead of `TextOptions`.\n\n - Use the `EncryptOptions.stringOptions()` method instead of `textOptions()`.\n\n - Use the `EncryptOptions.getStringOptions()` method instead of `getTextOptions()`.\n\n - Set the encryption algorithm to `\"String\"`.\n\n- Upgrades the `libmongocrypt` version to 1.20.0.\n\nTo learn more about this release, see the v5.9 Release Notes on GitHub.\n\n## What's New in 5.8\n\nThe 5.8 driver release includes the following changes, fixes, and features:\n\n- Adds a typed builder API for vector search index definitions.\n\n- Adds support for the `$rerank` aggregation stage. When connected to an Atlas cluster running MongoDB 8.3 or later, you can use the `Aggregates.rerank()` builder method to create this stage.\n\n- Adds support for the `vectorSearch` operator in a `$search` pipeline stage. You can use the `SearchOperator.vectorSearch()` builder method to perform approximate nearest neighbor (ANN) vector search, or `SearchOperator.vectorSearchExact()` for exact nearest neighbor (ENN) search. The returned `VectorSearchOperator` supports a `filter()` method to apply lexical prefilters.\n\n- Adds support for configuring stored source on vector search index definitions by using the `storedSource()` method in the `VectorSearchIndexDefinition` class.\n\n- Adds support for requesting stored source fields in `$vectorSearch` results by using the `returnStoredSource()` method in the `VectorSearchOptions` class.\n\n- Optimizes `RawBsonDocument` encode and decode performance by eliminating intermediate allocations.\n\n- Fixes an OSGi bundle resolution failure when Micrometer is not present.\n\n- Adds Javadoc documentation to the `MongodbObservation` and `MongodbObservationContext` classes.\n\n- Upgrades the `libmongocrypt` version to 1.18.1.\n\nTo learn more about this release, see the v5.8 Release Notes on GitHub.\n\n## What's New in 5.7.1\n\nThe 5.7.1 driver patch release includes the following changes:\n\n- Fixes Javadoc warnings in the Micrometer integration.\n\n- Marks Micrometer OSGi imports as optional to resolve bundle resolution issues in OSGi runtime environments.\n\nTo learn more about this release, see the v5.7.1 Release Notes on GitHub."} -{"chunk_id": "695ca9502d5be1431b31844d-1", "page_id": "695ca9502d5be1431b31844d", "source_name": "kotlin", "product_name": "Kotlin Coroutine Driver", "url": "https://mongodb.com/docs/drivers/kotlin/coroutine/current/reference/release-notes", "title": "Release Notes", "text": "## What's New in 5.7\n\nThe 5.7 driver release includes the following changes, fixes, and features:\n\n- Important: An upcoming minor release will drop support for MongoDB Server version 4.2 and raise the minimum supported version to 4.4. This change aligns with the MongoDB Software Lifecycle Schedules.\n\n We recommend making changes to your application to accommodate breaking changes. To learn more about upgrading your server version, see the Release Notes section in the MongoDB Server manual.\n\n- Adds Scala 3 support.\n\n- Adds auto-embedding support as part of vector search APIs.\n\n- Adds Micrometer/OpenTelemetry tracing support to the reactive-streams driver, and includes general Micrometer support improvements.\n\n- Adds stack-safe async loop support with trampoline pattern to prevent stack overflow errors.\n\n- Improves client-side timeout handling to better account for round-trip time (RTT) variations, along with various small timeout-related improvements.\n\n- Reuses `ConnectionSource` to avoid extra server selection.\n\n- Restores the optimized codec path for `RawBsonDocument` encoding, fixing a performance regression.\n\n- Releases the connection between empty `getMore` responses in `AsyncCommandCursor`, preventing connection pool exhaustion when idle change streams reach `maxPoolSize`.\n\n- The encryption client now uses `writeConcern` majority.\n\n- Handles unexpected end-of-stream errors from KMS.\n\n- Fixes `JsonBsonEncoder` parsing of `JsonPrimitive` numbers, where scientifically formatted numbers were parsed as plain Ints or Longs.\n\n- Simplifies `ServerMonitor` thread names and removes the `=` character, which some monitoring systems cannot process.\n\n- Fixes Kotlin BSON decoding of optionals.\n\n- Upgrades `libmongocrypt` to 1.17.3.\n\n- Uses `ZstdInputStreamNoFinalizer` for Zstandard decompression.\n\n- Updates Netty to the latest version.\n\n- Updates Snappy for the latest security fixes.\n\n- Updates JUnit 5 to the latest version.\n\n- Aligns the log level to warning when removing a server from the cluster.\n\n## What's New in 5.6\n\nThe 5.6 driver release includes the following changes, fixes, and features:\n\nIn-Use Encryption\n\n- Adds experimental support for Queryable Encryption prefix, suffix, and substring queries. To learn more about QE, see In-Use Encryption.\n\n Queryable Encryption prefix, suffix, and substring queries are unstable, and their security is not guaranteed until they're generally available (GA). Use them in experimental workloads only.\n\n- Adds an `nsType` field to `ChangeStreamDocument` objects. This field contains the namespace type (`COLLECTION`, `TIMESERIES`, or `VIEW`) of the change event.\n\n- Adds experimental client-side operation timeout (CSOT) support for OIDC authentication.\n\n The CSOT feature is experimental and might change in future driver releases.\n\n- When `timeoutMS` is set for CSOT, the driver ignores the value of the `maxWaitTime` connection setting.\n\n- Adds an `appendMetadata()` method to the `MongoClient` class. You can use this method to append metadata to an existing client's metadata. The maximum metadata size is 512 MB.\n\n- Adds a public constructor to the `RewrapManyDataKeyOptions` class.\n\n- Merges the `AsyncReadOperation` and `AsyncWriteOperation` interfaces into the `ReadOperation` and `WriteOperation` interfaces. You can create read and write operations by using builder methods in the `Operations` class.\n\n- Deprecates the `MongoNamespace.COMMAND_COLLECTION_NAME` constant.\n\n- Fixes a bug that prevented OIDC reauthentication within a session.\n\n- When serializing a POJO annotated with `@BsonDiscriminator`, if the property's `readName` matches the discriminator key, the driver serializes the field only once.\n\n- After you call the `next()` or `tryNext()` method on a `CommandCursorResult` instance, the driver clears the `CommandCursorResult.results` property to free memory.\n\n- The `PojoBuilderHelper` class creates property models that include properties from abstract classes and interfaces.\n\n- The driver publishes and logs the following events when the cluster topology changes:\n\n - `ClusterOpeningEvent`: Published when the topology opens\n\n - `ClusterDescriptionChangedEvent`: Published when the topology description changes\n\n - `ClusterClosedEvent`: Published when the topology closes\n\n- The driver throws a `MongoStalePrimaryException` when the primary replica set member becomes stale for one of the following reasons:\n\n - A new primary member is elected or discovered.\n\n - The value of the `electionId` or `setVersion` field in the primary member doesn't match the values of these fields in the other replica set members.\n\n To learn more about replica sets, see Replication in the MongoDB server manual.\n\n## What's New in 5.5.1\n\nThe 5.5.1 driver patch release includes the following changes:\n\n- Fixes an issue where OIDC reauthentication failed when triggered by an operation run in a session, including operations run in a transaction.\n\n## What's New in 5.5\n\nKotlin driver v5.5 removes support for MongoDB server 4.0. To learn more about compatible versions of the server, see Compatibility.\n\nThe 5.5 driver release includes the following changes, fixes, and features:\n\n- Adds support for the `connectTimeoutMS` option when using the default TLS transport layer.\n\n- Introduces performance improvements that are reflected in the driver performance benchmarks. To view the results of the performance benchmark tests, see the following Performance Improvements section."} -{"chunk_id": "695ca9502d5be1431b31844d-2", "page_id": "695ca9502d5be1431b31844d", "source_name": "kotlin", "product_name": "Kotlin Coroutine Driver", "url": "https://mongodb.com/docs/drivers/kotlin/coroutine/current/reference/release-notes", "title": "Release Notes", "text": "### Performance Improvements\n\nThe tables in this section show the results of performance tests for the synchronous Java driver. The tests were conducted on a MongoDB Server 8.0 deployment with the following configuration:\n\n- Running on `localhost` with negligible network latency. In higher-latency environments, you might see less significant performance improvements.\n\n- Authentication disabled.\n\n- TLS disabled.\n\nWe expect similar performance increases for all MongoDB Java drivers because they share the improved `driver-core` API.\n\n#### Standard Transport Settings\n\nThe following table shows the results of performance tests for v5.5 of the driver configured with standard transport settings. Each row includes the feature tested, the percent improvement in performance, and the z-score.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nFeature\n\n\nPercent Improvement\n\n\nZ-score\n\n
\nDeep BSON decoding\n\n\n19.44%\n\n\n5.4\n\n
\nDeep BSON encoding\n\n\n102%\n\n\n22.8\n\n
\nFind many and empty the cursor\n\n\n25.08%\n\n\n13.72\n\n
\nFind one by ID\n\n\n2.7%\n\n\n3.16\n\n
\nFlat BSON decoding\n\n\n31.2%\n\n\n9.38\n\n
\nFlat BSON encoding\n\n\n199.5%\n\n\n12.34\n\n
\nFull BSON decoding\n\n\n16.5%\n\n\n7.23\n\n
\nFull BSON encoding\n\n\n147.3%\n\n\n10.39\n\n
\nJSON-LD multi-file import\n\n\n21.8%\n\n\n8.21\n\n
\nClient bulk insert with large documents\n\n\n91.3%\n\n\n24.44\n\n
\nCollection bulk insert with large documents\n\n\n96.5%\n\n\n8.79\n\n
\nBulk insert with large documents\n\n\n93.3%\n\n\n8.11\n\n
\nBulk insert with small documents\n\n\n39.3%\n\n\n5.72\n\n
\nInsert one with large documents\n\n\n82.4%\n\n\n7.28\n\n
\nClient bulk insert with small documents\n\n\n49.5%\n\n\n17.99\n\n
\nCollection bulk insert with small documents\n\n\n47.8%\n\n\n6.44\n\n
\n\n#### Netty Transport Settings\n\nThe following table shows the results of performance tests for v5.5 of the driver configured with Netty transport settings. Each row includes the feature tested, the percent improvement in performance, and the z-score.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nFeature\n\n\nPercent Improvement\n\n\nZ-score\n\n
\nFind many and empty the cursor\n\n\n40.3%\n\n\n14.81\n\n
\nFind one by ID\n\n\n4.4%\n\n\n4.12\n\n
\nJSON-LD multi-file import\n\n\n16.9%\n\n\n3.77\n\n
\nClient bulk insert with large documents\n\n\n54.8%\n\n\n14.49\n\n
\nCollection bulk insert with large documents\n\n\n104.9%\n\n\n38.72\n\n
\nBulk insert with large documents\n\n\n74.6%\n\n\n65.55\n\n
\nInsert one with large documents\n\n\n66.6%\n\n\n58.65\n\n
\nClient bulk insert with small documents\n\n\n36.1%\n\n\n15.41\n\n
\nCollection bulk insert with small documents\n\n\n39.3%\n\n\n37.38\n\n
\nBulk insert with small documents\n\n\n35.1%\n\n\n41.51\n\n
To learn more about how we conduct driver performance benchmark tests, see the Performance Benchmarking specification.\n\n## What's New in 5.4\n\nThe 5.4 driver release includes the following changes, fixes, and features:\n\n- Adds `BsonConfiguration` support for `bson-kotlinx` snake case conversion during serialization. To learn more, see the Implement Snake Case Naming Strategy section on the Serialization page.\n\nthe Add the Driver Bill of Materials step of the Quick Start\n\nthe Update Operation and Replace Operation sections of the Bulk Operations guide\n\nthe MONGODB-OIDC: Kubernetes section of the Enterprise Authentication Mechanisms guide\n\nthe SearchOperator interface API documentation\n\nthe Search Operator Methods section of the Aggregates Builders guide\n\n- Supports `$lookup` operations for CSFLE and QE. To learn more, see the following references in the Server manual:\n\n - $lookup and $graphLookup Behavior for CSFLE\n\n - $lookup and $graphLookup Behavior for QE\n\n- Introduces a Bill of Materials (BOM) to manage versions of MongoDB JVM artifacts that you might use in your application. To view instructions on adding the BOM to your application, see the Add the Driver Bill of Materials step of the Quick Start.\n\n- Updates AWS SDK dependencies to 2.30.31 and 1.12.782 for testing the `MONGODB-AWS` authentication mechanism.\n\n- Adds a sort option to the `ClientUpdateOneOptions` and `ClientReplaceOneOptions` classes. This change allows you to set a sort order for update and replace operations in client bulk writes. To learn more, see the Update Operation and Replace Operation sections of the Bulk Operations guide.\n\n- Adds Kubernetes support for OIDC authentication. To learn more, see the MONGODB-OIDC: Kubernetes section of the Enterprise Authentication Mechanisms guide.\n\n- Adds first class support for the following MongoDB Search query operators:\n\n - `phrase`\n\n - `regex`\n\n - `queryString`\n\n - `equals`\n\n - `moreLikeThis`\n\n - `in`\n\n - `wildcard`\n\n To learn more, see the Search Operator Methods section of the Aggregates Builders guide.\n\n- Updates cursors to refresh the `timeoutMS` setting when you call `close()` without affecting the operation timeout.\n\n- Enables you to use an index when calling the `distinct()` method by specifying a `hint` option.\n\nTo view a full list of changes in this release, see the v5.4 release notes on GitHub."} -{"chunk_id": "695ca9502d5be1431b31844d-3", "page_id": "695ca9502d5be1431b31844d", "source_name": "kotlin", "product_name": "Kotlin Coroutine Driver", "url": "https://mongodb.com/docs/drivers/kotlin/coroutine/current/reference/release-notes", "title": "Release Notes", "text": "## What's New in 5.3\n\nThe 5.3 driver release includes the following new features, improvements, and fixes:\n\nTo learn about how to use this type when using the MongoDB Vector Search feature, see the MongoDB Vector Search guide.\n\nthe Update Documents and Bulk Operations guides\n\n- Important: The next minor release will drop support for MongoDB Server version 4.0 and raise the minimum supported version to 4.2. We recommend making changes to your application to accommodate breaking changes. See the Release Notes section in the Server manual to learn more about upgrading.\n\n- Adds the `BinaryVector` class to implement BSON Binary Subtype 9 for vector storage and retrieval. This class provides more effective storage of values compared a list of `Double` instances. You can create the following vector types based on the type of elements your vector contains:\n\n - `Int8BinaryVector`: Vector of 8-bit signed integers\n\n - `Float32BinaryVector`: Vector of floating-point numbers\n\n - `PackedBitBinaryVector`: Binary quantized vector *(In beta and subject to change before becoming generally available)*\n\n To learn more about this feature, see Vector Quantization in the Atlas documentation. To learn about how to use this type when using the MongoDB Vector Search feature, see the MongoDB Vector Search guide.\n\n- Removes explicit fairness from the connection pool implementation. This change might contribute to better throughput when you use a `MongoClient` instance in many application threads. However, this change might cause increased tail latency.\n\n- Adds a sort option to the `updateOne()` and `replaceOne()` methods. This change also allows you to set a sort as an option when creating `ReplaceOneModel` and `UpdateOneModel` instances. To learn more, see the Update Documents and Bulk Operations guides.\n\n- Support for using builders class methods directly with data class properties. To learn more, see the Use Builders with Data Classes guide. This functionality is supported by the Kotlin driver Extensions package published with this release.\n\n- Implements a *client* bulk write API that allows you to perform write operations on multiple databases and collections in the same call. To learn more about this feature, see the Client Bulk Write section of the Bulk Operations guide.\n\n## What's New in 5.2\n\nKotlin driver v5.2 removes support for MongoDB server 3.6. To learn more about compatible versions of the server, see Compatibility.\n\nThe 5.2 driver release includes the following new features, improvements, and fixes:\n\nthe Limit Server Execution Time guide\n\nMongoDB Search and MongoDB Vector Search Indexes in the Indexes guide\n\nthe In-Use Encryption guide\n\nMongoDB Vector Search in the Aggregates Builders guide\n\n- Enables setting a client-side operations timeout (CSOT). This feature allows you to set a single timeout on your `MongoClient` instance that applies to all operations performed with that client. To learn more, see the Limit Server Execution Time guide.\n\n If, and only if, the CSOT feature is enabled, the following timeout options are ignored by the driver:\n\n - `waitQueueTimeoutMS`\n\n - `socketTimeoutMS`\n\n - `wTimeoutMS`\n\n - `maxTimeMS`\n\n - `maxCommitTimeMS`\n\n CSOT is an **experimental** feature and not yet production ready. This feature is optional in the current release and existing timeout options remain functional.\n\n- Adds the `SearchIndexType` class, which you can pass when constructing a `SearchIndexModel` instance. This change allows you to specify the index type when creating an Atlas Search or Vector Search index. To learn more, see MongoDB Search and MongoDB Vector Search Indexes in the Indexes guide.\n\n- Delegates the implementation of the algorithms that implement the `SCRAM-SHA-1` and `SCRAM-SHA-256` authentication mechanisms to the configured JCA provider. This change means that your application can use a configured FIPS-compliant JCA provider to provide a higher level of security.\n\n- Revises the mongodb-crypt dependency versioning to match the versioning for the JVM drivers. Future versions of `mongodb-crypt` will be released alongside the driver and will share the same version number. You must upgrade your `mongodb-crypt` dependency to v5.2.0 when upgrading your driver for this release. To learn more, see the In-Use Encryption guide.\n\n- Performance improvements due to implementation of native cryptography on all supported platforms. The following list describes the actions needed to implement this improvement depending on your operating system:\n\n - **Windows**: Upgrade your `mongodb-crypt` version to v5.2.0.\n\n - **Mac**: Upgrade your `mongodb-crypt` version to v5.2.0.\n\n - **Linux**: Install `libmongocrypt.so` directly on the file system, instead of using the file that is bundled within the `mongodb-crypt` JAR file. You can find Linux instructions to install `libmongocrypt` in the Server manual. If you use a package manager to install `libmongocrypt`, Java Native Access (JNA) will find it there without further configuration. Alternatively, you can specify the search path by setting the `LD_LIBRARY_PATH` environment variable to the file path of the `libmongocrypt` package.\n\n We recommend direct installation because the bundled shared library does not link with OpenSSL due to the potential for OpenSSL binary incompatibilities.\n\n The shared library loading is handled by JNA. You can view the rules for library loading search path order in the NativeLibrary class documentation.\n\n- Fixes an issue that caused the `InsertOneResult.getInsertedId()` and `InsertManyResult.getInsertedIds()` methods to return incorrect document IDs in some situations. This change is backported to Kotlin driver v5.1.4 and v4.11.4.\n\n- When a sharded cluster operation is unsuccessful, the driver avoids selecting the same `mongos` server for operation retry attempts if other `mongos` servers are available.\n\n- Adds reachability metadata needed when your application uses GraalVM Native Image. This metadata replaces the need for collecting reachability metadata when using the driver libraries. To learn more, see Reachability Metadata in the GraalVM documentation.\n\n This change does not add the `libjnidispatch` and `libmongocrypt` resource entries, because adding entries for all supported platforms (targets) significantly affects the size of native executables built using GraalVM Native Image. View this sample resource-config.json file in the driver GitHub repository to see how to specify these entries explicitly if your application depends on the `org.mongodb:mongodb-crypt` library.\n\n- Enables exact vector search by extending the `VectorSearchOptions` API to introduce the following specific option subtypes:\n\n - `ExactVectorSearchOptions`: Use this options type to enable precise matching, ensuring that results are the closest vectors to a given query vector.\n\n - `ApproximateVectorSearchOptions`: Use this options type to enable searches that might not return the exact closest vectors. You can pass a `numCandidates` parameter when instantiating this type to specify the number of nearest neighbors to consider.\n\n To learn more about using the MongoDB Vector Search feature, see MongoDB Vector Search in the Aggregates Builders guide.\n\n- Adds support for serializers from the `kotlinx-datetime` library that let you map Kotlin date and time types to BSON as the expected types instead of as strings. To learn more, see the Serialize Dates and Times section of the Kotlin Serialization guide.\n\n- Supports serialization of JsonElement values. To work with the `JsonElement` type, you must add the `kotlinx-serialization-json` library as a dependency in your application.\n\n## What's New in 5.1.3\n\nThe 5.1.3 driver patch release includes the following changes:\n\n- Fixes an issue that could cause assertion errors when using `Cursor` types."} -{"chunk_id": "695ca9502d5be1431b31844d-4", "page_id": "695ca9502d5be1431b31844d", "source_name": "kotlin", "product_name": "Kotlin Coroutine Driver", "url": "https://mongodb.com/docs/drivers/kotlin/coroutine/current/reference/release-notes", "title": "Release Notes", "text": "## What's New in 5.1.2\n\nThe 5.1.2 driver patch release includes the following changes:\n\n- Support for encoding Kotlin data classes with nullable generic parameter types. For example, you can encode the `Container` class in the following code:\n\n ```kotlin\n @Serializable\n data class Box(\n val boxed: T\n )\n\n @Serializable\n data class Container(\n val box: Box\n )\n ```\n\n## What's New in 5.1.1\n\nThe 5.1.1 driver patch release includes the following changes:\n\n- When using the `MONGODB-OIDC` authentication mechanism, you must not include comma characters in the `authMechanismProperties` connection string value. To learn more about this behavior, see the MONGODB-OIDC section of the Enterprise Authentication guide.\n\n## What's New in 5.1\n\nTo avoid breaking changes in future major releases of the driver, replace any application code that depends on deprecated program elements.\n\nThis section includes the following information:\n\n- Deprecations in 5.1\n\n- Improvements in 5.1\n\n- New Features in 5.1\n\n### Deprecations in 5.1\n\n- Support for MongoDB server v3.6 is deprecated and will be removed in the next driver version release. To learn how to upgrade your MongoDB server deployment, see Release Notes in the MongoDB server manual.\n\n### Improvements in 5.1\n\n- Internal testing of GraalVM native image technology. These tests involve building native applications by using the GraalVM native-image tool.\n\n- Enhanced support for the `MONGODB-OIDC` authentication mechanism. To learn more about OIDC, see the OIDC (Workload Identity Federation) section of the Enterprise Authentication Mechanisms guide.\n\n- Fixes an issue in which operations used the incorrect codec when using a polymorphic `MongoCollection` instance. This ensures that discriminator information is not lost when using `bson-kotlinx`.\n\n- Fixes an issue in which the class discriminator was the first field when decoding, resulting in field type errors when using a polymorphic `MongoCollection` instance.\n\n### New Features in 5.1\n\n- Support for polymorphic serialization. To learn more, see the Polymorphic Serialization section of the Kotlin Serialization guide.\n\n- Introduces the `serverMonitoringMode` connection URI option. To learn more, see the Connection Options guide.\n\n## What's New in 5.0\n\nNew features of the 5.0 driver release include:\n\n- The `KotlinSerializerCodecProvider` constructor now accepts `serializersModule` and `bsonConfiguration` objects:\n\n ```kotlin\n KotlinSerializerCodec.create(clazz.kotlin, serializersModule=serializersModule, bsonConfiguration=bsonConfiguration)\n ```\n\n This makes it easier to customize your configuration.\n\n- Fixes a Kotlin reflection bug that resulted in container type erasure.\n\n## What's New in 4.11\n\nThis section includes the following information:\n\n- Deprecations in 4.11\n\n- New Features in 4.11\n\n### Deprecations in 4.11\n\nTo avoid breaking changes in future major releases of the driver, replace any application code that depends on deprecated methods and types.\n\nThe 4.11 driver release deprecates the following items:\n\n- The following network address-related methods are deprecated and will be removed in v5.0:\n\n - The ServerAddress methods `getSocketAddress()` and `getSocketAddresses()`.\n\n Instead of `getSocketAddress()`, use the `getByName()` instance method of `java.net.InetAddress`.\n\n Instead of `getSocketAddresses()`, use the `getAllByName()` instance method of `java.net.InetAddress`.\n\n - The UnixServerAddress method `getUnixSocketAddress()`.\n\n Instead of `getUnixSocketAddress()`, construct an instance of `jnr.unixsocket.UnixSocketAddress`. Pass the full path of the UNIX socket file to the constructor. By default, MongoDB creates a UNIX socket file located at `\"/tmp/mongodb-27017.sock\"`. To learn more about the `UnixSocketAddress`, see the UnixSocketAddress API documentation.\n\n- The following methods and types related to the StreamFactory interface are deprecated and scheduled for removal in v5.0:\n\n - `streamFactoryFactory()` method from `MongoClientSettings.Builder`\n\n - `getStreamFactoryFactory()` method from `MongoClientSettings`\n\n - `NettyStreamFactoryFactory` class\n\n - `NettyStreamFactory` class\n\n - `AsynchronousSocketChannelStreamFactory` class\n\n - `AsynchronousSocketChannelStreamFactoryFactory` class\n\n - `BufferProvider` class\n\n - `SocketStreamFactory` class\n\n - `Stream` class\n\n - `StreamFactory` class\n\n - `StreamFactoryFactory` class\n\n - `TlsChannelStreamFactoryFactory` class\n\n If you configure Netty by using `MongoClientSettings.Builder.streamFactoryFactory()`, your code might resemble the following:\n\n ```java\n import com.mongodb.connection.netty.NettyStreamFactoryFactory;\n\n // ...\n\n MongoClientSettings settings = MongoClientSettings.builder()\n .streamFactoryFactory(NettyStreamFactoryFactory.builder().build())\n .build();\n ```\n\n Replace this code with the TransportSettings.nettyBuilder() as shown in the following example:\n\n ```java\n import com.mongodb.connection.TransportSettings;\n\n // ...\n\n MongoClientSettings settings = MongoClientSettings.builder()\n .transportSettings(TransportSettings.nettyBuilder().build())\n .build();\n ```\n\n### New Features in 4.11\n\nNew features of the 4.11 driver release include:\n\n- Support for connecting to MongoDB by using a SOCKS5 proxy.\n\n- Added the `getSplitEvent()` method to the `ChangeStreamDocument` class to identify fragments of a change stream event that exceeds 16MB. You must use the aggregation stage `$changeStreamSplitLargeEvent` in your change stream to handle events that exceed 16MB.\n\n- Added an aggregation stage builder for `$vectorSearch`.\n\n- Added MongoDB Search index management helpers.\n\n- Updated Snappy and Zstd compression library dependency versions. To learn more about the current dependency versions, see Compress Network Traffic.\n\n- Added `getElapsedTime()` methods to the following classes to monitor the duration of connection pool events:\n\n - ConnectionCheckOutFailedEvent\n\n - ConnectionCheckedOutEvent\n\n - ConnectionReadyEvent\n\n- Support for Java 21 virtual threads and structured concurrency. The driver internals were updated to avoid unnecessary pinning of virtual threads and to preserve interrupted status of a thread, as the latter matters for structured concurrency where it is used for cancellation.\n\n To learn more about virtual threads, see the Virtual Threads JDK enhancement proposal. To learn more about structured concurrency, see the Structured Concurrency JDK enhancement proposal.\n\n- Updated API documentation for the following types:\n\n - ClusterListener\n\n - ServerListener\n\n - ServerMonitorListener\n\n## What's New in 4.10\n\nStarting in version 4.10.1 of the Kotlin driver, you must add the `bson-kotlinx` library as an explicit dependency to use the `kotlinx-serialization` library.\n\n- Support for Kotlin server-side usage, both for coroutines and for synchronous applications.\n\n- Codec support for Kotlin data classes.\n\n- Support for the `kotlinx.serialization` library"} -{"chunk_id": "695ca9502d5be1431b3183b4-0", "page_id": "695ca9502d5be1431b3183b4", "source_name": "kotlin", "product_name": "Kotlin Coroutine Driver", "url": "https://mongodb.com/docs/drivers/kotlin/coroutine/current/crud/delete", "title": "Delete Documents", "text": "# Delete Documents\n\n## Overview\n\nIn this guide, you can learn how to remove documents with the MongoDB Kotlin driver.\n\nYou can remove documents by passing a query filter to the `deleteOne()`, `deleteMany()`, or `findOneAndDelete()` methods:\n\n- `deleteOne()` method: Deletes a single document. If the query filter matches more than one document, the method will remove the first occurrence of a match in the collection.\n\n- `deleteMany()` method: Deletes all documents that match the query filter.\n\n- `findOneAndDelete()` method: Finds and deletes the first occurrence of a match in the collection. Returns the matched document.\n\nTo specify a collation or hint an index, use `DeleteOptions` as a second parameter to the `deleteOne()` and `deleteMany()` methods.\n\nTo specify a collation, hint an index, specify sort order, or specify a projection on the returned document, use `FindOneAndDeleteOptions` as the second parameter to the `findOneAndDelete()` method.\n\nWhen deleting a single document, filter your query by a unique index, such as an `_id`, to ensure your query matches the document you want to delete.\n\n### Sample Documents\n\nThe following examples are about a paint store that sells eight different colors of paint. The store had their annual online sale resulting in the following documents in their `paint_inventory` collection:\n\n```json\n{ \"_id\": 1, \"color\": \"red\", \"qty\": 5 }\n{ \"_id\": 2, \"color\": \"purple\", \"qty\": 8 }\n{ \"_id\": 3, \"color\": \"blue\", \"qty\": 0 }\n{ \"_id\": 4, \"color\": \"white\", \"qty\": 0 }\n{ \"_id\": 5, \"color\": \"yellow\", \"qty\": 6 }\n{ \"_id\": 6, \"color\": \"pink\", \"qty\": 0 }\n{ \"_id\": 7, \"color\": \"green\", \"qty\": 0 }\n{ \"_id\": 8, \"color\": \"black\", \"qty\": 8 }\n```\n\nThis data is modeled with the following Kotlin data class:\n\n```kotlin\ndata class PaintOrder(\n @BsonId val id: Int,\n val qty: Int,\n val color: String\n)\n\n```\n\n## Delete Many Documents\n\nThe paint store website displays all documents in the `paint_inventory` collection. To reduce customer confusion, the store wants to remove the colors that are out of stock.\n\nTo remove the out of stock colors, query the `paint_inventory` collection where the `qty` is `0` and pass the query to the `deleteMany()` method:\n\n```kotlin\nval filter = Filters.eq(\"qty\", 0)\ncollection.deleteMany(filter)\n\n```\n\nThe following shows the documents remaining in the `paint_inventory` collection:\n\n```json\n{ \"_id\": 1, \"color\": \"red\", \"qty\": 5 }\n{ \"_id\": 2, \"color\": \"purple\", \"qty\": 8 }\n{ \"_id\": 5, \"color\": \"yellow\", \"qty\": 6 }\n{ \"_id\": 8, \"color\": \"black\", \"qty\": 8 }\n```\n\n### deleteMany() Example: Full File\n\nThis example connects to an instance of MongoDB by using a connection URI. To learn more about connecting to your MongoDB instance, see the Connect to MongoDB guide. This example also uses the `movies` collection in the `sample_mflix` database included in the Atlas sample datasets. You can load them into your database on a free cluster in MongoDB Atlas by following the MongoDB Get Started guide.\n\nThe following example is a fully runnable file that finds and deletes all documents in the `movies` collection that contain a `rating` of less than `2.9` in the `imdb` sub-document:\n\n```kotlin\n\nimport com.mongodb.MongoException\nimport com.mongodb.client.model.Filters\nimport com.mongodb.kotlin.client.coroutine.MongoClient\nimport kotlinx.coroutines.runBlocking\n\ndata class Movie(val imdb: IMDB){\n data class IMDB(val rating: Double)\n}\n\nfun main() = runBlocking {\n // Replace the uri string with your MongoDB deployment's connection string\n val uri = \"\"\n val mongoClient = MongoClient.create(uri)\n val database = mongoClient.getDatabase(\"sample_mflix\")\n val collection = database.getCollection(\"movies\")\n\n val query = Filters.lt(\"${Movie::imdb.name}.${Movie.IMDB::rating.name}\", 2.9)\n try {\n val result = collection.deleteMany(query)\n println(\"Deleted document count: \" + result.deletedCount)\n } catch (e: MongoException) {\n System.err.println(\"Unable to delete due to an error: $e\")\n }\n mongoClient.close()\n}\n\n```\n\n```console\nDeleted document count: 4\n```\n\n## Delete a Document\n\nThe store is donating the remaining quantity of their yellow paint. This means that the `qty` for yellow is now `0` and we need to remove yellow from the collection.\n\nTo remove yellow, query the `paint_inventory` collection where the `color` is `\"yellow\"` and pass the query to the `deleteOne()` method:\n\n```kotlin\nval filter = Filters.eq(\"color\", \"yellow\")\ncollection.deleteOne(filter)\n\n```\n\nThe following shows the documents remaining in the `paint_inventory` collection:\n\n```json\n{ \"_id\": 1, \"color\": \"red\", \"qty\": 5 }\n{ \"_id\": 2, \"color\": \"purple\", \"qty\": 8 }\n{ \"_id\": 8, \"color\": \"black\", \"qty\": 8 }\n```\n\n### deleteOne() Example: Full File\n\nThis example connects to an instance of MongoDB by using a connection URI. To learn more about connecting to your MongoDB instance, see the Connect to MongoDB guide. This example also uses the `movies` collection in the `sample_mflix` database included in the Atlas sample datasets. You can load them into your database on a free cluster in MongoDB Atlas by following the MongoDB Get Started guide.\n\nThe following example is a fully runnable file that performs the following actions:\n\n- Uses the `eq()` filter to match movies with the `title` exactly matching the text `'The Garbage Pail Kids Movie'`.\n\n- Deletes the single matching document from the `movies` collection.\n\n```kotlin\n\nimport com.mongodb.MongoException\nimport com.mongodb.client.model.Filters\nimport com.mongodb.kotlin.client.coroutine.MongoClient\nimport kotlinx.coroutines.runBlocking\n\ndata class Movie(val title: String)\n\nfun main() = runBlocking {\n // Replace the uri string with your MongoDB deployment's connection string\n val uri = \"\"\n val mongoClient = MongoClient.create(uri)\n val database = mongoClient.getDatabase(\"sample_mflix\")\n val collection = database.getCollection(\"movies\")\n\n val query = Filters.eq(Movie::title.name, \"The Garbage Pail Kids Movie\")\n\n try {\n val result = collection.deleteOne(query)\n println(\"Deleted document count: \" + result.deletedCount)\n } catch (e: MongoException) {\n System.err.println(\"Unable to delete due to an error: $e\")\n }\n mongoClient.close()\n}\n\n```\n\nWhen you run the example, if the query filter you passed in your call to `deleteOne()` matches a document and removes it, you see output similar to the following:\n\n```none\nDeleted document count: 1\n```\n\nIf your query filter does not match a document in your collection, your call to `deleteOne()` removes no documents and returns the following:\n\n```none\nDeleted document count: 0\n```"} -{"chunk_id": "695ca9502d5be1431b3183b4-1", "page_id": "695ca9502d5be1431b3183b4", "source_name": "kotlin", "product_name": "Kotlin Coroutine Driver", "url": "https://mongodb.com/docs/drivers/kotlin/coroutine/current/crud/delete", "title": "Delete Documents", "text": "## Find and Delete a Document\n\nThe store would like to raffle the remaining quantity of purple paint and remove purple from the `paint_inventory` collection.\n\nTo pick a color, query the `paint_inventory` collection where the `color` is `\"purple\"` and pass the query to the `findOneAndDelete()` method. Unlike the other delete methods, `findOneAndDelete()` returns the deleted document:\n\n```kotlin\nval filter = Filters.eq(\"color\", \"purple\")\nval result = collection.findOneAndDelete(filter)\n\nprintln(\"The following was deleted: $result\")\n\n```\n\n```console\nThe following was deleted: PaintOrder(id=2, qty=8, color=purple)\n```\n\nIf there are no matches to your query filter, no document gets deleted and the method returns `null`.\n\nThe following shows the documents remaining in the `paint_inventory` collection:\n\n```json\n { \"_id\": 1, \"color\": \"red\", \"qty\": 5 }\n { \"_id\": 8, \"color\": \"black\", \"qty\": 8 }\n```\n\nFor more information about the methods and classes mentioned in this guide, see the following resources:\n\n- deleteOne() API Documentation\n\n- deleteMany() API Documentation\n\n- findOneAndDelete() API Documentation\n\n- DeleteOptions API Documentation\n\n- FindOneAndDeleteOptions API Documentation\n\n- db.collection.deleteOne() Server Manual Entry\n\n- db.collection.deleteMany() Server Manual Entry\n\n- db.collection.findOneAndDelete() Server Manual Entry"} -{"chunk_id": "696b29eb455b28a12b3b39ad-0", "page_id": "696b29eb455b28a12b3b39ad", "source_name": "kotlin", "product_name": "Kotlin Coroutine Driver", "url": "https://mongodb.com/docs/drivers/kotlin/coroutine/current/connect/connection-options/network-compression", "title": "Compress Network Traffic", "text": "# Compress Network Traffic\n\n## Overview\n\nMongoDB drivers can compress the messages sent to and received from MongoDB server. This reduces the amount of data transferred for each operation. Compression can improve performance over constrained networks and lower the data transfer costs associated with running MongoDB Atlas.\n\nCompression operates at the wire protocol level, so it applies to every operation that your application performs. If you specify more than one algorithm, the driver uses the first algorithm in your list that MongoDB server also supports.\n\n### Compression Algorithms\n\nMongoDB drivers support the following compression algorithms:\n\n- Snappy\n\n- Zlib\n\n- Zstandard\n\n## Network Compression Benefits\n\nMongoDB Atlas charges for data transferred across cloud regions, cloud providers, and between your infrastructure and MongoDB Atlas. Network compression reduces the amount of data that your application sends and receives, which can lower these data transfer costs. To learn more about pricing, see Data Transfer Costs.\n\nNetwork compression also has productivity benefits. Compressed messages take less time to transfer across the network, which can improve your application's response times. Compression also reduces the bandwidth that your MongoDB traffic uses, which leaves more bandwidth available for other applications on the same network.\n\nWhen you choose a compression algorithm, consider the following guidelines:\n\n- Use **Zstandard** for a balance of compression efficiency and resource usage. Zstandard is a good default choice for most applications.\n\n- Use **Snappy** for latency-sensitive applications that require minimal computational overhead.\n\n- Use **Zlib** for broad compatibility across MongoDB drivers and environments.\n\nCompression trades network bandwidth for CPU usage. After you enable network compression, monitor your application's CPU utilization to confirm that the trade-off benefits your workload. To learn more about these trade-offs, see the CPU Utilization and Network Compression in MongoDB blog post.\n\n## Version Compatibility\n\nThe following table lists the minimum supported driver and MongoDB server version for each compression algorithm:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nCompression Algorithm\n\n\nMinimum Driver Version\n\n\nMinimum Server Version\n\n
\nSnappy\n\n\n4.10\n\n\n4.2\n\n
\nZlib\n\n\n4.10\n\n\n4.2\n\n
\nZstandard\n\n\n4.10\n\n\n4.2\n\n
\n\n## Enable Network Compression\n\nTo enable network compression for your MongoDB connection, install the required dependencies and specify the compression algorithms that you want to use.\n\n### Compression Algorithm Dependencies\n\nThe following table lists each algorithm and the dependency it requires, if any:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nCompression Algorithm\n\n\nDependency\n\n
\nSnappy\n\n\nDownload `snappy-java`, a Java JNI wrapper for the Snappy library. To install, see snappy-java in Maven Central.\n\n
\nZlib\n\n\nNone. The driver natively supports Zlib compression.\n\n
\nZstandard\n\n\nDownload `zstd-jni`, a Java JNI wrapper for the Zstandard library. To install, see zstd-jni in Maven Central.\n\n
\n\n### Specify Compression Algorithms\n\nYou can enable compression on your connection by specifying the algorithms in the following ways:\n\n- Adding the `compressors` parameter to your `ConnectionString` instance\n\n- Calling the `compressorList()` method from the `MongoClientSettings` builder\n\n\n\n\n\nTo enable compression on your connection in a ConnectionString instance, specify the `compressors` parameter. You can specify one or more of the following values for the `compressors` parameter:\n\n- `\"snappy\"` for Snappy compression\n\n- `\"zlib\"` for Zlib compression\n\n- `\"zstd\"` for Zstandard compression\n\nThe following example shows how to specify Snappy, Zlib, and Zstandard as the compression algorithms for a connection:\n\n```kotlin\n// Replace the placeholders with values from your MongoDB deployment's connection string\nval connectionString = ConnectionString(\"mongodb+srv://:@/?compressors=snappy,zlib,zstd\")\n\n// Create a new client with your settings\nval mongoClient = MongoClient.create(connectionString)\n```\n\n\n\n\n\nTo enable compression using within your MongoClientSettings, call the compressorList() builder method and pass one or more MongoCompressor instances as a parameter.\n\nYou can specify compression algorithms by calling the following methods from `MongoCompressor`:\n\n- `createSnappyCompressor()` for Snappy compression\n\n- `createZlibCompressor()` for Zlib compression\n\n- `createZstdCompressor()` for Zstandard compression\n\nThe following example shows how to specify Snappy, Zlib, and Zstandard as the compression algorithms for a connection:\n\n```kotlin\n// Replace the placeholder with your MongoDB deployment's connection string\nval uri = \"\"\n\nval settings = MongoClientSettings.builder()\n .applyConnectionString(ConnectionString(uri))\n .compressorList(\n listOf(\n MongoCompressor.createSnappyCompressor(),\n MongoCompressor.createZlibCompressor(),\n MongoCompressor.createZstdCompressor())\n )\n .build()\n\n// Create a new client with your settings\nval mongoClient = MongoClient.create(settings)\n\n```\n\n\n\n"} -{"chunk_id": "695ca9502d5be1431b31842d-0", "page_id": "695ca9502d5be1431b31842d", "source_name": "kotlin", "product_name": "Kotlin Coroutine Driver", "url": "https://mongodb.com/docs/drivers/kotlin/coroutine/current/logging-monitoring/monitoring", "title": "Monitoring", "text": "# Monitoring\n\n## Overview\n\nIn this guide, you can learn how to set up and configure **monitoring** in the MongoDB Kotlin driver.\n\nMonitoring is the process of getting information about the activities a running program performs for use in an application or an application performance management library.\n\nMonitoring the MongoDB Kotlin driver lets you understand the driver's resource usage and performance, and can help you make informed decisions when designing and debugging your application.\n\nIn this guide you will learn how to perform these tasks:\n\n- Monitor different types of events in the MongoDB Kotlin driver\n\n- Monitor connection pool events with Java Management Extensions (JMX) and JConsole\n\nThis guide shows how to use information about the activity of the driver in code. If you would like to learn how to record events in the driver, consider reading our guide on logging.\n\n## Monitor Events\n\nTo monitor an **event**, you must register a **listener** on your `MongoClient` instance.\n\nAn event is any action that happens in a running program. The driver includes functionality for listening to a subset of the events that occur when the driver is running.\n\nA listener is a class that performs some action when certain events occur. A listener's API defines the events it can respond to.\n\nEach method of a listener class represents a response to a certain event. Each method receives one argument: an object representing the event the method responds to.\n\nThe MongoDB Kotlin driver organizes the events it defines into three categories:\n\n- Command Events\n\n- Server Discovery and Monitoring Events\n\n- Connection Pool Events\n\nThe following sections show how to monitor each event category.\n\nFor a full list of the events you can monitor, see the event package of the MongoDB Kotlin driver.\n\n### Command Events\n\nA command event is an event related to a MongoDB database command. Some examples of database commands that produce command events are `find`, `insert`, `delete`, and `count`.\n\nTo monitor command events, write a class that implements the `CommandListener` interface and register an instance of that class with your `MongoClient` instance.\n\nFor more information on MongoDB database commands, see the MongoDB manual entry on database commands.\n\nThe driver does not publish events for commands it calls internally. This includes database commands the driver uses to monitor your cluster and commands related to connection establishment (such as the initial `hello` command).\n\nAs a security measure, the driver redacts the contents of some command events. This protects the sensitive information contained in these command events. For a full list of redacted command events, see the MongoDB command logging and monitoring specification.\n\n#### Example\n\nThis example shows how to make a counter for database commands. The counter keeps track of the number of times the driver successfully executes each database command, and prints this information every time a database command finishes.\n\nTo make a counter, do the following:\n\n1. Make a class with counter functionality that implements the `CommandListener` interface.\n\n2. Add an instance of the new class that implements `CommandListener` to a `MongoClientSettings` object.\n\n3. Configure a `MongoClient` instance with the `MongoClientSettings` object.\n\nThe following code defines the `CommandCounter` class which implements the `CommandListener` interface:\n\n```kotlin\nclass CommandCounter : CommandListener {\n private val commands = mutableMapOf()\n\n @Synchronized\n override fun commandSucceeded(event: CommandSucceededEvent) {\n val commandName = event.commandName\n val count = commands[commandName] ?: 0\n commands[commandName] = count + 1\n println(commands.toString())\n }\n\n override fun commandFailed(event: CommandFailedEvent) {\n println(\"Failed execution of command '${event.commandName}' with id ${event.requestId}\")\n }\n}\n\n```\n\nThe following code adds an instance of the `CommandCounter` class to a `MongoClientSettings` object, and configures a `MongoClient` instance with the `MongoClientSettings` object. The code then runs some database commands to test the counter.\n\n```kotlin\nval commandCounter = CommandCounter()\n\nval settings = MongoClientSettings.builder()\n .applyConnectionString(URI)\n .addCommandListener(commandCounter)\n .build()\nval mongoClient = MongoClient.create(settings)\nval database = mongoClient.getDatabase(DATABASE)\nval collection = database.getCollection(COLLECTION)\n\n// Run some commands to test the counter\ncollection.find().firstOrNull()\ncollection.find().firstOrNull()\n\n```\n\n```console\n{find=1}\n{find=2}\n{find=2, endSessions=1}\n```\n\nFor more information on the classes and methods mentioned in this section, see the following API Documentation:\n\n- CommandListener\n\n- MongoClientSettings\n\n- MongoClient\n\n- CommandStartedEvent\n\n- CommandSucceededEvent\n\n- CommandFailedEvent\n\n### Server Discovery and Monitoring Events\n\nA server discovery and monitoring (SDAM) event is an event related to a change in the state of the MongoDB instance or cluster you have connected the driver to.\n\nThe driver defines nine SDAM events. The driver divides these nine events between three separate listener interfaces which each listen for three of the nine events. Here are the three interfaces and the events they listen for:\n\n- `ClusterListener`: topology-related events\n\n- `ServerListener`: events related to `mongod` or `mongos` processes\n\n- `ServerMonitorListener`: heartbeat related events\n\nTo monitor a type of SDAM event, write a class that implements one of the three preceding interfaces and register an instance of that class with your `MongoClient` instance.\n\nFor a detailed description of each SDAM event, see the MongoDB SDAM monitoring events specification.\n\n#### Example\n\nThis example shows how to make a listener class that prints a message that lets you know if the driver can write to your MongoDB instance.\n\nThe following code defines the `IsWritable` class which implements the `ClusterListener` interface.\n\n```kotlin\nclass IsWriteable : ClusterListener {\n private var isWritable = false\n\n @Synchronized\n override fun clusterDescriptionChanged(event: ClusterDescriptionChangedEvent) {\n if (!isWritable) {\n if (event.newDescription.hasWritableServer()) {\n isWritable = true\n println(\"Able to write to cluster\")\n }\n } else {\n if (!event.newDescription.hasWritableServer()) {\n isWritable = false\n println(\"Unable to write to cluster\")\n }\n }\n }\n}\n\n```\n\nThe following code adds an instance of the `IsWritable` class to a `MongoClient` object. The code then runs a find operation to test the `IsWritable` class.\n\n```kotlin\nval clusterListener = IsWriteable()\nval settings = MongoClientSettings.builder()\n .applyConnectionString(URI)\n .applyToClusterSettings { builder ->\n builder.addClusterListener(clusterListener)\n }\n .build()\nval mongoClient = MongoClient.create(settings)\nval database = mongoClient.getDatabase(DATABASE)\nval collection = database.getCollection(COLLECTION)\n// Run a command to trigger a ClusterDescriptionChangedEvent event\ncollection.find().firstOrNull()\n\n```\n\n```console\nAble to write to server\n```\n\nFor more information on the classes and methods mentioned in this section, see the following API Documentation:\n\n- ClusterListener\n\n- ServerListener\n\n- ServerMonitorListener\n\n- MongoClientSettings\n\n- MongoClient\n\n- ClusterDescriptionChangedEvent"} -{"chunk_id": "695ca9502d5be1431b31842d-1", "page_id": "695ca9502d5be1431b31842d", "source_name": "kotlin", "product_name": "Kotlin Coroutine Driver", "url": "https://mongodb.com/docs/drivers/kotlin/coroutine/current/logging-monitoring/monitoring", "title": "Monitoring", "text": "### Connection Pool Events\n\nA connection pool event is an event related to a **connection pool** held by the driver. A connection pool is a set of open TCP connections your driver maintains with a MongoDB instance. Connection pools help reduce the number of network handshakes your application needs to perform with a MongoDB instance, and can help your application run faster. To learn more about connection pools, see the Connection Pools section of the Connect to MongoDB guide.\n\nTo monitor connection pool events, write a class that implements the `ConnectionPoolListener` interface and register an instance of that class with your `MongoClient` instance.\n\n#### Example\n\nThis example shows how to make a listener class that prints a message each time you check out a connection from your connection pool.\n\nThe following code defines the `ConnectionPoolLibrarian` class which implements the `ConnectionPoolListener` interface.\n\n```kotlin\nclass ConnectionPoolLibrarian : ConnectionPoolListener {\n\n override fun connectionCheckedOut(event: ConnectionCheckedOutEvent) {\n println(\"Let me get you the connection with id ${event.connectionId.localValue}...\")\n }\n\n override fun connectionCheckOutFailed(event: ConnectionCheckOutFailedEvent) {\n println(\"Something went wrong! Failed to checkout connection.\")\n }\n}\n\n```\n\nThe following code adds an instance of the `ConnectionPoolLibrarian` class to a `MongoClient` object. The code then runs a database command to test the librarian.\n\n```kotlin\nval cpListener = ConnectionPoolLibrarian()\nval settings = MongoClientSettings.builder()\n .applyConnectionString(URI)\n .applyToConnectionPoolSettings { builder ->\n builder.addConnectionPoolListener(cpListener)\n }\n .build()\nval mongoClient = MongoClient.create(settings)\nval database = mongoClient.getDatabase(DATABASE)\nval collection = database.getCollection(COLLECTION)\n// Run a command to trigger connection pool events\ncollection.find().firstOrNull()\n\n```\n\n```console\nLet me get you the connection with id 21...\n```\n\nFor more information on the classes and methods mentioned in this section, see the following API Documentation:\n\n- ConnectionPoolListener\n\n- MongoClientSettings\n\n- MongoClient\n\n- ConnectionCheckedOutEvent\n\n- ConnectionCheckOutFailedEvent\n\n## Monitor Connection Pool Events with JMX\n\nYou can monitor connection pool events using **Java Management Extensions (JMX)**. JMX provides tools to monitor applications and devices.\n\nFor more information on JMX, see the official Oracle JMX documentation.\n\n### JMX Support\n\nTo enable JMX connection pool monitoring, add an instance of the `JMXConnectionPoolListener` class to your `MongoClient` object.\n\nThe `JMXConnectionPoolListener` class performs the following actions:\n\n1. Creates MXBean instances for each `mongod` or `mongos` process the driver maintains a connection pool with.\n\n2. Registers these MXBean instances with the platform MBean server.\n\nMXBeans registered on the platform MBean server have the following properties:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nProperty\n\n\nDescription\n\n
\n`clusterId`\n\n\nA client-generated unique identifier. This identifier ensures that each MXBean the driver makes has a unique name when an application has multiple `MongoClient` instances connected to the same MongoDB deployment.\n\n
\n`host`\n\n\nThe hostname of the machine running the `mongod` or `mongos` process.\n\n
\n`port`\n\n\nThe port on which the `mongod` or `mongos` process is listening.\n\n
\n`minSize`\n\n\nThe minimum size of the connection pool, including idle and in-use connections.\n\n
\n`maxSize`\n\n\nThe maximum size of the connection pool, including idle and in-use connections.\n\n
\n`size`\n\n\nThe current size of the connection pool, including idle and in-use connections.\n\n
\n`checkedOutCount`\n\n\nThe current count of connections that are in use.\n\n
All MXBean instances created by the driver are under the domain `\"org.mongodb.driver\"`.\n\nFor more information on the topics discussed in this subsection, see the following resources from Oracle:\n\n- Platform MBean Server Reference Documentation\n\n- MXBean Documentation\n\n- MBean Documentation\n\n### JMX and JConsole Example\n\nThis example shows how you can monitor the driver's connection pools using JMX and **JConsole**. JConsole is a JMX compliant GUI monitoring tool that comes with the Java Platform.\n\nThe descriptions of JMX and JConsole in this example are illustrative rather than a source of truth. For guaranteed up to date information, consult the following official Oracle resources:\n\n- JConsole documentation.\n\n- JMX documentation\n\nThe following code snippet adds a `JMXConnectionPoolListener` to a `MongoClient` instance. The code then pauses execution so you can navigate to JConsole and inspect your connection pools.\n\n```kotlin\nval connectionPoolListener = JMXConnectionPoolListener()\nval settings = MongoClientSettings.builder()\n .applyConnectionString(uri)\n .applyToConnectionPoolSettings {\n it.addConnectionPoolListener(connectionPoolListener)\n }\n .build()\nval mongoClient: MongoClient = MongoClient.create(settings)\n\ntry {\n println(\"Navigate to JConsole to see your connection pools...\")\n Thread.sleep(Long.MAX_VALUE)\n} catch (e: Exception) {\n e.printStackTrace()\n}\n\n```\n\n```console\nNavigate to JConsole to see your connection pools...\n```\n\nOnce you have started your server, open JConsole in your terminal using the following command:\n\n```shell\njconsole\n```\n\nOnce JConsole is open, perform the following actions in the GUI:\n\n1. Select the process running the preceding example code.\n\n2. Press Insecure Connection in the warning dialog box.\n\n3. Click on the MBeans tab.\n\n4. Inspect your connection pool events under the `\"org.mongodb.driver\"` domain.\n\nWhen you no longer want to inspect your connection pools in JConsole, do the following:\n\n- Exit JConsole by closing the JConsole window\n\n- Stop the program running the preceding code snippet\n\nFor more information on JMX and JConsole, see the following resources from Oracle:\n\n- JConsole Documentation.\n\n- Monitoring and Management Guide\n\nFor more information on the `JMXConnectionPoolListener` class, see the API Documentation for JMXConnectionPoolListener.\n\n## Include the Driver in Your Distributed Tracing System\n\nIf you use a **distributed tracing system**, you can include event data from the driver. A distributed tracing system is an application that tracks requests as they propagate throughout different services in a service-oriented architecture.\n\nIf you use the driver in a Spring Cloud application, use Spring Cloud Sleuth to include MongoDB event data in the Zipkin distributed tracing system.\n\nIf you do not use Spring Cloud or need to include driver event data in a distributed tracing system other than Zipkin, you must write a command event listener that manages spans for your desired distributed tracing system. To see an implementation of such a listener, see the Java source code for the TraceMongoCommandListener class in the Spring Cloud Sleuth source code.\n\nTo learn more about Spring Cloud Sleuth, see Getting Started in the Spring Cloud Sleuth documentation.\n\nTo view a detailed description of a distributed tracing system, see Dapper from Google Research."} -{"chunk_id": "68d23bc6530172e0e12645e2-0", "page_id": "68d23bc6530172e0e12645e2", "source_name": "kotlin-sync", "product_name": "Kotlin Sync Driver", "url": "https://mongodb.com/docs/languages/kotlin/kotlin-sync-driver/current/connect/connection-troubleshooting", "title": "Connection Troubleshooting", "text": "# Connection Troubleshooting\n\nThis page addresses only connection issues. If you encounter other issues when using MongoDB or the driver, visit the following resources:\n\n- The Issues & Help page for information about reporting bugs, contributing to the driver, and finding more resources\n\n- The MongoDB Stack Overflow page or the MongoDB Reddit community for questions, discussions, or general technical support\n\n```none\nError: couldn't connect to server 127.0.0.1:27017\n```\n\nTo learn how to specify multiple replica set hosts, see the Replica Sets section of the Connection Guide.\n\n```none\nCommand failed with error 18 (AuthenticationFailed): 'Authentication failed.' on server localhost:27017.\n```\n\nFor more information about using connection strings, see Connection URI in the Connection Guide.\n\nIf you construct a client by using a `MongoCredential`, the builder method corresponds to the authentication mechanism. The following code shows the builder method for the `SCRAM-SHA-256` authentication mechanism:\n\n```kotlin\nval credential = MongoCredential.createScramSha256Credential(\n \"\", \"\", \"\".toCharArray()\n)\n\nval settings = MongoClientSettings.builder()\n .applyToClusterSettings { builder: ClusterSettings.Builder ->\n builder.hosts(\n listOf(ServerAddress(\"\", ))\n )\n }\n .credential(credential)\n .build()\n\nval mongoClient = MongoClient.create(settings)\n```\n\nTo learn more about specifying authentication mechanisms, see the Authentication Mechanisms section.\n\n```kotlin\nval mongoClient = MongoClient.create(\"mongodb://:@:/?authSource=users\");\n```\n\n```none\ncom.mongodb.MongoSocketWriteException: Exception sending message\n```\n\n`MongoClient`\n\n`maxPoolSize`\n\n`100`\n\n`maxIdleTimeMS`\n\n```\nCommand failed with error 18 (AuthenticationFailed): 'Authentication failed.' on server localhost:27017.\n```\n\nTo learn more about how connection pooling works in the driver, see the Connection Pools page.\n\nThis page offers potential solutions to issues that you might encounter when using the MongoDB Kotlin Sync Driver to connect to a MongoDB deployment.\n\nThis page addresses only connection issues. If you encounter other issues when using MongoDB or the driver, visit the following resources:\n\n- The Issues & Help page for information about reporting bugs, contributing to the driver, and finding more resources\n\n- The MongoDB Stack Overflow page or the MongoDB Reddit community for questions, discussions, or general technical support\n\n## Server Connection Errors\n\nIf an issue occurs when you attempt to connect to a server, the Kotlin Sync driver returns an error message. If this error resembles the following message, it indicates that the driver cannot connect to a MongoDB deployment:\n\n```none\nError: couldn't connect to server 127.0.0.1:27017\n```\n\nThe following sections describe methods that might help resolve the issue.\n\n### Check the Connection String\n\nVerify that the hostname and port number in the connection string are both accurate. In the sample error message, the hostname is `127.0.0.1` and the port is `27017`. The default port value for an instance of MongoDB Server is `27017`, but you can configure MongoDB to listen on another port.\n\nWhen connecting to a replica set, include all the replica set hosts in your connection string. Separate each of the hosts in the connection string with a comma. This enables the driver to establish a connection if one of the hosts is unreachable.\n\nTo learn how to specify multiple replica set hosts, see the Replica Sets section of the Connection Guide.\n\n### Configure the Firewall\n\nIf your MongoDB deployment is hosted behind a firewall, ensure the port on which MongoDB listens is open in the firewall. If your deployment listens on the default network port, ensure that port `27017` is open in the firewall. If your deployment listens on a different port, ensure that port is open on the firewall.\n\nDo not open a firewall port unless you are sure that it is the one that your MongoDB deployment listens on.\n\n### Check the Number of Connections\n\nEach `MongoClient` instance supports a maximum number of concurrent open connections in its connection pool. The configuration parameter `maxPoolSize` defines this value and is set to `100` by default. If the number of open connections is equal to `maxPoolSize`, the server waits until a connection becomes available. If this wait time exceeds the `maxIdleTimeMS` value, the driver responds with an error.\n\nTo learn more about how connection pooling works in the driver, see the Connection Pools page.\n\n## Authentication Errors\n\nThe Kotlin Sync driver may be unable connect to a MongoDB deployment if the authorization is not configured correctly. In these cases, the driver raises an error message similar to the following message:\n\n```\nCommand failed with error 18 (AuthenticationFailed): 'Authentication failed.' on server localhost:27017.\n```\n\nThe following sections describe methods that may help resolve the issue.\n\n### Check the Credentials Formatting\n\nOne of the most common causes of authentication issues is invalid credentials formatting in the MongoDB connection string.\n\nFor more information about using connection strings, see Connection URI in the Connection Guide.\n\nIf your connection string contains a username and password, ensure that they are correctly formatted.\n\nIf your username or password includes any of the following characters, you must percent-encode it:\n\n```none\n: / ? # [ ] @\n```\n\nUse your percent-encoded username and password in your connection string.\n\n### Verify the Authentication Mechanism\n\nEnsure that your credentials and authentication mechanism are correct. You can specify your authentication credentials in the options of your connection string.\n\nIf you construct a client by using a `MongoCredential`, the builder method corresponds to the authentication mechanism. The following code shows the builder method for the `SCRAM-SHA-256` authentication mechanism:\n\n```kotlin\nval credential = MongoCredential.createScramSha256Credential(\n \"\", \"\", \"\".toCharArray()\n)\n\nval settings = MongoClientSettings.builder()\n .applyToClusterSettings { builder: ClusterSettings.Builder ->\n builder.hosts(\n listOf(ServerAddress(\"\", ))\n )\n }\n .credential(credential)\n .build()\n\nval mongoClient = MongoClient.create(settings)\n```\n\nTo learn more about specifying authentication mechanisms, see the Authentication Mechanisms section.\n\n### Verify User Is in Authentication Database\n\nWhen using a username and password-based authentication method, the username must be defined in the authentication database.\n\nThe default authentication database is the `admin` database. To use a different database for authentication, specify the `authSource` option in the connection string.\n\nThe following example instructs MongoDB to use the `users` database as the authentication database:\n\n```kotlin\nval mongoClient = MongoClient.create(\"mongodb://:@:/?authSource=users\");\n```\n\n## DNS Resolution Errors\n\nThe Kotlin Sync driver may be unable to resolve your DNS connection. When this happens, you might receive an error message similar to the following message:\n\n```none\ncom.mongodb.MongoSocketWriteException: Exception sending message\n```\n\nIf the driver reports this error, try the methods in the following sections to resolve the issue."} -{"chunk_id": "68d23bc6530172e0e12645e2-1", "page_id": "68d23bc6530172e0e12645e2", "source_name": "kotlin-sync", "product_name": "Kotlin Sync Driver", "url": "https://mongodb.com/docs/languages/kotlin/kotlin-sync-driver/current/connect/connection-troubleshooting", "title": "Connection Troubleshooting", "text": "### Check Database Deployment Availability\n\nIf you are connecting to MongoDB Atlas and your driver cannot find the DNS host of the Atlas database deployment, the database deployment might be paused or deleted.\n\nEnsure that the database deployment exists in Atlas. If the cluster is paused, you can resume the cluster in the Atlas UI or the Atlas command line interface.\n\nTo learn how to resume a cluster, see Resume One Cluster in the Atlas documentation.\n\n### Check the Network Addresses\n\nVerify that the network addresses or hostnames in your connection string are accurate.\n\nIf your deployment is hosted on MongoDB Atlas, you can follow the Connect to Your Cluster tutorial to find your Atlas connection string.\n\n## Timeout Errors\n\nWhen you send messages through the driver to the server, sometimes the messages take a while to respond. When this happens, you might receive an error message similar to one of the following messages:\n\n```none\nTimed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}.\n```\n\n```none\nNo server chosen by ReadPreferenceServerSelector{readPreference=primary} from cluster description\n```\n\nIf you receive one of these errors, try the following methods to resolve the issue.\n\n### Set `maxConnectionTimeoutMS`\n\nThe `maxConnectionTimeoutMS` option indicates the time the Kotlin Sync driver waits for a connection before timing out. The default value is `10000`. You can increase this value or set it to `0` if you want the driver to never timeout.\n\n### Set `maxConnectionLifeTime` and `maxConnectionIdleTime`\n\nConsider setting `maxConnectionLifeTime` and `maxConnectionIdleTime`. These parameters configure how long the driver maintains a connection to a MongoDB instance. For more information about these parameters, see Connection Pools.\n\n## Server Selection Timeout Exceptions\n\nYour application might not be able to complete a request even when some servers are available, causing the driver to return a server selection timeout exception.\n\nThis exception is of type `MongoTimeoutException`. The following shows a sample of the exception that occurs if you attempt to send a request to a replica set in which the primary is not reachable:\n\n```none\ncom.mongodb.MongoTimeoutException:\nTimed out while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}.\nClient view of cluster state is\n{type=REPLICA_SET,\n servers=[\n {address=localhost:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused}},\n {address=localhost:27018, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused}},\n {address=localhost:27019, type=REPLICA_SET_SECONDARY, roundTripTime=15.0 ms, state=CONNECTED}\n ]\n}\n```\n\nThe error includes a view of the cluster state that describes the connection state of each node, which can help you identify the source of your connection issue.\n\nIn the preceding error, the only connected server, `localhost:27019`, is a secondary node. Because of this, the request times out as the driver is unable to select a server that satisfies the read preference of `primary`. In this situation, you can still perform read operations against the connected secondary node if you set the read preference to `secondary`, `secondaryPreferred`, or `nearest`.\n\nYou can also specify the `serverSelectionTimeoutMS` connection option to adjust the amount of time in which the driver must select a server. To learn more, see the Specify Connection Options guide.\n\n## Miscellaneous Errors\n\nThis section shows connection errors that do not fall into a broader category.\n\n### Monitor Thread Exception\n\n```none\nINFO: Exception in monitor thread while connecting to server ssc-cluster-01-shard-00-02.9cbnp.mongodb.net:27017\n```\n\nThis log line indicates that the monitor that continuously checks the status of each replica set member or `mongos` server failed to contact one of the nodes or servers. This is an expected message during server maintenance operations and can be safely ignored.\n\n### Certificate Request Exception\n\n```none\njavax.net.ssl.SSLHandshakeException: extension (5) should not be presented in certificate_request\n```\n\nThis is a known issue in certain versions of the JDK that can occur when attempting to connect by using the TLS 1.3 protocol.\n\nIf you encounter this error when connecting to your MongoDB instance or cluster, update your JDK to one of the following patch versions or newer:\n\n- JDK 11.0.7\n\n- JDK 13.0.3\n\n- JDK 14.0.2\n\nTo learn more about this issue, see the issue description in the OpenJDK Bug system tracker issue.\n\n## Debugging Tips\n\nWhile not related to a specific error message, this section includes information that can help in the process of troubleshooting connection issues.\n\n### Verbose Logging for TLS/SSL\n\nYou can use the `-Djavax.net.debug=all` system property to enable debug-level logging related to all connections, including those established by using TLS/SSL.\n\nEnabling debug-level logging can help you diagnose the root problem of connection issues. To learn more about the TLS/SSL logging messages, see the Debugging SSL/TLS Connections Java documentation."} -{"chunk_id": "68d23bc6530172e0e126462b-0", "page_id": "68d23bc6530172e0e126462b", "source_name": "kotlin-sync", "product_name": "Kotlin Sync Driver", "url": "https://mongodb.com/docs/languages/kotlin/kotlin-sync-driver/current/security/authentication/aws-iam", "title": "AWS IAM Authentication", "text": "# AWS IAM Authentication\n\n## Overview\n\nThe **MONGODB-AWS** authentication mechanism uses Amazon Web Services Identity and Access Management (AWS IAM) credentials to authenticate a user to MongoDB. You can use this mechanism only when authenticating to MongoDB Atlas.\n\nTo learn more about configuring MongoDB Atlas for AWS IAM authentication, see Set Up Authentication with AWS IAM in the Atlas documentation.\n\n## Specify MONGODB-AWS Authentication\n\nTo instruct the Kotlin Sync driver to use the `MONGODB-AWS` authentication mechanism, you can either specify `MONGODB-AWS` as a parameter in the connection string or call the `MongoCredential.createAwsCredential()` factory method.\n\nIn the following sections, you can learn different ways to specify the `MONGODB-AWS` authentication mechanism and provide your AWS IAM credentials.\n\nThese sections contain code examples that use the following placeholders:\n\n- `awsKeyId`: The value of your AWS access key ID\n\n- `awsSecretKey`: The value of your AWS secret access key\n\n- `atlasUri`: The network address of your MongoDB Atlas deployment\n\n- `hostname`: The hostname of your MongoDB Atlas deployment\n\n- `port`: The port of your MongoDB Atlas deployment\n\n- `awsSessionToken`: The value of your AWS session token\n\n### AWS SDK\n\nThe AWS SDK for Java v1 will reach end of support on December 31, 2025. AWS recommends migrating to AWS SDK for Java v2. For more information, see the end of support announcement on the AWS site.\n\nAWS provides software development kits (SDKs) for Java v1 and v2. The AWS SDK offers the following features:\n\n- Multiple options for obtaining credentials\n\n- Credential caching, which helps your application avoid rate limiting\n\n- Credential provider management for use with the Elastic Kubernetes Service\n\nTo use the AWS SDK for `MONGODB-AWS` authentication, perform the following steps:\n\n1. Specify the authentication mechanism.\n\n2. Add the SDK as a dependency to your project.\n\n3. Supply your credentials by using one of the methods in the credential provider chain.\n\n#### Specify the Authentication Mechanism\n\nYou can specify the `MONGODB-AWS` authentication mechanism by using a connection string or a `MongoCredential` object. Select the Connection String or the MongoCredential tab below for corresponding instructions and sample code:\n\n\n\n\n\nTo specify the `MONGODB-AWS` authentication mechanism in the connection string, set the `authMechanism` parameter to `MONGODB-AWS`, as shown in the following example:\n\n```kotlin\nval mongoClient =\n MongoClient.create(\"mongodb://?authMechanism=MONGODB-AWS\")\n```\n\n\n\n\n\nTo specify the `MONGODB-AWS` authentication mechanism by using a `MongoCredential` object, call the `MongoCredential.createAwsCredential()` factory method and add the `MongoCredential` instance to your `MongoClient`, as shown in the following example:\n\n```kotlin\nval credential = MongoCredential.createAwsCredential(null, null)\n\nval settings = MongoClientSettings.builder()\n .applyToClusterSettings { builder: ClusterSettings.Builder ->\n builder.hosts(\n listOf(ServerAddress(\"\"))\n )\n }\n .credential(credential)\n .build()\n\nval mongoClient = MongoClient.create(settings)\n```\n\n\n\n\n\n#### Add the AWS SDK Dependency\n\nTo add the AWS SDK as a dependency to your project, see the following AWS documentation for the version you need:\n\n- For the **AWS SDK for Java v2**, see the Setting Up guide.\n\n- For the **AWS SDK for Java v1**, see the Getting Started guide.\n\nFor the AWS SDK for Java v2, the Java driver tests by using the `software.amazon.awssdk:auth:2.30.31` dependency.\n\nFor the AWS SDK for Java v1, the Java driver tests by using the `com.amazonaws:aws-java-sdk-core:1.12.782` dependency.\n\n#### Supply Your Credentials\n\nTo supply your credentials, see the following AWS documentation for the version you need:\n\n- To learn more about the **AWS SDK for Java v2** class the driver uses to get the credentials, see the DefaultCredentialsProvider API documentation.\n\n Learn how to supply your credentials to this class from the Use the default credential provider chain section.\n\n- To learn more about the **AWS SDK for Java v1** class the driver uses to get the credentials, see the DefaultAWSCredentialsProviderChain API documentation.\n\n Learn how to supply your credentials to this class from the Using the Default Credential Provider Chain section.\n\nIf you include both v1 and v2 of the AWS SDK for Java in your project, you must use the v2 methods to supply your credentials.\n\n### Specify Your Credentials in the Environment\n\nYou can provide your AWS IAM credentials by instructing the driver to use the `MONGODB-AWS` authentication mechanism and by setting the appropriate environment variables.\n\nTo use the environment variables to supply your credentials, perform the following steps:\n\n1. Specify the authentication mechanism.\n\n2. Add the appropriate environment variables.\n\n#### Specify the Authentication Mechanism\n\nYou can specify the `MONGODB-AWS` authentication mechanism by using a `MongoCredential` object or in the connection string.\n\nTo specify the authentication mechanism by using a `MongoCredential` object, call the `MongoCredential.createAwsCredential()` factory method and add the `MongoCredential` instance to your `MongoClient`, as shown in the following example:\n\n```kotlin\nval credential = MongoCredential.createAwsCredential(null, null)\n\nval settings = MongoClientSettings.builder()\n .applyToClusterSettings { builder: ClusterSettings.Builder ->\n builder.hosts(\n listOf(ServerAddress(\"\"))\n )\n }\n .credential(credential)\n .build()\n\nval mongoClient = MongoClient.create(settings)\n```\n\nTo specify the `MONGODB-AWS` authentication mechanism in the connection string, add it as a parameter as shown in the following example:\n\n```kotlin\nval mongoClient =\n MongoClient.create(\"mongodb://?authMechanism=MONGODB-AWS\")\n```\n\n#### Set Environment Variables\n\nThis section shows how to provide your credentials by setting environment variables for the following types of authentication:\n\n- Programmatic access keys\n\n- ECS container credentials\n\n- EC2 container credentials\n\nThe following example shows how you can set your **programmatic access keys** in environment variables by using `bash` or a similar shell:\n\n```bash\nexport AWS_ACCESS_KEY_ID=\nexport AWS_SECRET_ACCESS_KEY=\nexport AWS_SESSION_TOKEN=\n```\n\nOmit the line that sets the `AWS_SESSION_TOKEN` variable if you don't need an AWS session token for that role.\n\nTo authenticate by using **ECS container credentials**, set the ECS endpoint relative URI in an environment variable by using `bash` or a similar shell, as shown in the following example:\n\n```bash\nexport AWS_CONTAINER_CREDENTIALS_RELATIVE_URI=\n```\n\nTo authenticate by using **EC2 container credentials**, do not set the AWS environment variables. The driver obtains the credentials from the default IPv4 EC2 instance metadata endpoint."} -{"chunk_id": "68d23bc6530172e0e126462b-1", "page_id": "68d23bc6530172e0e126462b", "source_name": "kotlin-sync", "product_name": "Kotlin Sync Driver", "url": "https://mongodb.com/docs/languages/kotlin/kotlin-sync-driver/current/security/authentication/aws-iam", "title": "AWS IAM Authentication", "text": "### Specify Your Credentials in a MongoCredential\n\nYou can supply your AWS IAM credentials to a `MongoClient` by using a `MongoCredential` instance. To construct the `MongoCredential` instance for `MONGODB-AWS` authentication, call the createAwsCredential() factory method.\n\nYou can supply only programmatic access keys to the `MongoCredential.createAwsCredential()` method. If you must supply ECS or EC2 container credentials, follow the instructions in Specify Your Credentials in the Environment.\n\nTo use a `MongoCredential` object for `MONGODB-AWS` authentication, perform the following steps:\n\n1. Specify the authentication mechanism.\n\n2. Supply the credentials.\n\nTo specify the authentication mechanism by using a `MongoCredential` object, call the `MongoCredential.createAwsCredential()` factory method and add the `MongoCredential` instance to your `MongoClient`, as shown in the following example:\n\n```kotlin\nval credential = MongoCredential.createAwsCredential(\"\", \"\".toCharArray())\n\nval settings = MongoClientSettings.builder()\n .applyToClusterSettings { builder: ClusterSettings.Builder ->\n builder.hosts(\n listOf(ServerAddress(\"\"))\n )\n }\n .credential(credential)\n .build()\n\nval mongoClient = MongoClient.create(settings)\n```\n\nIf you must specify an AWS session token, pass it to the withMechanismProperty() method, as shown in the following example:\n\n```kotlin\nval credential = MongoCredential.createAwsCredential(\"\", \"\".toCharArray())\n .withMechanismProperty(\"AWS_SESSION_TOKEN\", \"\")\n\nval settings = MongoClientSettings.builder()\n .applyToClusterSettings { builder: ClusterSettings.Builder ->\n builder.hosts(\n listOf(ServerAddress(\"\"))\n )\n }\n .credential(credential)\n .build()\n\nval mongoClient = MongoClient.create(settings)\n```\n\nTo refresh your credentials, you can declare a `Supplier` lambda expression that returns new credentials, as shown in the following example:\n\n```kotlin\nval awsFreshCredentialSupplier: Supplier = Supplier {\n // Add your code here to fetch new credentials\n\n // Return the new credentials\n AwsCredential(\"\", \"\", \"\")\n}\n\nval credential = MongoCredential.createAwsCredential(\"\", \"\".toCharArray())\n .withMechanismProperty(MongoCredential.AWS_CREDENTIAL_PROVIDER_KEY, awsFreshCredentialSupplier)\n\nval settings = MongoClientSettings.builder()\n .applyToClusterSettings { builder ->\n builder.hosts(listOf(ServerAddress(\"\", )))\n }\n .credential(credential)\n .build()\n\nval mongoClient = MongoClient.create(settings)\n```\n\nIf you must provide AWS IAM credentials in a connection string, you can add it to your `MongoClientSettings` object by calling the applyConnectionString() method:\n\n```kotlin\nval credential = MongoCredential.createAwsCredential(\"\", \"\".toCharArray())\nval connectionString = ConnectionString(\"mongodb:///?authMechanism=MONGODB-AWS&authMechanismProperties=AWS_SESSION_TOKEN:\")\n\nval settings = MongoClientSettings.builder()\n .applyConnectionString(connectionString)\n .credential(credential)\n .build()\n\nval mongoClient = MongoClient.create(settings)\n```\n\n## Additional Information\n\nTo learn more about authenticating to MongoDB, see Authentication in the MongoDB Server manual.\n\nTo learn more about creating a `MongoClient` object by using the Kotlin Sync driver, see the Create a MongoClient guide."} -{"chunk_id": "68d23bc6530172e0e1264611-0", "page_id": "68d23bc6530172e0e1264611", "source_name": "kotlin-sync", "product_name": "Kotlin Sync Driver", "url": "https://mongodb.com/docs/languages/kotlin/kotlin-sync-driver/current/crud/update", "title": "Update Documents", "text": "# Update Documents\n\n## Overview\n\nIn this guide, you can learn how to use the Kotlin Sync driver to update documents in a MongoDB collection by using the `updateOne()` and `updateMany()` methods.\n\n### Sample Data\n\nThe examples in this guide use the `sample_restaurants.restaurants` collection from the Atlas sample datasets. To learn how to create a free MongoDB deployment and load the sample datasets, see the MongoDB Get Started guide.\n\nThe documents in this collection are modeled by the following Kotlin data class:\n\n```kotlin\ndata class Restaurant(\n val name: String,\n val borough: String,\n val cuisine: String,\n val address: Document\n)\n```\n\n## Update Operations\n\nYou can update documents in MongoDB by using the following methods:\n\n- `updateOne()`, which updates *the first document* that matches the search criteria\n\n- `updateMany()`, which updates *all documents* that match the search criteria\n\nEach update method requires the following parameters:\n\n- **Query filter**, which matches which documents to update. To learn more about query filters, see the Specify a Query guide.\n\n- **Update document**, which specifies the update operator, or the kind of update to perform, and the fields and values to be updated. For a list of update operators and their usages, see the Field Update Operators guide page in the MongoDB Server manual.\n\n### Update One Document\n\nThe following example uses the `updateOne()` method to update the `name` value of a document from `\"Happy Garden\"` to `\"Mountain House\"`:\n\n```kotlin\nval filter = eq(Restaurant::name.name, \"Happy Garden\")\nval update = set(Restaurant::name.name, \"Mountain House\")\nval result = collection.updateOne(filter, update)\n```\n\n### Update Many Documents\n\nThe following example uses the `updateMany()` method to update all documents in which the `name` value is `\"Starbucks\"`. The update renames the `address` field to `location`.\n\n```kotlin\nval filter = eq(Restaurant::name.name, \"Starbucks\")\nval update = rename(Restaurant::address.name, \"location\")\nval result = collection.updateMany(filter, update)\n```\n\n### Customize the Update Operation\n\nThe `updateOne()` and `updateMany()` methods optionally accept a parameter that sets options to configure the update operation. If you don't specify any options, the driver performs update operations with default settings.\n\nThe following table describes the setter methods that you can use to configure an `UpdateOptions` instance:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nProperty\n\n\nDescription\n\n
\n`upsert()`\n\n\nSpecifies whether the update operation performs an upsert operation if no documents match the query filter. For more information, see the upsert statement in the MongoDB Server manual.Defaults to `false`\n\n
\n`sort(Bson sort)`\n\n\nSets the sort criteria to apply to the operation. If multiple documents match the query filter that you pass to the `updateOne()` method, the operation updates the first result. You can set this option to apply an order to matched documents to have more control over which document is updated.\n\n
\n`bypassDocumentValidation()`\n\n\nSpecifies whether the update operation bypasses document validation. This lets you update documents that don't meet the schema validation requirements, if any exist. For more information about schema validation, see Schema Validation in the MongoDB Server manual.Defaults to `false`.\n\n
\n`collation()`\n\n\nSpecifies the kind of language collation to use when sorting results. For more information, see Collation in the MongoDB Server manual.\n\n
\n`arrayFilters()`\n\n\nProvides a list of filters that you specify to select which array elements the update applies to.\n\n
\n`hint()`\n\n\nSets the index to use when matching documents. For more information, see the hint statement in the MongoDB Server manual.\n\n
\n`let()`\n\n\nProvides a map of parameter names and values to set top-level variables for the operation. Values must be constant or closed expressions that don't reference document fields. For more information, see the let statement in the MongoDB Server manual.\n\n
\n`comment()`\n\n\nSets a comment to attach to the operation. For more information, see the update command fields guide in the MongoDB Server manual for more information.\n\n
\n\n### Upsert Documents Example\n\nThe following code uses the `updateOne()` method to match documents in which the `name` field value is `\"Sunrise Pizzeria\"`. It then sets the `borough` value in the first matching document to `\"Queens\"` and the `cuisine` value to `\"Italian\"`.\n\nBecause the `upsert` option is set to `true`, the driver inserts a new document that has the fields and values specified in the update document if the query filter doesn't match any existing documents.\n\n```kotlin\nval opts = UpdateOptions().upsert(true)\nval filter = eq(Restaurant::name.name, \"Sunrise Pizzeria\")\nval update = combine(\n set(Restaurant::borough.name, \"Queens\"),\n set(Restaurant::cuisine.name, \"Italian\")\n)\n\ncollection.updateOne(filter, update, opts)\n```\n\n### Return Value\n\nThe `updateOne()` and `updateMany()` methods each return an `UpdateResult` object. You can use the following methods to access information from an `UpdateResult` instance:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nProperty\n\n\nDescription\n\n
\n`getMatchedCount()`\n\n\nReturns the number of documents that matched the query filter, regardless of how many updates were performed.\n\n
\n`getModifiedCount()`\n\n\nReturns the number of documents modified by the update operation. If an updated document is identical to the original, it is not included in this count.\n\n
\n`wasAcknowledged()`\n\n\nReturns `true` if the server acknowledged the result.\n\n
\n`getUpsertedId()`\n\n\nReturns the `_id` value of the document that was upserted in the database, if the driver performed an upsert.\n\n
If the `wasAcknowledged()` method returns `false`, trying to access other information from the `UpdateResult` instance results in an `InvalidOperation` exception. The driver cannot determine these values if the server does not acknowledge the write operation.\n\n## Additional Information\n\nTo view runnable code examples that demonstrate how to update documents by using the Kotlin Sync driver, see Insert Documents.\n\n### API Documentation\n\nTo learn more about any of the methods or types discussed in this guide, see the following API documentation:\n\n- updateOne()\n\n- updateMany()\n\n- UpdateOptions\n\n- UpdateResult"} -{"chunk_id": "68d23bc6530172e0e1264632-0", "page_id": "68d23bc6530172e0e1264632", "source_name": "kotlin-sync", "product_name": "Kotlin Sync Driver", "url": "https://mongodb.com/docs/languages/kotlin/kotlin-sync-driver/current/security/authentication/kerberos", "title": "Kerberos (GSSAPI) Authentication", "text": "# Kerberos (GSSAPI) Authentication\n\n## Overview\n\nThe Generic Security Services API (`GSSAPI`) authentication mechanism allows you to authenticate to a Kerberos service by specifying your Kerberos principal name.\n\nThe page refers to the `GSSAPI` authentication mechanism instead of `Kerberos` because the driver authenticates by using the GSSAPI RFC-4652 SASL mechanism.\n\n## Specify Kerberos Authentication\n\nThe examples in this section show how to specify the `GSSAPI` authentication mechanism and use the following placeholder values:\n\n- ``: Your URL-encoded principal name.\n\n- ``: The network address of your MongoDB deployment, accessible by your client.\n\n- ``: The port number of your MongoDB deployment. If you omit this parameter, the driver uses the default port number (`27017`).\n\nSelect the Connection String or the MongoCredential tab below for instructions and sample code for specifying this authentication mechanism:\n\n\n\n\n\nTo specify the GSSAPI authentication mechanism in your a connection string, perform the following actions:\n\n- Set the `authMechanism` URL parameter to `GSSAPI`\n\n- *(optional)* Set the `authSource` URL parameter to `$external`\n\nIf you specify the `GSSAPI` mechanism, you cannot assign `authSource` to any value other than `$external`.\n\nThe following example specifies the authentication mechanism in a connection string:\n\n```kotlin\nval connectionString = ConnectionString(\"@:/?authSource=$external&authMechanism=GSSAPI\")\nval mongoClient = MongoClient.create(connectionString)\n```\n\n\n\n\n\nTo specify the GSSAPI authentication mechanism by using the `MongoCredential` class, use the `createGSSAPICredential()` method as shown in the following example:\n\n```kotlin\nval credential = MongoCredential.createGSSAPICredential(\"\")\n\nval settings = MongoClientSettings.builder()\n .applyToClusterSettings { builder ->\n builder.hosts(listOf(ServerAddress(\"\", )))\n }\n .credential(credential)\n .build()\n\nval mongoClient = MongoClient.create(settings)\n```\n\n\n\n\n\n### Acquiring a Kerberos Ticket\n\nIn order to acquire a Kerberos ticket, the GSSAPI Java libraries require you to specify the realm and Key Distribution Center (KDC) system properties.\n\nThe following code shows sample values for these properties:\n\n```none\njava.security.krb5.realm=MYREALM.ME\njava.security.krb5.kdc=mykdc.myrealm.me\n```\n\n### Additional Properties\n\nYou may need to specify one or more of the following additional `MongoCredential` mechanism properties depending on your Kerberos setup:\n\n- `SERVICE_NAME`\n\n- `CANONICALIZE_HOST_NAME`\n\n- `JAVA_SUBJECT`\n\n- `JAVA_SASL_CLIENT_PROPERTIES`\n\n- `JAVA_SUBJECT_PROVIDER`\n\n\n\n\n\nYou can only specify the following GSSAPI properties by using the `MongoCredential`:\n\n- `JAVA_SUBJECT`\n\n- `JAVA_SASL_CLIENT_PROPERTIES`\n\n- `JAVA_SUBJECT_PROVIDER`\n\nSelect the MongoCredential tab to see how to specify them.\n\nTo specify one of the GSSAPI additional properties, include it in the connection string as a URL parameter by using the format: `:`.\n\nYour code to instantiate a `MongoClient` using GSSAPI and additional properties resembles the following example:\n\n```kotlin\nval connectionString = ConnectionString(\"@:/?authSource=$external&authMechanism=GSSAPI&authMechanismProperties=SERVICE_NAME:myService\")\nval mongoClient = MongoClient.create(connectionString)\n```\n\n\n\n\n\nTo specify one of the GSSAPI additional properties, call the `withMechanismProperty()` method on your `MongoCredential` instance and pass the property name and value as parameters. Use the following property name constants defined in the `MongoCredential` class:\n\n- SERVICE_NAME_KEY\n\n- CANONICALIZE_HOST_NAME_KEY\n\n- JAVA_SUBJECT_KEY\n\n- JAVA_SASL_CLIENT_PROPERTIES_KEY\n\n- JAVA_SUBJECT_PROVIDER_KEY\n\nSelect the **SERVICE_NAME_KEY** or **JAVA_SUBJECT_KEY** tab to see sample code to instantiate a `MongoCredential` that uses GSSAPI and the selected property:\n\n\n\n\n\n```kotlin\nval credential = MongoCredential.createGSSAPICredential(\"\")\n .withMechanismProperty(MongoCredential.SERVICE_NAME_KEY, \"myService\")\n```\n\n\n\n\n\n```kotlin\nval loginContext = LoginContext(\"\")\nloginContext.login()\nval subject: Subject = loginContext.subject\n\nval credential = MongoCredential.createGSSAPICredential(\"\")\n .withMechanismProperty(MongoCredential.JAVA_SUBJECT_KEY, subject)\n```\n\n\n\n\n\n\n\n\n\n### Ticket Caching\n\nBy default, the Kotlin driver caches Kerberos tickets by `MongoClient` instance. If your deployment needs to frequently create and destroy `MongoClient` instances, you can change the default Kerberos ticket caching behavior to cache by process to improve performance.\n\n\n\n\n\nTo cache Kerberos tickets by process, you must use the `MongoCredential` authentication mechanism, as the connection string authentication mechanism does not support the `JAVA_SUBJECT_PROVIDER` mechanism property. To view instructions, select the MongoCredential tab.\n\n\n\n\n\nTo cache Kerberos tickets by process, you must specify the `JAVA_SUBJECT_PROVIDER` mechanism property and provide a KerberosSubjectProvider in your `MongoCredential` instance. The following code configures the Kotlin driver to cache Kerberos tickets by process:\n\n```kotlin\n/* All MongoClient instances sharing this instance of KerberosSubjectProvider\nwill share a Kerberos ticket cache */\nval myLoginContext = \"myContext\"\n/* Login context defaults to \"com.sun.security.jgss.krb5.initiate\"\nif unspecified in KerberosSubjectProvider */\nval credential = MongoCredential.createGSSAPICredential(\"\")\n .withMechanismProperty(\n MongoCredential.JAVA_SUBJECT_PROVIDER_KEY,\n KerberosSubjectProvider(myLoginContext)\n )\n```\n\n\n\n\n\nOn Windows, Oracle's JRE uses LSA rather than SSPI in its implementation of GSSAPI, which limits interoperability with Windows Active Directory and implementations of single sign-on. See the following articles for more information:\n\n- JDK-8054026\n\n- JDK-6722928\n\n- SO 23427343\n\n## Additional Information\n\nTo learn more about authenticating to MongoDB, see Authentication in the MongoDB Server manual.\n\nTo learn more about creating a `MongoClient` object by using the Kotlin Sync driver, see the Create a MongoClient guide.\n\n## API Documentation\n\nTo learn more about the classes and methods for authenticating your application with Kotlin Sync driver, see the following API documentation:\n\n- MongoClient.create()\n\n- MongoClient\n\n- MongoClientSettings.Builder\n\n- MongoCredential"} -{"chunk_id": "68d23bc6530172e0e1264604-0", "page_id": "68d23bc6530172e0e1264604", "source_name": "kotlin-sync", "product_name": "Kotlin Sync Driver", "url": "https://mongodb.com/docs/languages/kotlin/kotlin-sync-driver/current/crud/query/specify-a-query", "title": "Specify a Query", "text": "# Specify a Query\n\n## Overview\n\nIn this guide, you can learn how to specify a query by using the Kotlin Sync driver.\n\nYou can refine the set of documents that a query returns by creating a **query filter**. A query filter is an expression that specifies the search criteria MongoDB uses to match documents in a read or write operation. In a query filter, you can prompt the driver to search for documents with an exact match to your query, or you can compose query filters to express more complex matching criteria.\n\nThe examples in this guide use the Filters class from the `com.mongodb.client.model` package to create query filters. Alternatively, you can use the Filters class from the Kotlin Sync driver's `mongodb-driver-kotlin-extensions` extension library, which allows you to create query filters that recognize serialization annotations.\n\nTo view an example that uses the extension library's `Filters` class, see Query Annotated Classes in the Data Serialization guide.\n\n### Sample Data\n\nThe examples in this guide run operations on a collection called `fruits` that contains the following documents:\n\n```json\n{ \"_id\": 1, \"name\": \"apples\", \"quantity\": 5, \"rating\": 3, \"color\": \"red\", \"type\": [\"fuji\", \"honeycrisp\"] },\n{ \"_id\": 2, \"name\": \"bananas\", \"quantity\": 7, \"rating\": 4, \"color\": \"yellow\", \"type\": [\"cavendish\"] },\n{ \"_id\": 3, \"name\": \"oranges\", \"quantity\": 6, \"rating\": 2, \"type\": [\"naval\", \"mandarin\"] },\n{ \"_id\": 4, \"name\": \"pineapple\", \"quantity\": 3, \"rating\": 5, \"color\": \"yellow\" },\n```\n\nThe documents in this collection are modeled by the following Kotlin data class:\n\n```kotlin\ndata class Fruit(\n @BsonId\n val id: Int,\n val name: String,\n val quantity: Int,\n val rating: Int,\n val color: String,\n val type: List\n)\n```\n\nThe following code example shows how to create a database and collection, then insert the sample documents into your collection:\n\n```kotlin\nval uri = \"\"\n\nval settings = MongoClientSettings.builder()\n .applyConnectionString(ConnectionString(uri))\n .retryWrites(true)\n .build()\n\nval mongoClient = MongoClient.create(settings)\nval database = mongoClient.getDatabase(\"sample_fruit\")\nval collection = database.getCollection(\"fruits\")\n\ncollection.insertMany(listOf(\n Fruit(1, \"apples\", 5, 3, \"red\", listOf(\"fuji\", \"honeycrisp\")),\n Fruit(2, \"bananas\", 7, 4, \"yellow\", listOf(\"cavendish\")),\n Fruit(3, \"oranges\", 6, 2, null, listOf(\"naval\", \"mandarin\")),\n Fruit(4, \"pineapples\", 3, 5, \"yellow\", null)\n))\n```\n\n## Exact Match\n\nLiteral value queries return documents with an exact match to your query filter.\n\nThe following example specifies a query filter as a parameter to the `find()` method. The code returns all documents with a `color` field value of `\"yellow\"`.\n\n```kotlin\nval results = collection.find(eq(Fruit::color.name, \"yellow\"))\n\nresults.forEach { result ->\n println(result);\n}\n```\n\n```\nFruit(id=2, name=bananas, quantity=7, rating=4, color=yellow, type=[cavendish])\nFruit(id=4, name=pineapples, quantity=3, rating=5, color=yellow, type=null)\n```\n\n## Comparison Operators\n\nComparison operators evaluate a document field value against a specified value in your query filter. The following is a list of common comparison operators:\n\n- `$gt`: Greater than\n\n- `$lte`: Less than or Equal\n\n- `$ne`: Not equal\n\nTo view a full list of comparison operators, see the Comparison Query Operators guide in the MongoDB Server manual.\n\nThe following example specifies a comparison operator in a query filter as a parameter to the `find()` method. The code returns all documents with a `rating` field value greater than `2`.\n\n```kotlin\nval results = collection.find(gt(Fruit::rating.name, 2))\n\nresults.forEach { result ->\n println(result)\n}\n```\n\n```\nFruit(id=1, name=apples, quantity=5, rating=3, color=red, type=[fuji, honeycrisp])\nFruit(id=2, name=bananas, quantity=7, rating=4, color=yellow, type=[cavendish])\nFruit(id=4, name=pineapples, quantity=3, rating=5, color=yellow, type=null)\n```\n\n## Logical Operators\n\nLogical operators match documents by using logic applied to the results of two or more sets of expressions. The following is a list of logical operators:\n\n- `$and`, which returns all documents that match the conditions of *all* clauses\n\n- `$or`, which returns all documents that match the conditions of *one* clause\n\n- `$nor`, which returns all documents that *do not* match the conditions of any clause\n\n- `$not`, which returns all documents that *do not* match the expression\n\nTo learn more about logical operators, see the Logical Query Operators guide in the MongoDB Server manual.\n\nThe following example specifies a logical operator in a query filter as a parameter to the `find()` method. The code returns all documents with a `quantity` field value greater than `5` **or** a `color` field value of `\"yellow\"`.\n\n```kotlin\nval results = collection.find(\n or(\n gt(Fruit::quantity.name, 5),\n eq(Fruit::color.name, \"yellow\")\n )\n)\n\nresults.forEach { result ->\n println(result)\n}\n```\n\n```\nFruit(id=2, name=bananas, quantity=7, rating=4, color=yellow, type=[cavendish])\nFruit(id=3, name=oranges, quantity=6, rating=2, color=null, type=[naval, mandarin])\nFruit(id=4, name=pineapples, quantity=3, rating=5, color=yellow, type=null)\n```\n\n## Array Operators\n\nArray operators match documents based on the value or quantity of elements in an array field. The following is a list of available array operators:\n\n- `$all`, which returns documents with arrays that contain all elements in the query\n\n- `$elemMatch`, which returns documents if an element in their array field matches all conditions in the query\n\n- `$size`, which returns all documents with arrays of a specified size\n\nTo learn more about array operators, see the Array Query Operators guide in the MongoDB Server manual.\n\nThe following example specifies an array operator in a query filter as a parameter to the `find()` method. The code returns all documents with a `type` array field containing exactly `2` elements.\n\n```kotlin\nval results = collection.find(size(Fruit::type.name, 2))\n\nresults.forEach { result ->\n println(result)\n}\n```\n\n```\nFruit(id=1, name=apples, quantity=5, rating=3, color=red, type=[fuji, honeycrisp])\nFruit(id=3, name=oranges, quantity=6, rating=2, color=null, type=[naval, mandarin])\n```\n\n## Element Operators\n\nElement operators query data based on the presence or type of a field.\n\nTo learn more about element operators, see the Element Query Operators guide in the MongoDB Server manual.\n\nThe following example specifies an element operator in a query filter as a parameter to the `find()` method. The code returns all documents that have a `color` field.\n\n```kotlin\nval results = collection.find(exists(Fruit::color.name))\n\nresults.forEach { result ->\n println(result)\n}\n```\n\n```\nFruit(id=1, name=apples, quantity=5, rating=3, color=red, type=[fuji, honeycrisp])\nFruit(id=2, name=bananas, quantity=7, rating=4, color=yellow, type=[cavendish])\nFruit(id=4, name=pineapples, quantity=3, rating=5, color=yellow, type=null)\n```"} -{"chunk_id": "68d23bc6530172e0e1264604-1", "page_id": "68d23bc6530172e0e1264604", "source_name": "kotlin-sync", "product_name": "Kotlin Sync Driver", "url": "https://mongodb.com/docs/languages/kotlin/kotlin-sync-driver/current/crud/query/specify-a-query", "title": "Specify a Query", "text": "## Evaluation Operators\n\nEvaluation operators return data based on evaluations of either individual fields or the entire collection's documents.\n\nThe following is a list of common evaluation operators:\n\n- `$text`, which performs a text search on the documents\n\n- `$regex`, which returns documents that match a specified regular expression\n\n- `$mod`, which performs a modulo operation on the value of a field and returns documents where the remainder is a specified value\n\nTo view a full list of evaluation operators, see the Evaluation Query Operators guide in the MongoDB Server manual.\n\nThe following example specifies an evaluation operator in a query filter as a parameter to the `find()` method. The code uses a regular expression to return all documents with a `name` field value that has at least two consecutive `\"p\"` characters.\n\n```kotlin\nval results = collection.find(regex(Fruit::name.name, \"p{2,}\"))\n\nresults.forEach { result ->\n println(result)\n}\n```\n\n```\nFruit(id=1, name=apples, quantity=5, rating=3, color=red, type=[fuji, honeycrisp])\nFruit(id=4, name=pineapples, quantity=3, rating=5, color=yellow, type=null)\n```\n\n## Additional Information\n\nTo learn more about querying documents, see the Query Documents guide in the MongoDB Server manual.\n\nTo learn more about retrieving documents with the Kotlin Sync driver, see Find Documents.\n\n### API Documentation\n\nTo learn more about any of the methods or types discussed in this guide, see the following API documentation:\n\n- find()"} -{"chunk_id": "68d23bc6530172e0e12645d9-0", "page_id": "68d23bc6530172e0e12645d9", "source_name": "kotlin-sync", "product_name": "Kotlin Sync Driver", "url": "https://mongodb.com/docs/languages/kotlin/kotlin-sync-driver/current/connect/connection-options/server-selection", "title": "Customize Server Selection", "text": "# Customize Server Selection\n\n## Overview\n\nAll MongoDB drivers follow a defined algorithm when selecting a server to read or write from. By using the `ClusterSettings` property of a `MongoClientSettings` object, you can customize this algorithm to choose the server that works best for your application.\n\nCustomizing the server selection algorithm might have unintended consequences, such as degraded read or write performance.\n\n## Server Selection Algorithm\n\nWhen the Kotlin Sync driver executes a read operation, it performs the following steps, in order, to select a MongoDB deployment:\n\n1. Selects all servers from the list of known servers suitable for the requested operation, barring those that the driver considers unavailable or problematic\n\n 1. For reads, selects all servers that match the active read preference\n\n 2. For writes, selects all writeable servers\n\n2. Calls the user-defined server-selector function, if the user provides one, and passes in the list from the previous step\n\n3. Applies the `localThreshold` connection setting to the list of servers returned from the function\n\n4. Selects at most two random servers from the list of servers that match the preceding criteria, then selects the server with fewer outstanding concurrent operations\n\nWhen the Kotlin Sync driver executes a write operation, it begins by selecting all writeable servers from the list of known servers, not just those that match the active read preference. The remaining steps are identical to the preceding list.\n\nTo learn more about the MongoDB server selection algorithm, see Server Selection Algorithm in the MongoDB Server manual.\n\n## Implement Custom Server Selection Logic\n\nYou can implement your own custom server selection logic by creating a class that implements the `ServerSelector` interface. The following example shows a simple custom server selection class that selects servers with a `type` value of `ServerType.REPLICA_SET_SECONDARY`:\n\n```kotlin\nclass CustomServerSelector : ServerSelector {\n override fun select(cluster: ClusterDescription): List {\n return cluster.serverDescriptions.filter { it.type == ServerType.REPLICA_SET_SECONDARY }\n }\n}\n```\n\nUse the `applyToClusterSettings()` method to pass an instance of this class to your `MongoClientSettings`. The following example shows how to create a `MongoClient` with an instance of the custom server selector class from the preceding example:\n\n```kotlin\nval settings = MongoClientSettings.builder()\n .applyConnectionString(ConnectionString(\"\"))\n .applyToClusterSettings { builder ->\n builder.serverSelector(CustomServerSelector())\n }\n .build()\n\nval mongoClient = MongoClient.create(settings)\n```\n\n## Use Settings to Configure Server Selection\n\nYou can specify the following server selection settings in your `MongoClient` object or in your connection URI:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nSetting\n\n\nDescription\n\n
\n`localThreshold`\n\n\nThe latency window for server eligibility. If a server's round trip takes longerthan the fastest server's round-trip time plus this value, the server isn'teligible for selection. You can specify this setting to a `ClusterSettings` object in addition to the connection URI.**Data Type**: `Integer`**Default**: 15 milliseconds**Connection URI Example**: `localThresholdMS=0`\n\n
\n`readPreference`\n\n\nThe client's default read-preference settings. For more information on read preference options, see Read Preference in the MongoDB Server manual. You can specify this setting to a `MongoClientSettings` object in addition to the connection URI.**Data Type**: ReadPreference**Default**: `ReadPreference.primary()`**Connection URI Example**:```none\nreadPreference=primaryPreferred\n&maxStalenessSeconds=90\n&readPreferenceTags=dc:ny,rack:1\n```\n\n
\n`serverSelectionTimeout`\n\n\nThe length of time the driver tries to select a server before timing out. You can specify this setting to a `ClusterSettings` object in addition to the connection URI.**Data Type**: `Long`**Default**: 30 seconds**Connection URI Example**: `serverSelectionTimeoutMS=15000`\n\n
\n\n## API Documentation\n\nTo learn more about the classes and methods used in this guide, see the following API documentation:\n\n- MongoClient\n\n- MongoClientSettings\n\n- ServerSelector\n\n- ReadPreference"} -{"chunk_id": "68a95c175e79d242619dc787-0", "page_id": "68a95c175e79d242619dc787", "source_name": "kotlin-sync", "product_name": "Kotlin Sync Driver", "url": "https://mongodb.com/docs/languages/kotlin/kotlin-sync-driver/current/builders/builders-data-classes", "title": "Use Builders with Data Classes", "text": "# Use Builders with Data Classes\n\n## Overview\n\nIn this guide, you can learn how to use your Data Class properties directly with the builder classes available in the Kotlin Sync driver.\n\nThe Kotlin Sync driver implements extensions that allow you to reference your data class properties when using builder methods instead of using string field names. You can structure your code in this way to make your code more type-safe and improve your applications Kotlin interoperability.\n\nThe extensions library also allows you to construct queries, update documents, and write other statements by using infix notation. To learn more about this notation, see Infix notation in the Kotlin reference documentation.\n\nThis page provides a limited number of code examples to demonstrate this functionality. To learn more about using builder classes, see the Use Builders Code Pattern guide.\n\n## Add Kotlin Extensions to Your Project\n\nTo implement this functionality, you must add the `mongodb-driver-kotlin-extensions` dependency to your dependencies list.\n\nAdd the Driver Bill of Materials step of the Get Started guide.\n\nWe recommend adding the JVM driver Bill of Materials (BOM) to your application to manage the versions of driver artifacts. This removes the need to specify a version for any individual package covered by the BOM, simplifying dependency management. To learn more, see the Add the Driver Bill of Materials step of the Get Started guide.\n\nSelect from the following tabs to see how to add the extension dependency to your project by using the Gradle and Maven package managers:\n\n\n\n\n\nIf you are using Gradle to manage your dependencies, add the following to your `build.gradle.kts` dependencies list:\n\n```kotlin\nimplementation(\"org.mongodb:mongodb-driver-kotlin-extensions\")\n```\n\n\n\n\n\nIf you are using Maven to manage your dependencies, add the following to your `pom.xml` dependencies list:\n\n```xml\n\n org.mongodb\n mongodb-driver-kotlin-extensions\n\n```\n\n\n\n\n\nAfter you install the extensions dependency, you can use the extension methods by importing classes and methods from the `com.mongodb.kotlin.client.model` path. You can mix usage of these methods and the standard builder methods in the same application, as shown in the Aggregates example in this guide.\n\n## Builders Examples\n\nThis section contains examples that demonstrate how to use data class properties directly with builder class methods from the extensions package.\n\nWhen you the extension builder class methods data classes, the methods respect your data class annotations from the `bson-kotlin` and `bson-kotlinx` packages. To learn more about annotations, see the Specify Component Conversion Using Annotations section of the Document Data Format: Data Classes guide.\n\n### Sample Data\n\nThe examples in this section use documents in the `students` collection that describe students at a school. Documents in the `students` collection are modeled by the following Kotlin data class:\n\n```kotlin\ndata class Student(\n val name: String,\n val teachers: List,\n val gradeAverage: Double\n)\n```\n\n### Filters\n\nYou can use helpers from the `Filters` builders class to query on data class properties.\n\nThe following code shows different ways to use `Filters` extension methods to perform queries on the `Student` data class:\n\n```kotlin\nimport com.mongodb.kotlin.client.model.Filters.eq\nimport com.mongodb.kotlin.client.model.Filters.all\n```\n\n```kotlin\nval student = Student(\n \"Sandra Nook\",\n listOf(\"Alvarez\", \"Gruber\"),\n 85.7\n)\n\n// Equivalent equality queries\nStudent::name.eq(student.name)\neq(Student::name, student.name)\nStudent::name eq student.name // Infix notation\n\n// Equivalent array queries\nall(Student::teachers, student.teachers)\nStudent::teachers.all(student.teachers)\nStudent::teachers all student.teachers // Infix notation\n```\n\n### Indexes\n\nYou can use helpers from the `Indexes` builders class to create indexes on data class properties.\n\nThe following code shows different ways to use `Indexes` extension methods to create indexes on the `Student` data class:\n\n```kotlin\nimport com.mongodb.kotlin.client.model.Indexes.ascending\nimport com.mongodb.kotlin.client.model.Indexes.descending\n```\n\n```kotlin\nval ascendingIdx = Indexes.ascending(Student::name)\nval descendingIdx = Indexes.descending(Student::teachers)\n\nval ascIdxName = collection.createIndex(ascendingIdx)\nval descIdxName = collection.createIndex(descendingIdx)\n```\n\n### Projections\n\nYou can use helpers from the `Projections` builders class to create projections for data class properties.\n\nThe following code shows how to use `Projections` extension methods to create a projection on the `Student` data class:\n\n```kotlin\nimport com.mongodb.kotlin.client.model.Projections.excludeId\nimport com.mongodb.kotlin.client.model.Projections.fields\nimport com.mongodb.kotlin.client.model.Projections.include\n```\n\n```kotlin\nval combinedProj = fields(\n include(Student::name, Student::gradeAverage),\n excludeId()\n)\n\ncollection.find().projection(combinedProj)\n```\n\n### Sorts\n\nYou can use helpers from the `Sorts` builders class to sort on your data class properties.\n\nThe following code shows how to use `Sorts` extension methods to create different sorts on the `Student` data class:\n\n```kotlin\nimport com.mongodb.client.model.Sorts.orderBy\nimport com.mongodb.kotlin.client.model.Sorts\n```\n\n```kotlin\nval sort = orderBy(\n Sorts.descending(Student::gradeAverage),\n Sorts.ascending(Student::name)\n)\n\ncollection.find().sort(sort)\n```\n\n### Updates\n\nYou can use helpers from the `Updates` builders class to perform updates by using your data class properties.\n\nThe following code shows how to use `Sorts` extension methods to create different sorts on the `Student` data class:\n\n```kotlin\nimport com.mongodb.kotlin.client.model.Filters.gte\nimport com.mongodb.kotlin.client.model.Updates.addToSet\nimport com.mongodb.kotlin.client.model.Updates.combine\nimport com.mongodb.kotlin.client.model.Updates.max\n```\n\n```kotlin\nval filter = Student::gradeAverage gte 85.0\nval update = combine(\n addToSet(Student::teachers, \"Soto\"),\n Student::gradeAverage.max(90.0)\n)\ncollection.updateMany(filter, update)\n```\n\n### Aggregates\n\nYou can use helpers from the `Aggregates` and `Accumulators` builders classes to perform aggregations by using you data class properties.\n\nThe following code shows how to use `Accumulators` extension methods and `Aggregates` helper methods to perform an aggregation on the `Student` data class:\n\n```kotlin\nimport com.mongodb.client.model.Aggregates.group\nimport com.mongodb.client.model.Aggregates.limit\nimport com.mongodb.client.model.Aggregates.sort\nimport com.mongodb.kotlin.client.model.Accumulators.avg\n```\n\n```kotlin\n// Data class to store aggregation result\ndata class Summary ( val average: Double )\n\nval pipeline = listOf(\n // Sorts grades from high to low\n sort(Sorts.descending(Student::gradeAverage)),\n // Selects the top 3 students\n limit(3),\n // Calculates the average of their grades and stores value in a Summary instance\n group(null, avg(Summary::average, \"\\$${Student::gradeAverage.name}\"))\n)\n\nval result = collection.aggregate(pipeline)\n```\n\n## API Documentation\n\n- Kotlin Sync driver Extensions"} -{"chunk_id": "68d23bc6530172e0e1264631-0", "page_id": "68d23bc6530172e0e1264631", "source_name": "kotlin-sync", "product_name": "Kotlin Sync Driver", "url": "https://mongodb.com/docs/languages/kotlin/kotlin-sync-driver/current/security/authentication/ldap", "title": "LDAP (PLAIN) Authentication", "text": "# LDAP (PLAIN) Authentication\n\n## Overview\n\nYou can authenticate to a Lightweight Directory Access Protocol (LDAP) server by using your directory server username and password.\n\nThe authentication mechanism is named `PLAIN` instead of `LDAP` because the driver authenticates by using the `PLAIN` Simple Authentication and Security Layer (SASL) defined in RFC-4616.\n\n## Specify LDAP Authentication\n\nThe examples in this section show how to specify `LDAP` authentication by using either a connection string or the `MongoCredential` class. Replace the following placeholder values:\n\n- ``: Your LDAP username.\n\n- ``: Your LDAP password.\n\n- ``: The network address of your MongoDB deployment, accessible by your client.\n\n- ``: The port number of your MongoDB deployment. If you omit this parameter, the driver uses the default port number (`27017`).\n\nSelect the Connection String or the MongoCredential tab below for instructions and sample code for specifying this authentication mechanism:\n\n\n\n\n\nTo specify the `LDAP` authentication mechanism by using a connection string:\n\n- Assign the `authMechanism` URL parameter to the value `PLAIN`\n\n- *(Optional)* Assign the `authSource` URL parameter to the value `$external`\n\nIf you specify the `PLAIN` mechanism, you cannot assign `authSource` to any value other than `$external`.\n\nThe following code specifies the authentication mechanism in a connection string:\n\n```kotlin\nval connectionString = ConnectionString(\":@:/?authSource=$external&authMechanism=PLAIN\")\nval mongoClient = MongoClient.create(connectionString)\n```\n\n\n\n\n\nTo specify the `LDAP` authentication mechanism by using the `MongoCredential` class, use the `createPlainCredential()` method as shown in the following example:\n\n```kotlin\nval credential = MongoCredential.createPlainCredential(\"\", \"$external\", \"\".toCharArray())\n\nval settings = MongoClientSettings.builder()\n .applyToClusterSettings { builder ->\n builder.hosts(listOf(ServerAddress(\"\", )))\n }\n .credential(credential)\n .build()\n\nval mongoClient = MongoClient.create(settings)\n```\n\n\n\n\n\n## Additional Information\n\nTo learn more about authenticating to MongoDB, see Authentication in the MongoDB Server manual.\n\nTo learn more about creating a `MongoClient` object by using the Kotlin Sync driver, see the Create a MongoClient guide.\n\n## API Documentation\n\nTo learn more about the classes and methods for authenticating your application with Kotlin Sync driver, see the following API documentation:\n\n- MongoClient.create()\n\n- MongoClient\n\n- MongoClientSettings.Builder\n\n- MongoCredential"} -{"chunk_id": "68a95c175e79d242619dc7cd-0", "page_id": "68a95c175e79d242619dc7cd", "source_name": "kotlin-sync", "product_name": "Kotlin Sync Driver", "url": "https://mongodb.com/docs/languages/kotlin/kotlin-sync-driver/current/issues-and-help", "title": "Report Issues & Request Help", "text": "# Report Issues & Request Help\n\nIn this guide, you can learn how to report issues, suggest new features, and contribute to the Kotlin Sync driver.\n\nYou can find support for general questions by using the MongoDB Stack Overflow tag or the MongoDB Reddit community.\n\n## Bugs / Feature Requests\n\nIf you have feedback about the Kotlin Sync driver, visit the MongoDB Feedback Engine and select Drivers from the list of products on the right side of your screen. You can propose improvements, report issues, and provide other types of feedback by using this site.\n\nYou can also open a case in Jira, our issue management tool, to identify bugs or propose improvements. The following steps describe how to create a Jira issue:\n\n1. Visit the MongoDB Jira issue tracker and click the signup link. Create an account, and then log in to Jira.\n\n2. Navigate to the JAVA Jira project.\n\n3. Click Create to create a ticket. Please provide as much information as possible about the issue or request in the ticket.\n\nBug reports in the JAVA Jira project are publicly viewable.\n\nIf you\u2019ve identified a security vulnerability in any official MongoDB product, please report it according to the instructions found in the Create a Vulnerability Report page.\n\n## Pull Requests\n\nWe are happy to accept contributions to help improve the driver. We will guide user contributions to ensure they meet the standards of the codebase. Please ensure that any pull requests include documentation, tests, and pass the **gradle** checks.\n\nTo get started, clone the source repository and work on a branch by running the following commands:\n\n```bash\ngit clone https://github.com/mongodb/mongo-java-driver.git\ncd mongo-java-driver\ngit checkout -b myNewFeature\n```\n\nFinally, ensure that the code passes gradle check by running the following command:\n\n```bash\n./gradlew check\n```"} -{"chunk_id": "68d23bc6530172e0e1264606-0", "page_id": "68d23bc6530172e0e1264606", "source_name": "kotlin-sync", "product_name": "Kotlin Sync Driver", "url": "https://mongodb.com/docs/languages/kotlin/kotlin-sync-driver/current/crud/query/specify-documents-to-return", "title": "Specify Documents to Return", "text": "# Specify Documents to Return\n\n## Overview\n\nIn this guide, you can learn how to specify which documents to return from a read operation by using the following methods:\n\n- `limit()`: Specifies the maximum number of documents to return from a query\n\n- `sort()`: Specifies the sort order for the returned documents\n\n- `skip()`: Specifies the number of documents to skip before returning query results\n\n### Sample Data\n\nThe examples in this guide use the `restaurants` collection in the `sample_restaurants` database from the Atlas sample datasets. To learn how to create a free MongoDB deployment and load the sample datasets, see the MongoDB Get Started guide.\n\nThe documents in this collection are modeled by the following Kotlin data class:\n\n```kotlin\ndata class Restaurant(\n val name: String,\n val borough: String,\n val cuisine: String\n)\n```\n\n## Limit\n\nTo specify the maximum number of documents returned from a read operation, call the `limit()` method.\n\nThe following example finds all restaurants that have a `cuisine` field value of `\"Italian\"` and limits the results to 5 documents:\n\n```kotlin\nval results = collection\n .find(eq(Restaurant::cuisine.name, \"Italian\"))\n .limit(5)\n\nresults.forEach { result ->\n println(result)\n}\n```\n\n```\nRestaurant(name=Philadelphia Grille Express, borough=Brooklyn, cuisine=Italian)\nRestaurant(name=Isle Of Capri Resturant, borough=Manhattan, cuisine=Italian)\nRestaurant(name=Marchis Restaurant, borough=Manhattan, cuisine=Italian)\nRestaurant(name=Crystal Room, borough=Staten Island, cuisine=Italian)\nRestaurant(name=Forlinis Restaurant, borough=Manhattan, cuisine=Italian)\n```\n\nThe preceding example returns the first five documents returned by the query in natural order. The following section describes how to return the documents in a specified sort order.\n\n## Sort\n\nTo return documents in a specified order, call the `sort()` method. The `sort()` method takes a sort direction as a parameter. To specify the sort direction, use the `Sorts.ascending()` or `Sorts.descending()` method. The `Sorts.ascending()` method sorts values from lowest to highest, and the `Sorts.descending()` method sorts values from highest to lowest. If you don't specify a sort direction, `sort()` returns the documents in ascending order.\n\nThe following example returns all documents with a `cuisine` field value of `\"Italian\"`, sorted by the value of the `name` field in ascending order:\n\n```kotlin\nval results = collection\n .find(eq(Restaurant::cuisine.name, \"Italian\"))\n .sort(Sorts.ascending(Restaurant::name.name))\n\nresults.forEach { result ->\n println(result)\n}\n```\n\n```\nRestaurant(name=(Lewis Drug Store) Locanda Vini E Olii, borough=Brooklyn, cuisine=Italian)\nRestaurant(name=101 Restaurant And Bar, borough=Brooklyn, cuisine=Italian)\nRestaurant(name=44 Sw Ristorante & Bar, borough=Manhattan, cuisine=Italian)\nRestaurant(name=900 Park, borough=Bronx, cuisine=Italian)\nRestaurant(name=A Voce, borough=Manhattan, cuisine=Italian)\n...\n```\n\n## Skip\n\nTo skip a specified number of documents before returning your query results, call the `skip()` method and pass in the number of documents to skip. The `skip()` method ignores the specified number of documents in your query results and returns the rest.\n\nThe following example returns all documents that have a `cuisine` field value of `\"Italian\"` and skips the first 10 documents:\n\n```kotlin\nval results = collection\n .find(eq(Restaurant::cuisine.name, \"Italian\"))\n .skip(10)\n\nresults.forEach { result ->\n println(result)\n}\n```\n\n```\nRestaurant(name=San Pietro, borough=Manhattan, cuisine=Italian)\nRestaurant(name=Manetta's Ristorante, borough=Queens, cuisine=Italian)\nRestaurant(name=Salvi Restaurant, borough=Brooklyn, cuisine=Italian)\nRestaurant(name=Tommaso Restaurant, borough=Brooklyn, cuisine=Italian)\nRestaurant(name=Da Rosina Restaurant, borough=Manhattan, cuisine=Italian)\n...\n```\n\n## Combine Limit, Sort, and Skip\n\nYou can combine the `limit()`, `sort()`, and `skip()` methods in a single operation. This allows you to set a maximum number of sorted documents to return, skipping a specified number of documents before returning.\n\nThe following example returns documents with the `cuisine` field value of `\"Italian\"`. The results are sorted in alphabetical order, skipping the first 10 documents and limiting the results to 5 documents:\n\n```kotlin\nval results = collection\n .find(eq(Restaurant::cuisine.name, \"Italian\"))\n .sort(Sorts.ascending(Restaurant::name.name))\n .skip(10)\n .limit(5)\n\nresults.forEach { result ->\n println(result)\n}\n```\n\n```\nRestaurant(name=Acqua, borough=Manhattan, cuisine=Italian)\nRestaurant(name=Acqua Restaurant, borough=Manhattan, cuisine=Italian)\nRestaurant(name=Acqua Santa, borough=Brooklyn, cuisine=Italian)\nRestaurant(name=Acquista Trattoria, borough=Queens, cuisine=Italian)\nRestaurant(name=Acquolina Catering, borough=Manhattan, cuisine=Italian)\n```\n\nThe order in which you call these methods doesn't change the documents that are returned. The driver automatically reorders the calls to perform the sort and skip operations first, and the limit operation afterward.\n\n## Additional Information\n\nFor more information about specifying a query, see Specify a Query.\n\nFor more information about retrieving documents, see Find Documents.\n\n### API Documentation\n\nTo learn more about any of the methods or types discussed in this guide, see the following API documentation:\n\n- find()\n\n- limit()\n\n- sort()\n\n- skip()"} -{"chunk_id": "68a95c185e79d242619dca49-0", "page_id": "68a95c185e79d242619dca49", "source_name": "landing", "product_name": null, "url": "https://mongodb.com/docs/languages/php", "title": "MongoDB with PHP", "text": "# MongoDB with PHP\n\nBuild PHP applications with MongoDB's Atlas cloud database. Utilize PHP drivers, MongoDB integrations with Laravel and Symfony, Doctrine ODM, and other developer tools for seamless integration with your PHP applications.\n\n## Drivers\n\nThe MongoDB PHP Driver consists of the extension and library. While it is possible to use the extension alone, MongoDB recommends using the extension and the library together to build an application.\n\nProvides a low-level API and serves to integrate the C libraries `libmongoc` and `libbson` with PHP.\n\nProvides a high-level API for working with MongoDB databases consistent with other MongoDB language drivers.\n\n## Frameworks\n\nConfigure connections to different databases or clusters, store and retrieve objects, or use MongoDB as a data store.\n\n## Integrations\n\nDoctrine ODM \u2192\n\nFlysystem \u2192\n\nLLPhant \u2192\n\n## Content Management Systems\n\n## More Ways to Learn\n\nPHP Reference \u2192\n\nPHP Associate Developer Exam \u2192\n\nPHP Developer Path \u2192\n\nMongoDB Community \u2192"} -{"chunk_id": "69cb67f136a2a5baa36ab908-0", "page_id": "69cb67f136a2a5baa36ab908", "source_name": "landing", "product_name": null, "url": "https://mongodb.com/docs/gemini", "title": "MongoDB with Gemini", "text": "# MongoDB with Gemini\n\nYou can use MongoDB with Gemini through the official MongoDB Gemini Extension.\n\nThe MongoDB Gemini Extension provides:\n\n- The MongoDB MCP Server\n\n- Pre-built agent skills for common MongoDB tasks. See the MongoDB Agent Skills documentation for more information.\n\n## Install the MongoDB Gemini Extension\n\nThe MongoDB Gemini Extension is available in the official Gemini Extension Marketplace.\n\n### Install the MongoDB Gemini Extension from Gemini\n\nTo install the MongoDB Gemini Extension:\n\n1. Start a Gemini session.\n\n2. Install the extension:\n\n ```bash\n gemini extensions install https://github.com/mongodb/agent-skills\n ```\n\n3. Follow the prompts to complete the installation.\n\nAfter installing the Extension, you must configure the MCP Server before using any agent skills or functionality that connects to MongoDB.\n\n## Configure the MCP Server\n\nThe MongoDB Gemini Extension bundles the MongoDB MCP Server. To configure the MCP Server, see MongoDB MCP Server Get Started."} -{"chunk_id": "68a95c185e79d242619dca60-0", "page_id": "68a95c185e79d242619dca60", "source_name": "landing", "product_name": null, "url": "https://mongodb.com/docs/preview-features", "title": "Preview Features", "text": "# Preview Features\n\nProducts and features that we offer as private or public previews (or any other type of beta stage) are only for internal evaluation by our end users. Use these experimental features in isolated development environments only, never in production systems or with critical data.\n\n## Technical Considerations\n\nPreview and other beta-stage offerings:\n\n- Are not production-ready\n\n- May contain bugs, errors, or defects\n\n- In production environments, could potentially lead to unexpected or undesired results like data loss and other operational disruptions\n\n## Other Considerations\n\nPreview and other beta-stage offerings:\n\n- Are not covered by MongoDB's standard support channels or uptime SLAs\n\n- May not be subject to MongoDB's regular security and compliance frameworks\n\nMongoDB might modify or terminate preview offerings at any time. If we change or end-of-life one of these offerings, we do our best to notify users beforehand but do not guarantee a pre-announcement."} -{"chunk_id": "68a95c185e79d242619dca33-0", "page_id": "68a95c185e79d242619dca33", "source_name": "landing", "product_name": null, "url": "https://mongodb.com/docs/generative-ai-faq", "title": "Generative AI FAQs", "text": "# Generative AI FAQs\n\nLast Updated: 30 October, 2025\n\n## What GenAI Features Does MongoDB Currently Offer?\n\nMongoDB offers various generative AI (GenAI) capabilities in its products and services, including within Atlas and in its software products.\n\nFor example, in MongoDB Compass and Charts, Atlas users can leverage natural language to generate queries or visualizations. With MongoDB for VS Code, the MongoDB Extension for Github Copilot participant allows developers to generate MongoDB-related code more efficiently through Github Copilot Chat. In Atlas, users can also query data in natural language within Data Explorer.\n\nWe also offer a GenAI Chatbot within our MongoDB Documentation and across various other MongoDB properties.\n\n## What Services Do These GenAI Features Rely On?\n\nMongoDB's current GenAI features are powered by Azure OpenAI, with the exception of the participant within MongoDB for VS Code, which is powered by Github Copilot. When you use these features, your data is processed in Microsoft Azure's OpenAI service or Github Copilot. **No data processed by these services is used to train those third-party models.**\n\nNo prompts or responses are stored with Azure OpenAI. For more details, refer to Azure OpenAI's data management practices. For information about how Github Copilot processes data, please refer to the Github Trust Center.\n\n## What Data Is Sent To The Model?\n\nEach MongoDB tool backed by GenAI sends only the minimal required information to produce the best possible answer. For more specifics about the data transferred by each tool, please refer to our Documentation.\n\n## Are My Inputs or Outputs from my Use of MongoDB GenAI Features Used to Train Models?\n\nNo. The data input and output from MongoDB's GenAI features is not used to train the third-party models that power those features.\n\n## Does MongoDB Store My Inputs or Outputs from My Use of GenAI Features?\n\nMongoDB may temporarily store inputs and outputs generated by the GenAI features for up to one year for troubleshooting, analytics, and feature improvement. MongoDB will not share those inputs and outputs with any third party that is not its supplier.\n\n## How Can I Disable MongoDB's GenAI Features?\n\nGenAI features within MongoDB's products and services are **optional**. While they are enabled by default in Atlas for your convenience, you have the ability to disable them at any time or simply not use them.\n\nPlease consult our Atlas Organization Settings Documentation for information on how Organization Owners can disable Atlas GenAI features in Atlas at the organization level.\n\nWhen Atlas GenAI features are enabled at the organization level, individual Project Owners can still enable or disable individual AI features at the project level. To learn more about Atlas Project Settings for GenAI features, please consult the Documentation for each Atlas feature:\n\n- Data Explorer\n\n- Atlas Charts\n\nGenAI capabilities offered in our on-premises Compass software can be disabled from within Compass.\n\n## What Agreements Govern My Use of MongoDB's GenAI Features?\n\nYour use of these features is subject to your applicable MongoDB legal agreement, our Acceptable Use Policy and our Privacy Policy.\n\n## What About Voyage AI Embedding and Reranking Models?\n\nWe recently acquired Voyage AI, which offers AI embedding and reranking models. For more details on how these models work and what data they use, please refer to the Voyage AI FAQ and the Voyage Terms of Service."} -{"chunk_id": "68a95c185e79d242619dca4b-0", "page_id": "68a95c185e79d242619dca4b", "source_name": "landing", "product_name": null, "url": "https://mongodb.com/docs/legacy", "title": "Legacy Documentation", "text": "# Legacy Documentation\n\nMongoDB recommends that you upgrade products to the most recent version so that you can use the most up-to-date documentation. MongoDB documents supported product versions through MongoDB Documentation.\n\nIf you cannot upgrade to a supported version, MongoDB provides legacy documentation for versions that have reached their end-of-life and are no longer recommended for use. MongoDB does not maintain or update legacy documentation."} -{"chunk_id": "68a95c185e79d242619dca53-0", "page_id": "68a95c185e79d242619dca53", "source_name": "landing", "product_name": null, "url": "https://mongodb.com/docs/languages/python", "title": "MongoDB with Python", "text": "# MongoDB with Python\n\nBuild cutting-edge applications with Python and MongoDB, from dynamic modern web applications to Gen-AI systems and data science projects. MongoDB's scalable cloud database infrastructure ensures your solutions are robust and optimized for performance.\n\nAs of May 14, 2025, Motor is deprecated in favor of the GA release of the PyMongo Async API in the PyMongo library. We will not add new features to Motor, and we will provide only bug fixes until it reaches end of life on May 14, 2026. After that, we will fix only critical bugs until final support ends on May 14, 2027. We strongly recommend migrating to the PyMongo Async API while Motor is still supported.\n\nFor more information about migrating, see the Migrate to PyMongo Async guide in the PyMongo documentation.\n\n## Driver\n\nProvides a synchronous and asynchronous API for working with MongoDB databases consistent with other MongoDB language drivers.\n\nPyMongo Documentation \u2192\n\n## Frameworks\n\nConfigure connections to different databases or clusters, store and retrieve objects, or use MongoDB as a data store.\n\nCommunity built ODMs (ORMs for Document Database):\n\n## Libraries and Extensions\n\nPyMongoArrow\n\n## Integrations\n\n## More Ways to Learn\n\nPython Associate Developer Exam \u2192\n\nPython Developer Path \u2192\n\nMongoDB Community \u2192"} -{"chunk_id": "69cb67f136a2a5baa36ab906-0", "page_id": "69cb67f136a2a5baa36ab906", "source_name": "landing", "product_name": null, "url": "https://mongodb.com/docs/agent-skills", "title": "MongoDB Agent Skills", "text": "# MongoDB Agent Skills\n\nMongoDB Agent Skills are pre-built, reusable instructions that help AI coding agents perform common MongoDB tasks efficiently. These skills provide agents with expert knowledge about MongoDB best practices, enabling them to help you build applications faster and with fewer errors.\n\n## What are Agent Skills?\n\nAgent skills are specialized instructions that teach AI coding agents how to:\n\n- Set up and configure MongoDB connections\n\n- Design and implement database schemas\n\n- Write efficient queries and aggregations\n\nWhen you install MongoDB agent skills, your AI coding agent gains access to MongoDB-specific knowledge and can provide more accurate, context-aware assistance for your MongoDB development tasks.\n\n## Available Skills\n\nThe MongoDB agent skills collection includes the following skills.\n\n### Infrastructure\n\n#### MongoDB MCP Setup\n\nGuides the agent through setting up the MongoDB MCP (Model Context Protocol) Server, which enables direct interaction with your MongoDB databases. This skill helps configure authentication credentials and connection settings.\n\n#### MongoDB Connection\n\nOptimize MongoDB client connection configuration (pools, timeouts, patterns) to configure connection pools, debug or troubleshoot connection errors, and optimize performance issues related to connections. Inlcudes building serverless functions with MongoDB, creating API endpoints that use MongoDB, optimizing high-traffic MongoDB applications, creating long-running tasks and concurrency, or debugging connection-related failures.\n\n### Data Modeling\n\n#### Schema Design\n\nGuides developers through MongoDB schema design best practices. This skill helps design efficient document structures, implement validation rules, and optimize schemas for specific use cases.\n\n### Advanced Features\n\n#### Atlas Stream Processing\n\nComprehensive skill for building, operating, and debugging MongoDB Atlas Stream Processing pipelines. Handles workspace provisioning, data source/sink connections, processor lifecycle operations, debugging diagnostics, and tier sizing. Supports Kafka, Atlas clusters, S3, HTTPS, and Lambda integrations for streaming data workloads and event processing.\n\n#### Natural Language Querying\n\nTranslates natural language descriptions into MongoDB queries and aggregation pipelines. This skill uses collection schemas, sample documents, and index information to generate accurate, optimized queries. Supports complex operations like geospatial queries, text search, and multi-collection joins. Distinct from MongoDB Atlas Search and Vector Search (see Search and AI Recommendations skill below).\n\n#### Query Optimizer\n\nAnalyzes and optimizes MongoDB query performance. This skill ensures queries are properly indexed, debugs slow queries using Atlas Performance Advisor, and provides best practice recommendations for aggregation pipelines.\n\n#### Queryable Encryption Size Estimation\n\nEstimates the storage and memory impact of encrypting fields in collections with Queryable Encryption enabled. This skill calculates index storage, total disk storage, and memory from your schema, fields, and query types, so you can configure Queryable Encryption without scalability and performance issues. For Queryable Encryption only, not Client-Side Field Level Encryption (CSFLE).\n\n#### Search and AI Recommendations\n\nProvides guidance for implementing MongoDB Atlas Search and AI-powered recommendations. This skill helps configure search indexes, build search queries, and integrate AI capabilities into applications.\n\n## Installation\n\nMongoDB agent skills are available for multiple AI coding platforms. You can install MongoDB agent skills from official plugins, the Vercel Skills Marketplace, or manually from the MongoDB agent-skills repository.\n\n### Install from Official Plugins\n\nInstall MongoDB agent skills from official plugins for your AI coding platform:\n\n- **Claude Code**: Install from the official MongoDB Claude Plugin. See the Install the MongoDB Claude Plugin page for more information.\n\n- **Codex**: Install from the official MongoDB Codex Plugin. See the Install the MongoDB Codex Plugin page for more information.\n\n- **Cursor**: Install from the Cursor marketplace. See the Install the MongoDB Cursor Plugin page for more information.\n\n- **Gemini CLI**: Install as a Gemini CLI extension. See the Install the MongoDB Gemini Extension from Gemini page for more information.\n\n- **VS Code Extension**: Install from the official MongoDB VS Code Extension. See the Install MongoDB for VS Code Extension page for more information.\n\nOfficial MongoDB plugins for AI coding platforms bundle the MongoDB MCP Server and pre-built agent skills. To configure the MCP Server, see MongoDB MCP Server Get Started.\n\n### Install from Vercel's Agent Skills Directory\n\nInstall MongoDB agent skills from Vercel's Agent Skills Directory using the Vercel CLI.\n\n1. Run the following command (requires Node.js):\n\n ```bash\n npx skills add mongodb/agent-skills\n ```\n\n2. Follow the prompts to complete the installation.\n\n3. If you are using the MCP Server, configure the MCP Server with your MongoDB connection details:\n\n ```bash\n `npx mongodb-mcp-server@1 setup`\n ```\n\n4. Follow the instructions to complete the setup.\n\n### Install from GitHub Repository\n\nManually install MongoDB agent skills from the MongoDB agent-skills repository.\n\n1. Clone the repository:\n\n ```bash\n git clone https://github.com/mongodb/agent-skills.git\n ```\n\n2. Install the skills for your platform:\n\n **Supported platforms (Claude Code, Codex, Cursor, Gemini CLI)**\n\n Copy the appropriate plugin directory to your project root:\n\n - For Claude Code: Copy the `.claude-plugin/` directory\n\n - For Codex: Copy the `.codex-plugin/` directory\n\n - For Cursor: Copy the `.cursor-plugin/` directory\n\n - For Gemini CLI: Copy the `skills/` directory\n\n **Other platforms**\n\n Copy the `skills/` directory to the location where your coding agent reads its skills or context files. Refer to your agent's documentation for the correct path.\n\n3. Copy `mcp.json` to your project root (if using MCP Server).\n\n4. If using MCP Server, configure the MCP Server with your MongoDB connection details.\n\n## Configure the MCP Server\n\nConfigure the MongoDB MCP Server for the skills that access a live database. You can use Skills focused on design, tuning, and best-practices guidance without MCP, though some provide a richer experience when you enable it.\n\nFor complete MCP Server configuration options, see MongoDB MCP Server Get Started.\n\n## Using Agent Skills\n\nOnce installed, agent skills work automatically in the background. When you ask your AI coding agent for help with MongoDB tasks, it will use the installed skills to provide more accurate and helpful responses.\n\nExample interactions:\n\n- \"Help me set up a MongoDB connection in my Node.js application\"\n\n- \"Create a schema for a user collection with email validation\"\n\n- \"Write an aggregation pipeline to calculate monthly sales totals\"\n\n- \"Show me how to implement pagination for this query\"\n\nThe agent will use the MongoDB skills to provide responses that follow MongoDB best practices and are tailored to your specific use case.\n\n### Invoke Agent Skills\n\nAgent skills are invoked automatically when you ask your AI coding agent for help with MongoDB tasks. Some platforms allow you to invoke skills manually.\n\nFor example, you can invoke a skill directly in Claude Code using `/`.\n\n## Learn More\n\n- MongoDB Agent Skills Repository\n\n- MongoDB MCP Server Documentation"} -{"chunk_id": "68a95c185e79d242619dca52-0", "page_id": "68a95c185e79d242619dca52", "source_name": "landing", "product_name": null, "url": "https://mongodb.com/docs/languages/kotlin", "title": "MongoDB with Kotlin", "text": "# MongoDB with Kotlin\n\nDevelop server-side Kotlin applications with MongoDB's Atlas cloud database. With support for both coroutine-based and synchronous development, the MongoDB Kotlin drivers support developers in building server-side applications in Kotlin that are interoperable with the JVM ecosystem.\n\n## Drivers\n\nMongoDB provides drivers for both coroutine-based and synchronous applications.\n\nProvides an API to connect to MongoDB in server-side Kotlin applications that use coroutines.\n\nProvides an API to connect to MongoDB in synchronous Kotlin applications. The Kotlin Sync Driver is built on the Kotlin Coroutine Driver.\n\n## Frameworks\n\nBuild web applications by using Kotlin web frameworks compatible with MongoDB.\n\n## More Ways to Learn\n\nMongoDB Community \u2192"} -{"chunk_id": "68a95c185e79d242619dca4e-0", "page_id": "68a95c185e79d242619dca4e", "source_name": "landing", "product_name": null, "url": "https://mongodb.com/docs/languages/javascript", "title": "MongoDB with JavaScript", "text": "# MongoDB with JavaScript\n\nDevelop lightweight Javascript or TypeScript applications backed by a MongoDB's Atlas cloud database. Developer integrations like Prisma and Mongoose support your MERN and MEAN stack applications. MongoDB's Node.js driver is written in TypeScript and offers all the quality-of-life improvements modern developers expect, such as predictability, better readability, rich IDE support, and strong type safety.\n\n## Drivers\n\nProvides a Node.js API for working with MongoDB databases consistent with other MongoDB language drivers.\n\nProvides a TypeScript API for working with MongoDB databases consistent with other MongoDB language drivers.\n\n## Integrations\n\nPrisma \u2192\n\nMongoose \u2192\n\nFlowiseAI \u2192\n\n## More Ways to Learn\n\nNode.js Associate Developer Exam \u2192\n\nJavascript Developer Path \u2192\n\nMongoDB Community \u2192"} -{"chunk_id": "68a95c185e79d242619dca4f-0", "page_id": "68a95c185e79d242619dca4f", "source_name": "landing", "product_name": null, "url": "https://mongodb.com/docs/languages/scala", "title": "MongoDB with Scala", "text": "# MongoDB with Scala\n\nCreate high-performance and highly-scalable applications using the MongoDB Atlas cloud database. Use the MongoDB Scala driver to combine both functional and object-oriented programming styles to build fast applications for the JVM.\n\n## Drivers\n\nScala driver documentation \u2192\n\n## More ways to learn\n\nMongoDB Community \u2192"} -{"chunk_id": "68a95c295e79d242619df30a-0", "page_id": "68a95c295e79d242619df30a", "source_name": "laravel", "product_name": "Laravel MongoDB", "url": "https://mongodb.com/docs/drivers/php/laravel-mongodb/current/database-collection/time-series", "title": "Time Series Collections", "text": "# Time Series Collections\n\n## Overview\n\nIn this guide, you can learn how to use the Laravel Integration to create and interact with **time series collections**. These collections store time series data, which is composed of the following components:\n\n- Measured quantity\n\n- Timestamp for the measurement\n\n- Metadata that describes the measurement\n\nThe following table describes sample situations for which you can store time series data:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nSituation\n\n\nMeasured Quantity\n\n\nMetadata\n\n
\nRecording monthly sales by industry\n\n\nRevenue in USD\n\n\nCompany, country\n\n
\nTracking weather changes\n\n\nPrecipitation level\n\n\nLocation, sensor type\n\n
\nRecording fluctuations in housing prices\n\n\nMonthly rent price\n\n\nLocation, currency\n\n
\n\n## Create a Time Series Collection\n\nTo create and interact with time series collections, you must be connected to a deployment running MongoDB Server 5.0 or later.\n\nYou can create a time series collection to store time series data. To create a time series collection, create a migration class and add an `up()` function to specify the collection configuration. In the `up()` function, pass the new collection's name and the `timeseries` option to the `Schema::create()` method.\n\nTo learn more about creating a migration class, see Perform Laravel Migrations in the Schema Builder guide.\n\nWhen setting the `timeseries` option, include the following fields:\n\n- `timeField`: Specifies the field that stores a timestamp in each time series document.\n\n- `metaField`: Specifies the field that stores metadata in each time series document.\n\n- `granularity`: Specifies the approximate time between consecutive timestamps. The possible values are `'seconds'`, `'minutes'`, and `'hours'`.\n\n### Example\n\nThis example migration class creates the `precipitation` time series collection with the following configuration:\n\n- `timeField` is set to `'timestamp'`\n\n- `metaField` is set to `'location'`\n\n- `granularity` is set to `'minutes'`\n\n```php\n [\n 'timeField' => 'timestamp',\n 'metaField' => 'location',\n 'granularity' => 'minutes',\n ],\n ];\n\n Schema::create('precipitation', null, $options);\n }\n\n /**\n * Reverse the migrations.\n */\n public function down(): void\n {\n Schema::drop('precipitation');\n }\n};\n\n```\n\nTo verify that you successfully created the time series collection, call the `Schema::hasCollection()` method and pass the collection name as a parameter:\n\n```php\n$result = Schema::hasCollection('precipitation');\necho $result;\n```\n\nIf the collection exists, the `hasCollection()` method returns a value of `true`.\n\n## Insert Time Series Data\n\nYou can insert data into a time series collection by passing your documents to the `insert()` method and specifying the measurement, timestamp, and metadata in each inserted document.\n\nTo learn more about inserting documents into a collection, see Insert Documents in the Write Operations guide.\n\n### Example\n\nThis example inserts New York City precipitation data into the `precipitation` time series collection created in the Create a Time Series Collection example. Each document contains the following fields:\n\n- `precipitation_mm`, which stores precipitation measurements in millimeters\n\n- `location`, which stores location metadata\n\n- `timestamp`, which stores the time of the measurement collection\n\n```php\n$data = [\n [\n 'precipitation_mm' => 0.5,\n 'location' => 'New York City',\n 'timestamp' => new UTCDateTime(Carbon::create(2023, 9, 12, 0, 0, 0, 'CET')),\n ],\n [\n 'precipitation_mm' => 2.8,\n 'location' => 'New York City',\n 'timestamp' => new UTCDateTime(Carbon::create(2023, 9, 17, 0, 0, 0, 'CET')),\n ],\n];\n\n$result = DB::table('precipitation')\n ->insert($data);\n```\n\nThe preceding example uses the Laravel query builder to insert documents into the time series collection. Alternatively, you can create an Eloquent model that represents the collection and perform insert operations on your model. To learn more, see the Eloquent Model Class guide.\n\n## Query Time Series Collections\n\nYou can use the same syntax and conventions to query data stored in a time series collection as you use when performing read or aggregation operations on other collections. To find more information about these operations, see the Additional Information section.\n\n## Additional Information\n\nTo learn more about the concepts mentioned in this guide, see the following MongoDB Server manual entries:\n\n- Time Series\n\n- Create and Query a Time Series Collection\n\n- Set Granularity for Time Series Data\n\nTo learn more about querying data, see the Query Builder guide.\n\nTo learn more about performing aggregation operations, see the Aggregation Operations guide."} -{"chunk_id": "6a912a064f25feb7b9024b89-0", "page_id": "6a912a064f25feb7b9024b89", "source_name": "laravel", "product_name": "Laravel MongoDB", "url": "https://mongodb.com/docs/drivers/php/laravel-mongodb/current/connect/network-compression", "title": "Compress Network Traffic", "text": "# Compress Network Traffic\n\n## Overview\n\nMongoDB drivers can compress the messages sent to and received from MongoDB Server. This reduces the amount of data transferred for each operation. Compression can improve performance over constrained networks and lower the data transfer costs associated with running MongoDB Atlas.\n\nCompression operates at the wire protocol level, so it applies to every operation that your application performs. If you specify more than one algorithm, the driver uses the first algorithm in your list that MongoDB Server also supports.\n\n### Compression Algorithms\n\nMongoDB drivers support the following compression algorithms:\n\n- Snappy\n\n- Zlib\n\n- Zstandard\n\n## Network Compression Benefits\n\nMongoDB Atlas charges for data transferred across cloud regions, cloud providers, and between your infrastructure and MongoDB Atlas. Network compression reduces the amount of data that your application sends and receives, which can lower these data transfer costs. To learn more about pricing, see Data Transfer Costs.\n\nNetwork compression also has productivity benefits. Compressed messages take less time to transfer across the network, which can improve your application's response times. Compression also reduces the bandwidth that your MongoDB traffic uses, which leaves more bandwidth available for other applications on the same network.\n\nWhen you choose a compression algorithm, consider the following guidelines:\n\n- Use **Zstandard** for a balance of compression efficiency and resource usage. Zstandard is a good default choice for most applications.\n\n- Use **Snappy** for latency-sensitive applications that require minimal computational overhead.\n\n- Use **Zlib** for broad compatibility across MongoDB drivers and environments.\n\nCompression trades network bandwidth for CPU usage. After you enable network compression, monitor your application's CPU utilization to confirm that the trade-off benefits your workload. To learn more about these trade-offs, see the CPU Utilization and Network Compression in MongoDB blog post.\n\n## Version Compatibility\n\nAll versions of the Laravel Integration support each network compression algorithm.\n\nThe following table lists the minimum supported MongoDB Server version for each algorithm:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nCompression Algorithm\n\n\nMinimum Server Version\n\n
\nSnappy\n\n\n4.2\n\n
\nZlib\n\n\n4.2\n\n
\nZstandard\n\n\n4.2\n\n
\n\n## Enable Network Compression\n\nTo enable network compression for your MongoDB connection, perform the following steps:\n\n- Build the MongoDB PHP Extension with the required dependencies. The extension handles network compression, not the Laravel Integration.\n\n- Specify the compression algorithms you want to use.\n\n### Install Dependencies\n\nBecause the Laravel Integration uses the MongoDB PHP Extension and the MongoDB C Driver to implement network compression, you must install the C driver with the required dependencies. To view these dependencies, see Install Dependencies in the C driver documentation.\n\n### Specify Compression Algorithms\n\nTo enable compression for the connection to your MongoDB instance, update the `connections` array in your application's `config/database.php` configuration file. You can specify the compression algorithms in one of the following ways:\n\n- Include the `compressors` option in the `options` array\n\n- Use the `compressors` parameter in the `dsn` connection string\n\nSelect the Options Array or Connection String tab to view an example that specifies all available compressors:\n\n\n\n\n\n```php\n'connections' => [\n 'mongodb' => [\n 'dsn' => 'mongodb+srv://mongodb0.example.com/',\n 'driver' => 'mongodb',\n 'database' => 'sample_mflix',\n 'options' => [\n 'compressors' => 'snappy,zstd,zlib',\n ],\n ],\n],\n```\n\n\n\n\n\n```php\n'connections' => [\n 'mongodb' => [\n 'dsn' => 'mongodb+srv://mongodb0.example.com/?compressors=snappy,zstd,zlib',\n 'driver' => 'mongodb',\n 'database' => 'sample_mflix',\n ],\n],\n```\n\n\n\n\n\n### Set the Zlib Compression Level\n\nIf you specify Zlib as one of your compression algorithms, you can use the `zlibCompressionLevel` option to specify a compression level. This option accepts an integer value between `-1` and `9`, and values have the following effects:\n\n- **-1:** *(Default)* Zlib uses its default compression level (usually `6`).\n\n- **0:** No compression.\n\n- **1:** Fastest speed but lowest compression.\n\n- **9:** Best compression but slowest speed.\n\nSelect the Options Array or Connection String tab to view an example that sets the `zlibCompressionLevel` option to `1`:\n\n\n\n\n\n```php\n'connections' => [\n 'mongodb' => [\n 'dsn' => 'mongodb+srv://mongodb0.example.com/',\n 'driver' => 'mongodb',\n 'database' => 'sample_mflix',\n 'options' => [\n 'compressors' => 'zlib',\n 'zlibCompressionLevel' => 1,\n ],\n ],\n],\n```\n\n\n\n\n\n```php\n'connections' => [\n 'mongodb' => [\n 'dsn' => 'mongodb+srv://mongodb0.example.com/?compressors=zlib&zlibCompressionLevel=1',\n 'driver' => 'mongodb',\n 'database' => 'sample_mflix',\n ],\n],\n```\n\n\n\n"} -{"chunk_id": "6a514da3d727379c91b9f089-0", "page_id": "6a514da3d727379c91b9f089", "source_name": "laravel", "product_name": "Laravel MongoDB", "url": "https://mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query/query-logging", "title": "Enable Query Logging", "text": "# Enable Query Logging\n\n## Overview\n\nIn this guide, you can learn how to enable query logging in Laravel MongoDB. Query logging can help you debug your queries and monitor database interactions.\n\n### Before You Get Started\n\nTo run the code examples in this guide, complete the Quick Start tutorial. This tutorial provides instructions on setting up a MongoDB Atlas instance with sample data and creating the following files in your Laravel web application:\n\n- `Movie.php` file, which contains a `Movie` model to represent documents in the `movies` collection\n\n- `MovieController.php` file, which contains a `show()` function to run database operations\n\n- `browse_movies.blade.php` file, which contains HTML code to display the results of database operations\n\nThe following sections describe how to edit the files in your Laravel application to run the find operation code examples and view the expected output.\n\n## Enable Logs On a Connection\n\nTo enable logs on a connection, you can use the `enableQueryLog()` method on the `DB` facade. This method enables MongoDB command logging on any queries that you perform on the database connection.\n\nAfter you enable query logging, any queries you perform are stored in memory. To retrieve the logs, use one of the following methods:\n\n- `getQueryLog()`: Returns a log of MongoDB queries\n\n- `getRawQueryLog()`: Returns a log of raw MongoDB queries\n\nThe following example enables query logging, performs some queries, then prints the query log:\n\n```php\nDB::connection('mongodb')->enableQueryLog();\n\nMovie::where('title', 'Carrie')->get();\nMovie::where('year', '<', 2005)->get();\nMovie::where('imdb.rating', '>', 8.5)->get();\n\n$logs = DB::connection('mongodb')->getQueryLog();\nforeach ($logs as $log) {\n echo json_encode($log, JSON_PRETTY_PRINT) . PHP_EOL;\n}\n\n```\n\n```json\n{\n \"query\": \"{ \\\"find\\\" : \\\"movies\\\", \\\"filter\\\" : { \\\"title\\\" : \\\"Carrie\\\" } }\",\n \"bindings\": [],\n \"time\": 29476\n}\n{\n \"query\": \"{ \\\"find\\\" : \\\"movies\\\", \\\"filter\\\" : { \\\"year\\\" : { \\\"$lt\\\" : { \\\"$numberInt\\\" : \\\"2005\\\" } } } }\",\n \"bindings\": [],\n \"time\": 29861\n}\n{\n \"query\": \"{ \\\"find\\\" : \\\"movies\\\", \\\"filter\\\" : { \\\"imdb.rating\\\" : { \\\"$gt\\\" : { \\\"$numberDouble\\\" : \\\"8.5\\\" } } } }\",\n \"bindings\": [],\n \"time\": 27251\n}\n```\n\n## Additional Information\n\nTo learn more about connecting to MongoDB, see the Connection Guide.\n\nTo learn how to retrieve data based on filter criteria, see the Retrieve MongoDB Data guide."} -{"chunk_id": "6a514da3d727379c91b9f070-0", "page_id": "6a514da3d727379c91b9f070", "source_name": "laravel", "product_name": "Laravel MongoDB", "url": "https://mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/modify", "title": "Update Documents", "text": "# Update Documents\n\n## Overview\n\nIn this guide, you can learn how to modify documents in your MongoDB collection from your Laravel application by using Laravel MongoDB. Use update operations to modify existing documents or to insert a document if none match the search criteria.\n\nYou can persist changes on an instance of an Eloquent model or use Eloquent's fluent syntax to chain an update operation on methods that return a Laravel collection object.\n\nThis guide provides examples of the following update operations:\n\n- Update a document\n\n- Update multiple documents\n\n- Update or insert in a single operation\n\n- Update arrays in a document\n\n### Sample Model\n\nThe operations in this guide reference the following Eloquent model class:\n\n```php\n 'datetime'];\n}\n\n```\n\nThe `$fillable` attribute lets you use Laravel mass assignment for insert operations. To learn more about mass assignment, see Customize Mass Assignment in the Eloquent Model Class documentation.\n\nThe `$casts` attribute instructs Laravel to convert attributes to common data types. To learn more, see Attribute Casting in the Laravel documentation.\n\n## Update One Document\n\nYou can update a document in the following ways:\n\n- Modify an instance of the model and save the changes by calling the `save()` method.\n\n- Chain methods to retrieve an instance of a model and perform updates on it by calling the `update()` method.\n\nThe following example shows how to update a document by modifying an instance of the model and calling its `save()` method:\n\n```php\n$concert = Concert::first();\n$concert->venue = 'Manchester Arena';\n$concert->ticketsSold = 9543;\n$concert->save();\n```\n\nWhen the `save()` method succeeds, the model instance on which you called the method contains the updated values.\n\nIf the operation fails, the Laravel Integration assigns the model instance a `null` value.\n\nThe following example shows how to update a document by chaining methods to retrieve and update the first matching document:\n\n```php\n$concert = Concert::where(['performer' => 'Brad Mehldau'])\n ->orderBy('id')\n ->first()\n ->update(['venue' => 'Manchester Arena', 'ticketsSold' => 9543]);\n```\n\nThe `orderBy()` call sorts the results by the `_id` field to guarantee a consistent sort order. To learn more about sorting in MongoDB, see the Natural order glossary entry in the Server manual.\n\nWhen the `update()` method succeeds, the operation returns the number of documents updated.\n\nIf the retrieve part of the call does not match any documents, the Laravel Integration returns the following error:\n\n```none\nError: Call to a member function update() on null\n```\n\n## Update Multiple Documents\n\nTo perform an update on one or more documents, chain the `update()` method to the results of a method that retrieves the documents as a Laravel collection object, such as `where()`.\n\nThe following example shows how to chain calls to retrieve matching documents and update them:\n\n```php\nConcert::whereIn('venue', ['Philharmonie de Paris', 'Soldier Field'])\n ->update(['venue' => 'Concertgebouw', 'ticketsSold' => 0]);\n```\n\nWhen the `update()` method succeeds, the operation returns the number of documents updated.\n\nIf the retrieve part of the call does not match any documents in the collection, the Laravel Integration returns the following error:\n\n```none\nError: Call to a member function update() on null\n```\n\n## Update or Insert in a Single Operation\n\nAn **upsert** operation lets you perform an update or insert in a single operation. This operation streamlines the task of updating a document or inserting one if it does not exist.\n\nStarting in v4.7, you can perform an upsert operation by using either of the following methods:\n\n- `upsert()`: When you use this method, you can perform a **batch upsert** to change or insert multiple documents in one operation.\n\n- `update()`: When you use this method, you must specify the `upsert` option to update all documents that match the query filter or insert one document if no documents are matched. Only this upsert method is supported in versions v4.6 and earlier.\n\n### Upsert Method\n\nThe `upsert()` method accepts the following parameters:\n\n- `$values`: Array of fields and values that specify documents to update or insert.\n\n- `$uniqueBy`: One or more fields that uniquely identify documents in your first array parameter.\n\n- `$update`: Optional array of fields to update if a matching document exists. If you omit this parameter, the Laravel Integration updates all fields.\n\nTo specify an upsert in the `upsert()` method, pass the required parameters as shown in the following code example:\n\n```php\nYourModel::upsert(\n [/* documents to update or insert */],\n '/* unique field */',\n [/* fields to update */],\n);\n```\n\n#### Example\n\nThis example shows how to use the `upsert()` method to perform an update or insert in a single operation. Click the VIEW OUTPUT button to see the resulting data changes when there is a document in which the value of `performer` is `'Angel Olsen'` in the collection already:\n\n```php\nConcert::upsert([\n ['performer' => 'Angel Olsen', 'venue' => 'Academy of Music', 'ticketsSold' => 275],\n ['performer' => 'Darondo', 'venue' => 'Cafe du Nord', 'ticketsSold' => 300],\n], 'performer', ['ticketsSold']);\n```\n\n```json\n{\n \"_id\": \"...\",\n \"performer\": \"Angel Olsen\",\n \"venue\": \"State Theatre\",\n \"genres\": [\n \"indie\",\n \"rock\"\n ],\n \"ticketsSold\": 275,\n \"updated_at\": ...\n},\n{\n \"_id\": \"...\",\n \"performer\": \"Darondo\",\n \"venue\": \"Cafe du Nord\",\n \"ticketsSold\": 300,\n \"updated_at\": ...\n}\n```\n\nIn the document in which the value of `performer` is `'Angel Olsen'`, the `venue` field value is not updated, as the upsert specifies that the update applies only to the `ticketsSold` field.\n\n### Update Method\n\nTo specify an upsert in an `update()` method, set the `upsert` option to `true` as shown in the following code example:\n\n```php\nYourModel::where(/* match criteria */)\n ->update(\n [/* update data */],\n ['upsert' => true]);\n```\n\nWhen the `update()` method is chained to a query, it performs one of the following actions:\n\n- If the query matches documents, the `update()` method modifies the matching documents.\n\n- If the query matches zero documents, the `update()` method inserts a document that contains the update data and the equality match criteria data.\n\n#### Example\n\nThis example shows how to pass the `upsert` option to the `update()` method to perform an update or insert in a single operation. Click the VIEW OUTPUT button to see the example document inserted when no matching documents exist:\n\n```php\nConcert::where(['performer' => 'Jon Batiste', 'venue' => 'Radio City Music Hall'])\n ->update(\n ['genres' => ['R&B', 'soul'], 'ticketsSold' => 4000],\n ['upsert' => true],\n );\n```\n\n```json\n{\n \"_id\": \"660c...\",\n \"performer\": \"Jon Batiste\",\n \"venue\": \"Radio City Music Hall\",\n \"genres\": [\n \"R&B\",\n \"soul\"\n ],\n \"ticketsSold\": 4000,\n \"updated_at\": ...\n}\n```\n\n## Update Arrays in a Document\n\nIn this section, you can see examples of the following operations that update array values in a MongoDB document:\n\n- Add values to an array\n\n- Remove values from an array\n\n- Update the value of an array element\n\nThese examples modify the sample document created by the following insert operation:\n\n```php\nConcert::create([\n 'performer' => 'Mitsuko Uchida',\n 'genres' => ['classical', 'dance-pop'],\n]);\n```"} -{"chunk_id": "6a514da3d727379c91b9f070-1", "page_id": "6a514da3d727379c91b9f070", "source_name": "laravel", "product_name": "Laravel MongoDB", "url": "https://mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/modify", "title": "Update Documents", "text": "### Add Values to an Array Example\n\nThis section shows how to use the `push()` method to add values to an array in a MongoDB document. You can pass one or more values to add and set the optional parameter `unique` to `true` to skip adding any duplicate values in the array. The following code example shows the structure of a `push()` method call:\n\n```php\nYourModel::where()\n ->push(\n ,\n [], // array or single value to add\n unique: true); // whether to skip existing values\n```\n\nThe following example shows how to add the value `\"baroque\"` to the `genres` array field of a matching document. Click the VIEW OUTPUT button to see the updated document:\n\n```php\nConcert::where('performer', 'Mitsuko Uchida')\n ->push(\n 'genres',\n ['baroque'],\n );\n```\n\n```json\n{\n \"_id\": \"660eb...\",\n \"performer\": \"Mitsuko Uchida\",\n \"genres\": [\n \"classical\",\n \"dance-pop\",\n\n ],\n \"updated_at\": ...,\n \"created_at\": ...\n}\n```\n\n### Remove Values From an Array Example\n\nThis section shows how to use the `pull()` method to remove values from an array in a MongoDB document. You can pass one or more values to remove from the array. The following code example shows the structure of a `pull()` method call:\n\n```php\nYourModel::where()\n ->pull(\n ,\n []); // array or single value to remove\n```\n\nThe following example shows how to remove array values `\"classical\"` and `\"dance-pop\"` from the `genres` array field. Click the VIEW OUTPUT button to see the updated document:\n\n```php\nConcert::where('performer', 'Mitsuko Uchida')\n ->pull(\n 'genres',\n ['dance-pop', 'classical'],\n );\n```\n\n```json\n{\n \"_id\": \"660e...\",\n \"performer\": \"Mitsuko Uchida\",\n \"genres\": [],\n \"updated_at\": ...,\n \"created_at\": ...\n}\n```\n\n### Update the Value of an Array Element Example\n\nThis section shows how to use the `$` positional operator to update specific array elements in a MongoDB document. The `$` operator represents the first array element that matches the query. The following code example shows the structure of a positional operator update call on a single matching document:\n\nCurrently, the Laravel Integration offers this operation only on the `DB` facade and not on the Eloquent ORM.\n\n```php\nDB::connection('mongodb')\n ->getCollection()\n ->updateOne(\n ,\n ['$set' => ['.$' => ]]);\n```\n\nThe following example shows how to replace the array value `\"dance-pop\"` with `\"contemporary\"` in the `genres` array field. Click the VIEW OUTPUT button to see the updated document:\n\n```php\n$match = ['performer' => 'Mitsuko Uchida', 'genres' => 'dance-pop'];\n$update = ['$set' => ['genres.$' => 'contemporary']];\n\nDB::connection('mongodb')\n ->getCollection('concerts')\n ->updateOne($match, $update);\n```\n\n```json\n{\n \"_id\": \"660e...\",\n \"performer\": \"Mitsuko Uchida\",\n \"genres\": [\n \"classical\",\n \"contemporary\"\n ],\n \"updated_at\": ...,\n \"created_at\": ...\n}\n```\n\nTo learn more about array update operators, see Array Update Operators in the Server manual.\n\n## Fully Runnable Examples\n\nThe following sections provide fully runnable code examples that demonstrate how to update documents by using the Laravel Integration. These examples use the `sample_mflix.movies` collection from the Atlas sample datasets.\n\nYou can run the full examples from your own Laravel application or from the `my-app` application created in the Get Started tutorial. The examples use the `Movie.php` model class created in this tutorial to demonstrate operations on the `movies` MongoDB collection. To run the operation, you can copy the sample code to a controller endpoint in your Laravel application.\n\nTo view the expected output of the operation, you can add a web route to your application that calls the controller function and returns the result to a web interface.\n\n### Update a Document\n\nThis example performs the following actions:\n\n- Uses the `Movie` Eloquent model to represent the `movies` collection in the `sample_mflix` database\n\n- Updates a document from the `movies` collection that matches the query filter\n\n- Prints the number of updated documents\n\nThe example calls the following methods on the `Movie` model:\n\n- `where()`: Matches documents in which the value of the `title` field is `\"Carol\"`\n\n- `orderBy()`: Sorts matched documents by their ascending `_id` values\n\n- `first()`: Retrieves only the first matching document\n\n- `update()`: Updates the value of the `imdb.rating` nested field from `6.9` to `7.3` and the value of the `imdb.votes` nested field from `493` to `142000`\n\n```php\n$updates = Movie::where('title', 'Carol')\n ->orderBy('id')\n ->first()\n ->update([\n 'imdb' => [\n 'rating' => 7.3,\n 'votes' => 142000,\n ],\n ]);\n\necho 'Updated documents: ' . $updates;\n```\n\n```console\nUpdated documents: 1\n```\n\n### Update Multiple Documents\n\nSelect from the following Eloquent and Query Builder tabs to view examples for each corresponding query syntax:\n\n\n\n\n\nThis example performs the following actions:\n\n- Uses the `Movie` Eloquent model to represent the `movies` collection in the `sample_mflix` database\n\n- Updates documents from the `movies` collection that match a query filter\n\n- Prints the number of updated documents\n\nThe example calls the following methods on the `Movie` model:\n\n- `where()`: Matches documents in which the value of the `imdb.rating` nested field is greater than `9.0`\n\n- `update()`: Updates the matching documents by adding an `acclaimed` field and setting its value to `true`, then returns the number of updated documents\n\n```php\n$updates = Movie::where('imdb.rating', '>', 9.0)\n ->update(['acclaimed' => true]);\n\necho 'Updated documents: ' . $updates;\n```\n\n```console\nUpdated documents: 20\n```\n\n\n\n\n\nThis example performs the following actions:\n\n- Accesses the `movies` collection by calling the `table()` method from the `DB` facade\n\n- Updates documents from the `movies` collection that match a query filter\n\n- Prints the number of updated documents\n\nThe example calls the following query builder methods:\n\n- `where()`: Matches documents in which the value of the `imdb.rating` nested field is greater than `9.0`\n\n- `update()`: Updates the matching documents by adding an `acclaimed` field and setting its value to `true`, then returns the number of updated documents\n\n```php\n$updates = DB::table('movies')\n ->where('imdb.rating', '>', 9.0)\n ->update(['acclaimed' => true]);\n\necho 'Updated documents: ' . $updates;\n```\n\n```console\nUpdated documents: 20\n```\n\n\n\n\n\n## Additional Information\n\nTo learn how to insert documents into a MongoDB collection, see the Insert Documents guide."} -{"chunk_id": "68a95c2a5e79d242619df339-0", "page_id": "68a95c2a5e79d242619df339", "source_name": "laravel", "product_name": "Laravel MongoDB", "url": "https://mongodb.com/docs/drivers/php/laravel-mongodb/current/upgrade", "title": "Upgrade Library Version", "text": "# Upgrade Library Version\n\n## Overview\n\nOn this page, you can learn how to upgrade Laravel MongoDB to a new major version. This page also includes the changes you must make to your application to upgrade your version of the Laravel Integration without losing functionality, if applicable.\n\n## How to Upgrade\n\nBefore you upgrade, perform the following actions:\n\n- Ensure the new library version is compatible with the MongoDB Server version your application connects to and the version of Laravel that your application runs on. See the Compatibility page for this information.\n\n- Address any breaking changes between the version of the Laravel Integration that your application now uses and your planned upgrade version in the Breaking Changes section of this guide.\n\n- Address any deprecation notices for your current version in the Deprecations section of this guide.\n\nTo upgrade your library version, run the following command in your application's directory:\n\n```bash\ncomposer require mongodb/laravel-mongodb:5.11\n```\n\nTo upgrade to a different version of the library, replace the information after `laravel-mongodb:` with your preferred version number.\n\n## Breaking Changes\n\nA breaking change is a modification in a convention or behavior in a specific version of the Laravel Integration that might prevent your application from working as expected.\n\nThe breaking changes in this section are categorized by the major version releases that introduced them. When upgrading library versions, address all the breaking changes between your current version and the planned upgrade version.\n\n- Version 5.x Breaking Changes\n\n- Version 4.x Breaking Changes\n\n### Version 5.x Breaking Changes\n\nThis library version introduces the following breaking changes:\n\n- The query builder returns results as `stdClass` objects instead of as arrays. This change requires that you change array access to property access when interacting with query results.\n\n The following code shows how to retrieve a query result and access a property from the result object in older versions compared to v5.0:\n\n ```php\n $document = DB::table('accounts')\n ->where('name', 'Anita Charles')\n ->first();\n\n // older versions\n $document['balance'];\n\n // v5.0\n $document->balance;\n ```\n\n- Removes support for the following classes:\n\n - `MongoDB\\Laravel\\Auth\\DatabaseTokenRepository`. Instead, use the default `Illuminate\\Queue\\Failed\\DatabaseFailedJobProvider` class and specify a connection to MongoDB.\n\n - `MongoDB\\Laravel\\Queue\\Failed\\MongoFailedJobProvider`. Instead, use the default `Illuminate\\Queue\\Failed\\DatabaseFailedJobProvider` class and specify a connection to MongoDB.\n\n- When using a `DateTimeInterface` object, including `Carbon`, in a query, the library converts the `DateTimeInterface` to a `MongoDB\\BSON\\UTCDateTime` object. This conversion applies to `DateTimeInterface` objects passed as query filters to the `where()` method or as data passed to the `insert()` and `update()` methods.\n\n To view an example that passes a `Carbon` object to the `DB::where()` method, see the Match Dates Example section of the Query Builder guide.\n\n- In query results, the library converts BSON `UTCDateTime` objects to `Carbon` date classes, applying the default timezone.\n\n In v5.1, the library also performs this conversion to the `Model::raw()` method results before hydrating a Model instance.\n\n- `id` is an alias for the `_id` field in MongoDB documents, and the library automatically converts between `id` and `_id` when querying data. The query result object includes an `id` field to represent the document's `_id` field. Because of this behavior, you cannot have two separate `id` and `_id` fields in your documents.\n\n In v5.1, the library also performs this conversion to the `Model::raw()` method results before hydrating a Model instance. When passing a complex query filter, use the `DB::where()` method instead of `Model::raw()`.\n\n Starting in v5.3, you can disable automatic conversion of `id` to `_id` for embedded documents. To learn more, see the Disable Use of id Field Name Conversion section of the Connection Options guide.\n\n- Removes support for the `$collection` property. The following code shows how to assign a MongoDB collection to a variable in your `User` class in older versions compared to v5.0:\n\n ```php\n use MongoDB\\Laravel\\Eloquent\\Model;\n\n class User extends Model\n {\n protected $keyType = 'string';\n\n // older versions\n protected $collection = 'app_user';\n\n // v5.0\n protected $table = 'app_user';\n\n ...\n }\n ```\n\n This release also modifies the associated `DB` and `Schema` methods for accessing a MongoDB collection. The following code shows how to access the `app_user` collection in older versions compared to v5.0:\n\n ```php\n use Illuminate\\Support\\Facades\\Schema;\n use Illuminate\\Support\\Facades\\DB;\n use MongoDB\\Laravel\\Schema\\Blueprint;\n\n // older versions\n Schema::collection('app_user', function (Blueprint $collection) { ... });\n DB::collection('app_user')->find($id);\n\n // v5.0\n Schema::table('app_user', function (Blueprint $table) { ... });\n DB::table('app_user')->find($id);\n ```\n\n- Starting in v5.9, the minimum Laravel version is 12.0. For instructions on upgrading your Laravel version, see the Upgrade Guide in the Laravel documentation.\n\n- Starting in v5.9, the minimum PHP version is 8.2. Before you upgrade, confirm that your application runs on a supported version of PHP.\n\n- Starting in v5.11, the `where()` method interprets an array value as a literal value under the following conditions:\n\n - You pass 3 arguments to the `where()` method.\n\n - One of those arguments is the `=` operator.\n\n - Another argument is an array value.\n\n In earlier versions, the Laravel Integration passed the array to MongoDB as an operator document, which could inject unintended query conditions. To learn more, see Array Values in the Query Builder guide and the related CVE-2026-88022 issue.\n\n### Version 4.x Breaking Changes\n\nThis library version introduces the following breaking changes:\n\n- Minimum Laravel version is now 10.0. For instructions on upgrading your Laravel version, see the Upgrade Guide in the Laravel documentation.\n\n- Dependency name is now `\"mongodb/laravel-mongodb\"`. Ensure that the dependency name in your `composer.json` file is `\"mongodb/laravel-mongodb\": \"^4.0\"`. Then, run `composer update`.\n\n- Namespace is now `MongoDB\\Laravel\\`. Ensure that you change the namespace from `Jenssegers\\Mongodb\\` to `MongoDB\\Laravel\\` in your models and config files.\n\n- Removes support for non-Laravel projects.\n\n- Removes support for the `$dates` property. Ensure that you change all instances of `$dates` to `$casts` in your model files.\n\n- `Model::unset($field)` does not persist the change. Ensure that you follow all calls to `Model::unset($field)` with `Model::save()`.\n\n- Removes the `Query\\Builder::whereAll($column, $values)` method. Ensure that you replace all calls to `Query\\Builder::whereAll($column, $values)` with `Query\\Builder::where($column, 'all', $values)`.\n\n- `Query\\Builder::delete()` can delete one or all documents. Ensure that you pass only the values `1` or `null` to `limit()`.\n\n- `whereDate()`, `whereDay()`, `whereMonth()`, `whereYear()`, and `whereTime()` methods now use MongoDB operators on date fields.\n\n- Adds the `MongoDB\\Laravel\\Eloquent\\MassPrunable` trait. Ensure that you replace all instances of `Illuminate\\Database\\Eloquent\\MassPrunable` with `MongoDB\\Laravel\\Eloquent\\MassPrunable` in your models.\n\n- Removes support for the following `Query\\Builder` methods:\n\n - `toSql()`\n\n - `toRawSql()`\n\n - `whereColumn()`\n\n - `whereFullText()`\n\n - `groupByRaw()`\n\n - `orderByRaw()`\n\n - `unionAll()`\n\n - `union()`\n\n - `having()`\n\n - `havingRaw()`\n\n - `havingBetween()`\n\n - `whereIntegerInRaw()`\n\n - `orWhereIntegerInRaw()`\n\n - `whereIntegerNotInRaw()`\n\n - `orWhereIntegerNotInRaw()`"} -{"chunk_id": "68a95c2a5e79d242619df339-1", "page_id": "68a95c2a5e79d242619df339", "source_name": "laravel", "product_name": "Laravel MongoDB", "url": "https://mongodb.com/docs/drivers/php/laravel-mongodb/current/upgrade", "title": "Upgrade Library Version", "text": "## Deprecations\n\nA deprecation notice indicates that a feature is scheduled for removal in a future major version. Address deprecation notices in your application before upgrading to the next major version.\n\n- Version 5.8 Deprecations\n\n### Version 5.8 Deprecations\n\nStarting in Laravel MongoDB v5.8, the `array` cast type for Eloquent model attributes is deprecated. Using `array` as a cast type stores attribute values as JSON-encoded strings in MongoDB, which is not the native BSON format. When you write to an attribute that uses the `array` cast, the library emits the following deprecation notice:\n\n```none\nUSER DEPRECATED The \"array\" cast on attribute \"\"\nof model \"\" stores values as a JSON-encoded string in\nMongoDB, which is not the native format. Remove the cast to\nstore native BSON arrays. If you must keep JSON string\nstorage, use the \"json\" cast explicitly.\n```\n\nThe deprecation notice includes the name of the affected attribute and model class.\n\nTo migrate your model attributes for future versions, use one of the following options:\n\n- Remove the `array` cast (recommended). Without a cast type, MongoDB natively stores and retrieves PHP arrays as BSON arrays. The following code shows how to update your model:\n\n ```php\n // Before (deprecated in v5.8)\n protected $casts = [\n 'options' => 'array',\n ];\n\n // After: remove the cast to use native BSON storage\n protected $casts = [\n // other casts...\n ];\n ```\n\n- Replace `array` with `json` to explicitly keep JSON string storage:\n\n ```php\n protected $casts = [\n 'options' => 'json',\n ];\n ```\n\nIf a field already holds a native BSON array and the model still uses the `array` cast, the library reads it back correctly.\n\nBefore removing the `array` cast from a field, migrate any existing JSON-encoded string values in the field to native BSON arrays. The library doesn't automatically migrate existing data."} -{"chunk_id": "68a95c295e79d242619df2d7-0", "page_id": "68a95c295e79d242619df2d7", "source_name": "laravel", "product_name": "Laravel MongoDB", "url": "https://mongodb.com/docs/drivers/php/laravel-mongodb/current/feature-compatibility", "title": "Laravel Feature Compatibility", "text": "# Laravel Feature Compatibility\n\n## Overview\n\nThis guide describes the Laravel features that are supported by Laravel MongoDB. This page discusses Laravel version 12.x feature availability in the Laravel Integration.\n\nThe following sections contain tables that describe whether individual features are available in the Laravel Integration.\n\nTo learn about how MongoDB represents SQL terminology, concepts, and functionality, see the SQL to MongoDB Mapping Chart.\n\n## Database Features\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nDatabase Feature\n\n\nAvailability\n\n
\nConfiguration\n\n\n\u2713\n\n
\nRead/Write Connections\n\n\nUse read preference instead.\n\n
\nMultiple Database Connections\n\n\n\u2713\n\n
\nListening for Query Events\n\n\n\u2713\n\n
\nMonitoring Cumulative Query Time\n\n\n\u2713\n\n
\nTransactions\n\n\n\u2713 See Run a Database Transaction.\n\n
\nCommand Line Interface (CLI)\n\n\nUse the MongoDB Shell (`mongosh`).\n\n
\nDatabase Inspection\n\n\n*Unsupported*\n\n
\nDatabase Monitoring\n\n\n*Unsupported*\n\n
\nMulti-database Support / Multiple Schemas\n\n\n*Unsupported*Laravel uses a dot separator (`.`) between SQL schema and table names, but MongoDB allows `.` characters within collection names, which might lead to unexpected namespace parsing.\n\n
\nCollection and Index Name Prefixes\n\n\n*Unsupported*\n\n
\n\n## Query Features\n\nThe following Eloquent methods are not supported in the Laravel Integration:\n\n- `toSql()`\n\n- `toRawSql()`\n\n- `whereColumn()`\n\n- `orWhereColumn()`\n\n- `whereFulltext()`\n\n- `groupByRaw()`\n\n- `orderByRaw()`\n\n- `inRandomOrder()`\n\n- `union()`\n\n- `unionAll()`\n\n- `havingRaw()`\n\n- `having()`\n\n- `havingBetween()`\n\n- `orHavingRaw()`\n\n- `whereIntegerInRaw()`\n\n- `orWhereIntegerInRaw()`\n\n- `whereIntegerNotInRaw()`\n\n- `orWhereIntegerNotInRaw()`\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nQuery Feature\n\n\nAvailability\n\n
\nRunning Queries\n\n\n\u2713\n\n
\nChunking Results\n\n\n\u2713\n\n
\nAggregates\n\n\n\u2713\n\n
\nSelect Statements\n\n\n\u2713\n\n
\nRaw Expressions\n\n\n*Unsupported*\n\n
\nJoins\n\n\nUse the `$lookup` aggregation stage. To learn more, see the $lookup reference in the Server manual. Laravel MongoDB provides the Aggregation Operations to perform aggregations.\n\n
\nUnions\n\n\nUse the `$unionWith` aggregation stage. To learn more, see the $unionWith reference in the Server manual. Laravel MongoDB provides the Aggregation Operations to perform aggregations.\n\n
\nBasic Where Clauses\n\n\n\u2713\n\n
\nAdditional Where Clauses\n\n\n\u2713\n\n
\nLogical Grouping\n\n\n\u2713\n\n
\nAdvanced Where Clauses\n\n\n\u2713\n\n
\nSubquery Where Clauses\n\n\n*Unsupported*\n\n
\nOrdering\n\n\n\u2713\n\n
\nRandom Ordering\n\n\n*Unsupported*\n\n
\nGrouping\n\n\nUse the `$group` aggregation stage. To learn more, see the $group reference in the Server manual. Laravel MongoDB provides the Aggregation Operations to perform aggregations.\n\n
\nLimit and Offset\n\n\n\u2713\n\n
\nConditional Clauses\n\n\n\u2713\n\n
\nInsert Statements\n\n\n\u2713\n\n
\nAuto-Incrementing IDs\n\n\n*Unsupported as MongoDB uses ObjectIDs*\n\n
\nUpserts\n\n\n\u2713 See Upsert a Document Example.\n\n
\nUpdate Statements\n\n\n\u2713\n\n
\nUpdating JSON Columns\n\n\n*Unsupported*\n\n
\nIncrement and Decrement Values\n\n\n\u2713\n\n
\nDebugging\n\n\n\u2713\n\n
\n\n## Pagination Features\n\nThe Laravel Integration supports all Laravel pagination features.\n\n## Migration Features\n\nThe Laravel Integration supports all Laravel migration features, but the implementation is specific to MongoDB's schema-flexible model.\n\n## Seeding Features\n\nThe Laravel Integration supports all Laravel seeding features.\n\n## Eloquent Features\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nEloquent Feature\n\n\nAvailability\n\n
\nModels\n\n\n\u2713\n\n
\nUUID and ULID Keys\n\n\n\u2713\n\n
\nTimestamps\n\n\n\u2713\n\n
\nRetrieving Models\n\n\n\u2713\n\n
\nAdvanced Subqueries\n\n\n*Unsupported*\n\n
\nRetrieving or Creating Models\n\n\n\u2713\n\n
\nRetrieving Aggregates\n\n\n*Partially supported*\n\n
\nInserting and Updating Models\n\n\n\u2713\n\n
\nUpserts\n\n\n\u2713 See Update or Insert in a Single Operation.\n\n
\nDeleting Models\n\n\n\u2713\n\n
\nSoft Deleting\n\n\n\u2713\n\n
\nPruning Models\n\n\n\u2713\n\n
To learn more, see the Eloquent Model Class guide."} -{"chunk_id": "68a95c295e79d242619df2d7-1", "page_id": "68a95c295e79d242619df2d7", "source_name": "laravel", "product_name": "Laravel MongoDB", "url": "https://mongodb.com/docs/drivers/php/laravel-mongodb/current/feature-compatibility", "title": "Laravel Feature Compatibility", "text": "## Eloquent Relationship Features\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nEloquent Feature\n\n\nAvailability\n\n
\nDefining Relationships\n\n\n\u2713\n\n
\nMany-to-Many Relationships\n\n\n\u2713\n\n
\nPolymorphic Relationships\n\n\n\u2713\n\n
\nDynamic Relationships\n\n\n\u2713\n\n
\nQuerying Relations\n\n\n\u2713\n\n
\nAggregating Related Models\n\n\n\u2713\n\n
\nInserting and Updating Related Models\n\n\n\u2713\n\n
To learn more, see the Eloquent Model Relationships guide.\n\n## Eloquent Collection Features\n\nThe Laravel Integration supports all Eloquent collection features.\n\nAn Eloquent collection is a PHP class that holds a list of models, whereas a MongoDB collection stores documents in a database.\n\n## Eloquent Mutator Features\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nEloquent Feature\n\n\nAvailability\n\n
\nCasts\n\n\n\u2713\n\n
\nArray and JSON Casting\n\n\n\u2713 You can store objects and arrays in MongoDB without serializing to JSON. Starting in Laravel MongoDB v5.8, the `array` cast type is deprecated. To learn more, see Version 5.8 Deprecations.\n\n
\nDate Casting\n\n\n\u2713\n\n
\nEnum Casting\n\n\n\u2713\n\n
\nEncrypted Casting\n\n\n\u2713\n\n
\nCustom Casts\n\n\n\u2713\n\n
To learn more, see the Eloquent Model Class guide.\n\n## Eloquent Model Factory Features\n\nThe Laravel Integration supports all Eloquent factory features."} -{"chunk_id": "68a95c295e79d242619df2fc-0", "page_id": "68a95c295e79d242619df2fc", "source_name": "laravel", "product_name": "Laravel MongoDB", "url": "https://mongodb.com/docs/drivers/php/laravel-mongodb/current/issues-and-help", "title": "Issues & Help", "text": "# Issues & Help\n\nIn this guide, you can learn how to report issues, suggest new features, and contribute to the Laravel Integration.\n\nYou can find support for general questions by using the MongoDB Stack Overflow tag or the MongoDB Reddit community.\n\n## Bugs / Feature Requests\n\nIf you find a bug or want to see a new feature in the Laravel Integration, please report it as a GitHub issue in the mongodb/laravel-mongodb repository.\n\nIf you want to contribute code, see the Pull Requests section for instructions on submitting pull requests.\n\nTo report a bug or request a new feature, perform the following steps:\n\n1. Review the GitHub issues list in the source repository and search for any existing issues that address your concern.\n\n2. If you find a matching issue, you can reply to the thread to report that you have a similar issue or request.\n\n3. If you cannot find a matching issue, click New issue and select the appropriate issue type.\n\n4. If you select \"Bug report\" or \"Feature request\" as the issue type, please provide as much information as possible about the issue. Click Submit new issue to complete your submission.\n\nIf you've identified a security vulnerability in any official MongoDB product, please report it according to the instructions found in the Create a Vulnerability Report page.\n\nFor general questions and support requests, please use one of MongoDB's Technical Support channels.\n\n## Pull Requests\n\nWe are happy to accept contributions to help improve Laravel MongoDB.\n\nWe track current development in PHPORM MongoDB JIRA project.\n\nTo learn more about contributing to this project, see the CONTRIBUTING.md guide on GitHub."} -{"chunk_id": "6a514da3d727379c91b9f080-0", "page_id": "6a514da3d727379c91b9f080", "source_name": "laravel", "product_name": "Laravel MongoDB", "url": "https://mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/transactions", "title": "Run a Database Transaction", "text": "# Run a Database Transaction\n\n## Overview\n\nIn this guide, you can learn how to perform a **transaction** in MongoDB by using Laravel MongoDB. Transactions let you run a sequence of write operations that update the data only after the transaction is committed.\n\nIf the transaction fails, the MongoDB PHP Library, which manages MongoDB operations for the Laravel Integration, ensures that MongoDB discards all the changes made within the transaction before they become visible. This property of transactions that ensures that all changes within a transaction are either applied or discarded is called **atomicity**.\n\nMongoDB performs write operations on single documents atomically. If you need atomicity in write operations on multiple documents or data consistency across multiple documents for your operations, run them in a multi-document transaction.\n\nMulti-document transactions are **ACID compliant** because MongoDB guarantees that the data in your transaction operations remains consistent, even if the driver encounters unexpected errors.\n\nTo learn more about transactions in MongoDB, see Transactions in the Server manual.\n\nThis guide contains the following sections:\n\n- Requirements and Limitations\n\n- Run a Transaction in a Callback\n\n- Begin and Commit a Transaction\n\n- Roll Back a Transaction\n\nPractice using the Laravel Integration to perform transactions in the Laravel Transactions Learning Byte.\n\n## Requirements and Limitations\n\nMongoDB Server and the Laravel Integration have the following limitations:\n\n- MongoDB standalone deployments do not support transactions. To use transactions, your deployment must be a multiple node replica set or sharded cluster.\n\n- MongoDB does not support nested transactions. If you attempt to start a transaction within another one, the extension raises a `RuntimeException`. To learn more about this limitation, see Transactions and Sessions in the Server manual.\n\n- Laravel MongoDB does not support the database testing traits `Illuminate\\Foundation\\Testing\\DatabaseTransactions` and `Illuminate\\Foundation\\Testing\\RefreshDatabase`. As a workaround, you can create migrations with the `Illuminate\\Foundation\\Testing\\DatabaseMigrations` trait to reset the database after each test.\n\n- Laravel MongoDB does not support running parallel operations within a single transaction.\n\n## Run a Transaction in a Callback\n\nThis section shows how you can run a transaction in a callback.\n\nWhen using this method of running a transaction, all the code in the callback method runs as a single transaction.\n\nIn the following example, the transaction consists of write operations that transfer the funds from a bank account, represented by the `Account` model, to another account:\n\n```php\nDB::transaction(function () {\n $transferAmount = 200;\n\n $sender = Account::where('number', 223344)->first();\n $sender->balance -= $transferAmount;\n $sender->save();\n\n $receiver = Account::where('number', 776655)->first();\n $receiver->balance += $transferAmount;\n $receiver->save();\n});\n```\n\nYou can optionally pass the maximum number of times to retry a failed transaction as the second parameter, as shown in the following code example:\n\n```php\nDB::transaction(function() {\n // transaction code\n },\n attempts: 5,\n);\n```\n\n## Begin and Commit a Transaction\n\nThis section shows how to start and commit a transaction.\n\nTo use this method of starting and committing a transaction, call the `DB::beginTransaction()` method to start the transaction. Then, call the `DB::commit()` method to end the transaction, which applies all the updates performed within the transaction.\n\nIn the following example, the balance from the first account is moved to the second account, after which the first account is deleted:\n\n```php\nDB::beginTransaction();\n$oldAccount = Account::where('number', 223344)->first();\n\n$newAccount = Account::where('number', 776655)->first();\n$newAccount->balance += $oldAccount->balance;\n$newAccount->save();\n\n$oldAccount->delete();\nDB::commit();\n```\n\n## Roll Back a Transaction\n\nThis section shows how to roll back a transaction. A rollback reverts all the write operations performed within that transaction. This means that the data is reverted to its state before the transaction.\n\nTo perform the rollback, call the `DB::rollback()` function anytime before the transaction is committed.\n\nIn the following example, the transaction consists of write operations that transfer funds from one account, represented by the `Account` model, to multiple other accounts. If the sender account has insufficient funds, the transaction is rolled back, and none of the models are updated:\n\n```php\nDB::beginTransaction();\n\n$sender = Account::where('number', 223344)->first();\n$receiverA = Account::where('number', 776655)->first();\n$receiverB = Account::where('number', 990011)->first();\n\n$amountA = 100;\n$amountB = 200;\n\n$sender->balance -= $amountA;\n$receiverA->balance += $amountA;\n\n$sender->balance -= $amountB;\n$receiverB->balance += $amountB;\n\nif ($sender->balance < 0) {\n // insufficient balance, roll back the transaction\n DB::rollback();\n} else {\n DB::commit();\n}\n\n```"} -{"chunk_id": "6a514da3d727379c91b9f069-0", "page_id": "6a514da3d727379c91b9f069", "source_name": "laravel", "product_name": "Laravel MongoDB", "url": "https://mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/backend-service-tutorial", "title": "Build a Back End Service", "text": "# Build a Back End Service\n\n## Overview\n\nIn this tutorial, you create a simple REST back end for a front-end app by using Laravel MongoDB. The tutorial uses Laravel's built-in API routing features.\n\n## Prerequisites\n\nBefore you can start this tutorial, you need the following software installed in your development environment:\n\n- MongoDB Atlas cluster with sample data loaded. To learn how to create a cluster, see the Create a MongoDB Deployment step of the Quick Start guide.\n\n- PHP.\n\n- Composer.\n\n- MongoDB PHP Extension.\n\n- A terminal app and shell. For MacOS users, use Terminal or a similar app. For Windows users, use PowerShell.\n\n## Steps\n\n### Create a Laravel project.\n\nFirst, create a Laravel project directory. Then, run the following command to create a new Laravel project called `laraproject`:\n\n```bash\ncomposer create-project laravel/laravel laraproject\n```\n\n### Install Laravel MongoDB.\n\nTo check that Laravel MongoDB is running in the web server, add a webpage to your Laravel website. In your project, navigate to `/routes/web.php` and add the following route:\n\n```php\nRoute::get('/info', function () {\n phpinfo();\n});\n```\n\nThen, run the following command in your shell to start your application:\n\n```bash\nphp artisan serve\n```\n\nAfter the application begins running, navigate to http://127.0.0.1:8000/info to view the PHPinfo page. Scroll down to or search for the **mongodb** entry to verify that the MongoDB PHP Extension is installed.\n\nRun the following command in your shell to install Laravel MongoDB:\n\n```bash\ncomposer require mongodb/laravel-mongodb:^5.11\n```\n\n### Configure your MongoDB connection.\n\nOpen your project's `config/database.php` file and update the `connections` array as shown in the following code:\n\n```php\n'connections' => [\n 'mongodb' => [\n 'driver' => 'mongodb',\n 'dsn' => '',\n 'database' => 'db',\n ],\n```\n\nEnsure that you replace the connection string placeholder in the preceding code with your connection string before you run your application. To learn how to locate your connection string, see Create a Connection String in the Quick Start guide.\n\nYou can also set the default database connection. At the top of the `config/database.php` file, change 'default' to the following:\n\n```php\n'default' => 'mongodb',\n```\n\nThe Laravel application can now connect to the `db` database in your MongoDB cluster.\n\n### Create an endpoint to ping your deployment.\n\nRun the following shell command to set up API routing:\n\n```bash\nphp artisan install:api\n```\n\nIn the newly created `routes/api.php` file, add the following route:\n\n```php\n// Add the DB use statement to the top of the file.\nuse Illuminate\\Support\\Facades\\DB;\n\nRoute::get('/ping', function (Request $request) {\n $connection = DB::connection('mongodb');\n $msg = 'MongoDB is accessible!';\n try {\n $connection->command(['ping' => 1]);\n } catch (\\Exception $e) {\n $msg = 'MongoDB is not accessible. Error: ' . $e->getMessage();\n }\n return ['msg' => $msg];\n});\n```\n\nReload the application, then verify that http://127.0.0.1:8000/api/ping shows the succesful ping message.\n\n### Create Eloquent models.\n\nLaravel is integrated with Eloquent, an ORM that abstracts the database back end so that you can connect to different databases by using a common interface.\n\nEloquent provides a `Model` class to serve as the interface between your code and a specific collection. Instances of the `Model` classes represent rows of tables in relational databases. In MongoDB, they are documents in the collection.\n\nYou can define fillable fields in your Eloquent models to enforce a document schema in your application and prevent errors such as name typos. To learn more, see the Customize Mass Assignment section of the Eloquent Model Class guide.\n\nCreate an Eloquent model called `CustomerMongoDB` by running the following command from the project root:\n\n```bash\nphp artisan make:model CustomerMongoDB\n```\n\nLaravel creates the `CustomerMongoDB` class in the `/models` directory. By default, models use the `default` database connection, but you can specify which connection to use by adding the `$connection` member to the class. You can also specify the collection name by adding the `$collection` member.\n\nEnsure you include the `use` statement for the MongoDB Eloquent model. This is necessary to set `_id` as the primary key.\n\nReplace the contents of the `CustomerMongoDB.php` file with the following code:\n\n```php\nuse MongoDB\\Laravel\\Eloquent\\Model;\n\nclass CustomerMongoDB extends Model\n{\n // the selected database as defined in /config/database.php\n protected $connection = 'mongodb';\n\n // equivalent to $table for MySQL\n protected $collection = 'laracoll';\n\n // defines the schema for top-level properties (optional).\n protected $fillable = ['guid', 'first_name', 'family_name', 'email', 'address'];\n}\n```\n\n### Perform CRUD operations.\n\nAfter you create your models, you can perform data operations.\n\nCreate the following route in your `api.php` file:\n\n```php\nRoute::get('/create_eloquent_mongo/', function (Request $request) {\n $success = CustomerMongoDB::create([\n 'guid'=> 'cust_1111',\n 'first_name'=> 'John',\n 'family_name' => 'Doe',\n 'email' => 'j.doe@gmail.com',\n 'address' => '123 my street, my city, zip, state, country'\n ]);\n});\n```\n\nAfter you insert the document, you can retrieve it by using the `where()` method as shown in the following code:\n\n```php\nRoute::get('/find_eloquent/', function (Request $request) {\n $customer = CustomerMongoDB::where('guid', 'cust_1111')->get();\n});\n```\n\nEloquent allows you to find data by using complex queries with multiple matching conditions.\n\nYou can also update and delete data shown in the following routes:\n\n```php\nRoute::get('/update_eloquent/', function (Request $request) {\n $result = CustomerMongoDB::where('guid', 'cust_1111')->update( ['first_name' => 'Jimmy'] );\n});\n\nRoute::get('/delete_eloquent/', function (Request $request) {\n $result = CustomerMongoDB::where('guid', 'cust_1111')->delete();\n});\n```\n\nAt this point, your MongoDB-connected back-end service is running, but MongoDB provides more functionality to support your operations."} -{"chunk_id": "6a514da3d727379c91b9f069-1", "page_id": "6a514da3d727379c91b9f069", "source_name": "laravel", "product_name": "Laravel MongoDB", "url": "https://mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/backend-service-tutorial", "title": "Build a Back End Service", "text": "### Perform operations on nested data.\n\nLaravel MongoDB offers MongoDB-specific operations for nested data. However, adding nested data is also intuitive without using the `embedsMany()` and `embedsOne()` methods.\n\nAs shown in the preceding step, you can define top-level schema attributes. However, it is more complicated when to define these attribute if your documents include arrays and embedded documents.\n\nYou can create the model's data structures in PHP. In the following example, the `address` field is an object type. The `email` field is an array of strings:\n\n```php\nRoute::get('/create_nested/', function (Request $request) {\n $message = \"executed\";\n $success = null;\n\n $address = new stdClass;\n $address->street = '123 my street name';\n $address->city = 'my city';\n $address->zip= '12345';\n $emails = ['j.doe@gmail.com', 'j.doe@work.com'];\n\n try {\n $customer = new CustomerMongoDB();\n $customer->guid = 'cust_2222';\n $customer->first_name = 'John';\n $customer->family_name= 'Doe';\n $customer->email= $emails;\n $customer->address= $address;\n $success = $customer->save(); // save() returns 1 or 0\n }\n catch (\\Exception $e) {\n $message = $e->getMessage();\n }\n return ['msg' => $message, 'data' => $success];\n});\n```\n\nWhen you access the `/api/create_nested/` endpoint, it creates a document in MongoDB:\n\n```json\n{\n \"_id\": {...},\n \"guid\": \"cust_2222\",\n \"first_name\": \"John\",\n \"family_name\": \"Doe\",\n \"email\": [\n \"j.doe@gmail.com\",\n \"j.doe@work.com\"\n ],\n \"address\": {\n \"street\": \"123 my street name\",\n \"city\": \"my city\",\n \"zip\": \"12345\"\n },\n \"updated_at\": {\n \"$date\": \"2025-05-27T17:38:28.793Z\"\n },\n \"created_at\": {\n \"$date\": \"2025-05-27T17:38:28.793Z\"\n }\n}\n```\n\n### Use the MongoDB Query API.\n\nMongoDB provides the Query API for optimized queries.\n\nYou can begin to build a query by using a `collection` object. Eloquent exposes the full capabilities of the underlying database by using \"raw queries,\" which Laravel sends to the database without any processing from the Eloquent Query Builder.\n\nYou can perform a raw native MongoDB query from the model as shown in the following code:\n\n```php\n$mongodbquery = ['guid' => 'cust_1111'];\n\n// returns a \"Illuminate\\Database\\Eloquent\\Collection\" Object\n$results = CustomerMongoDB::whereRaw( $mongodbquery )->get();\n```\n\nYou can also access the native MongoDB collection object and perform a query that returns objects such as native MongoDB documents or cursors:\n\n```php\n$mongodbquery = ['guid' => 'cust_1111', ];\n$mongodb_native_collection = DB::connection('mongodb')->getCollection('laracoll');\n$document = $mongodb_native_collection->findOne( $mongodbquery );\n$cursor = $mongodb_native_collection->find( $mongodbquery );\n```\n\nThe following code demonstrates multiple ways to perform queries:\n\n```php\nRoute::get('/find_native/', function (Request $request) {\n // a simple MongoDB query that looks for a customer based on the guid\n $mongodbquery = ['guid' => 'cust_2222'];\n\n // Option #1\n // =========\n // use Eloquent's whereRaw() function\n // returns a \"Illuminate\\Database\\Eloquent\\Collection\" Object\n\n $results = CustomerMongoDB::whereRaw( $mongodbquery )->get();\n\n // Option #2 & #3\n // ==============\n // use the native MongoDB driver Collection object and the Query API\n\n $mdb_collection = DB::connection('mongodb')->getCollection('laracoll');\n\n // find the first document that matches the query\n $mdb_bsondoc = $mdb_collection->findOne( $mongodbquery ); // returns a \"MongoDB\\Model\\BSONDocument\" Object\n\n // to convert the MongoDB Document to a Laravel Model, use the Model's newFromBuilder() method\n $cust = new CustomerMongoDB();\n $one_doc = $cust->newFromBuilder((array) $mdb_bsondoc);\n\n // find all documents because you pass an empty query\n $mdb_cursor = $mdb_collection->find(); // returns a \"MongoDB\\Driver\\Cursor\" object\n $cust_array = array();\n foreach ($mdb_cursor->toArray() as $bson) {\n $cust_array[] = $cust->newFromBuilder( $bson );\n }\n\n return ['msg' => 'executed', 'whereraw' => $results, 'document' => $one_doc, 'cursor_array' => $cust_array];\n});\n```\n\nThe following code demonstrates how to use the `updateOne()` method to update documents:\n\n```php\nRoute::get('/update_native/', function (Request $request) {\n $mdb_collection = DB::connection('mongodb')->getCollection('laracoll');\n $match = ['guid' => 'cust_2222'];\n $update = ['$set' => ['first_name' => 'Henry', 'address.street' => '777 new street name'] ];\n $result = $mdb_collection->updateOne($match, $update );\n return ['msg' => 'executed', 'matched_docs' => $result->getMatchedCount(), 'modified_docs' => $result->getModifiedCount()];\n});\n```\n\nThe following code demonstrates how to use the `deleteOne()` method to delete documents:\n\n```php\nRoute::get('/delete_native/', function (Request $request) {\n $mdb_collection = DB::connection('mongodb')->getCollection('laracoll');\n $match = ['guid' => 'cust_2222'];\n $result = $mdb_collection->deleteOne($match );\n return ['msg' => 'executed', 'deleted_docs' =>\n $result->getDeletedCount() ];\n});\n```\n\nTo learn more about how to perform CRUD operations, see the Insert Documents and Query Documents guides.\n\n### Use the aggregation framework.\n\nAn aggregation pipeline is a task in MongoDB's aggregation framework. You can use the aggregation framework to perform various tasks such as real-time dashboards and big data analysis.\n\nAn aggregation pipeline consists of multiple stages in which the output of each stage is the input of the following stage. This step uses the `sample_mflix` from the Atlas sample datasets. Laravel allows you to access multiple MongoDB databases in the same app, so add the `sample_mflix` database connection to `database.php`:\n\n```php\n'mongodb_mflix' => [\n 'driver' => 'mongodb',\n 'dsn' => env('DB_URI'),\n 'database' => 'sample_mflix',\n ],\n```\n\nNext, create the `/aggregate/` API endpoint and define an aggregation pipeline to retrieve data from the `movies` collection, compute the average movie rating for each genre, and return a list.\n\n```php\nRoute::get('/aggregate/', function (Request $request) {\n $mdb_collection = DB::connection('mongodb_mflix')->getCollection('movies');\n\n $stage0 = ['$unwind' => ['path' => '$genres']];\n $stage1 = ['$group' => ['_id' => '$genres', 'averageGenreRating' => ['$avg' => '$imdb.rating']]];\n $stage2 = ['$sort' => ['averageGenreRating' => -1]];\n $aggregation = [$stage0, $stage1, $stage2];\n\n $mdb_cursor = $mdb_collection->aggregate( $aggregation );\n\n return ['msg' => 'executed', 'data' => $mdb_cursor->toArray() ];\n});\n```\n\nLaravel MongoDB provides the Aggregation Operations to build type-safe aggregation pipelines directly from your models. We recommend using the aggregation builder to perform aggregations.\n\n### Use indexes to optimize query performance.\n\nYou can create indexes to support your queries and improve performance. To learn more about how to create indexes programmatically, see the Manage Indexes section of the Schema Builder guide.\n\n## Conclusion\n\nIn this tutorial, you learned how to create a back-end service by using Laravel and MongoDB for a front-end web application. This tutorial also showed how you can use the document model to improve database efficiency and scalability. You can use the document model with the MongoDB Query API to create better apps with less downtime.\n\nYou can access the full code for this tutorial in the laravel-mongodb-tutorial repository on GitHub.\n\nNavigate through the rest of the Laravel MongoDB documentation to learn more about Laravel MongoDB's features."} -{"chunk_id": "6a514da3d727379c91b9f06b-0", "page_id": "6a514da3d727379c91b9f06b", "source_name": "laravel", "product_name": "Laravel MongoDB", "url": "https://mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/aggregation-builder", "title": "Aggregation Operations", "text": "# Aggregation Operations\n\n## Overview\n\nIn this guide, you can learn how to perform aggregations and construct pipelines by using the Laravel Integration aggregation builder. The aggregation builder lets you use a type-safe syntax to construct a MongoDB **aggregation pipeline**.\n\nAn aggregation pipeline is a data processing pipeline that sequentially performs transformations and computations on data from the MongoDB database, then outputs the results as a new document or set of documents.\n\nAn aggregation pipeline is composed of **aggregation stages**. Aggregation stages use operators to process input data and produce data that the next stage uses as its input.\n\nThe Laravel MongoDB aggregation builder lets you build aggregation stages and aggregation pipelines. The following sections show examples of how to use the aggregation builder to create the stages of an aggregation pipeline:\n\n- Create Aggregation Stages\n\n- Build Aggregation Pipelines\n\n- Create a Custom Operator Factory\n\nThe aggregation builder feature is available only in Laravel MongoDB versions 4.3 and later. To learn more about running aggregations without using the aggregation builder, see Aggregations in the Query Builder guide.\n\n## Create Aggregation Stages\n\nTo start an aggregation pipeline, call the `Model::aggregate()` method. Then, chain aggregation stage methods and specify the necessary parameters for the stage. For example, you can call the `sort()` operator method to build a `$sort` stage.\n\nThe aggregation builder includes the following namespaces that you can import to build aggregation stages:\n\n- `MongoDB\\Builder\\Accumulator`\n\n- `MongoDB\\Builder\\Expression`\n\n- `MongoDB\\Builder\\Query`\n\n- `MongoDB\\Builder\\Type`\n\nThis section features the following examples that show how to use common aggregation stages:\n\n- Match Stage Example\n\n- Group Stage Example\n\n- Sort Stage Example\n\n- Project Stage Example\n\nTo learn more about MongoDB aggregation operators, see Aggregation Stages in the Server manual.\n\n### Sample Documents\n\nThe following examples run aggregation pipelines on a collection represented by the `User` model. You can add the sample data by running the following `insert()` method:\n\n```php\nUser::insert([\n ['name' => 'Alda Gr\u00f6ndal', 'occupation' => 'engineer', 'birthday' => new UTCDateTime(new DateTimeImmutable('2002-01-01'))],\n ['name' => 'Francois Soma', 'occupation' => 'engineer', 'birthday' => new UTCDateTime(new DateTimeImmutable('1998-02-02'))],\n ['name' => 'Janet Doe', 'occupation' => 'designer', 'birthday' => new UTCDateTime(new DateTimeImmutable('1987-03-03'))],\n ['name' => 'Eliud Nkosana', 'occupation' => 'engineer', 'birthday' => new UTCDateTime(new DateTimeImmutable('1984-04-04'))],\n ['name' => 'Bran Steafan', 'occupation' => 'engineer', 'birthday' => new UTCDateTime(new DateTimeImmutable('1998-05-05'))],\n ['name' => 'Ellis Lee', 'occupation' => 'designer', 'birthday' => new UTCDateTime(new DateTimeImmutable('1996-06-06'))],\n]);\n```\n\n### Match Stage Example\n\nYou can chain the `match()` method to your aggregation pipeline to specify a query filter. If you omit this stage, the `aggregate()` method outputs all the documents in the model's collection for the following stage.\n\nThis aggregation stage is often placed first to retrieve the data by using available indexes and reduce the amount of data the subsequent stages process.\n\nIf you omit the `match()` method, the aggregation pipeline matches all documents in the collection that correspond to the model before other aggregation stages.\n\nThis example constructs a query filter for a **match** aggregation stage by using the `MongoDB\\Builder\\Query` builder. The match stage includes the following criteria:\n\n- Returns results that match either of the query filters by using the `Query::or()` function\n\n- Matches documents that contain an `occupation` field with a value of `\"designer\"` by using the `Query::query()` and `Query::eq()` functions\n\n- Matches documents that contain a `name` field with a value of `\"Eliud Nkosana\"` by using the `Query::query()` and `Query::eq()` functions\n\nClick the VIEW OUTPUT button to see the documents returned by running the code:\n\n```php\n$pipeline = User::aggregate()\n ->match(Query::or(\n Query::query(occupation: Query::eq('designer')),\n Query::query(name: Query::eq('Eliud Nkosana')),\n ));\n$result = $pipeline->get();\n```\n\n```json\n[\n {\n \"_id\": ...,\n \"name\": \"Janet Doe\",\n \"occupation\": \"designer\",\n \"birthday\": {\n \"$date\": {\n \"$numberLong\": \"541728000000\"\n }\n }\n },\n {\n \"_id\": ...,\n \"name\": \"Eliud Nkosana\",\n \"occupation\": \"engineer\",\n \"birthday\": {\n \"$date\": {\n \"$numberLong\": \"449884800000\"\n }\n }\n },\n {\n \"_id\": ...,\n \"name\": \"Ellis Lee\",\n \"occupation\": \"designer\",\n \"birthday\": {\n \"$date\": {\n \"$numberLong\": \"834019200000\"\n }\n }\n }\n]\n```\n\nThe `Query::or()` function corresponds to the `$or` MongoDB query operator. To learn more about this operator, see $or in the Server manual.\n\n### Group Stage Example\n\nYou can chain the `group()` method to your aggregation pipeline to modify the structure of the data by performing calculations and grouping it by common field values.\n\nThis aggregation stage is often placed immediately after a match stage to reduce the data subsequent stages process.\n\nThis example uses the `MongoDB\\Builder\\Expression` builder to define the group keys in a **group** aggregation stage. The group stage specifies the following grouping behavior:\n\n- Sets the value of the group key, represented by the `_id` field, to the field value defined by the `Expression` builder\n\n- References the document values in the `occupation` field by calling the `Expression::fieldPath()` function\n\nClick the VIEW OUTPUT button to see the documents returned by running the code:\n\n```php\n$pipeline = User::aggregate()\n ->group(_id: Expression::fieldPath('occupation'));\n$result = $pipeline->get();\n```\n\n```json\n[\n { \"_id\": \"engineer\" },\n { \"_id\": \"designer\" }\n]\n```\n\nThis example stage performs a similar task as the `distinct()` query builder method. To learn more about the `distinct()` method, see the Retrieve Distinct Field Values usage example."} -{"chunk_id": "6a514da3d727379c91b9f06b-1", "page_id": "6a514da3d727379c91b9f06b", "source_name": "laravel", "product_name": "Laravel MongoDB", "url": "https://mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/aggregation-builder", "title": "Aggregation Operations", "text": "### Sort Stage Example\n\nYou can chain the `sort()` method to your aggregation pipeline to specify the documents' output order.\n\nYou can add this aggregation stage anywhere in the pipeline. It is often placed after the group stage since it can depend on the grouped data. We recommend placing the sort stage as late as possible in the pipeline to limit the data it processes.\n\nTo specify an sort, set the field value to the `Sort::Asc` enum for an ascending sort or the `Sort::Desc` enum for a descending sort.\n\nThis example shows a `sort()` aggregation pipeline stage that sorts the documents by the `name` field to `Sort::Desc`, corresponding to reverse alphabetical order. Click the VIEW OUTPUT button to see the documents returned by running the code:\n\n```php\n$pipeline = User::aggregate()\n ->sort(name: Sort::Desc);\n$result = $pipeline->get();\n```\n\n```json\n[\n {\n \"_id\": ...,\n \"name\": \"Janet Doe\",\n \"occupation\": \"designer\",\n \"birthday\": {\n \"$date\": {\n \"$numberLong\": \"541728000000\"\n }\n }\n },\n {\n \"_id\": ...,\n \"name\": \"Francois Soma\",\n \"occupation\": \"engineer\",\n \"birthday\": {\n \"$date\": {\n \"$numberLong\": \"886377600000\"\n }\n }\n },\n {\n \"_id\": ...,\n \"name\": \"Ellis Lee\",\n \"occupation\": \"designer\",\n \"birthday\": {\n \"$date\": {\n \"$numberLong\": \"834019200000\"\n }\n }\n },\n {\n \"_id\": ...,\n \"name\": \"Eliud Nkosana\",\n \"occupation\": \"engineer\",\n \"birthday\": {\n \"$date\": {\n \"$numberLong\": \"449884800000\"\n }\n }\n },\n {\n \"_id\": ...,\n \"name\": \"Bran Steafan\",\n \"occupation\": \"engineer\",\n \"birthday\": {\n \"$date\": {\n \"$numberLong\": \"894326400000\"\n }\n }\n },\n {\n \"_id\": ...,\n \"name\": \"Alda Gr\u00f6ndal\",\n \"occupation\": \"engineer\",\n \"birthday\": {\n \"$date\": {\n \"$numberLong\": \"1009843200000\"\n }\n }\n }\n]\n```\n\n### Project Stage Example\n\nYou can chain the `project()` method to your aggregation pipeline to specify which fields from the documents to display by this stage.\n\nTo specify fields to include, pass the name of a field and a truthy value, such as `1` or `true`. All other fields are omitted from the output.\n\nAlternatively, to specify fields to exclude, pass each field name and a falsy value, such as `0` or `false`. All other fields are included in the output.\n\nWhen you specify fields to include, the `_id` field is included by default. To exclude the `_id` field, explicitly exclude it in the projection stage.\n\nThis example shows how to use the `project()` method aggregation stage to include only the `name` field and exclude all other fields from the output. Click the VIEW OUTPUT button to see the data returned by running the code:\n\n```php\n$pipeline = User::aggregate()\n ->project(_id: 0, name: 1);\n$result = $pipeline->get();\n```\n\n```json\n[\n { \"name\": \"Alda Gr\u00f6ndal\" },\n { \"name\": \"Francois Soma\" },\n { \"name\": \"Janet Doe\" },\n { \"name\": \"Eliud Nkosana\" },\n { \"name\": \"Bran Steafan\" },\n { \"name\": \"Ellis Lee\" }\n]\n```\n\n## Build Aggregation Pipelines\n\nTo build an aggregation pipeline, call the `Model::aggregate()` method, then chain the aggregation stages in the sequence you want them to run. The examples in this section are adapted from the Server manual. Each example provides a link to the sample data that you can insert into your database to test the aggregation operation.\n\nThis section features the following examples, which show how to use common aggregation stages:\n\n- Filter and Group Example\n\n- Unwind Embedded Arrays Example\n\n- Single Equality Join Example\n\n### Filter and Group Example\n\nThis example uses the sample data given in the Calculate Count, Sum, and Average section of the `$group` stage reference in the Server manual.\n\nThe following code example calculates the total sales amount, average sales quantity, and sale count for each day in the year 2014. To do so, it uses an aggregation pipeline that contains the following stages:\n\n1. $match stage to filter for documents that contain a `date` field in which the year is 2014\n\n2. $group stage to group the documents by date and calculate the total sales amount, average sales quantity, and sale count for each group\n\n3. $sort stage to sort the results by the total sale amount for each group in descending order\n\nClick the VIEW OUTPUT button to see the data returned by running the code:\n\n```php\n$pipeline = Sale::aggregate()\n ->match(\n date: [\n Query::gte(new UTCDateTime(new DateTimeImmutable('2014-01-01'))),\n Query::lt(new UTCDateTime(new DateTimeImmutable('2015-01-01'))),\n ],\n )\n ->group(\n _id: Expression::dateToString(Expression::dateFieldPath('date'), '%Y-%m-%d'),\n totalSaleAmount: Accumulator::sum(\n Expression::multiply(\n Expression::numberFieldPath('price'),\n Expression::numberFieldPath('quantity'),\n ),\n ),\n averageQuantity: Accumulator::avg(\n Expression::numberFieldPath('quantity'),\n ),\n count: Accumulator::sum(1),\n )\n ->sort(\n totalSaleAmount: Sort::Desc,\n );\n```\n\n```json\n[\n { \"_id\": \"2014-04-04\", \"totalSaleAmount\": { \"$numberDecimal\": \"200\" }, \"averageQuantity\": 15, \"count\": 2 },\n { \"_id\": \"2014-03-15\", \"totalSaleAmount\": { \"$numberDecimal\": \"50\" }, \"averageQuantity\": 10, \"count\": 1 },\n { \"_id\": \"2014-03-01\", \"totalSaleAmount\": { \"$numberDecimal\": \"40\" }, \"averageQuantity\": 1.5, \"count\": 2 }\n]\n```\n\n### Unwind Embedded Arrays Example\n\nThis example uses the sample data given in the Unwind Embedded Arrays section of the `$unwind` stage reference in the Server manual.\n\nThe following code example groups sold items by their tags and calculates the total sales amount for each tag. To do so, it uses an aggregation pipeline that contains the following stages:\n\n1. $unwind stage to output a separate document for each element in the `items` array\n\n2. $unwind stage to output a separate document for each element in the `items.tags` arrays\n\n3. $group stage to group the documents by the tag value and calculate the total sales amount of items that have each tag\n\nClick the VIEW OUTPUT button to see the data returned by running the code:\n\n```php\n$pipeline = Sale::aggregate()\n ->unwind(Expression::arrayFieldPath('items'))\n ->unwind(Expression::arrayFieldPath('items.tags'))\n ->group(\n _id: Expression::fieldPath('items.tags'),\n totalSalesAmount: Accumulator::sum(\n Expression::multiply(\n Expression::numberFieldPath('items.price'),\n Expression::numberFieldPath('items.quantity'),\n ),\n ),\n );\n```\n\n```json\n[\n { \"_id\": \"school\", \"totalSalesAmount\": { \"$numberDecimal\": \"104.85\" } },\n { \"_id\": \"electronics\", \"totalSalesAmount\": { \"$numberDecimal\": \"800.00\" } },\n { \"_id\": \"writing\", \"totalSalesAmount\": { \"$numberDecimal\": \"60.00\" } },\n { \"_id\": \"office\", \"totalSalesAmount\": { \"$numberDecimal\": \"1019.60\" } },\n { \"_id\": \"stationary\", \"totalSalesAmount\": { \"$numberDecimal\": \"264.45\" } }\n]\n```"} -{"chunk_id": "6a514da3d727379c91b9f06b-2", "page_id": "6a514da3d727379c91b9f06b", "source_name": "laravel", "product_name": "Laravel MongoDB", "url": "https://mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/aggregation-builder", "title": "Aggregation Operations", "text": "### Single Equality Join Example\n\nThis example uses the sample data given in the Perform a Single Equality Join with $lookup section of the `$lookup` stage reference in the Server manual.\n\nThe following code example joins the documents from the `orders` collection with the documents from the `inventory` collection by using the `item` field from the `orders` collection and the `sku` field from the `inventory` collection.\n\nTo do so, the example uses an aggregation pipeline that contains a $lookup stage that specifies the collection to retrieve data from and the local and foreign field names.\n\nClick the VIEW OUTPUT button to see the data returned by running the code:\n\n```php\n$pipeline = Order::aggregate()\n ->lookup(\n from: 'inventory',\n localField: 'item',\n foreignField: 'sku',\n as: 'inventory_docs',\n );\n```\n\n```json\n[\n { \"_id\": 1, \"item\": \"almonds\", \"price\": 12, \"quantity\": 2, \"inventory_docs\": [\n { \"_id\": 1, \"sku\": \"almonds\", \"description\": \"product 1\", \"instock\": 120 }\n ] },\n { \"_id\": 2, \"item\": \"pecans\", \"price\": 20, \"quantity\": 1, \"inventory_docs\": [\n { \"_id\": 4, \"sku\": \"pecans\", \"description\": \"product 4\", \"instock\": 70 }\n ] },\n { \"_id\": 3, \"inventory_docs\": [\n { \"_id\": 5, \"sku\": null, \"description\": \"Incomplete\" },\n { \"_id\": 6 }\n ] }\n]\n```\n\n## Create a Custom Operator Factory\n\nWhen using the aggregation builder to create an aggregation pipeline, you can define operations or stages in a **custom operator factory**. A custom operator factory is a function that returns expressions or stages of an aggregation pipeline. You can create these functions to improve code readability and reuse.\n\nThis example shows how to create and use a custom operator factory that returns expressions that extract the year from a specified date field.\n\nThe following function accepts the name of a field that contains a date and returns an expression that extracts the year from the date:\n\n```php\npublic function yearFromField(string $dateFieldName): YearOperator\n{\n return Expression::year(\n Expression::dateFieldPath($dateFieldName),\n );\n}\n```\n\nThe example aggregation pipeline includes the following stages:\n\n- `addFields()`, which calls the custom operator factory function to extract the year from the `birthday` field and assign it to the `birth_year` field\n\n- `project()`, which includes only the `name` and `birth_year` fields in its output\n\nClick the VIEW OUTPUT button to see the data returned by running the code:\n\n```php\n$pipeline = User::aggregate()\n ->addFields(birth_year: $this->yearFromField('birthday'))\n ->project(_id: 0, name: 1, birth_year: 1);\n```\n\n```json\n[\n {\n \"name\": \"Alda Gr\u00f6ndal\",\n \"birth_year\": 2002\n },\n {\n \"name\": \"Francois Soma\",\n \"birth_year\": 1998\n },\n {\n \"name\": \"Janet Doe\",\n \"birth_year\": 1987\n },\n {\n \"name\": \"Eliud Nkosana\",\n \"birth_year\": 1984\n },\n {\n \"name\": \"Bran Steafan\",\n \"birth_year\": 1998\n },\n {\n \"name\": \"Ellis Lee\",\n \"birth_year\": 1996\n }\n]\n```"} -{"chunk_id": "68a95c105e79d242619db67d-0", "page_id": "68a95c105e79d242619db67d", "source_name": "mck", "product_name": "MongoDB Controllers for Kubernetes", "url": "https://mongodb.com/docs/kubernetes/current/multi-cluster-no-service-mesh-deploy-rs", "title": "Deploy Multi-Cluster Replica Sets Without a Service Mesh", "text": "# Deploy Multi-Cluster Replica Sets Without a Service Mesh\n\nUse this procedure to deploy a replica set in a multi-Kubernetes cluster MongoDB deployment without using a service mesh for establishing external connectivity between member Kubernetes clusters.\n\nAs an alternative to using this procedure, you can use the Multi-Kubernetes-Cluster Quick Start, which uses a service mesh.\n\n## Before You Begin\n\n- Learn about multi-Kubernetes-cluster deployments.\n\n- Review the list of multi-Kubernetes-cluster services and tools.\n\n- Complete the prerequisites, but don't set up a service mesh. Instead, decide whether you need a service mesh. If you choose to deploy without a service mesh, use external domains and configure DNS to enable external connectivity.\n\n- As part of completing the prerequisites, generate valid certificates for TLS (Transport Layer Security) encryption. To learn more, see Prepare for TLS-Encrypted Connections.\n\n- Deploy the Ops Manager resources.\n\n- Install the Kubernetes Operator in a multi-Kubernetes cluster MongoDB deployment. See Multi-Kubernetes-Cluster Quick Start.\n\n## Overview\n\nIn a multi-Kubernetes cluster MongoDB deployment without a service mesh, use the following `MongoDBMultiCluster` resource settings:\n\n- Use the spec.clusterSpecList.externalAccess.externalService setting so that the Kubernetes Operator creates an external service, and as part of its default configuration, configures a load balancer with default settings. Configure the load balancer to serve as the TCP proxy with a TLS (Transport Layer Security) passthrough (no TLS termination in the load balancer).\n\n- Customize external services that the Kubernetes Operator creates for each Pod in the Kubernetes cluster. Use the global \"all-clusters\" configuration in the spec.externalAccess settings and Kubernetes cluster-specific overrides in the spec.clusterSpecList.externalAccess.externalService settings.\n\n- Specify cloud provider-specific annotations for the load balancer in the spec.clusterSpecList.externalAccess.externalService.annotations for each Kubernetes cluster.\n\n- Specify an external domain in spec.clusterSpecList.externalAccess.externalDomain. This allows the Kubernetes Operator to register `mongod` processes by using the domain suffix. This enables external connections to the `mongod` processes in a multi-Kubernetes cluster MongoDB deployment.\n\n## Deploy a `MongoDBMultiCluster` Resource without a Service Mesh\n\nThe following procedure establishes TLS (Transport Layer Security)-encrypted connections between MongoDB hosts in a replica set, and between client applications and MongoDB deployments.\n\n### Create the secret for the TLS certificate of your `MongoDBMultiCluster` resource.\n\nRun the `kubectl` command to create a new secret that stores the `MongoDBMultiCluster` resource certificate:\n\n```sh\nkubectl --context $MDB_CENTRAL_CLUSTER_FULL_NAME \\\n --namespace= \\\n create secret tls --cert \\\n --cert= \\\n --key=\n```\n\nYou must prefix your secrets with `-`.\n\nFor example, if you call your deployment `my-deployment` and you set the prefix to `mdb`, you must name the TLS (Transport Layer Security) secret for the client TLS (Transport Layer Security) communications `mdb-my-deployment-cert`. Also, you must name the TLS (Transport Layer Security) secret for internal cluster authentication (if enabled) `mdb-my-deployment-clusterfile`.\n\n### Create the ConfigMap to link your CA with your `MongoDBMultiCluster` resource.\n\nRun the `kubectl` command to link your CA (Certificate Authority) to your `MongoDBMultiCluster` resource. Specify the CA (Certificate Authority) certificate file that you must always name `ca-pem` for the `MongoDBMultiCluster` resource:\n\n```sh\nkubectl --context $MDB_CENTRAL_CLUSTER_FULL_NAME \\\n --namespace= \\\n create configmap custom-ca -from-file=ca-pem=\n```\n\n### Configure `kubectl` to use the central cluster's namespace.\n\nIf you have not done so already, run the following commands to run all `kubectl` commands on the central cluster in the default namespace.\n\n```sh\nkubectl config use-context $MDB_CENTRAL_CLUSTER_FULL_NAME\nkubectl config set-context $(kubectl config current-context) \\\n --namespace=mongodb\n```\n\n### Copy and paste the sample resource.\n\n- Copy the sample replica set YAML (Yet Another Markup Language) file and paste it into a new text file.\n\n- Change the file's settings to match your desired replica set configuration.\n\n```yaml\n# Provides statefulSet override per cluster\n\napiVersion: mongodb.com/v1\nkind: MongoDBMultiCluster\nmetadata:\n name: multi-replica-set\nspec:\n version: 8.0.0\n type: ReplicaSet\n credentials: my-credentials\n opsManager:\n configMapRef:\n name: my-project\n externalAccess:\n externalService:\n annotations:\n # Global cloud-specific annotations added to external services in all clusters\n spec:\n # ServiceSpec attributes to override in external services in all clusters\n clusterSpecList:\n - clusterName: cluster1.example.com\n members: 2\n externalAccess:\n # Domain suffix that mongod processes will use in cluster1\n externalDomain: cluster1.example.com\n externalService:\n annotations:\n # Cloud-specific annotations for external services\n spec:\n # ServiceSpec attributes to override if necessary\n - clusterName: cluster2.example.com\n members: 1\n externalAccess:\n # Domain suffix that mongod processes will use in cluster2\n externalDomain: cluster2.example.com\n externalService:\n annotations:\n # Cloud-specific annotations for external services\n spec:\n # ServiceSpec attributes to override if necessary\n - clusterName: cluster3.example.com\n members: 1\n externalAccess:\n # Domain suffix that mongod processes will use in cluster3\n externalDomain: cluster3.example.com\n externalService:\n annotations:\n # Cloud-specific annotations for external services\n spec:\n # ServiceSpec attributes to override if necessary\n\n...\n\n```\n\n### Define external connectivity settings.\n\nSpecify global values that affect all clusters in a multi-Kubernetes cluster MongoDB deployment using the spec.externalAccess settings and cluster-specific overrides using the spec.clusterSpecList.externalAccess.externalService settings.\n\nWhen you provide these settings in the `MongoDBMultiCluster` resource specification, the Kubernetes Operator creates external services for each Pod in all Kubernetes clusters. You then use these services to establish external connectivity to all `mongod` processes in your deployment.\n\n### Define an external domain for each Kubernetes member cluster.\n\nDefine an external domain for each member cluster using the spec.clusterSpecList.externalAccess.externalDomain setting.\n\nAs a result, the Kubernetes Operator registers all `mongod` processes in the Kubernetes member cluster under a hostname according to the following convention:\n\n```sh\n.\n```\n\nFor example, a `mongod` process may have the following hostname: `my-replica-set-0-0.cluster-1.example.com`."} -{"chunk_id": "68a95c105e79d242619db67d-1", "page_id": "68a95c105e79d242619db67d", "source_name": "mck", "product_name": "MongoDB Controllers for Kubernetes", "url": "https://mongodb.com/docs/kubernetes/current/multi-cluster-no-service-mesh-deploy-rs", "title": "Deploy Multi-Cluster Replica Sets Without a Service Mesh", "text": "### Change the settings to your preferred values.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nKey\n\n\nType\n\n\nDescription\n\n\nExample\n\n
\n`metadata.name`\n\n\nstring\n\n\nLabel for the `MongoDBMultiCluster` resource.\n\nResource names must be 44 characters or less.\n\nSee also `metadata.name` and names in the Kubernetes documentation.\n\n\n`multi-replica-set`\n\n
\n`spec.version`\n\n\nstring\n\n\nVersion of MongoDB that this `MongoDBMultiCluster` resource should run.\n\nThe format should be `X.Y.Z` for the Community edition and `X.Y.Z-ent` for the Enterprise edition.\n\nIMPORTANT: Ensure that you choose a compatible MongoDB Server version. Compatible versions differ depending on the base image that the MongoDB database resource uses.\n\nTo learn more about MongoDB versioning, see MongoDB Versioning in the MongoDB Manual.\n\n\n`8.0.0`\n\n
\n`spec``.opsManager``.configMapRef``.name`\n\n\nstring\n\n\nName of the ConfigMap with the Ops Manager connection configuration. The `spec.cloudManager.configMapRef.name` setting is an alias for this setting and can be used in its place.\n\nThis value must exist on the *same* namespace as the resource you want to create.\n\nIMPORTANT: The Kubernetes Operator tracks any changes to the ConfigMap and reconciles the state of the `MongoDB` resource.\n\n\n``\n\n
\n`spec``.clusterSpecList``.clusterName`\n\n\nstring\n\n\nName of the cluster in the `MongoDBMultiCluster` resource.\n\n\n`cluster1.example.com`\n\n
\n`spec``.clusterSpecList``.members`\n\n\ninteger\n\n\nThe number of members in this cluster.\n\n\n`2`\n\n
\n`spec``.clusterSpecList``.statefulSet``.spec`\n\n\ncollection\n\n\n*Optional.*\n\nProvides the configuration for the StatefulSet override for each of the cluster's StatefulSets in a multi-Kubernetes cluster MongoDB deployment. If specified at an individual cluster level under `clusterSpecList`, overrides the global configuration for the StatefulSet for the entire multi-Kubernetes cluster MongoDB deployment. See Multi-Kubernetes-Cluster Resource Specification and StatefulSet v1 apps Kubernetes documentation.\n\n\nSee the example.\n\n
\n`spec``.clusterSpecList``.statefulSet``.spec``.volumeClaimTemplates``.spec`\n\n\ncollection\n\n\n*Optional.* If specified, provides a per-cluster override for the default storage size of the volumeClaimtemplates, for the persistent volume that stores the data.\n\n\nSee the example.\n\n
\n`spec.credentials`\n\n\nstring\n\n\nName of the secret you created as Ops Manager API (Application Programming Interface) authentication credentials for the Kubernetes Operator to communicate with Ops Manager.\n\nThe Ops Manager Kubernetes Secret object holding the Credentials must exist on the **same** Namespace as the resource you want to create.\n\nIMPORTANT: The Kubernetes Operator tracks any changes to the Secret and reconciles the state of the `MongoDB` resource.\n\n\n``\n\n
\n`spec.type`\n\n\nstring\n\n\nType of `MongoDB` resource to create. The only supported value for this field is `ReplicaSet`. See Limitations.\n\n\n`ReplicaSet`\n\n
\n\n### Add any additional accepted settings for a `MongoDBMultiCluster` resource deployment.\n\nYou can also add any optional settings to the object specification. See Multi-Kubernetes-Cluster Resource Specification.\n\n### Save this replica set config file with a `.yaml` extension.\n\n### Start your replica set deployment.\n\nIn any directory, invoke the following Kubernetes command to create your replica set:\n\n```sh\nkubectl apply -f .yaml\n```\n\n### Verify external connectivity for each member cluster.\n\n1. Check the status of external services in all member clusters:\n\n ```sh\n kubectl get services\n ```\n\n Kubernetes should return one external service created for each Pod of the replica set in all member clusters.\n\n2. Verify that each external service is exposed externally and is reachable. Run the command similar to the following example:\n\n ```sh\n mongosh mongodb://my-replica-set-0-0.cluster-0.example.com:27017 \\\n -tls -tlsCAFile \"issuer-ca.pem\"\n ```\n\n Connecting to `my-replica-set-0-0.cluster-0.example.com:27017` should direct client traffic to an external service named `my-replica-set-0-0-svc-external`, which, in turn, directs traffic to the `mongod` process.\n\n3. Configure your DNS (Domain Name System) zone for the specified external domain to point to the corresponding external services. This configuration depends on your environment or the cloud provider you are using.\n\n### Track the status of your multi-Kubernetes cluster MongoDB deployment.\n\nTo check the status of your `MongoDBMultiCluster` resource, use the following command on the central cluster:\n\n```sh\nkubectl get mdbmc -o yaml -w\n```\n\nWith the `-w` (watch) flag set, when the configuration changes, the output refreshes immediately until the status phase achieves the `Running` state. To learn more about resource deployment statuses, see Troubleshoot the Kubernetes Operator."} -{"chunk_id": "68a95c105e79d242619db708-0", "page_id": "68a95c105e79d242619db708", "source_name": "mck", "product_name": "MongoDB Controllers for Kubernetes", "url": "https://mongodb.com/docs/kubernetes/current/tutorial/create-x509-client-certs", "title": "Generate X.509 Client Certificates", "text": "# Generate X.509 Client Certificates\n\nThe MongoDB Controllers for Kubernetes Operator can deploy MongoDB instances with X.509 authentication enabled. If X.509 authentication has been enabled for the deployment, you must generate and use an X.509 certificate to connect to the deployment. This new client certificate must be signed by the same CA (Certificate Authority) that signs the server certificates for the MongoDB deployment to accept it.\n\nUse the procedure outlined in this document to use an X.509 certificate to connect to your X.509-enabled MongoDB deployment.\n\nIf you're using HashiCorp Vault as your secret storage tool, you can Create a Vault Secret instead.\n\nTo automate certificate renewal for Ops Manager deployments, consider setting up the cert-manager integration.\n\n## Prerequisites\n\nA full description of Transport Layer Security (TLS), Public Key Infrastructure (PKI) certificates, and Certificate Authorities is beyond the scope of this document. This page assumes prior knowledge of TLS (Transport Layer Security) and X.509 authentication.\n\n- To complete this tutorial, you must have the MongoDB Controllers for Kubernetes Operator installed. For instructions on installing the Kubernetes Operator, see Install the MongoDB Controllers for Kubernetes Operator.\n\n- This tutorial assumes you have a MongoDB deployment which requires X.509 authentication. For instructions on deploying MongoDB resources, see Deploy a MongoDB Database Resource.\n\n## Procedure\n\nFirst create the client certificate. Then create a MongoDB user and connect to the X.509-enabled deployment.\n\n### Generate an X.509 client certificate.\n\nFor production use, your MongoDB deployment should use valid certificates generated and signed by a CA (Certificate Authority). You or your organization can generate and maintain an independent CA (Certificate Authority) using Kubernetes-native tools such as cert-manager.\n\nObtaining and managing certificates is beyond the scope of this documentation.\n\nYou must concatenate your client's TLS (Transport Layer Security) certificate and the certificate's key in a `.pem` file. You must present this `.pem` file when you connect to your X.509-enabled MongoDB deployment.\n\nTo learn about the properties that your client certificates must have, see Client Certificate Requirements in the MongoDB Manual.\n\n### Configure `kubectl` to default to your namespace.\n\nIf you have not already, run the following command to execute all `kubectl` commands in the namespace you created.\n\nIf you are deploying an Ops Manager resource in a multi-Kubernetes cluster MongoDB deployment:\n\n- Set the `context` to the name of the central cluster, such as: `kubectl config set context \"$MDB_CENTRAL_CLUSTER_FULL_NAME\"`.\n\n- Set the `--namespace` to the same scope that you used for your multi-Kubernetes cluster MongoDB deployment, such as: `kubectl config --namespace \"mongodb\"`.\n\n```sh\nkubectl config set-context $(kubectl config current-context) --namespace=\n```\n\n### Copy and save the following example ConfigMap.\n\nSave the following ConfigMap as `x509-mongodb-user.yaml`:\n\n```none\n---\napiVersion: mongodb.com/v1\nkind: MongoDBUser\nmetadata:\n name: new-x509-user\nspec:\n username: \"CN=my-x509-authenticated-user,OU=organizationalunit,O=organization\"\n db: \"$external\"\n mongodbResourceRef:\n name: ''\n roles:\n - db: \"admin\"\n name: \"readWriteAnyDatabase\"\n```\n\nThis ConfigMap `.yaml` file describes a `MongoDBUser` custom object. You can use these custom objects to create MongoDB users. To learn more, see MongoDB User Resource Specification.\n\nIn this example, the ConfigMap describes the user as an X.509 user that the client can use to connect to MongoDB with the corresponding X.509 certificate.\n\n### Create the X.509 MongoDB user.\n\nRun the following command to apply the ConfigMap and create the X.509 MongoDB user:\n\n```sh\nkubectl apply -f x509-mongodb-user.yaml\n```\n\nYou should see an output similar to the following:\n\n```sh\nmongodbuser.mongodb.com/new-x509-user created\n```\n\n### Verify your newly created user\n\nRun the following command to check the state of the `new-x509-user`:\n\n```sh\nkubectl get mdbu/new-x509-user -o yaml\n```\n\nYou should see an output similar to the following:\n\n```sh\nNAME CREATED AT\nnew-x509-user 8m\n```\n\n### Find the mount location of the CA (Certificate Authority).\n\nRun the following command to find where in each pod the Kubernetes Operator mounted the CA (Certificate Authority) secret:\n\n```sh\nkubectl get statefulset -o yaml\n```\n\nIn the output, find the `secret-ca` mount:\n\n```yaml\nvolumeMounts:\n - mountPath: /opt/scripts\n name: database-scripts\n readOnly: true\n - mountPath: /var/lib/mongodb-automation/secrets/ca\n name: secret-ca\n readOnly: true\n - mountPath: /var/lib/mongodb-automation/secrets/certs\n name: secret-certs\n readOnly: true\n```\n\nIn the following step when you connect to your database deployment, append `secret-ca` to the `mountPath`, which forms the full path:\n\n```sh\n/var/lib/mongodb-automation/secrets/ca/secret-ca\n```\n\n### Use your X.509 user to connect to the MongoDB deployment\n\nOnce you have created your X.509 user, try to connect to the deployment using the MongoDB Shell (`mongosh`):\n\n```sh\nmongosh --host {host} --port {port} --tls \\\n --tlsCAFile \\\n --tlsCertificateKeyFile .pem \\\n --authenticationMechanism MONGODB-X509 \\\n --authenticationDatabase '$external'\n```"} -{"chunk_id": "68a95c105e79d242619db6cb-0", "page_id": "68a95c105e79d242619db6cb", "source_name": "mck", "product_name": "MongoDB Controllers for Kubernetes", "url": "https://mongodb.com/docs/kubernetes/current/openshift-tutorials", "title": "Openshift Tutorials", "text": "# Openshift Tutorials\n\nThis section contains the following:\n\n- OpenShift Quick Start\n\n- Deploy in Restricted Networks"} -{"chunk_id": "68a95c105e79d242619db6ff-0", "page_id": "68a95c105e79d242619db6ff", "source_name": "mck", "product_name": "MongoDB Controllers for Kubernetes", "url": "https://mongodb.com/docs/kubernetes/current/reference/k8s-operator-crd-logging-specification", "title": "MongoDB CRD Log Rotation Settings", "text": "# MongoDB CRD Log Rotation Settings\n\nYou can configure log rotation settings for CustomResourceDefinitions in the MongoDB and Ops Manager CRD (Custom Resource Definition) manifests.\n\nThe following table outlines logging configuration fields that you can define in the MongoDB CRD (Custom Resource Definition) manifests, and where they can be defined or accessed elsewhere if you choose not to configure them directly from the CRD (Custom Resource Definition) manifests.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nComponent\n\n\nLog type\n\n\nCRD manifest configuration\n\n\nDefault configuration location\n\n
\nMongoDB\n\n\nAutomation agent logs\n\n\n`MongoDB CRD`\n\n\n`spec.agent.startupOptions`\n\n
\nMongoDB\n\n\nMonitoring Agent logs\n\n\n`MongoDB CRD`\n\n\nOps Manager API or UI\n\n
\nMongoDB\n\n\nBackup logs\n\n\n`MongoDB CRD`\n\n\nOps Manager API or UI\n\n
\nMongoDB\n\n\nMongoDB logs\n\n\nOps Manager 7.0.4, 6.0.24, or later: `MongoDB CRD`\n\n\nOps Manager UI\n\n
\nMongoDB\n\n\nAudit logs\n\n\n`MongoDB CRD`\n\n\nOps Manager UI\n\n
\nMongoDB\n\n\nReadiness Probe\n\n\n`MongoDB CRD`\n\n\nContainer Environment Variables\n\n
\nApplication Database\n\n\nMongoDB Logs\n\n\n`MongoDBOpsManager CRD`\n\n\n`spec.applicationDatabase.agent.mongod.logRotate`\n\n
\nApplication Database\n\n\nAutomation Agent Logs\n\n\n`MongoDBOpsManager CRD`\n\n\n`spec.applicationDatabase.agent.startupOptions`\n\n
\nApplication Database\n\n\nMonitoring Agent logs\n\n\n`MongoDBOpsManager CRD`\n\n\nForwarded to `stdout` only (kubectl logs). Managed and stored in the Kubernetes control plane.\n\n
\nApplication Database\n\n\nAudit logs\n\n\n`MongoDBOpsManager CRD`\n\n\n`spec.applicationDatabase.agent.mongod.auditlogRotate`\n\n
\nOps Manager\n\n\nOps Manager logs\n\n\nMongoDBOpsManager CRD\n\n\nlogback.xml configuration file\n\n
## MongoDB Log Rotation\n\nFor Ops Manager 6, you can only configure `mongod` logs with this setting starting with version 6.0.2. For Ops Manager 7, you can only configure `mongod` logs with this setting starting with version 7.0.4. For previous Ops Manager versions, you must use the Ops Manager UI to configure `mongod` logs.\n\nYou can configure a log's rotation in the MongoDB CRD (Custom Resource Definition), as shown in the following example manifest.\n\nSee the preceding comparison table for more information about configuring the rotation of other MongoDB-specific logs.\n\n### Automation Agent Logs\n\nYou can configure the MongoDB automation agent logs in the MongoDB CRD (Custom Resource Definition) manifest under `spec.agent.startupOptions`.\n\n### Example Manifest\n\nThe following example manifest shows the schema for configuring log rotation in the MongoDB custom resource. The values shown are for demonstration only and aren't recommended settings. To learn more about configuration settings and their data types and usage, see the MongoDB Database Resource Specification.\n\nFor sharded clusters, you can only configure log rotation at the `spec.agent` level. Configuring log rotation on sub-spec levels such as `spec.configsrv.agent` or `spec.shardsvr.agent` is not supported.\n\n```yaml\napiVersion: mongodb.com/v1\nkind: MongoDB\nmetadata:\n name: log-rotate\n namespace: mongodb\nspec:\n podSpec:\n podTemplate:\n spec:\n containers:\n - name: mongodb-enterprise-database\n env:\n - name: READINESS_PROBE_LOGGER_MAX_SIZE\n value: \"50\"\n version: 8.0.0\n opsManager:\n configMapRef:\n name: my-project\n credentials: my-credentials\n type: Standalone\n persistent: false\n # https://docs.opsmanager.mongodb.com/current/reference/mongodb-agent-settings/\n agent:\n startupOptions:\n maxLogFiles: \"10\"\n maxLogFileSize: \"2\"\n readinessProbe:\n environmentVariables:\n READINESS_PROBE_LOGGER_MAX_SIZE: \"10\"\n READINESS_PROBE_LOGGER_BACKUPS: \"1\"\n READINESS_PROBE_LOGGER_MAX_AGE: \"3\"\n READINESS_PROBE_LOGGER_COMPRESS: \"true\"\n MDB_WITH_AGENT_FILE_LOGGING: \"false\"\n LOG_FILE_PATH: /var/log/mongodb-mms-automation/readiness.log\n backupAgent:\n logRotate:\n sizeThresholdMB: 10\n timeThresholdHrs: 10\n monitoringAgent:\n logRotate:\n sizeThresholdMB: 10\n timeThresholdHrs: 10\n # For Ops Manager 6, you can only configure mongod logs with this setting starting with version 6.0.2.\n # For Ops Manager 7, you can only configure mongod logs with this setting starting with version 7.0.4.\n # For previous Ops Manager versions, you must configure mongod logs using the Ops Manager UI.\n mongod:\n logRotate:\n sizeThresholdMB: \"10\"\n timeThresholdHrs: 10\n numUncompressed: 10\n numTotal: 10\n percentOfDiskspace: \"0.02\"\n auditlogRotate:\n sizeThresholdMB: \"10\"\n timeThresholdHrs: 10\n numUncompressed: 10\n numTotal: 10\n percentOfDiskspace: \"0.02\"\n\n```\n\n## Application Database Log Rotation\n\nYou can configure the following log's rotation in the `MongoDBOpsManager` CRD (Custom Resource Definition), as shown in the following example manifest. See the preceding table for more information about configuring the rotation of other Application Database-specific logs.\n\n### MongoDB Logs\n\nYou can configure the Application Database MongoDB log rotation in the `MongoDBOpsManager` manifest under `spec.applicationDatabase.agent..logRotate`. MongoDB compresses log files beyond the two most recent logs by default.\n\n- `/var/log/mongodb-mms-automation/mongodb.log`\n\n### Automation Agent Logs\n\nYou can configure the Application Database Automation Agent log rotation in the `MongoDBOpsManager` manifest under `spec.applicationDatabase.agent.startupOptions`.\n\n- `/var/log/mongodb-mms-automation/automation-agent-verbose.log`\n\n- `/var/log/mongodb-mms-automation/automation-agent.log`"} -{"chunk_id": "68a95c105e79d242619db6ff-1", "page_id": "68a95c105e79d242619db6ff", "source_name": "mck", "product_name": "MongoDB Controllers for Kubernetes", "url": "https://mongodb.com/docs/kubernetes/current/reference/k8s-operator-crd-logging-specification", "title": "MongoDB CRD Log Rotation Settings", "text": "### Audit Logs\n\nYou can configure the Application Database Audit log rotation in the `MongoDBOpsManager` manifest under `spec.applicationDatabase.agent.mongod.auditlogRotate`.\n\nThe `auditLogRotate` setting depends on the `logRotate` setting. In order for `auditLogRotate` to take effect, you must also configure `logRotate`.\n\n- `/var/log/mongodb-mms-automation/mongodb-audit.log`\n\n### Example Manifest\n\nThe following example manifest shows the schema for configuring Application Database log rotation in the `MongoDBOpsManager`\ncustom resource. The values shown are for demonstration only and aren't recommended settings. To learn more about configuration settings and their data types and usage, see the MongoDB Database Resource Specification.\n\n```yaml\napiVersion: mongodb.com/v1\nkind: MongoDBOpsManager\nmetadata:\n name: ops-manager\n namespace: mongodb\nspec:\n replicas: 1\n version: 8.0.0\n adminCredentials: ops-manager-admin-secret\n applicationDatabase:\n version: \"8.0.0\"\n members: 3\n agent:\n #agent.logRotate is deprecated and overwritten by agent.mongod.logRotate.\n logRotate:\n #Automation Agent log rotation\n startupOptions:\n maxLogFiles: \"10\"\n maxLogFileSize: \"2\"\n #Readiness probe log rotation\n readinessProbe:\n environmentVariables:\n READINESS_PROBE_LOGGER_MAX_SIZE: \"10\"\n READINESS_PROBE_LOGGER_BACKUPS: \"1\"\n READINESS_PROBE_LOGGER_MAX_AGE: \"3\"\n READINESS_PROBE_LOGGER_COMPRESS: \"true\"\n MDB_WITH_AGENT_FILE_LOGGING: \"false\"\n LOG_FILE_PATH: /var/log/mongodb-mms-automation/readiness.log\n #AppDB backup log rotation\n backupAgent:\n logRotate:\n sizeThresholdMB: 10\n timeThresholdHrs: 10\n #AppDB Monitoring Agent log rotation\n monitoringAgent:\n logRotate:\n sizeThresholdMB: 10\n timeThresholdHrs: 10\n #AppDB (mongod) log rotation\n mongod:\n logRotate:\n sizeThresholdMB: \"10\"\n timeThresholdHrs: 10\n numUncompressed: 10\n numTotal: 10\n percentOfDiskspace: \"0.02\"\n auditlogRotate:\n sizeThresholdMB: \"10\"\n timeThresholdHrs: 10\n numUncompressed: 10\n numTotal: 10\n percentOfDiskspace: \"0.02\"\n\n```\n\n## Ops Manager Log Rotation\n\nTo manage and rotate Ops Manager, you can either manually override the StatefulSet or use CRD settings.\n\n### Configure Ops Manager Logs with the StatefulSet\n\nTo manage and rotate Ops Manager logs, you can manually override the default logging configuration using a ConfigMap and StatefulSet override. This process involves creating a custom `logback.xml` configuration file and applying it to your Ops Manager Pods.\n\n#### Create the custom `logback.xml` configuration file.\n\nYou can retrieve the existing `logback.xml` to use as a template by running the following command:\n\n```sh\nkubectl cp om-pod-spec-0:/mongodb-ops-manager/conf/logback.xml ~/Downloads/logback-confs/logback.xml\n```\n\nTo learn more about creating a custom `logback.xml`, see Change Ops Manager Log Rotation Policy.\n\n#### Create a ConfigMap from the custom `logback.xml`.\n\nEnsure that the key in the ConfigMap is exactly the name of the file you want to replace so that the mount path and subpath only overwrite one file and not the entire directory. In this example, the file name is `logback.xml`:\n\n```sh\nkubectl create configmap logback-config --from-file=logback.xml=path/to/your/custom_logback.xml\n```\n\n#### Override the StatefulSet configuration.\n\nUse the StatefulSet override feature to mount the custom `logback.xml` in your Ops Manager Pods. Add the following to your StatefulSet configuration:\n\nThe `key` in the following ConfigMap is `logback.xml` by default to ensure it correctly replaces the default file with the same name.\n\n```yaml\nspec:\n template:\n spec:\n volumes:\n - name: logback-volume\n configMap:\n name: logback-config\n items:\n - key: logback.xml\n path: logback.xml\n containers:\n - name: mongodb-ops-manager\n volumeMounts:\n - name: logback-volume\n mountPath: /mongodb-ops-manager/conf-template/logback.xml\n subPath: logback.xml\n```\n\n#### Replicate the ConfigMap for multi-cluster-om|s.\n\nIf you are using a multi-cluster Ops Manager deployment, ensure you replicate the `logback-config` ConfigMap to all member clusters.\n\n### Configure Ops Manager Logs with the CRD\n\nYou can also manage Ops Manager log rotation by using CRD (Custom Resource Definition) settings, which simplifies the log rotation process by linking to the ConfigMap directly in the CRD (Custom Resource Definition).\n\n#### Create the custom `logback.xml` configuration file.\n\nYou can retrieve the existing `logback.xml` to use as a template by running the following command:\n\n```sh\nkubectl cp om-pod-spec-0:/mongodb-ops-manager/conf/logback.xml ~/Downloads/logback-confs/logback.xml\n```\n\nTo learn more about creating a custom `logback.xml`, see Change Ops Manager Log Rotation Policy.\n\n#### (Optional) Create a custom `logback-access.xml` configuration file.\n\nUse the `logback-access.xml` file to configure logging for HTTP access requests, such as those handled by a web server. If you want to customize how these access logs are managed, you can create a custom `logback-access.xml` file similar to the `logback.xml`.\n\nRetrieve the existing `logback-access.xml` to use as a template by running the following command:\n\n```sh\nkubectl cp om-pod-spec-0:/mongodb-ops-manager/conf/logback-access.xml ~/Downloads/logback-confs/logback-access.xml\n```\n\nModify this file according to your logging requirements.\n\n#### Create a ConfigMap from the custom `logback.xml` and `logback-access.xml`.\n\nEnsure that the key in the ConfigMap is exactly the name of the file you want to replace so that the mount path and subpath only overwrite one file and not the entire directory. The following examples use default file names, `logback.xml` and `logback-access.xml`:\n\n```sh\nkubectl create configmap logback-config --from-file=logback.xml=path/to/your/custom_logback.xml\n```\n\n```sh\nkubectl create configmap logback-access-config --from-file=logback-access.xml=path/to/your/custom_access_logback.xml\n```\n\n#### Set the CRD (Custom Resource Definition) logging properties.\n\nAdd the following settings to your Ops Manager CRD (Custom Resource Definition):\n\n- `spec.logging.LogBackAccessRef`\n\n- `spec.logging.LogBackRef`\n\n- `spec.backup.logging.LogBackAccessRef`\n\n- `spec.backup.logging.LogBackRef`\n\nThe file names `logback.xml` and `logback-access.xml` are the default file names and must be the keys in the ConfigMap for the Kubernetes Operator to recognize them.\n\nFor example:\n\n```yaml\napiVersion: mongodb.com/v1\nkind: MongoDBOpsManager\nmetadata:\n name: ops-manager\n namespace: mongodb\nspec:\n replicas: 1\n version: 8.0.0\n adminCredentials: ops-manager-admin-secret\n logging:\n LogBackAccessRef:\n name: logback-access-config\n LogBackRef:\n name: logback-config\n backup:\n enabled: true\n logging:\n LogBackAccessRef:\n name: my-logback-access-cm-backup\n LogBackRef:\n name: my-logback-cm-backup\n```\n\nAfter you define the volumes in your Ops Manager\ncustom resource, Kubernetes automatically generates the volume mounts similar to the preceding example and links the ConfigMap files to the correct locations in the Ops Manager Pods."} -{"chunk_id": "691eb238e337baf834ef5131-0", "page_id": "691eb238e337baf834ef5131", "source_name": "mck", "product_name": "MongoDB Controllers for Kubernetes", "url": "https://mongodb.com/docs/kubernetes/current/tutorial/install-fts-vs-with-community", "title": "Install and use With MongoDB Community Edition", "text": "# Install and use With MongoDB Community Edition\n\nYou can use the Kubernetes Operator and deploy the `mongot` process resources to run with MongoDB Community Edition v8.3 or later on a Kubernetes cluster. The `mongot` process supports both MongoDB Search and Vector Search. Optionally, you can enable and configure Vector Search to automatically generate vector embeddings for text data in your collections and queries using a supported Voyage AI embedding model.\n\nAutomated embedding is in Preview. The feature and the corresponding documentation might change at any time during the preview period. To learn more, see Preview Features.\n\nThe following procedure demonstrates how to deploy and configure MongoDB Search and Vector Search to run with a new or existing replica set in your Kubernetes cluster. The deployment uses TLS (Transport Layer Security) certificates to ensure secure communication between MongoDB nodes and the `mongot` search process.\n\n## Prerequisites\n\nTo deploy MongoDB Search and Vector Search, you must have the following:\n\n- A running Kubernetes cluster.\n\n- Kubernetes command-line tool, `kubectl`, configured to communicate with your cluster.\n\n- Helm, the package manager for Kubernetes, to install the Kubernetes Operator.\n\n- cert-manager or an alternative certificate management solution for TLS (Transport Layer Security) certificate provisioning.\n\n- Bash v5.1 or later for running the commands in this tutorial.\n\n**Optionally**, to configure Vector Search to automatically generate vector embeddings for text data in your collections and queries, you must create API (Application Programming Interface) keys for the embedding service. We recommend creating two keys, one for generating embeddings at index-time for text data in your collection and another for generating embeddings at query-time for your query text. If you don't have the keys, you can create the keys from the Atlas UI.\n\n## Procedure\n\n### Required. Set the environment variables.\n\nSet the environment variables for use in the subsequent steps in this procedure. Copy the following commands, update the values for your environment, and then run them to load the variables:\n\n```yaml\n# set it to the context name of the k8s cluster\nexport K8S_CTX=\"\"\n\n# the following namespace will be created if not exists\nexport MDB_NS=\"mongodb\"\n\n# MongoDBCommunity resource name referenced throughout the guide\nexport MDB_RESOURCE_NAME=\"mdbc-rs\"\n# Number of replica set members deployed in the sample MongoDBCommunity\nexport MDB_MEMBERS=3\n\n# TLS-related secret names used for MongoDBCommunity and MongoDBSearch\nexport MDB_TLS_CA_SECRET_NAME=\"${MDB_RESOURCE_NAME}-ca\"\nexport MDB_TLS_SERVER_CERT_SECRET_NAME=\"${MDB_RESOURCE_NAME}-tls\"\nexport MDB_SEARCH_TLS_SECRET_NAME=\"${MDB_RESOURCE_NAME}-search-tls\"\n\nexport MDB_TLS_CA_CONFIGMAP=\"${MDB_RESOURCE_NAME}-ca-configmap\"\nexport MDB_TLS_SELF_SIGNED_ISSUER=\"${MDB_RESOURCE_NAME}-selfsigned-cluster-issuer\"\nexport MDB_TLS_CA_CERT_NAME=\"${MDB_RESOURCE_NAME}-selfsigned-ca\"\nexport MDB_TLS_CA_ISSUER=\"${MDB_RESOURCE_NAME}-cluster-issuer\"\n\nexport MDB_VERSION=\"8.3.4\"\n\n# root admin user for convenience, not used here at all in this guide\nexport MDB_ADMIN_USER_PASSWORD=\"admin-user-password-CHANGE-ME\"\n# regular user performing restore and search queries on sample mflix database\nexport MDB_USER_PASSWORD=\"mdb-user-password-CHANGE-ME\"\n# user for MongoDB Search to connect to the replica set to synchronise data from\nexport MDB_SEARCH_SYNC_USER_PASSWORD=\"search-sync-user-password-CHANGE-ME\"\n\nexport OPERATOR_HELM_CHART=\"mongodb/mongodb-kubernetes\"\n# comma-separated key=value pairs for additional parameters passed to the helm-chart installing the operator\nexport OPERATOR_ADDITIONAL_HELM_VALUES=\"\"\n\n# TLS is mandatory; connection string must include tls=true\nexport MDB_CONNECTION_STRING=\"mongodb://mdb-user:${MDB_USER_PASSWORD}@${MDB_RESOURCE_NAME}-0.${MDB_RESOURCE_NAME}-svc.${MDB_NS}.svc.cluster.local:27017/?replicaSet=${MDB_RESOURCE_NAME}&tls=true&tlsCAFile=/tls/ca.crt\"\n\nexport CERT_MANAGER_NAMESPACE=\"cert-manager\"\n\n# Vector Search auto embedding related configurations\nexport AUTO_EMBEDDING_API_KEY_SECRET_NAME=\"voyage-api-keys\"\nexport AUTO_EMBEDDING_API_QUERY_KEY=\"\"\nexport AUTO_EMBEDDING_API_INDEXING_KEY=\"\"\nexport PROVIDER_ENDPOINT=\"https://ai.mongodb.com/v1/embeddings\"\nexport EMBEDDING_MODEL=\"voyage-4\"\n\n```\n\nIf you have the API (Application Programming Interface) keys to enable Vector Search to automatically generate embeddings, replace the following placeholder values in the environment variables:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n`AUTO_EMBEDDING_API_QUERY_KEY`\n\n\nAPI (Application Programming Interface) key for generating embeddings for the query text.\n\n
\n`AUTO_EMBEDDING_API_INDEXING_KEY`\n\n\nAPI (Application Programming Interface) key for generating embeddings for text data in your collection at index-time.\n\n
\n`PROVIDER_ENDPOINT`\n\n\nEmbedding model provider's endpoint. Value defaults to `https://ai.mongodb.com/v1/embeddings` for keys created from the Atlas UI. Replace with `https://api.voyageai.com/v1/embeddings` if you created the API (Application Programming Interface) keys directly from Voyage AI.\n\n
To verify that all necessary environment variables are set, run the following code in your terminal:\n\n```yaml\nrequired=(\n K8S_CTX\n MDB_NS\n MDB_RESOURCE_NAME\n MDB_VERSION\n MDB_MEMBERS\n CERT_MANAGER_NAMESPACE\n MDB_TLS_CA_SECRET_NAME\n MDB_TLS_SERVER_CERT_SECRET_NAME\n MDB_SEARCH_TLS_SECRET_NAME\n MDB_ADMIN_USER_PASSWORD\n MDB_SEARCH_SYNC_USER_PASSWORD\n MDB_USER_PASSWORD\n OPERATOR_HELM_CHART\n)\n\nmissing_req=()\nfor v in \"${required[@]}\"; do [[ -n \"${!v:-}\" ]] || missing_req+=(\"${v}\"); done\n\nif (( ${#missing_req[@]} )); then\n echo \"ERROR: Missing required environment variables:\" >&2\n for m in \"${missing_req[@]}\"; do echo \" - ${m}\" >&2; done\nelse\n echo \"All required environment variables present.\"\nfi\n\n```\n\n### Conditional. Add the MongoDB Helm repository.\n\nHelm automates the deployment and management of MongoDB instances on Kubernetes. If you already have the Helm repository that contains the Helm chart for installing the Kubernetes Operator operator, or skip this step. Otherwise, add the Helm repository.\n\nTo add the Helm repository, copy, paste, and run the following:\n\n```shell\nhelm repo add mongodb https://mongodb.github.io/helm-charts\nhelm repo update mongodb\nhelm search repo mongodb/mongodb-kubernetes\n\n```\n\n```shell\n\"mongodb\" has been added to your repositories\nHang tight while we grab the latest from your chart repositories...\n...Successfully got an update from the \"mongodb\" chart repository\nUpdate Complete. \u2388Happy Helming!\u2388\nNAME \tCHART VERSION\tAPP VERSION\tDESCRIPTION\nmongodb/mongodb-kubernetes\t1.14.0 \t \tMongoDB Controllers for Kubernetes translate th...\n\n```"} -{"chunk_id": "691eb238e337baf834ef5131-1", "page_id": "691eb238e337baf834ef5131", "source_name": "mck", "product_name": "MongoDB Controllers for Kubernetes", "url": "https://mongodb.com/docs/kubernetes/current/tutorial/install-fts-vs-with-community", "title": "Install and use With MongoDB Community Edition", "text": "HOOKS:\nMANIFEST:\n---\n# Source: mongodb-kubernetes/templates/database-roles.yaml\napiVersion: v1\nkind: ServiceAccount\nmetadata:\n name: mongodb-kubernetes-appdb\n namespace: mongodb\n---\n# Source: mongodb-kubernetes/templates/database-roles.yaml\napiVersion: v1\nkind: ServiceAccount\nmetadata:\n name: mongodb-kubernetes-database-pods\n namespace: mongodb\n---\n# Source: mongodb-kubernetes/templates/database-roles.yaml\napiVersion: v1\nkind: ServiceAccount\nmetadata:\n name: mongodb-kubernetes-ops-manager\n namespace: mongodb\n---\n# Source: mongodb-kubernetes/templates/operator-sa.yaml\napiVersion: v1\nkind: ServiceAccount\nmetadata:\n name: mongodb-kubernetes-operator\n namespace: mongodb\n---\n# Source: mongodb-kubernetes/templates/operator-roles-clustermongodbroles.yaml\nkind: ClusterRole\napiVersion: rbac.authorization.k8s.io/v1\nmetadata:\n name: mongodb-kubernetes-operator-mongodb-cluster-mongodb-role\nrules:\n - apiGroups:\n - mongodb.com\n verbs:\n - '*'\n resources:\n - clustermongodbroles\n---\n# Source: mongodb-kubernetes/templates/operator-roles-telemetry.yaml\n# Additional ClusterRole for clusterVersionDetection\nkind: ClusterRole\napiVersion: rbac.authorization.k8s.io/v1\nmetadata:\n name: mongodb-kubernetes-operator-cluster-telemetry\nrules:\n # Non-resource URL permissions\n - nonResourceURLs:\n - \"/version\"\n verbs:\n - get\n # Cluster-scoped resource permissions\n - apiGroups:\n - ''\n resources:\n - namespaces\n resourceNames:\n - kube-system\n verbs:\n - get\n - apiGroups:\n - ''\n resources:\n - nodes\n verbs:\n - list\n---\n# Source: mongodb-kubernetes/templates/operator-roles-webhook.yaml\nkind: ClusterRole\napiVersion: rbac.authorization.k8s.io/v1\nmetadata:\n name: mongodb-kubernetes-operator-mongodb-webhook-cr\nrules:\n - apiGroups:\n - \"admissionregistration.k8s.io\"\n resources:\n - validatingwebhookconfigurations\n verbs:\n - get\n - create\n - update\n - delete\n - apiGroups:\n - \"\"\n resources:\n - services\n verbs:\n - get\n - list\n - watch\n - create\n - update\n - delete\n---\n# Source: mongodb-kubernetes/templates/operator-roles-clustermongodbroles.yaml\nkind: ClusterRoleBinding\napiVersion: rbac.authorization.k8s.io/v1\nmetadata:\n name: mongodb-kubernetes-operator-mongodb-cluster-mongodb-role-binding\nroleRef:\n apiGroup: rbac.authorization.k8s.io\n kind: ClusterRole\n name: mongodb-kubernetes-operator-mongodb-cluster-mongodb-role\nsubjects:\n - kind: ServiceAccount\n name: mongodb-kubernetes-operator\n namespace: mongodb\n---\n# Source: mongodb-kubernetes/templates/operator-roles-telemetry.yaml\n# ClusterRoleBinding for clusterVersionDetection\nkind: ClusterRoleBinding\napiVersion: rbac.authorization.k8s.io/v1\nmetadata:\n name: mongodb-kubernetes-operator-mongodb-cluster-telemetry-binding\nroleRef:\n apiGroup: rbac.authorization.k8s.io\n kind: ClusterRole\n name: mongodb-kubernetes-operator-cluster-telemetry\nsubjects:\n - kind: ServiceAccount\n name: mongodb-kubernetes-operator\n namespace: mongodb\n---\n# Source: mongodb-kubernetes/templates/operator-roles-webhook.yaml\nkind: ClusterRoleBinding\napiVersion: rbac.authorization.k8s.io/v1\nmetadata:\n name: mongodb-kubernetes-operator-mongodb-webhook-crb\nroleRef:\n apiGroup: rbac.authorization.k8s.io\n kind: ClusterRole\n name: mongodb-kubernetes-operator-mongodb-webhook-cr\nsubjects:\n - kind: ServiceAccount\n name: mongodb-kubernetes-operator\n namespace: mongodb\n---\n# Source: mongodb-kubernetes/templates/database-roles.yaml\nkind: Role\napiVersion: rbac.authorization.k8s.io/v1\nmetadata:\n name: mongodb-kubernetes-appdb\n namespace: mongodb\nrules:\n - apiGroups:\n - ''\n resources:\n - secrets\n verbs:\n - get\n - apiGroups:\n - ''\n resources:\n - pods\n verbs:\n - patch\n - delete\n - get\n---\n# Source: mongodb-kubernetes/templates/operator-roles-base.yaml\nkind: Role\napiVersion: rbac.authorization.k8s.io/v1\nmetadata:\n name: mongodb-kubernetes-operator\n namespace: mongodb\nrules:\n - apiGroups:\n - ''\n resources:\n - services\n verbs:\n - get\n - list\n - watch\n - create\n - update\n - delete\n - apiGroups:\n - ''\n resources:\n - secrets\n - configmaps\n verbs:\n - get\n - list\n - create\n - update\n - delete\n - watch\n - apiGroups:\n - apps\n resources:\n - statefulsets\n - deployments\n verbs:\n - create\n - get\n - list\n - watch\n - delete\n - update\n - apiGroups:\n - batch\n resources:\n - jobs\n verbs:\n - create\n - get\n - list\n - watch\n - delete\n - apiGroups:\n - ''\n resources:\n - pods\n verbs:\n - get\n - list\n - watch\n - delete\n - deletecollection\n - apiGroups:\n - mongodbcommunity.mongodb.com\n resources:\n - mongodbcommunity\n - mongodbcommunity/status\n - mongodbcommunity/spec\n - mongodbcommunity/finalizers\n verbs:\n - '*'\n - apiGroups:\n - mongodb.com\n verbs:\n - '*'\n resources:\n - mongodb\n - mongodb/finalizers\n - mongodbusers\n - mongodbusers/finalizers\n - opsmanagers\n - opsmanagers/finalizers\n - mongodbmulticluster\n - mongodbmulticluster/finalizers\n - mongodbsearch\n - mongodbsearch/finalizers\n - mongodb/status\n - mongodbusers/status\n - opsmanagers/status\n - mongodbmulticluster/status\n - mongodbsearch/status\n - apiGroups:\n - ai.mongodb.com\n verbs:\n - '*'\n resources:\n - voyageais\n - voyageais/finalizers\n - voyageais/status\n---\n# Source: mongodb-kubernetes/templates/operator-roles-pvc-resize.yaml\nkind: Role\napiVersion: rbac.authorization.k8s.io/v1\nmetadata:\n name: mongodb-kubernetes-operator-pvc-resize\n namespace: mongodb\nrules:\n - apiGroups:\n - ''\n resources:\n - persistentvolumeclaims\n verbs:\n - get\n - delete\n - list\n - watch\n - patch\n - update\n---\n# Source: mongodb-kubernetes/templates/database-roles.yaml\nkind: RoleBinding\napiVersion: rbac.authorization.k8s.io/v1\nmetadata:\n name: mongodb-kubernetes-appdb\n namespace: mongodb\nroleRef:\n apiGroup: rbac.authorization.k8s.io\n kind: Role\n name: mongodb-kubernetes-appdb\nsubjects:\n - kind: ServiceAccount\n name: mongodb-kubernetes-appdb\n namespace: mongodb\n---\n# Source: mongodb-kubernetes/templates/operator-roles-base.yaml\nkind: RoleBinding\napiVersion: rbac.authorization.k8s.io/v1\nmetadata:\n name: mongodb-kubernetes-operator\n namespace: mongodb\nroleRef:\n apiGroup: rbac.authorization.k8s.io\n kind: Role\n name: mongodb-kubernetes-operator\nsubjects:\n - kind: ServiceAccount\n name: mongodb-kubernetes-operator\n namespace: mongodb\n---\n# Source: mongodb-kubernetes/templates/operator-roles-pvc-resize.yaml\nkind: RoleBinding\napiVersion: rbac.authorization.k8s.io/v1\nmetadata:\n name: mongodb-kubernetes-operator-pvc-resize-binding\n namespace: mongodb\nroleRef:\n apiGroup: rbac.authorization.k8s.io\n kind: Role\n name: mongodb-kubernetes-operator-pvc-resize\nsubjects:\n - kind: ServiceAccount\n name: mongodb-kubernetes-operator\n namespace: mongodb\n---\n# Source: mongodb-kubernetes/templates/operator.yaml\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: mongodb-kubernetes-operator\n namespace: mongodb\nspec:\n replicas: 1\n selector:\n matchLabels:\n app.kubernetes.io/component: controller\n app.kubernetes.io/name: mongodb-kubernetes-operator\n app.kubernetes.io/instance: mongodb-kubernetes-operator\n template:\n metadata:\n labels:\n app.kubernetes.io/component: controller\n app.kubernetes.io/name: mongodb-kubernetes-operator\n app.kubernetes.io/instance: mongodb-kubernetes-operator\n annotations:\n mongodb.com/installation-method: \"helm\"\n spec:\n serviceAccountName: mongodb-kubernetes-operator\n securityContext:\n "} -{"chunk_id": "691eb238e337baf834ef5131-2", "page_id": "691eb238e337baf834ef5131", "source_name": "mck", "product_name": "MongoDB Controllers for Kubernetes", "url": "https://mongodb.com/docs/kubernetes/current/tutorial/install-fts-vs-with-community", "title": "Install and use With MongoDB Community Edition", "text": "### Conditional. Install the MongoDB Controllers for Kubernetes Operator.\n\nThe Kubernetes Operator watches `MongoDBCommunity` and MongoDBSearch custom resources and manages the lifecycle of your MongoDB deployments. If you already installed the MongoDB Controllers for Kubernetes Operator, skip this step. Otherwise, install the MongoDB Controllers for Kubernetes Operator from the Helm repository you added in the previous step.\n\nTo install the MongoDB Controllers for Kubernetes Operator in the `mongodb` namespace, copy, paste, and run the following commands:\n\n```shell\nhelm upgrade --install --debug --kube-context \"${K8S_CTX}\" \\\n --create-namespace \\\n --namespace=\"${MDB_NS}\" \\\n mongodb-kubernetes \\\n ${OPERATOR_ADDITIONAL_HELM_VALUES:+--set ${OPERATOR_ADDITIONAL_HELM_VALUES}} \\\n \"${OPERATOR_HELM_CHART}\"\n\n```\n\n```shell\nRelease \"mongodb-kubernetes\" does not exist. Installing it now.\nNAME: mongodb-kubernetes\nLAST DEPLOYED: Tue Sep 29 11:07:22 2026\nNAMESPACE: mongodb\nSTATUS: deployed\nREVISION: 1\nTEST SUITE: None\nUSER-SUPPLIED VALUES:\n{}\n\nCOMPUTED VALUES:\nagent:\n name: mongodb-agent\n version: 109.0.1.9310-1\ncommunity:\n agent:\n name: mongodb-agent\n version: 109.0.1.9310-1\n mongodb:\n imageType: ubi8\n name: mongodb-community-server\n repo: quay.io/mongodb\n registry:\n agent: quay.io/mongodb\n resource:\n members: 3\n name: mongodb-replica-set\n tls:\n caCertificateSecretRef: tls-ca-key-pair\n certManager:\n certDuration: 8760h\n renewCertBefore: 720h\n certificateKeySecretRef: tls-certificate\n enabled: false\n sampleX509User: false\n useCertManager: true\n useX509: false\n version: 4.4.0\ndatabase:\n name: mongodb-kubernetes-database\n version: 1.14.0\ninitDatabase:\n name: mongodb-kubernetes-init-database\n version: 1.14.0\ninitOpsManager:\n name: mongodb-kubernetes-init-ops-manager\n version: 1.14.0\nmanagedSecurityContext: false\nmongodb:\n appdbAssumeOldFormat: false\n name: mongodb-enterprise-server\n repo: quay.io/mongodb\nmultiCluster:\n clusterClientTimeout: 10\n clusters: []\n kubeConfigSecretName: mongodb-enterprise-operator-multi-cluster-kubeconfig\n memberClusterRequiredHealthyStreak: 5\n performFailOver: true\noperator:\n additionalArguments: []\n affinity: {}\n clusterIdentity:\n clusterName: \"\"\n createOperatorServiceAccount: true\n createResourcesServiceAccountsAndRoles: true\n enableClusterMongoDBRoles: true\n enablePVCResize: true\n env: prod\n maxConcurrentReconciles: 1\n mdbDefaultArchitecture: non-static\n name: mongodb-kubernetes-operator\n nodeSelector: {}\n operator_image_name: mongodb-kubernetes\n podSecurityContext:\n runAsNonRoot: true\n runAsUser: 2000\n seccompProfile:\n type: RuntimeDefault\n replicas: 1\n resources:\n limits:\n cpu: 1100m\n memory: 1Gi\n requests:\n cpu: 500m\n memory: 200Mi\n securityContext:\n allowPrivilegeEscalation: false\n capabilities:\n drop:\n - ALL\n telemetry:\n collection:\n clusters: {}\n deployments: {}\n frequency: 1h\n operators: {}\n send:\n frequency: 168h\n tolerations: []\n vaultSecretBackend:\n enabled: false\n tlsSecretRef: \"\"\n version: 1.14.0\n watchedResources:\n - mongodb\n - opsmanagers\n - mongodbusers\n - mongodbcommunity\n - mongodbsearch\n - voyageais\n webhook:\n installClusterRole: true\n name: \"\"\n registerConfiguration: true\nopsManager:\n name: mongodb-enterprise-ops-manager-ubi\nreadinessProbe:\n name: mongodb-kubernetes-readinessprobe\n version: 1.0.24\nregistry:\n agent: quay.io/mongodb\n database: quay.io/mongodb\n imagePullSecrets: null\n initDatabase: quay.io/mongodb\n initOpsManager: quay.io/mongodb\n operator: quay.io/mongodb\n opsManager: quay.io/mongodb\n pullPolicy: Always\n readinessProbe: quay.io/mongodb\n versionUpgradeHook: quay.io/mongodb\nsearch:\n envoyImage: envoyproxy/envoy:v1.37-latest\n metricsForwarderImage: otel/opentelemetry-collector-contrib:0.152.0\n name: mongodb-search\n repo: quay.io/mongodb\n version: 1.70.1\nversionUpgradeHook:\n name: mongodb-kubernetes-operator-version-upgrade-post-start-hook\n version: 1.0.10\nvoyageai:\n repo: quay.io/mongodb/voyageai"} -{"chunk_id": "691eb238e337baf834ef5131-3", "page_id": "691eb238e337baf834ef5131", "source_name": "mck", "product_name": "MongoDB Controllers for Kubernetes", "url": "https://mongodb.com/docs/kubernetes/current/tutorial/install-fts-vs-with-community", "title": "Install and use With MongoDB Community Edition", "text": " runAsNonRoot: true\n runAsUser: 2000\n seccompProfile:\n type: RuntimeDefault\n containers:\n - name: mongodb-kubernetes-operator\n image: \"quay.io/mongodb/mongodb-kubernetes:1.14.0\"\n imagePullPolicy: Always\n args:\n - -watch-resource=mongodb\n - -watch-resource=opsmanagers\n - -watch-resource=mongodbusers\n - -watch-resource=mongodbcommunity\n - -watch-resource=mongodbsearch\n - -watch-resource=voyageais\n - -watch-resource=clustermongodbroles\n command:\n - /usr/local/bin/mongodb-kubernetes-operator\n volumeMounts:\n - mountPath: /tmp/k8s-webhook-server/serving-certs\n name: webhook-server-dir\n resources:\n limits:\n cpu: 1100m\n memory: 1Gi\n requests:\n cpu: 500m\n memory: 200Mi\n securityContext:\n allowPrivilegeEscalation: false\n capabilities:\n drop:\n - ALL\n env:\n - name: OPERATOR_ENV\n value: prod\n - name: MDB_DEFAULT_ARCHITECTURE\n value: non-static\n - name: NAMESPACE\n valueFrom:\n fieldRef:\n fieldPath: metadata.namespace\n # Migration dry-run job image.\n # Optional: it can be resolved from the API server.\n - name: MDB_OPERATOR_IMAGE\n value: \"quay.io/mongodb/mongodb-kubernetes:1.14.0\"\n - name: WATCH_NAMESPACE\n valueFrom:\n fieldRef:\n fieldPath: metadata.namespace\n - name: MDB_OPERATOR_TELEMETRY_COLLECTION_FREQUENCY\n value: \"1h\"\n - name: MDB_OPERATOR_TELEMETRY_SEND_FREQUENCY\n value: \"168h\"\n - name: CLUSTER_CLIENT_TIMEOUT\n value: \"10\"\n - name: MDB_MEMBER_CLUSTER_REQUIRED_HEALTHY_STREAK\n value: \"5\"\n - name: IMAGE_PULL_POLICY\n value: Always\n # Database\n - name: MONGODB_ENTERPRISE_DATABASE_IMAGE\n value: quay.io/mongodb/mongodb-kubernetes-database\n - name: INIT_DATABASE_IMAGE_REPOSITORY\n value: quay.io/mongodb/mongodb-kubernetes-init-database\n - name: INIT_DATABASE_VERSION\n value: \"1.14.0\"\n - name: DATABASE_VERSION\n value: \"1.14.0\"\n # Ops Manager\n - name: OPS_MANAGER_IMAGE_REPOSITORY\n value: quay.io/mongodb/mongodb-enterprise-ops-manager-ubi\n - name: INIT_OPS_MANAGER_IMAGE_REPOSITORY\n value: quay.io/mongodb/mongodb-kubernetes-init-ops-manager\n - name: INIT_OPS_MANAGER_VERSION\n value: \"1.14.0\"\n - name: OPS_MANAGER_IMAGE_PULL_POLICY\n value: Always\n - name: AGENT_IMAGE\n value: \"quay.io/mongodb/mongodb-agent:109.0.1.9310-1\"\n - name: MDB_AGENT_IMAGE_REPOSITORY\n value: \"quay.io/mongodb/mongodb-agent\"\n - name: MONGODB_IMAGE\n value: mongodb-enterprise-server\n - name: MONGODB_REPO_URL\n value: quay.io/mongodb\n - name: PERFORM_FAILOVER\n value: 'true'\n - name: MDB_MAX_CONCURRENT_RECONCILES\n value: \"1\"\n - name: POD_NAME\n valueFrom:\n fieldRef:\n fieldPath: metadata.name\n - name: MCK_INSTALLER\n valueFrom:\n fieldRef:\n fieldPath: metadata.annotations['mongodb.com/installation-method']\n - name: OPERATOR_NAME\n value: mongodb-kubernetes-operator\n # Community Env Vars Start\n - name: MDB_COMMUNITY_AGENT_IMAGE\n value: \"quay.io/mongodb/mongodb-agent:109.0.1.9310-1\"\n - name: VERSION_UPGRADE_HOOK_IMAGE\n value: \"quay.io/mongodb/mongodb-kubernetes-operator-version-upgrade-post-start-hook:1.0.10\"\n - name: READINESS_PROBE_IMAGE\n value: \"quay.io/mongodb/mongodb-kubernetes-readinessprobe:1.0.24\"\n - name: MDB_COMMUNITY_IMAGE\n value: \"mongodb-community-server\"\n - name: MDB_COMMUNITY_REPO_URL\n value: \"quay.io/mongodb\"\n - name: MDB_COMMUNITY_IMAGE_TYPE\n value: \"ubi8\"\n # Community Env Vars End\n - name: MDB_SEARCH_REPO_URL\n value: \"quay.io/mongodb\"\n - name: MDB_SEARCH_NAME\n value: \"mongodb-search\"\n - name: MDB_SEARCH_VERSION\n value: \"1.70.1\"\n - name: MDB_ENVOY_IMAGE\n value: \"envoyproxy/envoy:v1.37-latest\"\n - name: MDB_SEARCH_METRICS_FORWARDER_IMAGE\n value: \"otel/opentelemetry-collector-contrib:0.152.0\"\n - name: MDB_VOYAGEAI_REPO_URL\n value: \"quay.io/mongodb/voyageai\"\n volumes:\n - name: webhook-server-dir\n emptyDir: {}\n\n```\n\n### Optional. Wait for the operator deployment.\n\nEnsure that the Kubernetes Operator is fully operational before proceeding with the MongoDB Search and Vector Search deployment. Run the following command to verify that all operator components are running and available.\n\n```shell\nkubectl --context \"${K8S_CTX}\" -n \"${MDB_NS}\" rollout status --timeout=2m deployment/mongodb-kubernetes-operator\necho \"Operator deployment in ${MDB_NS} namespace\"\nkubectl --context \"${K8S_CTX}\" -n \"${MDB_NS}\" get deployments\necho; echo \"Operator pod in ${MDB_NS} namespace\"\nkubectl --context \"${K8S_CTX}\" -n \"${MDB_NS}\" get pods\n\n```\n\n```shell\nWaiting for deployment \"mongodb-kubernetes-operator\" rollout to finish: 0 of 1 updated replicas are available...\ndeployment \"mongodb-kubernetes-operator\" successfully rolled out\nOperator deployment in mongodb namespace\nNAME READY UP-TO-DATE AVAILABLE AGE\nmongodb-kubernetes-operator 1/1 1 1 3s\n\nOperator pod in mongodb namespace\nNAME READY STATUS RESTARTS AGE\nmongodb-kubernetes-operator-784795fb96-xhvpc 1/1 Running 0 3s\n\n```\n\n### Required. Create and load the MongoDB user secrets.\n\nMongoDB requires authentication for secure access. In this step, you create three Kubernetes secrets:\n\n- `mdb-admin-user-password`: Credentials for the MongoDB administrator.\n\n- `mdb-user-password`: Credentials for the user authorized to perform search queries.\n\n- `mdbc-rs-search-sync-source-password`: Credentials for a dedicated search user used internally by the `mongot` process to synchronize data and manage indexes.\n\nKubernetes Operator uses passwords from those secrets to automatically create the users in the MongoDB database.\n\nTo create the secrets, copy, paste, and run the following command:\n\n```shell\n# Create admin user secret\nkubectl create secret generic mdb-admin-user-password \\\n --from-literal=password=\"${MDB_ADMIN_USER_PASSWORD}\" \\\n --dry-run=client -o yaml | kubectl apply --context \"${K8S_CTX}\" --namespace \"${MDB_NS}\" -f -\n\n# Create search sync source user secret\nkubectl create secret generic \"${MDB_RESOURCE_NAME}-search-sync-source-password\" \\\n --from-literal=password=\"${MDB_SEARCH_SYNC_USER_PASSWORD}\" \\\n --dry-run=client -o yaml | kubectl apply --context \"${K8S_CTX}\" --namespace \"${MDB_NS}\" -f -\n\n# Create regular user secret\nkubectl create secret generic mdb-user-password \\\n --from-literal=password=\"${MDB_USER_PASSWORD}\" \\\n --dry-run=client -o yaml | kubectl apply --context \"${K8S_CTX}\" --namespace \"${MDB_NS}\" -f -\n\necho \"User secrets created.\"\n\n```\n\n```\nsecret/mdb-admin-user-password created\nsecret/mdbc-rs-search-sync-source-password created\nsecret/mdb-user-password created\n```"} -{"chunk_id": "691eb238e337baf834ef5131-4", "page_id": "691eb238e337baf834ef5131", "source_name": "mck", "product_name": "MongoDB Controllers for Kubernetes", "url": "https://mongodb.com/docs/kubernetes/current/tutorial/install-fts-vs-with-community", "title": "Install and use With MongoDB Community Edition", "text": "### Conditional. Install the `cert-manager`.\n\nThe `cert-manager` is required for managing TLS (Transport Layer Security) certificates. If you already have `cert-manager` installed in your cluster, skip this step. Otherwise, install `cert-manager` using Helm.\n\nTo install `cert-manager` in the `cert-manager` namespace, run the following command in your terminal:\n\n```shell\nhelm upgrade --install \\\n cert-manager \\\n oci://quay.io/jetstack/charts/cert-manager \\\n --kube-context \"${K8S_CTX}\" \\\n --namespace \"${CERT_MANAGER_NAMESPACE}\" \\\n --create-namespace \\\n --set crds.enabled=true\n\nfor deployment in cert-manager cert-manager-cainjector cert-manager-webhook; do\n kubectl --context \"${K8S_CTX}\" \\\n -n \"${CERT_MANAGER_NAMESPACE}\" \\\n wait --for=condition=Available \"deployment/${deployment}\" --timeout=300s\ndone\n\necho \"cert-manager is ready in namespace ${CERT_MANAGER_NAMESPACE}.\"\n\n```\n\n### Required. Prepare certificate issuer and CA infrastructure.\n\nCreate the certificate authority infrastructure that will issue TLS (Transport Layer Security) certificates for `MongoDB` and `MongoDBSearch` resources. The commands perform the following actions:\n\n- Create a self-signed `ClusterIssuer`.\n\n- Generate a CA certificate.\n\n- Publish a cluster-wide CA issuer that all namespaces can use.\n\n- Expose the CA bundle through a `ConfigMap` so that MongoDB resources can use it.\n\n```shell\n# Bootstrap a self-signed ClusterIssuer that will mint the CA material consumed by\n# the MongoDBCommunity deployment.\nkubectl apply --context \"${K8S_CTX}\" -f - < \"${TMP_CA_CERT}\"\n\n# Expose the CA bundle through a ConfigMap for workloads and the MongoDBCommunity resource.\nkubectl --context \"${K8S_CTX}\" create configmap \"${MDB_TLS_CA_CONFIGMAP}\" -n \"${MDB_NS}\" \\\n --from-file=ca-pem=\"${TMP_CA_CERT}\" --from-file=mms-ca.crt=\"${TMP_CA_CERT}\" \\\n --from-file=ca.crt=\"${TMP_CA_CERT}\" \\\n --dry-run=client -o yaml | kubectl --context \"${K8S_CTX}\" apply -f -\n\necho \"Cluster-wide CA issuer ${MDB_TLS_CA_ISSUER} is ready.\"\n\n```\n\n### Required. Issue TLS certificates.\n\nIssue TLS (Transport Layer Security) certificates for both the `MongoDB` server and the `MongoDBSearch` service. The MongoDB server certificate includes all necessary DNS names for the pod and service communication. Both certificates support server and client authentication.\n\n```shell\nserver_certificate=\"${MDB_RESOURCE_NAME}-server-tls\"\nsearch_certificate=\"${MDB_RESOURCE_NAME}-search-tls\"\n\nmongo_dns_names=()\nfor ((member = 0; member < MDB_MEMBERS; member++)); do\n mongo_dns_names+=(\"${MDB_RESOURCE_NAME}-${member}\")\n mongo_dns_names+=(\"${MDB_RESOURCE_NAME}-${member}.${MDB_RESOURCE_NAME}-svc.${MDB_NS}.svc.cluster.local\")\ndone\nmongo_dns_names+=(\n \"${MDB_RESOURCE_NAME}-svc.${MDB_NS}.svc.cluster.local\"\n \"*.${MDB_RESOURCE_NAME}-svc.${MDB_NS}.svc.cluster.local\"\n)\n\nsearch_dns_names=(\n \"*.${MDB_RESOURCE_NAME}-search-0-svc.${MDB_NS}.svc.cluster.local\"\n)\n\nrender_dns_list() {\n local dns_list=(\"$@\")\n for dns in \"${dns_list[@]}\"; do\n printf \" - \\\"%s\\\"\\n\" \"${dns}\"\n done\n}\n\nkubectl apply --context \"${K8S_CTX}\" -n \"${MDB_NS}\" -f - <\n\n \n \n `mdb-user`\n\n \n \n User that can restore database and run search queries. This user uses the `mdb-user-password` secret to perform these operations.\n\n \n \n \n \n `search-sync-source`\n\n \n \n User that MongoDB Search uses to connect to MongoDB database in order to manage and build indexes. This user uses `searchCoordinator` role that the Kubernetes operator creates. This uses uses the `mdbc-rs-search-sync-source-password` secret to connect `mongot` to `mongod`.\n\n \n \n \n \n `admin-user`\n\n \n \n Database admin user.\n\n \n \n The Kubernetes Operator uses this resource to configure a MongoDB replica set with 3 members.\n\n To create the secrets, copy, paste, and run the following commands:\n\n ```shell\n kubectl apply --context \"${K8S_CTX}\" -n \"${MDB_NS}\" -f - <\n\n \n\n ```shell\n # create a Kubernetes secret that would have embedding model's API Keys\n kubectl create secret generic \"${AUTO_EMBEDDING_API_KEY_SECRET_NAME}\" \\\n --from-literal=query-key=\"${AUTO_EMBEDDING_API_QUERY_KEY}\" \\\n --from-literal=indexing-key=\"${AUTO_EMBEDDING_API_INDEXING_KEY}\" --context \"${K8S_CTX}\" -n \"${MDB_NS}\"\n\n # create MongoDBSearch resource, enabling the auto embedding using the API Keys provided above\n kubectl apply --context \"${K8S_CTX}\" -n \"${MDB_NS}\" -f - <\n\n \n\n ```shell\n kubectl apply --context \"${K8S_CTX}\" -n \"${MDB_NS}\" -f - <\n\n \n\n- Wait for the MongoDBSearch resource deployment to complete.\n\n When you apply the MongoDBSearch custom resource, the Kubernetes operator begins deploying the search nodes (pods). This step pauses the execution until the `mdbc-rs` MongoDBSearch resource's status phase is `Running`, which indicates that the MongoDB Search is operational.\n\n ```shell\n echo \"Waiting for MongoDBSearch resource to reach Running phase...\"\n kubectl --context \"${K8S_CTX}\" -n \"${MDB_NS}\" wait \\\n --for=jsonpath='{.status.phase}'=Running mdbs/\"${MDB_RESOURCE_NAME}\" --timeout=300s\n\n ```\n\n### Optional. Verify the MongoDB Community resource status.\n\nEnsure that the `MongoDBCommunity` resource deployment with MongoDBSearch was successful.\n\n```javascript\necho \"Waiting for MongoDBCommunity resource to reach Running phase...\"\nkubectl --context \"${K8S_CTX}\" -n \"${MDB_NS}\" wait \\\n --for=jsonpath='{.status.phase}'=Running mdbc/mdbc-rs --timeout=400s\necho; echo \"MongoDBCommunity resource\"\nkubectl --context \"${K8S_CTX}\" -n \"${MDB_NS}\" get mdbc/mdbc-rs\necho; echo \"Pods running in cluster ${K8S_CTX}\"\nkubectl --context \"${K8S_CTX}\" -n \"${MDB_NS}\" get pods\n\n```\n\n### Optional. View all the running pods in your namespace.\n\nView all the running pods in your namespace pods for the MongoDB replica set members, the MongoDB Controllers for Kubernetes Operator, and the Search nodes.\n\n```shell\necho; echo \"MongoDBCommunity resource\"\nkubectl --context \"${K8S_CTX}\" -n \"${MDB_NS}\" get mdbc/mdbc-rs\necho; echo \"MongoDBSearch resource\"\nkubectl --context \"${K8S_CTX}\" -n \"${MDB_NS}\" get mdbs/mdbc-rs\necho; echo \"Pods running in cluster ${K8S_CTX}\"\nkubectl --context \"${K8S_CTX}\" -n \"${MDB_NS}\" get pods\n\n```\n\n```shell\n\nMongoDBCommunity resource\nNAME PHASE VERSION\nmdbc-rs Running 8.3.4\n\nMongoDBSearch resource\nNAME PHASE VERSION LOADBALANCER METRICSFORWARDER AGE\nmdbc-rs Running 1.70.1 Running 5m11s\n\nPods running in cluster kind-kind\nNAME READY STATUS RESTARTS AGE\nmdbc-rs-0 2/2 Running 1 (25s ago) 7m42s\nmdbc-rs-1 2/2 Running 1 (2m58s ago) 6m40s\nmdbc-rs-2 2/2 Running 1 (102s ago) 5m54s\nmdbc-rs-search-0-0 1/1 Running 0 4m31s\nmongodb-kubernetes-operator-784795fb96-xhvpc 1/1 Running 0 8m6s\n\n```\n\n## Verify the Deployment\n\nAfter the procedure completes, confirm the deployment is healthy before running queries.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nCheckpoint\n\n\nVerification Step\n\n
\nMongoDB Community resource running\n\n\nRun `kubectl get mongodbcommunity -n ` and confirm the `MongoDBCommunity` resource shows the `Running` phase.\n\n
\nMongoDB Search resource running\n\n\nRun `kubectl get mongodbsearch -n ` and confirm the `MongoDBSearch` resource shows the `Running` phase.\n\n
\nAll pods healthy\n\n\nRun `kubectl get pods -n ` and confirm all replica set member pods and search pods show a `Running` status with all containers ready.\n\n
\nSearch queries succeed\n\n\nConnect to the replica set and run a MongoDB Search or Vector Search query to confirm the search index is reachable.\n\n
\n\n## Next Steps\n\nAfter you deploy MongoDB Search and Vector Search with MongoDB Community Edition, you can:\n\n- **Add data and run queries**: Load data into your MongoDB cluster, create MongoDB Search and Vector Search indexes, and run queries against your data. To learn more, see Use MongoDB Search and Vector Search.\n\n- **Configure Search settings**: Adjust resource settings for your search deployment. To learn more, see MongoDB Search and Vector Search Settings."} -{"chunk_id": "68a95c105e79d242619db6af-0", "page_id": "68a95c105e79d242619db6af", "source_name": "mck", "product_name": "MongoDB Controllers for Kubernetes", "url": "https://mongodb.com/docs/kubernetes/current/reference-architectures/multi-cluster/istio-service-mesh", "title": "Istio Service Mesh", "text": "# Istio Service Mesh\n\nWhile it is possible to deploy Multi-Cluster Ops Manager, Multi-Cluster Sharded Cluster, and Multi-Cluster Replica Set configurations without a service mesh, the recommended approach (presented here) is to leverage a service mesh to handle the networking across multiple Kubernetes clusters. To learn more, see How Does the Kubernetes Operator Establish Connectivity.\n\nThis page walks you through the process of deploying and validating an Istio service mesh across multiple Kubernetes clusters. Istio is only one of many options for deploying a service mesh, and it is not supported by MongoDB.\n\nIstio is not supported by MongoDB and is only one of many tools you can use to deploy a service mesh across your Kubernetes clusters.\n\n## Prerequisites\n\nBefore you begin, perform the following tasks:\n\n- Install `kubectl`.\n\n- Set the `K8S_CLUSTER_*_CONTEXT_NAME` environment variables as explained in the GKE Clusters guide.\n\n## Source Code\n\nYou can find all included source code in the MongoDB Kubernetes Operator repository.\n\n## Procedure\n\n### Clone the Kubernetes Operator repository.\n\nRun the following command to clone the repository.\n\n```bash\ngit clone https://github.com/mongodb/mongodb-kubernetes.git\ncd mongodb-kubernetes\ngit checkout 1.14.0\ncd public/architectures\n```\n\n### Install Istio service mesh.\n\nInstall Istio service mesh to allow cross-cluster DNS (Domain Name System) resolution and network connectivity between Kubernetes clusters.\n\n```bash\nCTX_CLUSTER1=${K8S_CLUSTER_0_CONTEXT_NAME} \\\nCTX_CLUSTER2=${K8S_CLUSTER_1_CONTEXT_NAME} \\\nCTX_CLUSTER3=${K8S_CLUSTER_2_CONTEXT_NAME} \\\nISTIO_VERSION=\"1.20.2\" \\\n./install_istio_separate_network.sh\n\n```\n\n### Label the Kubernetes namespaces.\n\nLabel the Kubernetes namespaces in each cluster to enable Istio sidecar injection.\n\n```\nkubectl --context \"${K8S_CLUSTER_0_CONTEXT_NAME}\" label namespace \"${OPERATOR_NAMESPACE}\" istio-injection=enabled --overwrite\nkubectl --context \"${K8S_CLUSTER_1_CONTEXT_NAME}\" label namespace \"${OPERATOR_NAMESPACE}\" istio-injection=enabled --overwrite\nkubectl --context \"${K8S_CLUSTER_2_CONTEXT_NAME}\" label namespace \"${OPERATOR_NAMESPACE}\" istio-injection=enabled --overwrite\n\nkubectl --context \"${K8S_CLUSTER_0_CONTEXT_NAME}\" label namespace \"${OM_NAMESPACE}\" istio-injection=enabled --overwrite\nkubectl --context \"${K8S_CLUSTER_1_CONTEXT_NAME}\" label namespace \"${OM_NAMESPACE}\" istio-injection=enabled --overwrite\nkubectl --context \"${K8S_CLUSTER_2_CONTEXT_NAME}\" label namespace \"${OM_NAMESPACE}\" istio-injection=enabled --overwrite\n\nkubectl --context \"${K8S_CLUSTER_0_CONTEXT_NAME}\" label namespace \"${MDB_NAMESPACE}\" istio-injection=enabled --overwrite\nkubectl --context \"${K8S_CLUSTER_1_CONTEXT_NAME}\" label namespace \"${MDB_NAMESPACE}\" istio-injection=enabled --overwrite\nkubectl --context \"${K8S_CLUSTER_2_CONTEXT_NAME}\" label namespace \"${MDB_NAMESPACE}\" istio-injection=enabled --overwrite\n\n```"} -{"chunk_id": "68a95c105e79d242619db6af-1", "page_id": "68a95c105e79d242619db6af", "source_name": "mck", "product_name": "MongoDB Controllers for Kubernetes", "url": "https://mongodb.com/docs/kubernetes/current/reference-architectures/multi-cluster/istio-service-mesh", "title": "Istio Service Mesh", "text": "### Optional. Check cluster connectivity.\n\nThe following optional scripts verify whether the service mesh is configured correctly for cross-cluster DNS resolution and connectivity.\n\n- Create a Kubernetes namespace for the connectivity test.\n\n ```bash\n kubectl --context \"${K8S_CLUSTER_0_CONTEXT_NAME}\" create namespace \"connectivity-test\"\n kubectl --context \"${K8S_CLUSTER_0_CONTEXT_NAME}\" label namespace \"connectivity-test\" istio-injection=enabled --overwrite\n\n kubectl --context \"${K8S_CLUSTER_1_CONTEXT_NAME}\" create namespace \"connectivity-test\"\n kubectl --context \"${K8S_CLUSTER_1_CONTEXT_NAME}\" label namespace \"connectivity-test\" istio-injection=enabled --overwrite\n\n kubectl --context \"${K8S_CLUSTER_2_CONTEXT_NAME}\" create namespace \"connectivity-test\"\n kubectl --context \"${K8S_CLUSTER_2_CONTEXT_NAME}\" label namespace \"connectivity-test\" istio-injection=enabled --overwrite\n\n ```\n\n- Run this script on cluster 0:\n\n ```bash\n kubectl apply --context \"${K8S_CLUSTER_0_CONTEXT_NAME}\" -n \"connectivity-test\" -f - <&1);\n\n if grep \"Hostname: ${target_pod}\" &>/dev/null <<< \"${out}\"\n then\n echo \"SUCCESS\"\n else\n echo \"ERROR: ${out}\"\n return 1\n fi\n\n ```\n\n ```bash\n Checking cross-cluster DNS resolution and connectivity from echoserver1-0 in gke_scratch-kubernetes-team_europe-central2-b_k8s-mdb-1-6abb9ad27d6x076f80-29737 to echoserver0-0\n SUCCESS\n\n ```\n\n- Verify Pod 1 from cluster 0:\n\n ```bash\n source_cluster=${K8S_CLUSTER_0_CONTEXT_NAME}\n target_pod=\"echoserver1-0\"\n source_pod=\"echoserver0-0\"\n target_url=\"http://${target_pod}.connectivity-test.svc.cluster.local:8080\"\n echo \"Checking cross-cluster DNS resolution and connectivity from ${source_pod} in ${source_cluster} to ${target_pod}\"\n out=$(kubectl exec --context \"${source_cluster}\" -n \"connectivity-test\" \"${source_pod}\" -- \\\n /bin/bash -c \"curl -v ${target_url}\" 2>&1);\n\n if grep \"Hostname: ${target_pod}\" &>/dev/null <<< \"${out}\"\n then\n echo \"SUCCESS\"\n else\n echo \"ERROR: ${out}\"\n return 1\n fi\n\n ```\n\n ```bash\n Checking cross-cluster DNS resolution and connectivity from echoserver0-0 in gke_scratch-kubernetes-team_europe-central2-a_k8s-mdb-0-6abb9ad27d6x076f80-29737 to echoserver1-0\n SUCCESS\n\n ```\n\n- Verify Pod 1 from cluster 2:\n\n ```bash\n source_cluster=${K8S_CLUSTER_2_CONTEXT_NAME}\n target_pod=\"echoserver1-0\"\n source_pod=\"echoserver2-0\"\n target_url=\"http://${target_pod}.connectivity-test.svc.cluster.local:8080\"\n echo \"Checking cross-cluster DNS resolution and connectivity from ${source_pod} in ${source_cluster} to ${target_pod}\"\n out=$(kubectl exec --context \"${source_cluster}\" -n \"connectivity-test\" \"${source_pod}\" -- \\\n /bin/bash -c \"curl -v ${target_url}\" 2>&1);\n\n if grep \"Hostname: ${target_pod}\" &>/dev/null <<< \"${out}\"\n then\n echo \"SUCCESS\"\n else\n echo \"ERROR: ${out}\"\n return 1\n fi\n\n ```"} -{"chunk_id": "68a95c105e79d242619db6af-2", "page_id": "68a95c105e79d242619db6af", "source_name": "mck", "product_name": "MongoDB Controllers for Kubernetes", "url": "https://mongodb.com/docs/kubernetes/current/reference-architectures/multi-cluster/istio-service-mesh", "title": "Istio Service Mesh", "text": " ```bash\n Checking cross-cluster DNS resolution and connectivity from echoserver2-0 in gke_scratch-kubernetes-team_europe-central2-c_k8s-mdb-2-6abb9ad27d6x076f80-29737 to echoserver1-0\n SUCCESS\n\n ```\n\n- Verify Pod 2 from cluster 0:\n\n ```bash\n source_cluster=${K8S_CLUSTER_0_CONTEXT_NAME}\n target_pod=\"echoserver2-0\"\n source_pod=\"echoserver0-0\"\n target_url=\"http://${target_pod}.connectivity-test.svc.cluster.local:8080\"\n echo \"Checking cross-cluster DNS resolution and connectivity from ${source_pod} in ${source_cluster} to ${target_pod}\"\n out=$(kubectl exec --context \"${source_cluster}\" -n \"connectivity-test\" \"${source_pod}\" -- \\\n /bin/bash -c \"curl -v ${target_url}\" 2>&1);\n\n if grep \"Hostname: ${target_pod}\" &>/dev/null <<< \"${out}\"\n then\n echo \"SUCCESS\"\n else\n echo \"ERROR: ${out}\"\n return 1\n fi\n\n ```\n\n ```bash\n Checking cross-cluster DNS resolution and connectivity from echoserver0-0 in gke_scratch-kubernetes-team_europe-central2-a_k8s-mdb-0-6abb9ad27d6x076f80-29737 to echoserver2-0\n SUCCESS\n\n ```\n\n- Run the cleanup script:\n\n ```bash\n kubectl --context \"${K8S_CLUSTER_0_CONTEXT_NAME}\" -n \"connectivity-test\" delete statefulset echoserver0\n kubectl --context \"${K8S_CLUSTER_1_CONTEXT_NAME}\" -n \"connectivity-test\" delete statefulset echoserver1\n kubectl --context \"${K8S_CLUSTER_2_CONTEXT_NAME}\" -n \"connectivity-test\" delete statefulset echoserver2\n kubectl --context \"${K8S_CLUSTER_0_CONTEXT_NAME}\" -n \"connectivity-test\" delete service echoserver\n kubectl --context \"${K8S_CLUSTER_1_CONTEXT_NAME}\" -n \"connectivity-test\" delete service echoserver\n kubectl --context \"${K8S_CLUSTER_2_CONTEXT_NAME}\" -n \"connectivity-test\" delete service echoserver\n kubectl --context \"${K8S_CLUSTER_0_CONTEXT_NAME}\" -n \"connectivity-test\" delete service echoserver0-0\n kubectl --context \"${K8S_CLUSTER_1_CONTEXT_NAME}\" -n \"connectivity-test\" delete service echoserver1-0\n kubectl --context \"${K8S_CLUSTER_2_CONTEXT_NAME}\" -n \"connectivity-test\" delete service echoserver2-0\n kubectl --context \"${K8S_CLUSTER_0_CONTEXT_NAME}\" delete ns \"connectivity-test\"\n kubectl --context \"${K8S_CLUSTER_1_CONTEXT_NAME}\" delete ns \"connectivity-test\"\n kubectl --context \"${K8S_CLUSTER_2_CONTEXT_NAME}\" delete ns \"connectivity-test\"\n\n ```"} -{"chunk_id": "6a514d73d727379c91b9dc05-0", "page_id": "6a514d73d727379c91b9dc05", "source_name": "mck", "product_name": "MongoDB Controllers for Kubernetes", "url": "https://mongodb.com/docs/kubernetes/current/fts-vs/deployment/upgrade-downgrade", "title": "Upgrade or Downgrade", "text": "# Upgrade or Downgrade"} -{"chunk_id": "68a95c105e79d242619db717-0", "page_id": "68a95c105e79d242619db717", "source_name": "mck", "product_name": "MongoDB Controllers for Kubernetes", "url": "https://mongodb.com/docs/kubernetes/current/tutorial/deploy-replica-set", "title": "Deploy a Replica Set", "text": "# Deploy a Replica Set\n\nAt any place on this page that says *Ops Manager*, you can substitute *Cloud Manager*.\n\n- You can use the Kubernetes Operator to deploy MongoDB resources with Cloud Manager and with Ops Manager version 6.0.x or later.\n\n- You can use the Atlas Operator to deploy MongoDB resources to Atlas.\n\nKubernetes Operator doesn't support arbiter nodes.\n\nA replica set is a group of MongoDB deployments that maintain the same data set. Replica sets provide redundancy and high availability and are the basis for all production deployments.\n\nTo learn more about replica sets, see the Replication Introduction in the MongoDB manual.\n\nUse this procedure to deploy a new replica set that Ops Manager manages. After deployment, use Ops Manager to manage the replica set, including such operations as adding, removing, and reconfiguring members.\n\n## Considerations\n\nWhen you deploy your replica set via the Kubernetes Operator, you must choose whether to encrypt connections using TLS (Transport Layer Security) certificates.\n\nThe following procedure for TLS-Encrypted connections:\n\n- Establishes TLS (Transport Layer Security)-encrypted connections between MongoDB hosts in the replica set.\n\n- Establishes TLS (Transport Layer Security)-encrypted connections between client applications and MongoDB deployments.\n\n- Requires valid certificates for TLS (Transport Layer Security) encryption.\n\nThe following procedure for Non-Encrypted Connections:\n\n- Doesn't encrypt connections between MongoDB hosts in the replica set.\n\n- Doesn't encrypt connections between client applications and MongoDB deployments.\n\n- Has fewer setup requirements than a deployment with TLS (Transport Layer Security)-encrypted connections.\n\nTo set up TLS (Transport Layer Security) encryption for a sharded cluster, see Deploy a Sharded Cluster.\n\nSelect the appropriate tab based on whether you want to encrypt your replica set connections with TLS (Transport Layer Security).\n\n## Prerequisites\n\n\n\n\n\nTo deploy a replica set using an object, you must:\n\n- Have or create an Ops Manager instance or a Cloud Manager organization.\n\n- Have or install the MongoDB Controllers for Kubernetes Operator.\n\n- Create or generate a Kubernetes Operator ConfigMap.\n\n- Create credentials for the Kubernetes Operator or configure a different secret storage tool.\n\nTo avoid storing secrets in single-cluster Kubernetes deployments, you can migrate all secrets to a secret storage tool. Deployments on multiple Kubernetes clusters don't support storing secrets in secret storage tools, such as HashiCorp Vault.\n\n- Generate one TLS (Transport Layer Security) certificate for each of the following components:\n\n - Your replica set. Ensure that you add SAN (Subject Alternative Name)s for each Kubernetes pod that hosts a member of your replica set to the certificate.\n\n In your TLS (Transport Layer Security) certificate, the SAN (Subject Alternative Name) for each pod must use the following format:\n\n ```none\n .-svc..svc.cluster.local\n ```\n\n If you're using an ACME (Automatic Certificate Management Environment) based service provider such as Let's Encrypt to issue TLS (Transport Layer Security) certificates, the provider might prohibit you from adding the Pod's default FQDN (fully qualified domain name)s (`*.svc.cluster.local`) to SAN (Subject Alternative Name)s in the certificate.\n\n To use an ACME (Automatic Certificate Management Environment) based certificate, you must configure the certificate for your replica set resource. To learn more, see the step about ACME (Automatic Certificate Management Environment) based TLS (Transport Layer Security) certificates in the procedure.\n\n - Your project's MongoDB Agent. For the MongoDB Agent certificate, ensure that you meet the following requirements:\n\n - The Common Name in the TLS (Transport Layer Security) certificate is not empty.\n\n - The combined Organization and Organizational Unit in each TLS (Transport Layer Security) certificate differs from the Organization and Organizational Unit in the TLS (Transport Layer Security) certificate for your replica set members.\n\n- You must have the CA (Certificate Authority) certificate file and name it `ca-pem`.\n\n- You must have the key that you used to sign your TLS (Transport Layer Security) certificates.\n\nThe Kubernetes Operator uses kubernetes.io/tls secrets to store TLS (Transport Layer Security) certificates and private keys for Ops Manager and MongoDB resources. Starting in Kubernetes Operator version 1.17.0, the Kubernetes Operator doesn't support concatenated PEM (Privacy-Enhanced Mail) files stored as Opaque secrets.\n\n\n\n\n\nreplica setTo deploy a replica set using an object, you must:\n\n- Have or create an Ops Manager instance or a Cloud Manager organization.\n\n- Have or install the MongoDB Controllers for Kubernetes Operator.\n\n- Create or generate a Kubernetes Operator ConfigMap.\n\n- Create credentials for the Kubernetes Operator or configure a different secret storage tool.\n\nTo avoid storing secrets in single-cluster Kubernetes deployments, you can migrate all secrets to a secret storage tool. Deployments on multiple Kubernetes clusters don't support storing secrets in secret storage tools, such as HashiCorp Vault.\n\n\n\n\n\n## Deploy a Replica Set\n\n\n\n\n\n`-.``replica-set-1.example.com``spec.externalAccess`default values### Configure `kubectl` to default to your namespace.\n\nIf you have not already, run the following command to execute all `kubectl` commands in the namespace you created.\n\nIf you are deploying an Ops Manager resource in a multi-Kubernetes cluster MongoDB deployment:\n\n- Set the `context` to the name of the central cluster, such as: `kubectl config set context \"$MDB_CENTRAL_CLUSTER_FULL_NAME\"`.\n\n- Set the `--namespace` to the same scope that you used for your multi-Kubernetes cluster MongoDB deployment, such as: `kubectl config --namespace \"mongodb\"`.\n\n```sh\nkubectl config set-context $(kubectl config current-context) --namespace=\n```\n\n### Create the secret for your replica set's TLS (Transport Layer Security) certificate.\n\nRun this `kubectl` command to create a new secret that stores the replica set's certificate:\n\n```sh\nkubectl create secret tls --cert \\\n --cert= \\\n --key=\n```\n\nYou must prefix your secrets with `-`.\n\nFor example, if you call your deployment `my-deployment` and you set the prefix to `mdb`, you must name the TLS (Transport Layer Security) secret for the client TLS (Transport Layer Security) communications `mdb-my-deployment-cert`. Also, you must name the TLS (Transport Layer Security) secret for internal cluster authentication (if enabled) `mdb-my-deployment-clusterfile`.\n\nIf you're using HashiCorp Vault as your secret storage tool, you can Create a Vault Secret instead.\n\nTo learn about your options for secret storage, see Configure Secret Storage.\n\n### Create the secret for your agent's TLS certificate.\n\nRun this `kubectl` command to create a new secret that stores the agent's TLS certificate:\n\n```sh\nkubectl create secret tls --agent-certs \\\n --cert= \\\n --key=\n```\n\nIf you're using HashiCorp Vault as your secret storage tool, you can Create a Vault Secret instead.\n\n### Create the ConfigMap to link your CA (Certificate Authority) with your deployment.\n\nRun this `kubectl` command to link your CA (Certificate Authority) to your replica set and specify the CA (Certificate Authority) certificate file.\n\nThe Kubernetes Operator requires that the certificate for the `MongoDB` resource is named `ca-pem` in the ConfigMap.\n\n```sh\nkubectl create configmap custom-ca --from-file=ca-pem=\n```"} -{"chunk_id": "68a95c105e79d242619db717-1", "page_id": "68a95c105e79d242619db717", "source_name": "mck", "product_name": "MongoDB Controllers for Kubernetes", "url": "https://mongodb.com/docs/kubernetes/current/tutorial/deploy-replica-set", "title": "Deploy a Replica Set", "text": "### Copy the sample replica set resource.\n\nChange the settings of this YAML (Yet Another Markup Language) file to match your desired replica set configuration.\n\n```yaml\n---\napiVersion: mongodb.com/v1\nkind: MongoDB\nmetadata:\n name: \nspec:\n members: 3\n version: \"8.0.0\"\n opsManager:\n configMapRef:\n # Must match metadata.name in ConfigMap file\n name: \n credentials: \n type: ReplicaSet\n persistent: true\n...\n```\n\n```yaml\n security:\n tls:\n ca: \n certsSecretPrefix: \n...\n```\n\n### Paste the copied example to create a new replica set resource.\n\nOpen your preferred text editor and paste the object specification into a new text file.\n\n### Change the settings to your preferred values.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nKey\n\n\nType\n\n\nDescription\n\n\nExample\n\n
\n`metadata.name`\n\n\nstring\n\n\nLabel for this Kubernetes replica set object.\n\nResource names must be 44 characters or less.\n\nTo learn more, see `metadata.name` and Kubernetes documentation on names.\n\n\n`myproject`\n\n
\n`spec.members`\n\n\ninteger\n\n\nNumber of members of the replica set.\n\n\n`3`\n\n
\n`spec.version`\n\n\nstring\n\n\nVersion of MongoDB that this replica set should run.\n\nThe format should be `X.Y.Z` for the Community edition and `X.Y.Z-ent` for the Enterprise edition.\n\nIMPORTANT: Ensure that you choose a compatible MongoDB Server version. Compatible versions differ depending on the base image that the MongoDB database resource uses.\n\nTo learn more about MongoDB versioning, see MongoDB Versioning in the MongoDB Manual.\n\n\n`8.0.0`\n\n
\n`spec``.opsManager``.configMapRef``.name`\n\n\nstring\n\n\nName of the ConfigMap with the Ops Manager connection configuration. The `spec.cloudManager.configMapRef.name` setting is an alias for this setting and can be used in its place.\n\nThis value must exist on the *same* namespace as the resource you want to create.\n\nIMPORTANT: The Kubernetes Operator tracks any changes to the ConfigMap and reconciles the state of the `MongoDB` resource.\n\n\n``\n\n
\n`spec.credentials`\n\n\nstring\n\n\nName of the secret you created as Ops Manager API (Application Programming Interface) authentication credentials for the Kubernetes Operator to communicate with Ops Manager.\n\nThe Ops Manager Kubernetes Secret object holding the Credentials must exist on the **same** Namespace as the resource you want to create.\n\nIMPORTANT: The Kubernetes Operator tracks any changes to the Secret and reconciles the state of the `MongoDB` resource.\n\n\n``\n\n
\n`spec.type`\n\n\nstring\n\n\nType of `MongoDB` resource to create.\n\n\n`ReplicaSet`\n\n
\n`spec.persistent`\n\n\nstring\n\n\n*Optional.*\n\nFlag indicating if this `MongoDB` resource should use Persistent Volumes for storage. Persistent volumes are not deleted when the `MongoDB` resource is stopped or restarted.\n\nIf this value is `true`, then `spec.podSpec.persistence.single` is set to its default value of `16Gi`.\n\nTo change your Persistent Volume Claims configuration, configure the following collections to meet your deployment requirements:\n\n- If you want one Persistent Volume for each Pod, configure the `spec.podSpec.persistence.single` collection.\n\n- If you want separate Persistent Volumes for data, journals, and logs for each Pod, configure the following collections:\n\n - `spec.podSpec.persistence.multiple.data`\n\n - `spec.podSpec.persistence.multiple.journal`\n\n - `spec.podSpec.persistence.multiple.logs`\n\nWARNING: Grant your containers permission to write to your Persistent Volume. The Kubernetes Operator sets `fsGroup = 2000`, `runAsUser = 2000`, and `runAsNonRoot = true` in `securityContext`. Kubernetes Operator sets `fsgroup` equal to `runAsUser` to make the volume writable for a user that runs the main process in the container. To learn more, see Configure a Security Context for a Pod or Container and the related discussion in the Kubernetes documentation. If redeploying the resource doesn't fix issues with your Persistent Volume, contact MongoDB Support.\n\nIf you do not use Persistent Volumes, the Disk Usage and Disk IOPS charts cannot be displayed in either the Processes tab on the Deployment page or in the Metrics page when reviewing the data for this deployment.\n\n\n`true`\n\n
\n\n### Configure the TLS settings for your replica set resource using a custom certificate authority (CA).\n\nTo enable TLS (Transport Layer Security) in your deployment, configure the following settings in your Kubernetes object:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nKey\n\n\nType\n\n\nNecessity\n\n\nDescription\n\n\nExample\n\n
\n`spec.security``.tls.ca`\n\n\nstring\n\n\nRequired\n\n\nAdd the ConfigMap's name that stores the custom CA (Certificate Authority) that you used to sign your deployment's TLS (Transport Layer Security) certificates.\n\n\n``\n\n
\n`spec.security``.certsSecretPrefix`\n\n\nstring\n\n\nRequired\n\n\nAdd the `` of the secret name that contains your MongoDB deployment's TLS (Transport Layer Security) certificates.\n\nFor example, if you call your deployment `my-deployment` and you set the prefix to `mdb`, you must name the TLS (Transport Layer Security) secret for the client TLS (Transport Layer Security) communications `mdb-my-deployment-cert`. Also, you must name the TLS (Transport Layer Security) secret for internal cluster authentication (if enabled) `mdb-my-deployment-clusterfile`.\n\n\n`devDb`\n\n
"} -{"chunk_id": "68a95c105e79d242619db717-2", "page_id": "68a95c105e79d242619db717", "source_name": "mck", "product_name": "MongoDB Controllers for Kubernetes", "url": "https://mongodb.com/docs/kubernetes/current/tutorial/deploy-replica-set", "title": "Deploy a Replica Set", "text": "### Optional: Configure ACME (Automatic Certificate Management Environment) based TLS (Transport Layer Security) certificates for your replica set resource.\n\nIf you're using an ACME (Automatic Certificate Management Environment) based service provider such as Let's Encrypt to issue TLS (Transport Layer Security) certificates, the provider might prohibit you from adding the Pod's default FQDN (fully qualified domain name)s (`*.svc.cluster.local`) to SAN (Subject Alternative Name)s in the certificate.\n\nTo configure a certificate that doesn't contain the pod's FQDN (fully qualified domain name)s:\n\n- Issue the certificate for an external domain. For more information, see the Let's Encrypt documentation or the documentation for your provider.\n\n- Ensure that your certificate contains all hostnames that you plan to deploy in the replica set. Alternatively, you can issue a wildcard certificate for `*.`.\n\n- To use a certificate containing only external domains for your replica set deployment, you must change the default hostname used by the replica set:\n\n - If you prefer to configure the hostname while creating your Kubernetes cluster, change the default domain from `cluster.local` to the external domain when creating or recreating your Kubernetes cluster. Then, set this domain in your MongoDB resource by using the `spec.clusterDomain` setting.\n\n - Otherwise, create your MongoDB deployment with the following settings configured in your Kubernetes object:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nKey\n\n\nType\n\n\nNecessity\n\n\nDescription\n\n
\n`spec.externalAccess``.externalDomain`\n\n\nstring\n\n\nRequired\n\n\nAn external domain used to externally expose your replica set deployment.\n\nBy default, each replica set member uses the Kubernetes Pod's FQDN (fully qualified domain name) (`*.svc.cluster.local`) as the default hostname. However, if you add an external domain to this setting, the replica set uses a hostname that is a subdomain of the specified domain instead. This hostname uses the following format:\n\n`-.`\n\nFor example:\n\n`replica-set-1.example.com`\n\nAfter you deploy the replica set with this setting, the Kubernetes Operator uses the hostname with the external domain to override the `processes[n].hostname` field in the Ops Manager automation configuration. Then, the MongoDB Agent uses this hostname to connect to `mongod`.\n\nTo specify other hostnames for connecting to the replica set, you can use the `spec.connectivity.replicaSetHorizons` setting. However, the following connections still use the hostname with the external domain:\n\n- The MongoDB Agent to connect to `mongod`.\n\n- `mongod` to connect to other `mongod` instances.\n\nWARNING: Specifying this field changes how Ops Manager registers `mongod` processes. You can't change the value of this field or any `processes[n].hostname` fields in the Ops Manager automation configuration for a running replica set deployment.\n\n
\n`spec.externalAccess``.externalService.spec`\n\n\ncollection\n\n\nOptional\n\n\nConfiguration for the ServiceSpec.\n\nWhen you set the `spec.externalAccess` setting, the Kubernetes Operator automatically creates an external load balancer service with default values. You can override certain values or add new values depending on your needs. For example, if you intend to create NodePort services and don't need a load balancer, you must configure overrides in your Kubernetes specification:\n\n```yaml\nexternalAccess:\n externalService:\n annotations:\n # cloud-specific annotations for the service\n spec:\n type: NodePort # default is LoadBalancer\n # you can specify other spec overrides if necessary\n```\n\nFor more information about the Kubernetes specification, see ServiceSpec in the Kubernetes documentation.\n\n
\n`spec.externalAccess``.externalService.annotations`\n\n\ncollection\n\n\nOptional\n\n\nKey-value pairs that let you add cloud provider-specific configuration settings to all clusters in your deployment. To learn more, see annotations and the documentation for your Kubernetes cloud provider.\n\nYou can specify placeholder values to customize your annotations. To learn more, see `spec.externalAccess.externalService.annotations`.\n\n
\n\n### Add any additional accepted settings for a replica set deployment.\n\nYou can also add any of the following optional settings to the object specification file for a replica set deployment:\n\n- `spec.additionalMongodConfig`\n\n- `spec.backup.assignmentLabels`\n\n- `spec.backup.mode`\n\n- `spec.backup.snapshotSchedule.snapshotIntervalHours`\n\n- `spec.backup.snapshotSchedule.snapshotRetentionDays`\n\n- `spec.backup.snapshotSchedule.dailySnapshotRetentionDays`\n\n- `spec.backup.snapshotSchedule.weeklySnapshotRetentionWeeks`\n\n- `spec.backup.snapshotSchedule.monthlySnapshotRetentionMonths`\n\n- `spec.backup.snapshotSchedule.pointInTimeWindowHours`\n\n- `spec.backup.snapshotSchedule.referenceHourOfDay`\n\n- `spec.backup.snapshotSchedule.referenceMinuteOfHour`\n\n- `spec.backup.snapshotSchedule.fullIncrementalDayOfWeek`\n\n- `spec.clusterDomain`\n\n- `spec.connectivity.replicaSetHorizons`\n\n- `spec.featureCompatibilityVersion`\n\n- `spec.logLevel`\n\n- `spec.podSpec.persistence.single`\n\n- `spec.podSpec.persistence.multiple.data`\n\n- `spec.podSpec.persistence.multiple.journal`\n\n- `spec.podSpec.persistence.multiple.logs`\n\n- `spec.podSpec.podTemplate.spec.affinity.podAffinity`\n\n- `spec.podSpec.podTemplate.spec.affinity.podAntiAffinity.requiredDuringSchedulingIgnoredDuringExecution.topologyKey`\n\n- `spec.podSpec.podTemplate.spec.affinity.nodeAffinity`\n\n- `spec.podSpec.podTemplate.metadata`\n\n- `spec.podSpec.podTemplate.spec`\n\nYou must set `spec.clusterDomain` if your Kubernetes cluster has a default domain other than the default `cluster.local`. If you neither use the default nor set the `spec.clusterDomain` option, the Kubernetes Operator might not function as expected.\n\n### Save this replica set config file with a `.yaml` extension.\n\n### Start your replica set deployment.\n\nIn any directory, invoke the following Kubernetes command to create your replica set:\n\n```sh\nkubectl apply -f .yaml\n```\n\n### Track the status of your replica set deployment.\n\nTo check the status of your `MongoDB` resource, use the following command:\n\n```sh\nkubectl get mdb -o yaml -w\n```\n\nWith the `-w` (watch) flag set, when the configuration changes, the output refreshes immediately until the status phase achieves the `Running` state. To learn more about resource deployment statuses, see Troubleshoot the Kubernetes Operator.\n\nAfter you encrypt your database resource with TLS (Transport Layer Security), you can secure the following:\n\n- Client authentication with LDAP\n\n- Client authentication with X.509\n\n- Internal authentication with X.509\n\n- Client authentication with OIDC"} -{"chunk_id": "68a95c105e79d242619db717-3", "page_id": "68a95c105e79d242619db717", "source_name": "mck", "product_name": "MongoDB Controllers for Kubernetes", "url": "https://mongodb.com/docs/kubernetes/current/tutorial/deploy-replica-set", "title": "Deploy a Replica Set", "text": "### Renew TLS Certificates for a Replica Set\n\nRenew your TLS (Transport Layer Security) certificates periodically using the following procedure:\n\n#### Configure `kubectl` to default to your namespace.\n\nIf you have not already, run the following command to execute all `kubectl` commands in the namespace you created.\n\nIf you are deploying an Ops Manager resource in a multi-Kubernetes cluster MongoDB deployment:\n\n- Set the `context` to the name of the central cluster, such as: `kubectl config set context \"$MDB_CENTRAL_CLUSTER_FULL_NAME\"`.\n\n- Set the `--namespace` to the same scope that you used for your multi-Kubernetes cluster MongoDB deployment, such as: `kubectl config --namespace \"mongodb\"`.\n\n```sh\nkubectl config set-context $(kubectl config current-context) --namespace=\n```\n\n#### Renew the secret for your TLS certificates.\n\nRun this `kubectl` command to renew an existing secret that stores the replica set's certificates:\n\n```sh\nkubectl create secret tls --cert \\\n --cert= \\\n --key= \\\n --dry-run=client \\\n -o yaml |\nkubectl apply -f -\n```\n\n
\n\n\n\n### Configure `kubectl` to default to your namespace.\n\nIf you have not already, run the following command to execute all `kubectl` commands in the namespace you created.\n\nIf you are deploying an Ops Manager resource in a multi-Kubernetes cluster MongoDB deployment:\n\n- Set the `context` to the name of the central cluster, such as: `kubectl config set context \"$MDB_CENTRAL_CLUSTER_FULL_NAME\"`.\n\n- Set the `--namespace` to the same scope that you used for your multi-Kubernetes cluster MongoDB deployment, such as: `kubectl config --namespace \"mongodb\"`.\n\n```sh\nkubectl config set-context $(kubectl config current-context) --namespace=\n```\n\n### Copy the sample replica set resource.\n\nChange the settings of this YAML (Yet Another Markup Language) file to match your desired replica set configuration.\n\n```yaml\n---\napiVersion: mongodb.com/v1\nkind: MongoDB\nmetadata:\n name: \nspec:\n members: 3\n version: \"8.0.0\"\n opsManager:\n configMapRef:\n # Must match metadata.name in ConfigMap file\n name: \n credentials: \n type: ReplicaSet\n persistent: true\n...\n```\n\n### Paste the copied example to create a new replica set resource.\n\nOpen your preferred text editor and paste the object specification into a new text file.\n\n### Change the settings to your preferred values.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nKey\n\n\nType\n\n\nDescription\n\n\nExample\n\n
\n`metadata.name`\n\n\nstring\n\n\nLabel for this Kubernetes replica set object.\n\nResource names must be 44 characters or less.\n\nTo learn more, see `metadata.name` and Kubernetes documentation on names.\n\n\n`myproject`\n\n
\n`spec.members`\n\n\ninteger\n\n\nNumber of members of the replica set.\n\n\n`3`\n\n
\n`spec.version`\n\n\nstring\n\n\nVersion of MongoDB that this replica set should run.\n\nThe format should be `X.Y.Z` for the Community edition and `X.Y.Z-ent` for the Enterprise edition.\n\nIMPORTANT: Ensure that you choose a compatible MongoDB Server version. Compatible versions differ depending on the base image that the MongoDB database resource uses.\n\nTo learn more about MongoDB versioning, see MongoDB Versioning in the MongoDB Manual.\n\n\n`8.0.0`\n\n
\n`spec``.opsManager``.configMapRef``.name`\n\n\nstring\n\n\nName of the ConfigMap with the Ops Manager connection configuration. The `spec.cloudManager.configMapRef.name` setting is an alias for this setting and can be used in its place.\n\nThis value must exist on the *same* namespace as the resource you want to create.\n\nIMPORTANT: The Kubernetes Operator tracks any changes to the ConfigMap and reconciles the state of the `MongoDB` resource.\n\n\n``\n\n
\n`spec.credentials`\n\n\nstring\n\n\nName of the secret you created as Ops Manager API (Application Programming Interface) authentication credentials for the Kubernetes Operator to communicate with Ops Manager.\n\nThe Ops Manager Kubernetes Secret object holding the Credentials must exist on the **same** Namespace as the resource you want to create.\n\nIMPORTANT: The Kubernetes Operator tracks any changes to the Secret and reconciles the state of the `MongoDB` resource.\n\n\n``\n\n
\n`spec.type`\n\n\nstring\n\n\nType of `MongoDB` resource to create.\n\n\n`ReplicaSet`\n\n
\n`spec.persistent`\n\n\nstring\n\n\n*Optional.*\n\nFlag indicating if this `MongoDB` resource should use Persistent Volumes for storage. Persistent volumes are not deleted when the `MongoDB` resource is stopped or restarted.\n\nIf this value is `true`, then `spec.podSpec.persistence.single` is set to its default value of `16Gi`.\n\nTo change your Persistent Volume Claims configuration, configure the following collections to meet your deployment requirements:\n\n- If you want one Persistent Volume for each Pod, configure the `spec.podSpec.persistence.single` collection.\n\n- If you want separate Persistent Volumes for data, journals, and logs for each Pod, configure the following collections:\n\n - `spec.podSpec.persistence.multiple.data`\n\n - `spec.podSpec.persistence.multiple.journal`\n\n - `spec.podSpec.persistence.multiple.logs`\n\nWARNING: Grant your containers permission to write to your Persistent Volume. The Kubernetes Operator sets `fsGroup = 2000`, `runAsUser = 2000`, and `runAsNonRoot = true` in `securityContext`. Kubernetes Operator sets `fsgroup` equal to `runAsUser` to make the volume writable for a user that runs the main process in the container. To learn more, see Configure a Security Context for a Pod or Container and the related discussion in the Kubernetes documentation. If redeploying the resource doesn't fix issues with your Persistent Volume, contact MongoDB Support.\n\nIf you do not use Persistent Volumes, the Disk Usage and Disk IOPS charts cannot be displayed in either the Processes tab on the Deployment page or in the Metrics page when reviewing the data for this deployment.\n\n\n`true`\n\n
"} -{"chunk_id": "68a95c105e79d242619db717-4", "page_id": "68a95c105e79d242619db717", "source_name": "mck", "product_name": "MongoDB Controllers for Kubernetes", "url": "https://mongodb.com/docs/kubernetes/current/tutorial/deploy-replica-set", "title": "Deploy a Replica Set", "text": "### Add any additional accepted settings for a replica set deployment.\n\nYou can also add any of the following optional settings to the object specification file for a replica set deployment:\n\n- `spec.additionalMongodConfig`\n\n- `spec.backup.assignmentLabels`\n\n- `spec.backup.mode`\n\n- `spec.backup.snapshotSchedule.snapshotIntervalHours`\n\n- `spec.backup.snapshotSchedule.snapshotRetentionDays`\n\n- `spec.backup.snapshotSchedule.dailySnapshotRetentionDays`\n\n- `spec.backup.snapshotSchedule.weeklySnapshotRetentionWeeks`\n\n- `spec.backup.snapshotSchedule.monthlySnapshotRetentionMonths`\n\n- `spec.backup.snapshotSchedule.pointInTimeWindowHours`\n\n- `spec.backup.snapshotSchedule.referenceHourOfDay`\n\n- `spec.backup.snapshotSchedule.referenceMinuteOfHour`\n\n- `spec.backup.snapshotSchedule.fullIncrementalDayOfWeek`\n\n- `spec.clusterDomain`\n\n- `spec.connectivity.replicaSetHorizons`\n\n- `spec.featureCompatibilityVersion`\n\n- `spec.logLevel`\n\n- `spec.podSpec.persistence.single`\n\n- `spec.podSpec.persistence.multiple.data`\n\n- `spec.podSpec.persistence.multiple.journal`\n\n- `spec.podSpec.persistence.multiple.logs`\n\n- `spec.podSpec.podTemplate.spec.affinity.podAffinity`\n\n- `spec.podSpec.podTemplate.spec.affinity.podAntiAffinity.requiredDuringSchedulingIgnoredDuringExecution.topologyKey`\n\n- `spec.podSpec.podTemplate.spec.affinity.nodeAffinity`\n\n- `spec.podSpec.podTemplate.metadata`\n\n- `spec.podSpec.podTemplate.spec`\n\nYou must set `spec.clusterDomain` if your Kubernetes cluster has a default domain other than the default `cluster.local`. If you neither use the default nor set the `spec.clusterDomain` option, the Kubernetes Operator might not function as expected.\n\n### Save this replica set config file with a `.yaml` extension.\n\n### Start your replica set deployment.\n\nIn any directory, invoke the following Kubernetes command to create your replica set:\n\n```sh\nkubectl apply -f .yaml\n```\n\n### Track the status of your replica set deployment.\n\nTo check the status of your `MongoDB` resource, use the following command:\n\n```sh\nkubectl get mdb -o yaml -w\n```\n\nWith the `-w` (watch) flag set, when the configuration changes, the output refreshes immediately until the status phase achieves the `Running` state. To learn more about resource deployment statuses, see Troubleshoot the Kubernetes Operator.\n\n
\n\n
"} -{"chunk_id": "68a95c105e79d242619db739-0", "page_id": "68a95c105e79d242619db739", "source_name": "mck", "product_name": "MongoDB Controllers for Kubernetes", "url": "https://mongodb.com/docs/kubernetes/current/tutorial/modify-resource-image", "title": "Modify Ops Manager or MongoDB Kubernetes Resource Containers", "text": "# Modify Ops Manager or MongoDB Kubernetes Resource Containers\n\nYou can modify the containers in the Pods in which Ops Manager and MongoDB database resources run using the `template` or `podTemplate` setting that applies to your deployment:\n\n- MongoDB database: `spec.podSpec.podTemplate`\n\n- Ops Manager: `spec.statefulSet.spec.template`\n\n- Backup Daemon Service: `spec.backup.statefulSet.spec.template`\n\nTo review which fields you can add to a `template` or a `podTemplate`, see the Kubernetes documentation.\n\nWhen you create containers with a `template` or `podTemplate`, the Kubernetes Operator handles container creation differently based on the `name` you provide for each container in the `containers` array:\n\n- If the `name` field *matches* the name of the applicable resource image, the Kubernetes Operator updates the Ops Manager or MongoDB database container in the Pod to which the `template` or `podTemplate` applies:\n\n - Ops Manager: `mongodb-kubernetes-ops-manager`\n\n - Backup Daemon Service: `mongodb-backup-daemon`\n\n - MongoDB database: `mongodb-enterprise-database`\n\n - Application Database: `mongodb-kubernetes-appdb`\n\n- If the `name` field *does not match* the name of the applicable resource image, the Kubernetes Operator creates a new container in each Pod to which the `template` or `podTemplate` applies.\n\n## Define a Volume Mount for a MongoDB Kubernetes Resource\n\nOn-disk files in containers in Pods don't survive container crashes or restarts. Using the `spec.podSpec.podTemplate` setting, you can add a volume mount to persist data in a MongoDB database resource for the life of the Pod.\n\nTo create a volume mount for a MongoDB database resource:\n\n1. Update the MongoDB database resource definition to include a volume mount for containers in the database pods that the Kubernetes Operator creates.\n\n Use `spec.podSpec.podTemplate` to define a volume mount:\n\n ```yaml\n podSpec:\n podTemplate:\n spec:\n containers:\n - name: mongodb-enterprise-database\n volumeMounts:\n - mountPath: \n name: survives-restart\n volumes:\n - name: survives-restart\n emptyDir: {}\n ```\n\n2. Apply the updated resource definition:\n\n ```sh\n kubectl apply -f .yaml -n \n ```\n\n## Tune MongoDB Kubernetes Resource Docker Images with an InitContainer\n\n`MongoDB` resource Docker images run on RHEL and use RHEL's default system configuration. To tune the underlying RHEL system configuration in the `MongoDB` resource containers, add a privileged InitContainer init container using one of the following settings:\n\n- `spec.podSpec.podTemplate`: add a privileged InitContainer to a MongoDB database resource container.\n\n- `spec.statefulSet.spec.template`: add a privileged InitContainer to an Ops Manager resource container.\n\nMongoDB database resource Docker images use the RHEL default `keepalive` time of `7200`. MongoDB recommends a shorter `keepalive` time of `120` for database deployments.\n\nYou can tune the `keepalive` time in the database resource Docker images if you experience network timeouts or socket errors in communication between clients and the database resources.\n\nDoes TCP keepalive time affect MongoDB Deployments? in the MongoDB Manual\n\nTo tune Docker images for a MongoDB database resource container:\n\n1. Update the MongoDB database resource definition to append a privileged InitContainer to the database pods that the Kubernetes Operator creates.\n\n Change `spec.podSpec.podTemplate` the `keepalive` value to the recommended value of `120`:\n\n ```yaml\n spec:\n podSpec:\n podTemplate:\n spec:\n initContainers:\n - name: \"adjust-tcp-keepalive\"\n image: \"busybox:latest\"\n securityContext:\n privileged: true\n command: [\"sysctl\", \"-w\", \"net.ipv4.tcp_keepalive_time=120\"]\n ```\n\n2. Apply the updated resource definition:\n\n ```sh\n kubectl apply -f .yaml -n \n ```\n\nKubernetes adds a privileged InitContainer to each Pod that the Kubernetes Operator creates using the `MongoDB` resource definition.\n\nOpen a shell session to a running container in your database resource Pod and verify your changes.\n\nTo follow the previous `keepalive` example, invoke the following command to get the current `keepalive` value:\n\n```sh\n> kubectl exec -n -it -- cat /proc/sys/net/ipv4/tcp_keepalive_time\n\n> 120\n```\n\nOperating System Configuration in the MongoDB Manual.\n\n## Build Custom Images with Dockerfile Templates\n\nYou can modify MongoDB Dockerfile templates to create custom Kubernetes Operator images that suit your use case. To build a custom image, you need:\n\n- Your custom Dockerfile, modified from a MongoDB template.\n\n- The MongoDB-provided context image for your template.\n\n### MongoDB Dockerfile Templates\n\nThe Dockerfiles used to build container images are publicly available from the MongoDB Kubernetes GitHub repository.\n\nThe Dockerfile directory is organized by resource name, version and distribution:\n\n```sh\n\u251c\u2500\u2500 \n\u2502 \u2514\u2500\u2500 \n\u2502 \u2514\u2500\u2500 \n\u2502 \u2514\u2500\u2500 Dockerfile template\n```\n\nCopy the template you want to use to your own Dockerfile and modify as desired.\n\n### Context Images\n\nTo build an image from any MongoDB Dockerfile template, you must supply its context image.\n\nEach Dockerfile template has one associated context image, retrievable from the same Quay registry as the original images. Context image are always tagged in the format `quay.io/mongodb/:-context`.\n\nTo supply a context image to `docker build`, include the `--build-arg` option with the `imagebase` variable set to a Quay.io tag, where `` and `` match your Dockerfile template.\n\nIf you want to build the `mongodb-enterprise-database` version 2.0.0 image for any distribution, include:\n\n```sh\n--build-arg imagebase=quay.io/mongodb/mongodb-kubernetes-database:2.0.0-context\n```\n\n### `docker build` Example\n\nThe Ubuntu distribution for `mongodb-kubernetes-operator` version 1.9.1 is based on `ubuntu:1604` by default. In this example, that base Dockerfile template is modified to use `ubuntu:1804` and saved as `myDockerfile`.\n\nThe following command builds the custom image and gives it the tag `1.9.1-ubuntu-1804`:\n\n```sh\ncat myDockerfile | docker build --build-arg imagebase=quay.io/mongodb/mongodb-kubernetes-operator:1.9.1-context \\\n--tag mongodb-kubernetes-operator:1.9.1-ubuntu-1804 -\n```\n\nInclude a hyphen (`-`) at the end of `docker build` to read the output of `cat myDockerfile` instead of providing a local directory as build context.\n\nTo learn more about `docker build`, see the Docker documentation."} -{"chunk_id": "68a95c105e79d242619db664-0", "page_id": "68a95c105e79d242619db664", "source_name": "mck", "product_name": "MongoDB Controllers for Kubernetes", "url": "https://mongodb.com/docs/kubernetes/current/gdc-hosted", "title": "Kubernetes Operator on GDC", "text": "# Kubernetes Operator on GDC\n\nMongoDB Enterprise Advanced is available on Google Distributed Cloud air-gapped (GDC air-gapped).\n\nGDC air-gapped is Google Cloud\u2019s Kubernetes-based private cloud. It enables you to manage infrastructure, services, APIs, and tooling without a connection to Google Cloud or the public Internet. GDC air-gapped provides compliance with strict data residency and security requirements for public sector organizations and regulated enterprises.\n\nInstall Kubernetes Operator through GDC air-gapped's built-in application marketplace to manage MongoDB instances in an air-gapped environment without needing to customize further.\n\nKubernetes Operator manages the namespace that you install Kubernetes Operator in. You can use Kubernetes Operator, according to standard Kubernetes Operator documentation, within GDC air-gapped.\n\nTo use Enterprise Advanced on GDC air-gapped, you must ensure you have the correct licenses from MongoDB. For more information, contact gcp@mongodb.com."} -{"chunk_id": "6a7d648bd54f2f30bc3a4bb6-0", "page_id": "6a7d648bd54f2f30bc3a4bb6", "source_name": "mcp-server", "product_name": "MongoDB MCP Server", "url": "https://mongodb.com/docs/mcp-server/local-mcp/configuration", "title": "Local MCP Server Configuration", "text": "# Local MCP Server Configuration\n\nConfigure the Local MCP to interact with your MongoDB deployments from AI clients.\n\nThe following sections describe AI client compatibility and prerequisites for the Local MCP, and provide links to pages with the Local MCP configuration options. For a basic Local MCP configuration and introduction, see Get Started with the MongoDB MCP Server.\n\n## AI Client Compatibility\n\nThe Local MCP is compatible with AI clients that support MCP. For example, you can use these AI clients:\n\n- Claude Desktop\n\n- Claude Code\n\n- Cursor\n\n- fx\n\nThe JSON configuration file structure can vary for each AI client. Read the AI client documentation for details.\n\nFor a list of clients that support MCP, see MCP Clients.\n\n## Prerequisites\n\nEnsure you have already installed the software as specified in MCP Server software prerequisites.\n\nThe Local MCP can run Atlas tools that perform various Atlas operations. To run the Atlas tools, your Atlas cluster requires a service account with the appropriate permissions.\n\nTo set up a service account, see MongoDB MCP Server Prerequisites for Running Atlas Tools.\n\nFor a list of the tools, see MongoDB MCP Server Tools.\n\n## Local MCP Configuration Tasks and Operations\n\nTo perform Local MCP configuration tasks and operations, see the following pages:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nPage\n\n\nDescription\n\n
\nOptions\n\n\nView Local MCP options that specify how to connect to a cluster and control Local MCP operations.\n\n
\nMethods\n\n\nSet Local MCP options in a JSON configuration file, a command line, and environment variables.\n\n
\nEnable or disable features\n\n\nEnable or disable Local MCP features such as read-only mode, specific MCP tools, telemetry data collection about system use, and using indexes in queries.\n\n
\nExport data\n\n\nExport results returned by queries and aggregation pipelines to files.\n\n
\nStandalone service\n\n\nConfigure the Local MCP to run as a standalone service.\n\n
\nTroubleshoot problems\n\n\nExamine Local MCP logs for information that can help resolve problems.\n\n
\n\n## Learn More\n\n- MongoDB MCP Server Tools\n\n- MongoDB MCP Server Usage Examples\n\n- MongoDB MCP Server Security\n\n- MongoDB MCP Server Security Best Practices"} -{"chunk_id": "6a7ac14ae5571fb2c0fdfefc-0", "page_id": "6a7ac14ae5571fb2c0fdfefc", "source_name": "mcp-server", "product_name": "MongoDB MCP Server", "url": "https://mongodb.com/docs/mcp-server/remote-mcp/manage-ai-client-access", "title": "Manage AI Client Access to Your Organization", "text": "# Manage AI Client Access to Your Organization\n\nAs an Organization Owner, you control whether AI clients can connect to your Atlas organization through user-delegated access, and what level of access those clients receive. AI clients can't connect to your organization until you enable AI client access.\n\nAtlas **disables** AI client access by default for existing organizations and for new organizations *an existing Atlas user creates*. Atlas **enables** AI client access by default for organizations new users create at the time they create their Atlas account.\n\nWhen AI client access is enabled, an AI client must be authorized by an individual Atlas user to act on that user's behalf. An AI client acts using its authorizing Atlas user's existing Atlas permissions and can't exceed them. A user's ability to read or modify cluster data is governed by that user's Atlas role and your organization's access mode. Before you enable AI client access, review which roles can connect AI clients to your clusters in User Roles and Database Access.\n\nYou can manage AI client access settings in the Atlas UI.\n\n## User Roles and Database Access\n\nWhen AI client access is enabled, users who hold any of the following Atlas roles can authorize an AI client to connect to your organization's clusters:\n\n- `ORG_OWNER`\n\n- `GROUP_OWNER`\n\n- `GROUP_DATA_ACCESS_ADMIN`\n\n- `GROUP_DATA_ACCESS_READ_WRITE`\n\n- `GROUP_DATA_ACCESS_READ_ONLY`\n\n- `GROUP_STREAM_PROCESSING_OWNER`\n\nAn AI client's access to cluster data is the more restrictive of two limits: the authorizing user's Atlas role and your organization's AI client access mode. The access mode can only reduce a user's access, never grant more than the user's role allows. For example, a user with the `GROUP_DATA_ACCESS_READ_ONLY` role has read-only access through an AI client, even when the organization allows AI clients to read and write.\n\n### Audit AI Client Activity\n\nAll tool calls are attributed to the individual user who authorized the AI client that made the call. You can identify which user performed each action in your audit log.\n\nAtlas records new audit events for App Connections and adds delegation context to existing audit events, so you can distinguish actions taken through an AI client from other activity.\n\nTo learn how Atlas attributes each action to an individual user, see Security, Governance, and Auditability.\n\nRead-only Atlas Administration API calls are not recorded in the audit log. This is an existing Atlas behavior and is not specific to AI client access.\n\n## Enable AI Client Access\n\nTo enable AI client access for your organization, complete the following steps:\n\n### Open the App Connections tab.\n\nIn the Atlas UI, open your organization settings, then select App Connections.\n\n### Set the access mode for AI clients.\n\nChoose the access mode that AI clients receive when they connect. For a description of each mode, see AI Client Access Modes.\n\n### Save your changes.\n\nAfter you save, AI clients can connect to your organization using the access mode that you selected.\n\n## AI Client Access Modes\n\nAI client access supports the following modes:\n\n- **Read**: AI clients can run read operations, including `find`, `aggregate`, `count`, `list-collections`, `collection-indexes`, and schema inspection.\n\n- **Read and write**: AI clients can run read operations and write operations, including `insert-many`, `update-many`, `create-collection`, and `create-index`.\n\n- **Disabled**: No AI client can connect to your organization.\n\nTools outside the configured mode are not registered with the AI client's session and are not visible to the client. For example, in read mode, write tools do not appear in the client's list of available tools.\n\n### Disable Access Org-Wide\n\nTo stop all AI client access to your organization, set the access mode to disabled. This prevents any new connections and immediately ends existing control-plane access for every AI client connected to the organization. Data-plane access through artifacts that a client already created, such as database users, continues to work.\n\nIndividual users can revoke their own connections at any time from the Atlas UI.\n\nFor revocation timing and how to handle federated users, see the revocation and lifecycle guidance in Atlas App Connections Overview.\n\n## AI Client Access Lifetime\n\nBy default, an AI client's access on behalf of a user ends after 7 days of inactivity, or 30 days from when access was initially granted regardless of activity. When this access ends, the user must reauthenticate through the AI client's plugin to reconnect the AI client.\n\nTo learn how AI clients connect to your database using short-lived credentials, see Security, Governance, and Auditability.\n\nAs an Organization Owner, you can reduce the maximum token lifetime for your organization. Reducing the maximum lifetime shortens the window during which a connection remains active without reauthentication.\n\nIf you rely on an identity provider (IdP) to manage Atlas access, reduce the maximum token lifetime so that access changes you make in your IdP take effect sooner. For example, if you revoke a user's access in your IdP, a shorter token lifetime reduces how long an AI client can continue acting on that user's behalf before it must reauthenticate.\n\n## Limitations\n\nAI client access applies at the organization level. You cannot set per-user, per-cluster, or per-client access controls, and the access mode applies to the entire organization.\n\nAI client access also shares the limitations of Atlas App Connections, including but not limited to the inability to:\n\n- Restrict access to specific AI clients\n\n- Revoke an individual user's connection as an Organization Owner\n\n- Delegate a subset of a user's permissions\n\nFor the complete list of limitations, see Limitations.\n\n## Learn More\n\nFor the delegated-access concepts that underlie AI client access, including authorization, consent, and lifecycle, see Atlas App Connections Overview."} -{"chunk_id": "68a95c1e5e79d242619dd7db-0", "page_id": "68a95c1e5e79d242619dd7db", "source_name": "mcp-server", "product_name": "MongoDB MCP Server", "url": "https://mongodb.com/docs/mcp-server/overview", "title": "MongoDB MCP Server Overview", "text": "# MongoDB MCP Server Overview\n\nThe feature described on this page is not currently supported on Atlas Infinite clusters during public preview. For the features supported in public preview, see Public Preview Availability.\n\nThe MongoDB MCP Server allows you to interact with your MongoDB data and deployments from AI clients in natural language.\n\nYou can use the MongoDB MCP Server with any MongoDB deployment, including MongoDB Atlas, MongoDB Atlas Local, MongoDB Community Edition, and MongoDB Enterprise Advanced.\n\nMongoDB offers two MCP Server deployment types: Local MCP for MongoDB MCP Server, which you run and manage yourself, and MongoDB Atlas Managed MCP Server, which MongoDB hosts and manages for you in Atlas. To learn more, see What is the MongoDB MCP Server? below.\n\nThis page describes key concepts and use cases. If you're already familiar with MCP, you can get started.\n\n## What is Model Context Protocol (MCP)?\n\nModel Context Protocol (MCP) is an open standard developed by Anthropic to standardize how LLMs connect to and interact with external resources and services. MCP consists of a client-server architecture with the following key components:\n\n- **MCP Host**: Application or environment where you want to use MCP, such as a chat interface or IDE. For example, Claude Desktop or VS Code.\n\n- **MCP Clients**: Components within the host that handle connections to MCP servers. For a list of clients that support MCP, see MCP Clients.\n\n- **MCP Servers**: Programs that expose specific capabilities to the client. For example, the MongoDB MCP Server.\n\n The primary way that MCP servers expose capabilities to clients is through tools. Tools are pre-defined, executable functions that enable LLMs to perform specific actions, such as interacting with external data sources like MongoDB.\n\nTo learn more, see MCP documentation.\n\n## What is the MongoDB MCP Server?\n\nThe MongoDB MCP Server is our official MCP server implementation that gives your AI client a set of tools that can be used to interact with your MongoDB data and deployments. These tools include various administrative actions, such as managing cluster resources, database operations like querying and indexing, and performance optimization through the Performance Advisor.\n\nMongoDB offers two deployment types for the MongoDB MCP Server:\n\n- **Local MCP for MongoDB MCP Server**: You run the MCP server yourself and directly manage your AI agent connections and MCP server infrastructure.\n\n- **MongoDB Atlas Managed MCP Server**: MongoDB runs the MCP server in Atlas and manages the AI agent connections and MCP server infrastructure for you.\n\nYou can set up either deployment type with the MongoDB MCP Plugin or by using a configuration file:\n\n- MongoDB MCP Plugin for AI Clients: You install MongoDB from an AI client's marketplace. An AI client is an interface that you use to prompt an AI model. The MongoDB MCP Plugin for the MongoDB Atlas Managed MCP Server provides user-delegated access for interactive AI clients.\n\n- Manual configuration file setup: You manually add the MongoDB MCP Server configuration and your OAuth client credentials to a configuration file for your AI client. This setup path is best for working with programmatic agents. Programmatic agents are automated, workflow-driven agents that can run multi-step workflows without a user's input or guidance.\n\nThe following table compares Local MCP for MongoDB MCP Server and MongoDB Atlas Managed MCP Server. Use this to help you select which deployment type best suits your needs:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n\n\nLocal MCP for MongoDB MCP Server\n\n\nMongoDB Atlas Managed MCP Server\n\n
\nHosting Model\n\n\nYou install, run, and maintain the MongoDB MCP Server yourself. You are responsible for server upgrades, connectivity, and credential rotation.\n\n\nMongoDB hosts, runs, and maintains the MongoDB MCP Server in Atlas. There is no MCP server infrastructure for you to deploy, upgrade, or operate.\n\n
\nSupported Database Deployments\n\n\nSelf-Managed (On-premises) and Atlas (Cloud)\n\n\nAtlas (Cloud) only\n\n
\nAccess Control Level\n\n\nUp to collection-level dataplane access\n\n\nUp to project-level dataplane access\n\n
\nBest For\n\n\nUsers who want direct, granular control over where the MongoDB MCP Server runs and how it connects to MongoDB deployments.\n\n\nUsers using Atlas deployments who want MongoDB to host and manage the server for them.\n\n
\n\n### MongoDB Atlas Managed MCP Server\n\nWith MongoDB Atlas Managed MCP Server, MongoDB hosts and manages the MongoDB MCP Server in Atlas instead of requiring you to run the server on your own machine or infrastructure. Because MongoDB operates the server, you don't deploy, upgrade, or maintain any MCP infrastructure, and you don't manage connection strings, secrets, or certificates for the connection to your Atlas deployment.\n\nMongoDB Atlas Managed MCP Server provides the following benefits:\n\n- **Streamlined deployment access**: When using the MongoDB MCP Plugin to connect to the MongoDB Atlas Managed MCP Server, you can access your database deployments directly using Atlas App Connections without needing to manage service account credentials.\n\n- **Wide user support**: MongoDB Atlas Managed MCP Server supports both users working with interactive AI clients and users using programmatic agents.\n\n- **Administrator governance controls**: Including org-level opt-in and read-only enforcement for AI clients and per-configuration roles, IP access lists, and read-only settings for programmatic agents.\n\n### Local MCP for MongoDB MCP Server\n\nLocal MCP for MongoDB MCP Server is the self-managed MongoDB MCP Server path. You run the MCP server yourself and manually connect it to your MongoDB deployment and tools.\n\nUse Local MCP when you want direct control over how and where the MCP server runs. In exchange for this control, you take on hosting and maintaining the server, including server upgrades and credential management.\n\nYou also use Local MCP when you want to use the MongoDB MCP Server with local deployment types, such as MongoDB Atlas Local, MongoDB Community Edition, and MongoDB Enterprise Advanced."} -{"chunk_id": "68a95c1e5e79d242619dd7db-1", "page_id": "68a95c1e5e79d242619dd7db", "source_name": "mcp-server", "product_name": "MongoDB MCP Server", "url": "https://mongodb.com/docs/mcp-server/overview", "title": "MongoDB MCP Server Overview", "text": "### Use Cases\n\nThe MongoDB MCP Server allows you to interact with your MongoDB data and deployments using natural language, streamlining developer workflows and making it easier to perform complex tasks from AI interfaces. For example, the MongoDB MCP Server enables the following use cases:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nUse case\n\n\nDescription\n\n\nPrompt example\n\n
\nData exploration\n\n\nLearn and explain your database schema and relationships.\n\n\n`Show the schema of the 'users' collection and explain the purpose of each field.`\n\n
\nDatabase operations\n\n\nCreate, read, update, and delete data in your MongoDB collections.\n\n\n`Find all users from the past week and update their orders to 'shipped'.`\n\n
\nDatabase Management\n\n\nPerform administrative tasks to manage your clusters, database users, and more.\n\n\n`Create a new database user for my Atlas cluster with read-only access.`\n\n
\nCode generation\n\n\nDescribe the data you need, then generate relevant MongoDB queries and application code.\n\n\n`Review the schema for the 'users' collection, then generate a Python script that deletes profiles older than 2 years.`\n\n
\nPerformance optimization\n\n\nAnalyze query performance and get recommendations for indexes and schema improvements.\n\n\n`Show me slow queries from the last 24 hours and suggest indexes to improve performance.`\n\n
For a list of the specific tools available in the MongoDB MCP Server, see MongoDB MCP Server Tools.\n\n## Setup Methods\n\nYou can set up Local MCP for MongoDB MCP Server and MongoDB Atlas Managed MCP Server using either the MongoDB MCP Plugin from an AI client's marketplace or by manually configuring the MongoDB MCP Server in a configuration file for your AI client.\n\n### MongoDB MCP Plugin for User-Delegated Access\n\nThe MongoDB MCP Plugin helps users give AI clients user-delegated access to explore MongoDB deployments. This method uses Atlas App Connections, which lets you authorize an AI client to access your Atlas resources through an OAuth flow tied to your Atlas identity.\n\nThis method requires no MCP infrastructure or credentials to manage. With the MongoDB MCP Plugin:\n\n- You find MongoDB as a connector or plugin in an AI client's marketplace and authorize it using Atlas App Connections.\n\n- The AI client acts on your behalf using your Atlas identity.\n\n- Token refresh is automatic. You don't manage a connection string, secret, or certificate.\n\n- You can view and revoke the AI clients you connected at any time.\n\nTo learn more, see Atlas App Connections Overview.\n\n### Configuration File Setup using OAuth Client Credentials\n\nYou can manually add a MongoDB MCP Server configuration to your AI client's configuration file. This setup method is especially useful for **programmatic agent access**.\n\nThe credentials you use depend on your deployment type\n\nFor **Local MCP for MongoDB MCP Server**, you add your own credentials to connect to your MongoDB deployment, including cluster connection strings and optional Atlas API credentials for Atlas tools.\n\nFor **MongoDB Atlas Managed MCP Server**, an Atlas Organization Owner or Project Owner creates an MongoDB Atlas Managed MCP Server configuration via Atlas. This configuration:\n\n- Provisions a service account and returns a client ID, a client secret, and the MongoDB Atlas Managed MCP Server URL (`https://mcp.mongodb.com`) that you provide to your agent.\n\n- Uses separate ingress and egress Atlas service accounts. The AI client receives ingress credentials that grant access only to MongoDB Atlas Managed MCP Server. The server then uses a separate egress service account, configured with the required Atlas permissions, to make API calls on the AI client's behalf. Egress credentials are not exposed to the AI client.\n\n- Authenticates the AI client using the service account and uses the roles that the administrator assigns, rather than an individual user's identity.\n\nAdministrators get granular, per-configuration control over MongoDB Atlas Managed MCP Server, including:\n\n- The Atlas roles granted\n\n- An IP access list\n\n- A read-only flag (enabled by default)\n\n#### Atlas Managed MCP Package for MCP Configuration Service Accounts\n\nSome AI clients don't natively support the MCP configuration service account OAuth client-credentials flow that MongoDB Atlas Managed MCP Server uses for programmatic access. To connect these clients, use the mongodb-atlas-mcp-remote npm package. You run this package using `npx` in your client's configuration file. The package acquires an access token from your MCP configuration service account credentials and forwards requests to MongoDB Atlas Managed MCP Server, handling token caching and refresh for you. This allows you to seamlessly connect AI clients to the MongoDB Atlas Managed MCP Server.\n\nUse this package only for AI clients that connect through a configuration file. Client-specific instructions on the Get Started with the MongoDB MCP Server page already use the package.\n\nIf you build a programmatic agent using an AI framework such as LangChain, don't use this package. Instead, fetch an access token and call MongoDB Atlas Managed MCP Server directly from your application code. To learn more, see Get Started with the MongoDB MCP Server and select AI Framework Clients from the AI CLIENT dropdown.\n\n## Learn More\n\nTo configure the MongoDB MCP Server and learn how to use it, see the following resources:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nGet Started with the MongoDB MCP Server\n\n\nQuickly get started with the MongoDB MCP Server.\n\n
\nPrerequisites\n\n\nView the prerequisites for configuring the MongoDB MCP Server.\n\n
\nConfigure MCP Server and Connections\n\n\nView all available configuration and connection options.\n\n
\nSupported Tools\n\n\nView all available tools in the MongoDB MCP Server.\n\n
\nUsage Examples\n\n\nTest example prompts to use with the MongoDB MCP Server.\n\n
\nSecurity\n\n\nLearn about the security best practices for the MongoDB MCP Server.\n\n
\nGitHub Repository\n\n\nView the MongoDB MCP Server source code and contributing guidelines.\n\n
"} -{"chunk_id": "68a95c1e5e79d242619dd7d9-0", "page_id": "68a95c1e5e79d242619dd7d9", "source_name": "mcp-server", "product_name": "MongoDB MCP Server", "url": "https://mongodb.com/docs/mcp-server", "title": "What is the MongoDB MCP Server?", "text": "# What is the MongoDB MCP Server?\n\nThe MongoDB MCP Server lets you connect to MongoDB from your agentic AI tools, assistants, and platforms. Interact with LLMs in natural language to query, explore, and manage your MongoDB data and deployments.\n\nLearn More About MCP\n\n## AI-Powered Software Development\n\nInteract with your MongoDB data and deployments in natural language and integrate it into your AI development workflows.\n\n\n\n\n\n### Explore your MongoDB data.\n\nExplain your database schema and ask questions about your data and its relationships.\n\n### Query your data in natural language.\n\nRun CRUD operations in natural language and perform complex aggregations on your data without writing any code.\n\n\n\n\n\n### Perform administrative tasks.\n\nUse the MongoDB MCP Server to manage your MongoDB deployments, including creating and managing databases, collections, and indexes.\n\n### Manage your Atlas clusters.\n\nCreate and manage Atlas organizations, projects, and clusters, and customize access to your data.\n\n\n\n\n\n### Give context to your AI tools.\n\nRetrieve relevant context about your data such as its schema and data types.\n\n### Generate context-aware code.\n\nUsing context from your MongoDB data allows you to generate more accurate MongoDB queries and application code.\n\n\n\n\n\n## Expand Your Toolkit\n\nLearn more about the MongoDB MCP Server and explore other tools to enable your development workflows.\n\nLearn about the tools available in the MongoDB MCP Server.\n\nExplore other MongoDB tools and connectors for your applications.\n\nIntegrate MongoDB with AI frameworks and platforms."} -{"chunk_id": "6a7d648bd54f2f30bc3a4bb7-0", "page_id": "6a7d648bd54f2f30bc3a4bb7", "source_name": "mcp-server", "product_name": "MongoDB MCP Server", "url": "https://mongodb.com/docs/mcp-server/local-mcp/configuration/enable-or-disable-features", "title": "Enable or Disable MongoDB MCP Server Features", "text": "# Enable or Disable MongoDB MCP Server Features\n\nThe MongoDB MCP Server has various options that you can enable or disable. For example: read-only mode, specific MCP tools, telemetry about system use, and database index checks.\n\n## Enabling MCP Server Read-Only Mode\n\nYou can limit the MCP Server to perform only read operations using read-only mode.\n\n**Default is to allow cluster write operations. Typically, always enable read-only mode.**\n\nTo enable read-only mode with a command line option, use:\n\n```bash\n--readOnly\n```\n\nTo enable read-only mode using an environment variable, set the `MDB_MCP_READ_ONLY` environment variable to `true`:\n\n```bash\nexport MDB_MCP_READ_ONLY=true\n```\n\nWhen you enable read-only mode, a message is added to the MCP Server log that indicates the tools that perform write operations are prevented from running.\n\n## Disabling MCP Server Tools\n\nTo restrict access to Atlas and database operations, you can disable specific MCP Server tools or categories of tools.\n\nTo disable tools, set the `disabledTools` MCP Server configuration option, which is an array of strings. Each string can be a tool name or tool category.\n\nThe following table shows the tool names that you can disable:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nTool Name\n\n\nDescription\n\n\nExample Operations Disabled\n\n
\n`create`\n\n\nCreate resources\n\n\n- Create cluster\n\n- Insert document\n\n
\n`update`\n\n\nUpdate resources\n\n\n- Update document\n\n- Rename collection\n\n- Pause or resume cluster\n\n
\n`delete`\n\n\nDelete resources\n\n\n- Delete document\n\n- Drop collection\n\n
\n`read`\n\n\nRead resources\n\n\n- Find\n\n- Aggregate\n\n- List clusters\n\n
\n`metadata`\n\n\nRead metadata\n\n\n- List databases\n\n- List collections\n\n- Read collection schema\n\n
The following table shows the tool categories that you can disable:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nTool Category\n\n\nDescription\n\n\nExample Operations Disabled\n\n
\n`atlas`\n\n\nAtlas tools\n\n\n- List clusters\n\n- Create cluster\n\n
\n`mongodb`\n\n\nDatabase tools\n\n\n- Find\n\n- Aggregate\n\n
To disable tools with the `disabledTools` command line option, use a comma-separated list. For example:\n\n```bash\n--disabledTools create,update,delete,atlas\n```\n\nTo disable tools with the `MDB_MCP_DISABLED_TOOLS` environment variable, use a comma-separated string. For example:\n\n```bash\nexport MDB_MCP_DISABLED_TOOLS=\"create,update,delete,atlas\"\n```\n\n## Disabling MCP Server Telemetry\n\nTo prevent the MCP Server from collecting data about usage, you can disable telemetry.\n\nTo disable telemetry using an environment variable, set either of these:\n\n```bash\nexport MDB_MCP_TELEMETRY=disabled\nexport DO_NOT_TRACK=1\n```\n\nTo disable telemetry using a command line option, use:\n\n```bash\n--telemetry disabled\n```\n\n## Enabling Index Check\n\nTo ensure query operations use an index, enable the index check option. When enabled, the MCP Server rejects queries that perform a collection scan to improve performance and ensure queries are optimized.\n\nTo enable the index check with a command line option, use:\n\n```bash\n--indexCheck\n```\n\nTo enable the index check with an environment variable, use:\n\n```bash\nexport MDB_MCP_INDEX_CHECK=true\n```\n\nIf you enable the index check, the MCP Server logs an error message if a query is rejected because it doesn't use an index.\n\n## Enabling Server-Side JavaScript Functions\n\nThe MCP Server disables server-side JavaScript functions (`$where`, `$function`, and `$accumulator`) by default to prevent unintended behavior. These functions are deprecated in MongoDB 8.0 and later. To learn more, see Server-Side JavaScript.\n\nTo enable server-side JavaScript functions with a command line option, use:\n\n```bash\n--disableServerSideJs false\n```\n\nTo enable server-side JavaScript functions using an environment variable, set the `MDB_MCP_DISABLE_SERVER_SIDE_JS` environment variable to `false`:\n\n```bash\nexport MDB_MCP_DISABLE_SERVER_SIDE_JS=false\n```\n\n## Enabling MCP Server Dry-Run Mode\n\nUse the dry-run option to examine your MCP Server configuration. When you enable the dry-run option, the MCP Server returns the MCP Server configuration settings and the list of enabled MongoDB MCP Server Tools.\n\nTo enable dry-run mode with a command line option, use:\n\n```bash\n--dryRun\n```\n\nTo enable dry-run mode using an environment variable, set the `MDB_MCP_DRY_RUN` environment variable to `true`:\n\n```bash\nexport MDB_MCP_DRY_RUN=true\n```\n\nThe MCP Server returns the configuration and enabled tools in the command line output.\n\n## Learn More\n\n- MongoDB MCP Server Configuration Options\n\n- MongoDB MCP Server Configuration Methods\n\n- Export Data from MongoDB MCP Server\n\n- Start MongoDB MCP Server as a Standalone Service\n\n- MongoDB MCP Server Memory Overflow\n\n- Troubleshoot the Local MCP Server"} -{"chunk_id": "6a7d648bd54f2f30bc3a4bbb-0", "page_id": "6a7d648bd54f2f30bc3a4bbb", "source_name": "mcp-server", "product_name": "MongoDB MCP Server", "url": "https://mongodb.com/docs/mcp-server/local-mcp/configuration/standalone-service", "title": "Start MongoDB MCP Server as a Standalone Service", "text": "# Start MongoDB MCP Server as a Standalone Service\n\nYou can start the MCP Server as a standalone service, which allows the MCP Server to run independently from an AI client. To start the MCP Server as a standalone service, use the `npx` command.\n\n## Standalone Service Using Environment Variables\n\nYou can use `npx` to start the MCP Server and use environment variables. You must define the MCP Server environment variables in the operating system before running `npx`.\n\nThe following examples define MCP Server Unix environment variables to connect to an Atlas cluster:\n\n```bash\nexport MDB_MCP_API_CLIENT_ID=\"\"\nexport MDB_MCP_API_CLIENT_SECRET=\"\"\nexport MDB_MCP_CONNECTION_STRING=\"mongodb+srv://:@.mongodb.net/\"\n```\n\nTo use the example, consider these points:\n\n- Replace the option values with your connection information and other details.\n\n- To define environment variables for other operating systems, see Defining MCP Server Environment Variables in the Operating System.\n\n- To examine the list of MCP Server options, see MongoDB MCP Server Configuration Options.\n\n- To create an Atlas service account, see MongoDB MCP Server Prerequisites for Running Atlas Tools.\n\nThe following example uses the previous environment variables that have the connection information, and also sets additional command line options:\n\n```bash\nnpx -y mongodb-mcp-server@latest --readOnly --indexCheck --loggers mcp,stderr --logPath=\n```\n\nReplace `` with the directory path to store the log files.\n\n## Standalone Service Running as an HTTP Server\n\nThe default MCP Server transport protocol is `stdio`, which is suitable for integration with most MCP clients.\n\nYou can also use the HTTP transport protocol with the MCP Server. HTTP is useful if you want to interact with the MCP Server from a Web client or to configure the MCP Server to respond to requests on a specific port.\n\nHTTP transport is not recommended for production use without implementing authentication and security measures. Only use HTTP transport if you must use HTTP to interact with the MCP Server.\n\nSecurity guidelines:\n\n- Implement authentication. For example, use an API gateway or a reverse proxy.\n\n- Use HTTPS/TLS encryption.\n\n- Deploy the MCP Server behind a firewall or in a private network.\n\n- Implement rate limiting.\n\n- Never expose connection credentials.\n\nTo view security recommendations, see MongoDB MCP Server Security and MongoDB MCP Server Security Best Practices.\n\nTo start the MCP Server with HTTP transport, use `--transport http`. For example:\n\n```bash\nnpx -y mongodb-mcp-server@latest --transport http --readOnly\n```\n\nBy default, the MCP Server responds to requests on `http://127.0.0.1:3000` and only accepts local connections.\n\n### Client Connection URL\n\nIf you connect an MCP client to the HTTP server, the client's connection URL must include the `/mcp` endpoint path. For example:\n\n```text\nhttp://127.0.0.1:3000/mcp\n```\n\n### Remote Connections\n\nTo allow remote connections from other computers or containers, bind the server to all network interfaces using `--httpHost=0.0.0.0`, and the client can then connect from another computer using the server's IP address or hostname.\n\nWith Streamable HTTP, the MCP Server is bound to `localhost (127.0.0.1)` by default. This ensures the MCP Server only accepts connections that originate on the same computer.\n\nBinding to `0.0.0.0` exposes the MCP Server to the entire local network, which allows other devices on the same network to potentially access the MCP Server. This is a security risk and could allow unauthorized access to your database context. If you must expose the MCP Server outside of `localhost`, implement strong security authentication.\n\n## Learn More\n\n- MongoDB MCP Server Configuration Options\n\n- MongoDB MCP Server Configuration Methods\n\n- Enable or Disable MongoDB MCP Server Features\n\n- Export Data from MongoDB MCP Server\n\n- MongoDB MCP Server Memory Overflow\n\n- Troubleshoot the Local MCP Server"} -{"chunk_id": "6a7d648bd54f2f30bc3a4bba-0", "page_id": "6a7d648bd54f2f30bc3a4bba", "source_name": "mcp-server", "product_name": "MongoDB MCP Server", "url": "https://mongodb.com/docs/mcp-server/local-mcp/configuration/methods", "title": "MongoDB MCP Server Configuration Methods", "text": "# MongoDB MCP Server Configuration Methods\n\nTo configure the MongoDB MCP Server to connect to your MongoDB cluster and set other MCP Server options, use any of these methods:\n\n- JSON configuration file with MCP Server options\n\n- Command line options\n\n- Operating system environment variables\n\nThe MCP Server uses Atlas API credentials or a connection string to access a cluster.\n\n## MCP Server Cluster Connection Methods and Options\n\nTo configure the MCP Server to connect to a cluster and set other MCP Server options, use a method described in this section.\n\nThe MCP Server configuration file examples include `--readOnly` to ensure read-only access to data. Typically, enable read-only mode to prevent data changes.\n\nTo enable write operations, omit `--readOnly` or set the operating system environment variable `MDB_MCP_READ_ONLY` to `false`. For more information, see Enabling MCP Server Read-Only Mode.\n\nMost MCP Server configuration file examples set the `type` field to `\"stdio\"`.\n\n`type` can be set to one of the following:\n\n- `\"stdio\"`, which uses the standard input and output for communications with the MCP Server. `stdio` is suitable for most AI clients. Typically use `stdio`.\n\n- `\"http\"`, which enables HTTP communications with the MCP Server. You can then use HTTP to interact with the MCP Server from a Web client.\n\n HTTP is **NOT** recommended for production use without implementing authentication and security.\n\nThe MCP Server configuration file examples also set the MCP Server name to `mongodb`. You can change the server name to match the name of your MCP Server after you start it. The server name identifies the MCP Server to the AI client.\n\n### Connecting with Atlas API Credentials\n\nYou can use the Atlas API credentials obtained in MongoDB MCP Server Prerequisites for Running Atlas Tools to connect to an Atlas cluster.\n\nAs you'll see in the next section, you can also connect to an Atlas cluster using a MongoDB connection string if you don't want to use Atlas API credentials for security or another reason.\n\nUse environment variables instead of command line arguments for sensitive configuration settings such as login credentials and connection information. For example, use `MDB_MCP_API_CLIENT_ID` and `MDB_MCP_API_CLIENT_SECRET` for API client settings, and `MDB_MCP_CONNECTION_STRING` for connection strings.\n\nEnvironment variables are more secure than command line arguments. Command line arguments can be tracked, cached, included in process lists, and logged in various locations.\n\nTo connect with Atlas API credentials, set the `MDB_MCP_API_CLIENT_ID` and `MDB_MCP_API_CLIENT_SECRET` environment variables in the `env` section of the JSON configuration file for the AI client:\n\n```json\n...\n\"args\": [\n \"-y\",\n \"mongodb-mcp-server@latest\",\n \"--readOnly\"\n],\n\"env\": {\n \"MDB_MCP_API_CLIENT_ID\": \"\",\n \"MDB_MCP_API_CLIENT_SECRET\": \"\"\n}\n...\n```\n\nReplace `` and `` with your Atlas information.\n\nFor complete JSON configuration file examples for various AI clients, see Get Started with the MongoDB MCP Server.\n\n### Connecting with Cluster Connection String\n\nIf you don't want to use Atlas API credentials for security or another reason, you can connect to a cluster using a MongoDB connection string.\n\nThe following example shows a connection string to connect to an Atlas cluster:\n\n```json\n...\n\"args\": [\n \"-y\",\n \"mongodb-mcp-server@latest\",\n \"--readOnly\"\n],\n\"env\": {\n \"MDB_MCP_CONNECTION_STRING\":\n \"mongodb+srv://:@.mongodb.net/\"\n}\n...\n```\n\nReplace ``, ``, ``, and `` with your Atlas information.\n\nYou can also connect to a local cluster with a connection string. For example:\n\n```json\n...\n\"args\": [\n \"-y\",\n \"mongodb-mcp-server@latest\",\n \"--readOnly\"\n],\n\"env\": {\n \"MDB_MCP_CONNECTION_STRING\":\n \"mongodb://127.0.0.1:27019/?directConnection=true\"\n}\n...\n```\n\nThe `--connectionString` CLI argument is deprecated. Use the `MDB_MCP_CONNECTION_STRING` environment variable instead. If environment variables are not an option, use the first positional argument.\n\n## Defining MCP Server Environment Variables in the Operating System\n\nYou can define environment variables to set various configuration options for the MCP Server.\n\nTo define operating system environment variables for the MCP Server, use the prefix `MDB_MCP_` followed by the variable name in uppercase with underscores. For example, use `MDB_MCP_CONNECTION_STRING` to set the `connectionString` option.\n\nUse environment variables instead of command line arguments for sensitive configuration settings such as login credentials and connection information. For example, use `MDB_MCP_API_CLIENT_ID` and `MDB_MCP_API_CLIENT_SECRET` for API client settings, and `MDB_MCP_CONNECTION_STRING` for connection strings.\n\nEnvironment variables are more secure than command line arguments. Command line arguments can be tracked, cached, included in process lists, and logged in various locations.\n\nIn the examples in the following sections, replace ``, ``, ``, ``, ``, and `` with your Atlas information.\n\n### Unix Environment Variables\n\nThe following examples show how to define MCP Server environment variables in a Unix-based operating system:\n\n```bash\n# Set Atlas API credentials for a service account\nexport MDB_MCP_API_CLIENT_ID=\"\"\nexport MDB_MCP_API_CLIENT_SECRET=\"\"\n\n# Set a MongoDB connection string\nexport MDB_MCP_CONNECTION_STRING=\"mongodb+srv://:@.mongodb.net/\"\n\n# Change the MCP Server log path from the default\nexport MDB_MCP_LOG_PATH=\"/mcp/logs\"\n```\n\n### Windows Command Line Environment Variables\n\nThe following examples set the variables using in a Windows command line:\n\n```cmd\n:: Set Atlas API credentials for a service account\nset MDB_MCP_API_CLIENT_ID=\nset MDB_MCP_API_CLIENT_SECRET=\n\n:: Set a MongoDB connection string\nset MDB_MCP_CONNECTION_STRING=\"mongodb+srv://:@.mongodb.net/\"\n\n:: Change the MCP Server log path from the default\nset MDB_MCP_LOG_PATH=\"C:\\mcp\\logs\"\n```\n\n### Windows PowerShell Environment Variables\n\nThe following examples set the variables in a Windows PowerShell session:\n\n```powershell\n# Set Atlas API credentials for a service account\n$env:MDB_MCP_API_CLIENT_ID=\"\"\n$env:MDB_MCP_API_CLIENT_SECRET=\"\"\n\n# Set a MongoDB connection string\n$env:MDB_MCP_CONNECTION_STRING=\"mongodb+srv://:@.mongodb.net/\"\n\n# Change the MCP Server log path from the default\n$env:MDB_MCP_LOG_PATH=\"C:\\mcp\\logs\"\n```\n\n## Learn More\n\n- MongoDB MCP Server Configuration Options\n\n- Enable or Disable MongoDB MCP Server Features\n\n- Export Data from MongoDB MCP Server\n\n- Start MongoDB MCP Server as a Standalone Service\n\n- MongoDB MCP Server Memory Overflow\n\n- Troubleshoot the Local MCP Server"} -{"chunk_id": "6a7d648bd54f2f30bc3a4bc2-0", "page_id": "6a7d648bd54f2f30bc3a4bc2", "source_name": "mcp-server", "product_name": "MongoDB MCP Server", "url": "https://mongodb.com/docs/mcp-server/local-mcp/security/connect-with-ldap", "title": "Connect with LDAP", "text": "# Connect with LDAP\n\nStarting in MongoDB 8.0, LDAP authentication and authorization is deprecated. LDAP is available and will continue to operate without changes throughout the lifetime of MongoDB 8. LDAP will be removed in a future major release.\n\nYou can connect to your MongoDB Enterprise deployment or MongoDB Atlas cluster using Lightweight Directory Access Protocol (LDAP) authentication with the MongoDB MCP Server.\n\nTo learn more, see the following resources:\n\n- LDAP on MongoDB Enterprise.\n\n- LDAP on MongoDB Atlas\n\n## Configuration Options\n\nTo connect to a MongoDB deployment with LDAP, configure the following options in your MCP server configuration:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nCLI Option Name\n\n\nOS Environment Variable Name\n\n\nType\n\n\nNecessity\n\n\nDescription\n\n
\n`username`\n\n\n`MDB_MCP_USERNAME`\n\n\nstring\n\n\nRequired\n\n\nSet the username to a username that respects the `security.ldap.authz.queryTemplate`, or any configured `security.ldap.userToDNMapping` template.\n\n
\n`password`\n\n\n`MDB_MCP_PASSWORD`\n\n\nstring\n\n\nRequired\n\n\nPassword for the specified LDAP user.\n\n
\n`authenticationDatabase`\n\n\n`MDB_MCP_AUTHENTICATION_DATABASE`\n\n\nstring\n\n\nRequired\n\n\nSet to `$external` for LDAP authentication.\n\n
\n`authenticationMechanism`\n\n\n`MDB_MCP_AUTHENTICATION_MECHANISM`\n\n\nstring\n\n\nRequired\n\n\nSet to `PLAIN` to use LDAP authentication.\n\n
"} -{"chunk_id": "6a7d648bd54f2f30bc3a4bc4-0", "page_id": "6a7d648bd54f2f30bc3a4bc4", "source_name": "mcp-server", "product_name": "MongoDB MCP Server", "url": "https://mongodb.com/docs/mcp-server/local-mcp/security/connect-with-proxy", "title": "Connect with Proxy", "text": "# Connect with Proxy\n\nThe MongoDB MCP Server supports connections to MongoDB deployments and Atlas clusters through proxies.\n\n## MCP Environment Variables\n\nTo establish a connection with proxy configurations, use the following variables when configuring environment variables for the MCP server:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nVariable\n\n\nDescription\n\n\nExample\n\n
\n`MONGODB_PROXY`\n\n\nProxy connections to `mongodb://` and `mongodb+srv://` URLs, such as database clusters.\n\n\nThe following example sets the `MONGODB_PROXY` environment variable to proxy all MongoDB connections through a CONNECT proxy located at `example.com:8080` with TLS enabled.\n\n```sh\nexport MONGODB_PROXY=socks5://example.com:8080\n```\n\n
\n`HTTP_PROXY`\n\n\nProxy connections to `http://` URLs. HTTP connections are mostly used for OIDC authentication.\n\nIf you also set `HTTPS_PROXY`, the value of `HTTPS_PROXY` takes precedence for all requests.\n\n\nThe following example sets the `HTTP_PROXY` environment variable to proxy HTTP connections through a HTTP proxy located at `example.com:8080`:\n\n```sh\nexport HTTP_PROXY=http://example.com:8080\n```\n\n
\n`HTTPS_PROXY`\n\n\nProxy connections to `https://` URLs. HTTPS connections are mostly used for OIDC authentication.\n\nIf you also set `HTTP_PROXY`, the value of `HTTPS_PROXY` takes precedence for all requests.\n\n\nThe following example sets the `HTTPS_PROXY` environment variable to proxy all HTTPS connections through a HTTPS proxy located at `localhost:8080` without TLS:\n\n```sh\nexport HTTPS_PROXY=http://localhost:8080\n```\n\n
\n`ALL_PROXY`\n\n\nProxy all connections to the specified URL.\n\n\nThe following example sets the `ALL_PROXY` environment variable to proxy all outbound network connections through a Socks5 proxy located at `example.com:1234` with credentials included in the URL:\n\n```sh\nexport ALL_PROXY=socks5://username:password@example.com:1234\n```\n\n
\n`NO_PROXY`\n\n\nComma-separated list of hostnames that should be excluded from proxying.\n\n\nThe following example sets the `NO_PROXY` environment variable to bypass the proxy for connections to `localhost` and `internal-db.example.com`.\n\n```sh\nexport NO_PROXY=localhost,internal-db.example.com\n```\n\n
The MongoDB MCP Server supports the following proxy types:\n\n- Socks5 proxies\n\n- HTTP proxies\n\n- CONNECT proxies\n\n- PAC (proxy auto-config) URLs that resolve to one of the previously listed proxies"} -{"chunk_id": "6a7d648bd54f2f30bc3a4bc7-0", "page_id": "6a7d648bd54f2f30bc3a4bc7", "source_name": "mcp-server", "product_name": "MongoDB MCP Server", "url": "https://mongodb.com/docs/mcp-server/local-mcp/security/connect-with-x509", "title": "Connect with X.509 Certificates", "text": "# Connect with X.509 Certificates\n\nYou can connect to your MongoDB Enterprise deployment or MongoDB Atlas cluster using X.509 certificate authentication with the MongoDB MCP Server.\n\nTo learn more, see X.509.\n\n## Prerequisites\n\nComplete one of the following procedures to set up X.509 authentication for your MongoDB deployment:\n\n- Set up X.509 for MongoDB Atlas\n\n- Set up X.509 for MongoDB Enterprise\n\nIf you need to configure your MongoDB instance to support TLS/SSL, see Configure MongoDB for TLS/SSL.\n\n## Configuration Options\n\nTo connect to a MongoDB deployment with X.509, configure the following options in your MCP server configuration:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nCLI Option Name\n\n\nOS Environment Variable Name\n\n\nType\n\n\nNecessity\n\n\nDescription\n\n
\n`username`\n\n\n`MDB_MCP_USERNAME`\n\n\nstring\n\n\nRequired\n\n\nSet the username to the subject from your client certificate. The username must match the distinguished subject name of the certificate. If you omit this parameter, the MongoDB deployment infers the username from the X.509 certificate.\n\n
\n`authenticationDatabase`\n\n\n`MDB_MCP_AUTHENTICATION_DATABASE`\n\n\nstring\n\n\nRequired\n\n\nSet to `$external` for X.509 authentication.\n\n
\n`authenticationMechanism`\n\n\n`MDB_MCP_AUTHENTICATION_MECHANISM`\n\n\nstring\n\n\nRequired\n\n\nSet to `MONGODB-X509` to use X.509 client certificate authentication.\n\n
\n`tls`\n\n\n`MDB_MCP_TLS`\n\n\nboolean\n\n\nOptional\n\n\nSet to `true` to enable TLS for the connection when using X.509.\n\n
\n`tlsCertificateKeyFile`\n\n\n`MDB_MCP_TLS_CERTIFICATE_KEY_FILE`\n\n\nstring\n\n\nOptional\n\n\nSpecifies the .pem file that contains both the TLS / SSL certificate and key. Specify the file name of the .pem file using relative or absolute paths. Required when using `tls` to connect to a `mongod` or `mongos` instance that requires client certificates.\n\n
\n`tlsCertificateSelector`\n\n\n`MDB_MCP_TLS_CERTIFICATE_SELECTOR`\n\n\nstring\n\n\nOptional\n\n\nAvailable on Windows and macOS as an alternative to `tlsCertificateKeyFile`. Specifies a certificate property in order to select a matching certificate from the operating system's certificate store. Accepts an argument of the format `=` where the property can be one of the following: `subject`, `thumbprint`. The options are mutually exclusive: you can only specify one of `tlsCertificateKeyFile` or `tlsCertificateSelector`.\n\n
\n`tlsCAFile`\n\n\n`MDB_MCP_TLS_CA_FILE`\n\n\nstring\n\n\nOptional\n\n\nSpecifies the .pem file that contains the root certificate chain from the Certificate Authority. This file is used to validate the certificate presented by the `mongod` / `mongos` instance. Specify the file name of the .pem file using relative or absolute paths.\n\n
\n`tlsCRLFile`\n\n\n`MDB_MCP_TLS_CRL_FILE`\n\n\nstring\n\n\nOptional\n\n\nSpecifies the .pem file that contains the Certificate Revocation List. Specify the file name of the .pem file using relative or absolute paths.\n\n
\n`tlsDisabledProtocols`\n\n\n`MDB_MCP_TLS_DISABLED_PROTOCOLS`\n\n\nstring\n\n\nOptional\n\n\nDisables the specified TLS protocols. To enable a disabled protocol, specify `none`.\n\n
\n`tlsAllowInvalidHostnames`\n\n\n`MDB_MCP_TLS_ALLOW_INVALID_HOSTNAMES`\n\n\nboolean\n\n\nOptional\n\n\nDisables the validation of the hostnames in the certificate presented by the `mongod` / `mongos` instance. Allows connections even if the hostname in the server certificate does not match the server's host.\n\n
\n`tlsAllowInvalidCertificates`\n\n\n`MDB_MCP_TLS_ALLOW_INVALID_CERTIFICATES`\n\n\nboolean\n\n\nOptional\n\n\nBypasses the validation checks for the certificates presented by the `mongod` / `mongos` instance and allows connections to servers that present invalid certificates.\n\n
"} -{"chunk_id": "68a95c1b5e79d242619dd3b1-0", "page_id": "68a95c1b5e79d242619dd3b1", "source_name": "mongocli", "product_name": "MongoDB CLI", "url": "https://mongodb.com/docs/mongocli/current/command/mongocli-cloud-manager-monitoring", "title": "mongocli cloud-manager monitoring", "text": "# mongocli cloud-manager monitoring\n\nManage monitoring for your project.\n\n## Options\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\n-h, --help\n\n\n\n\nfalse\n\n\nhelp for monitoring\n\n
\n\n## Inherited Options\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\n-P, --profile\n\n\nstring\n\n\nfalse\n\n\nName of the profile to use from your configuration file. To learn about profiles for MongoCLI, see https://dochub.mongodb.org/core/atlas-cli-configuration-file.\n\n
\n\n## Related Commands\n\n- mongocli cloud-manager monitoring disable - Disable monitoring for a given hostname\n\n- mongocli cloud-manager monitoring enable - Enable monitoring for a given hostname\n\n- mongocli cloud-manager monitoring stop - Stops monitoring the MongoDB process specified"} -{"chunk_id": "68a95c1b5e79d242619dd475-0", "page_id": "68a95c1b5e79d242619dd475", "source_name": "mongocli", "product_name": "MongoDB CLI", "url": "https://mongodb.com/docs/mongocli/current/command/mongocli-iam-teams-users-delete", "title": "mongocli iam teams users delete", "text": "# mongocli iam teams users delete\n\nRemove the specified user from a team for your organization.\n\nTo use this command, you must authenticate with a user account or an API key with the Organization User Admin role.\n\n## Syntax\n\n```\nmongocli iam teams users delete [options]\n```\n\n## Arguments\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\nuserId\n\n\nstring\n\n\ntrue\n\n\nUnique 24-digit string that identifies the user.\n\n
\n\n## Options\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\n--force\n\n\n\n\nfalse\n\n\nFlag that indicates whether to skip the confirmation prompt before proceeding with the requested action.\n\n
\n-h, --help\n\n\n\n\nfalse\n\n\nhelp for delete\n\n
\n--orgId\n\n\nstring\n\n\nfalse\n\n\nOrganization ID to use. This option overrides the settings in the configuration file or environment variable.\n\n
\n--teamId\n\n\nstring\n\n\ntrue\n\n\nUnique 24-digit string that identifies the team.\n\n
\n\n## Inherited Options\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\n-P, --profile\n\n\nstring\n\n\nfalse\n\n\nName of the profile to use from your configuration file. To learn about profiles for MongoCLI, see https://dochub.mongodb.org/core/atlas-cli-configuration-file.\n\n
\n\n## Output\n\nIf the command succeeds, the CLI returns output similar to the following sample. Values in brackets represent your values.\n\n```\nUser '' deleted from the team\n```\n\n## Examples\n\n```\n# Remove the user with the ID 5dd58c647a3e5a6c5bce46c7 from the team with the ID 5f6a5c6c713184005d72fe6e for the organization with ID 5e2211c17a3e5a48f5497de3:\nmongocli iam teams users delete 5dd58c647a3e5a6c5bce46c7 --teamId 5f6a5c6c713184005d72fe6e --orgId 5e1234c17a3e5a48f5497de3\n```"} -{"chunk_id": "68a95c1b5e79d242619dd322-0", "page_id": "68a95c1b5e79d242619dd322", "source_name": "mongocli", "product_name": "MongoDB CLI", "url": "https://mongodb.com/docs/mongocli/current/command/mongocli-cloud-manager-alerts-settings-update", "title": "mongocli cloud-manager alerts settings update", "text": "# mongocli cloud-manager alerts settings update\n\nModify the details of the specified alert configuration for your project.\n\nTo use this command, you must authenticate with a user account or an API key with the Project Owner role.\n\n## Syntax\n\n```\nmongocli cloud-manager alerts settings update [options]\n```\n\n## Arguments\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\nalertConfigId\n\n\nstring\n\n\ntrue\n\n\nUnique identifier of the alert configuration you want to update.\n\n
"} -{"chunk_id": "68a95c1b5e79d242619dd322-1", "page_id": "68a95c1b5e79d242619dd322", "source_name": "mongocli", "product_name": "MongoDB CLI", "url": "https://mongodb.com/docs/mongocli/current/command/mongocli-cloud-manager-alerts-settings-update", "title": "mongocli cloud-manager alerts settings update", "text": "## Options\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\n--apiKey\n\n\nstring\n\n\nfalse\n\n\nDatadog API Key, Opsgenie API Key, or VictorOps API key. Required if the notificationType is DATADOG, OPS_GENIE, or VICTOR_OPS, respectively.\n\n
\n--enabled\n\n\n\n\nfalse\n\n\nFlag that indicates whether to enable the alert configuration.\n\n
\n--event\n\n\nstring\n\n\nfalse\n\n\nType of event that triggered the alert. To learn which values the CLI accepts, see the possible eventTypeName values in the API documentation for Atlas (https://dochub.mongodb.org/core/atlas-event-names), Ops Manager (https://dochub.mongodb.org/core/om-event-names), or Cloud Manager (https://dochub.mongodb.org/core/cm-event-names).\n\n
\n-h, --help\n\n\n\n\nfalse\n\n\nhelp for update\n\n
\n--matcherFieldName\n\n\nstring\n\n\nfalse\n\n\nName of the field in the target object to match on. To learn the valid values, run mongocli atlas alerts settings fields type.\n\n
\n--matcherOperator\n\n\nstring\n\n\nfalse\n\n\nComparison operator to apply when checking the current metric against matcherValue. Valid values are CONTAINS, ENDS_WITH, EQUALS, NOT_CONTAINS, NOT_EQUALS, REGEX, STARTS_WITH.\n\n
\n--matcherValue\n\n\nstring\n\n\nfalse\n\n\nValue to test with the specified operator. If matcherFieldName is set to TYPE_NAME, you can match on the following values: CONFIG, MONGOS, PRIMARY, SECONDARY, STANDALONE.\n\n
\n--metricMode\n\n\nstring\n\n\nfalse\n\n\nOption that indicates whether Atlas computes the current metric value as an average. Valid value is AVERAGE.\n\n
\n--metricName\n\n\nstring\n\n\nfalse\n\n\nName of the metric against which this command checks the configured alert. To learn the valid values, see https://dochub.mongodb.org/core/alert-host-metrics-atlas. This option applies only if the event is set to OUTSIDE_METRIC_THRESHOLD.\n\n
\n--metricOperator\n\n\nstring\n\n\nfalse\n\n\nComparison operator to apply when checking the current metric value. Valid values are LESS_THAN and GREATER_THAN.\n\n
\n--metricThreshold\n\n\nfloat\n\n\nfalse\n\n\nThreshold value outside of which an alert will be triggered.\n\n
\n--metricUnits\n\n\nstring\n\n\nfalse\n\n\nUnits for the threshold value. Valid values are BITS, BYTES, DAYS, GIGABITS, GIGABYTES, HOURS, KILOBITS, KILOBYTES, MEGABITS, MEGABYTES, MILLISECONDS, MINUTES, PETABYTES, RAW, SECONDS, TERABYTES.\n\n
\n--notificationChannelName\n\n\nstring\n\n\nfalse\n\n\nSlack channel name. Required for the SLACK notifications type.\n\n
\n--notificationDelayMin\n\n\nint\n\n\nfalse\n\n\nNumber of minutes to wait after an alert condition is detected before sending out the first notification.\n\n
\n--notificationEmailAddress\n\n\nstring\n\n\nfalse\n\n\nEmail address to which alert notifications are sent.\n\n
\n--notificationEmailEnabled\n\n\n\n\nfalse\n\n\nFlag that enables email notifications. Configurable for GROUP and USER notification types.\n\n
\n--notificationIntervalMin\n\n\nint\n\n\nfalse\n\n\nNumber of minutes to wait between successive notifications for unacknowledged alerts that are not resolved.\n\n
\n--notificationMobileNumber\n\n\nstring\n\n\nfalse\n\n\nMobile number to which alert notifications are sent.\n\n
\n--notificationRegion\n\n\nstring\n\n\nfalse\n\n\nRegion that indicates which API URL to use.\n\n
\n--notificationServiceKey\n\n\nstring\n\n\nfalse\n\n\nPagerDuty service key.\n\n
\n--notificationSmsEnabled\n\n\n\n\nfalse\n\n\nFlag that enables text message notifications.\n\n
\n--notificationTeamId\n\n\nstring\n\n\nfalse\n\n\nUnique identifier of a team.\n\n
\n--notificationToken\n\n\nstring\n\n\nfalse\n\n\nSlack API token, or Bot token.\n\n
\n--notificationType\n\n\nstring\n\n\nfalse\n\n\nType of alert notification. Valid values are DATADOG, EMAIL, GROUP (Project), ORG, OPS_GENIE, PAGER_DUTY, SLACK, SMS, USER, or VICTOR_OPS.\n\n
\n--notificationUsername\n\n\nstring\n\n\nfalse\n\n\nName of the Atlas user to which to send notifications.\n\n
\n--notificationVictorOpsRoutingKey\n\n\nstring\n\n\nfalse\n\n\nRouting key associated with your Splunk On-Call account.\n\n
\n-o, --output\n\n\nstring\n\n\nfalse\n\n\nOutput format. Valid values are json, json-path, go-template, or go-template-file. To see the full output, use the -o json option.\n\n
\n--projectId\n\n\nstring\n\n\nfalse\n\n\nHexadecimal string that identifies the project to use. This option overrides the settings in the configuration file or environment variable.\n\n
"} -{"chunk_id": "68a95c1b5e79d242619dd322-2", "page_id": "68a95c1b5e79d242619dd322", "source_name": "mongocli", "product_name": "MongoDB CLI", "url": "https://mongodb.com/docs/mongocli/current/command/mongocli-cloud-manager-alerts-settings-update", "title": "mongocli cloud-manager alerts settings update", "text": "## Inherited Options\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\n-P, --profile\n\n\nstring\n\n\nfalse\n\n\nName of the profile to use from your configuration file. To learn about profiles for MongoCLI, see https://dochub.mongodb.org/core/atlas-cli-configuration-file.\n\n
\n\n## Output\n\nIf the command succeeds, the CLI returns output similar to the following sample. Values in brackets represent your values.\n\n```\nAlert configuration '' updated.\n```\n\n## Examples\n\n```\n# Modify the alert configuration with the ID 5d1113b25a115342acc2d1aa so that it notifies a user when they join a group for the project with the ID 5df90590f10fab5e33de2305:\nmongocli [ops-manager|cloud-manager] alerts settings update 5d1113b25a115342acc2d1aa --event JOINED_GROUP --enabled \\\n--notificationType USER --notificationEmailEnabled \\\n--notificationUsername john@example.com \\\n--output json --projectId 5df90590f10fab5e33de2305\n```"} -{"chunk_id": "68a95c1b5e79d242619dd36f-0", "page_id": "68a95c1b5e79d242619dd36f", "source_name": "mongocli", "product_name": "MongoDB CLI", "url": "https://mongodb.com/docs/mongocli/current/command/mongocli-cloud-manager-liveMigrations-link-delete", "title": "mongocli cloud-manager liveMigrations link delete", "text": "# mongocli cloud-manager liveMigrations link delete\n\nDelete one link-token.\n\n## Syntax\n\n```\nmongocli cloud-manager liveMigrations link delete [options]\n```\n\n## Options\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\n--force\n\n\n\n\nfalse\n\n\nFlag that indicates whether to skip the confirmation prompt before proceeding with the requested action.\n\n
\n-h, --help\n\n\n\n\nfalse\n\n\nhelp for delete\n\n
\n--orgId\n\n\nstring\n\n\nfalse\n\n\nOrganization ID to use. This option overrides the settings in the configuration file or environment variable.\n\n
\n\n## Inherited Options\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\n-P, --profile\n\n\nstring\n\n\nfalse\n\n\nName of the profile to use from your configuration file. To learn about profiles for MongoCLI, see https://dochub.mongodb.org/core/atlas-cli-configuration-file.\n\n
"} -{"chunk_id": "68a95c1b5e79d242619dd48a-0", "page_id": "68a95c1b5e79d242619dd48a", "source_name": "mongocli", "product_name": "MongoDB CLI", "url": "https://mongodb.com/docs/mongocli/current/command/mongocli-iam-projects-teams-update", "title": "mongocli iam projects teams update", "text": "# mongocli iam projects teams update\n\nModify the roles for the specified team for your project.\n\nTo use this command, you must authenticate with a user account or an API key with the Project User Admin role.\n\n## Syntax\n\n```\nmongocli iam projects teams update [options]\n```\n\n## Arguments\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\nteamId\n\n\nstring\n\n\ntrue\n\n\nUnique 24-digit string that identifies the team.\n\n
\n\n## Options\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\n-h, --help\n\n\n\n\nfalse\n\n\nhelp for update\n\n
\n-o, --output\n\n\nstring\n\n\nfalse\n\n\nOutput format. Valid values are json, json-path, go-template, or go-template-file. To see the full output, use the -o json option.\n\n
\n--projectId\n\n\nstring\n\n\nfalse\n\n\nHexadecimal string that identifies the project to use. This option overrides the settings in the configuration file or environment variable.\n\n
\n--role\n\n\nstrings\n\n\ntrue\n\n\nUser role that applies to all members of the specified team for the associated project. Valid values include GROUP_CLUSTER_MANAGER, GROUP_DATA_ACCESS_ADMIN, GROUP_DATA_ACCESS_READ_ONLY, GROUP_DATA_ACCESS_READ_WRITE, GROUP_OWNER, and GROUP_READ_ONLY. Passing this flag replaces preexisting data.\n\n
\n\n## Inherited Options\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\n-P, --profile\n\n\nstring\n\n\nfalse\n\n\nName of the profile to use from your configuration file. To learn about profiles for MongoCLI, see https://dochub.mongodb.org/core/atlas-cli-configuration-file.\n\n
\n\n## Output\n\nIf the command succeeds, the CLI returns output similar to the following sample. Values in brackets represent your values.\n\n```\nTeam's roles updated.\n```\n\n## Examples\n\n```\n# Modify the roles for the team with the ID 5dd56c847a3e5a1f363d424d to grant GROUP_READ_ONLY access to the project with the ID 5f71e5255afec75a3d0f96dc:\nmongocli iam projects teams update 5dd56c847a3e5a1f363d424d --projectId 5f71e5255afec75a3d0f96dc --role GROUP_READ_ONLY --output json\n```"} -{"chunk_id": "68a95c1b5e79d242619dd2c6-0", "page_id": "68a95c1b5e79d242619dd2c6", "source_name": "mongocli", "product_name": "MongoDB CLI", "url": "https://mongodb.com/docs/mongocli/current/command/mongocli", "title": "mongocli", "text": "# mongocli\n\nCLI tool to manage your MongoDB Cloud\n\nUse mongocli command help for information on a specific command\n\n## Options\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\n-h, --help\n\n\n\n\nfalse\n\n\nhelp for mongocli\n\n
\n-P, --profile\n\n\nstring\n\n\nfalse\n\n\nName of the profile to use from your configuration file. To learn about profiles for MongoCLI, see https://dochub.mongodb.org/core/atlas-cli-configuration-file.\n\n
\n\n## Examples\n\n```\n# Display the help menu for the config command:\nmongocli config --help\n```\n\n## Related Commands\n\n- mongocli auth - Manage the CLI's authentication state.\n\n- mongocli cloud-manager - MongoDB Cloud Manager operations.\n\n- mongocli completion - Generate the autocompletion script for the specified shell\n\n- mongocli config - Configure and manage your user profiles.\n\n- mongocli iam - Organization and projects operations.\n\n- mongocli ops-manager - MongoDB Ops Manager operations."} -{"chunk_id": "68a95c1b5e79d242619dd4d5-0", "page_id": "68a95c1b5e79d242619dd4d5", "source_name": "mongocli", "product_name": "MongoDB CLI", "url": "https://mongodb.com/docs/mongocli/current/command/mongocli-iam-teams-create", "title": "mongocli iam teams create", "text": "# mongocli iam teams create\n\nCreate a team for your organization.\n\nTo use this command, you must authenticate with a user account or an API key with the Organization Owner role.\n\n## Syntax\n\n```\nmongocli iam teams create [options]\n```\n\n## Arguments\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\nname\n\n\nstring\n\n\ntrue\n\n\nLabel that identifies the team.\n\n
\n\n## Options\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\n-h, --help\n\n\n\n\nfalse\n\n\nhelp for create\n\n
\n--orgId\n\n\nstring\n\n\nfalse\n\n\nOrganization ID to use. This option overrides the settings in the configuration file or environment variable.\n\n
\n-o, --output\n\n\nstring\n\n\nfalse\n\n\nOutput format. Valid values are json, json-path, go-template, or go-template-file. To see the full output, use the -o json option.\n\n
\n--username\n\n\nstrings\n\n\ntrue\n\n\nComma-separated list that contains the valid usernames of the MongoDB users to add to the new team. A team must have at least one user. New users must accept the invitation to join an organization before you can add them to a team.\n\n
\n\n## Inherited Options\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\n-P, --profile\n\n\nstring\n\n\nfalse\n\n\nName of the profile to use from your configuration file. To learn about profiles for MongoCLI, see https://dochub.mongodb.org/core/atlas-cli-configuration-file.\n\n
\n\n## Output\n\nIf the command succeeds, the CLI returns output similar to the following sample. Values in brackets represent your values.\n\n```\nTeam '' created.\n```\n\n## Examples\n\n```\n# Create a team named myTeam in the organization with ID 5e2211c17a3e5a48f5497de3:\nmongocli iam teams create myTeam --username user1@example.com,user2@example.com --orgId 5e1234c17a3e5a48f5497de3 --output json\n```"} -{"chunk_id": "68a95c1b5e79d242619dd3e3-0", "page_id": "68a95c1b5e79d242619dd3e3", "source_name": "mongocli", "product_name": "MongoDB CLI", "url": "https://mongodb.com/docs/mongocli/current/command/mongocli-config-edit", "title": "mongocli config edit", "text": "# mongocli config edit\n\nOpens the config file with the default text editor.\n\nUses the default editor to open the config file. You can use EDITOR or VISUAL envs to change the default.\n\n## Syntax\n\n```\nmongocli config edit [options]\n```\n\n## Options\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\n-h, --help\n\n\n\n\nfalse\n\n\nhelp for edit\n\n
\n\n## Inherited Options\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\n-P, --profile\n\n\nstring\n\n\nfalse\n\n\nName of the profile to use from your configuration file. To learn about profiles for MongoCLI, see https://dochub.mongodb.org/core/atlas-cli-configuration-file.\n\n
\n\n## Examples\n\n```\n# To open the config\nmongocli config edit\n```"} -{"chunk_id": "68a95c1b5e79d242619dd632-0", "page_id": "68a95c1b5e79d242619dd632", "source_name": "mongocli", "product_name": "MongoDB CLI", "url": "https://mongodb.com/docs/mongocli/current/troubleshooting", "title": "Troubleshooting", "text": "# Troubleshooting\n\n## Command Errors\n\n### Error: missing credentials\n\nYou might not have properly set up your API keys. Ensure that you added your API keys to your profile or your environment variables. If you created a profile with a custom name or are using more than one profile, ensure that you are specifying the correct profile with the `--profile` flag.\n\nFor more information on properly configuring your profile, see Configure the MongoDB CLI.\n\n### mongocli: command not found\n\nThe `mongocli` executable might be in a directory which is not in your path. You can either add the directory to your path, move the executable to a directory which is in your path, or run the executable directly from its location.\n\n### 401 (request \"Unauthorized\") You are not authorized for this resource.\n\nThe credentials you have provided are not valid for the project specified in your MongoDB CLI command. Check your public and private key strings for accuracy.\n\nIf your credentials are stored in a configuration file, make sure that the configuration file is in the correct location. The default location is the `.config` folder of your home directory. If you move the configuration file somewhere else, be sure to specify the location in the `$XDG_CONFIG_HOME` environment variable. If MongoDB CLI cannot find your configuration file and no credentials are stored in environment variables, a `401` error will result.\n\n### 401 (request \"Unauthorized\") Current user is not authorized to perform this action.\n\nThe API key specified in your configuration file does not have permission to perform the requested action. API keys are configured with specific permission levels, from `Project Read Only` (minimum permission level) up to `Project Owner` (full permissions).\n\n### 401 (request \"Unauthorized\") The currently logged in user does not have the group creator role in organization .\n\nThis error might appear when trying to create a new project. Your specified API key must have the `Organization Project Creator` role at the organization level in order to create new projects.\n\n### 403 (request \"Forbidden\") IP address is not allowed to access this resource.\n\nThe API key specified in your configuration file is not on the access list for the requested project.\n\n### 404 (request \"Not Found\") An invalid group ID was specified.\n\nThe project ID entered with the command does not exist. Check your project ID by navigating to the Settings sub-section of the Project section in the Atlas left-side navigation.\n\n`group ID` and `project ID` are synonymous in MongoDB cloud services.\n\n### 404 (request \"Not Found\") Organization is not an Atlas organization.\n\nTo use the MongoDB CLI with Cloud Manager or Ops Manager, you must specify the service in your configuration file. If you don't specify a service, MongoDB CLI defaults to `Atlas`.\n\n### Unsupported service: \n\nSome operations are available only for Atlas, while others are available only for Cloud Manager or Ops Manager. This error might appear if you request an operation which is not available for the specified service.\n\n### Alert Config Not Deleted\n\nThis error might appear if MongoDB CLI cannot delete the alert configuration specified by the ID.\n\n## Configuration Errors\n\n### Blank output when reading home directory\n\nThis error might appear if MongoDB CLI cannot access your home directory.\n\n### HOMEDRIVE, HOMEPATH, or USERPROFILE are blank\n\nThis error might appear if MongoDB CLI cannot access your home directory.\n\n### Connection timeouts on Internet-limited hosts\n\nMongoDB CLI checks for updates automatically. This can cause problems if you use MongoDB CLI on systems with limited Internet access. To prevent delays or timeouts, set the `MCLI_SKIP_UPDATE_CHECK`\nenvironment variable to `true`."} -{"chunk_id": "68a95c1b5e79d242619dd49c-0", "page_id": "68a95c1b5e79d242619dd49c", "source_name": "mongocli", "product_name": "MongoDB CLI", "url": "https://mongodb.com/docs/mongocli/current/command/mongocli-ops-manager-admin-backups-s3", "title": "mongocli ops-manager admin backups s3", "text": "# mongocli ops-manager admin backups s3\n\nManage backup s3 blockstore configurations.\n\n## Options\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\n-h, --help\n\n\n\n\nfalse\n\n\nhelp for s3\n\n
\n\n## Inherited Options\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\n-P, --profile\n\n\nstring\n\n\nfalse\n\n\nName of the profile to use from your configuration file. To learn about profiles for MongoCLI, see https://dochub.mongodb.org/core/atlas-cli-configuration-file.\n\n
\n\n## Related Commands\n\n- mongocli ops-manager admin backups s3 create - Create a backup S3 blockstore configuration.\n\n- mongocli ops-manager admin backups s3 delete - Delete a backup s3 blockstore configuration.\n\n- mongocli ops-manager admin backups s3 describe - Get a backup s3 blockstore configuration.\n\n- mongocli ops-manager admin backups s3 list - List backup s3 blockstore configurations.\n\n- mongocli ops-manager admin backups s3 update - Update a backup S3 blockstore configuration."} -{"chunk_id": "68a95c1b5e79d242619dd6bf-0", "page_id": "68a95c1b5e79d242619dd6bf", "source_name": "mongodb-shell", "product_name": "MongoDB Shell", "url": "https://mongodb.com/docs/mongodb-shell/logs/compression", "title": "Enable Log Compression", "text": "# Enable Log Compression\n\nYou can enable compression for MongoDB Shell log files. By default, MongoDB Shell does not compress log files.\n\n## About this Task\n\nWhen log compression is enabled, MongoDB Shell compresses log files with gzip.\n\nAfter you toggle log compression, you must start a new MongoDB Shell session for the change to take effect.\n\n## Before you Begin\n\nTo check if log compression is enabled, run the following command from MongoDB Shell:\n\n```javascript\nconfig.get(\"logCompressionEnabled\")\n```\n\n## Steps\n\nTo enable log compression, set the `logCompressionEnabled` configuration option to `true`. You can set configuration options in the configuration API or a configuration file.\n\n### Enable Log Compression with the Configuration API\n\nThe following command uses the config API to enable log compression:\n\n```javascript\nconfig.set(\"logCompressionEnabled\", true)\n```\n\n```javascript\nSetting \"logCompressionEnabled\" has been changed\n```\n\n### Enable Log Compression with a Configuration File\n\nThe following configuration file enables log compression:\n\n```yaml\nmongosh:\n logCompressionEnabled: true\n```\n\n### Disable Log Compression\n\nTo disable log compression, set `logCompressionEnabled` to `false`. You can perform this action through the config API or configuration file."} -{"chunk_id": "68a95c1b5e79d242619dd6b0-0", "page_id": "68a95c1b5e79d242619dd6b0", "source_name": "mongodb-shell", "product_name": "MongoDB Shell", "url": "https://mongodb.com/docs/mongodb-shell/mongoshrc", "title": "`.mongoshrc` Configuration File", "text": "# `.mongoshrc` Configuration File\n\nOn startup, `mongosh` checks your `HOME` directory for a JavaScript file named .mongoshrc.js. If this file is found, `mongosh` reads the content of .mongoshrc.js before displaying the prompt for the first time.\n\nIf you use `mongosh` to evaluate a JavaScript file or expression, either by using the `--eval` option on the command line or by specifying a .js file, `mongosh` reads .mongoshrc.js *after* the JavaScript has finished processing. You can prevent .mongoshrc.js from being loaded by using the `--norc` option.\n\nThe legacy `mongo` shell uses a configuration file named `.mongorc.js`.\n\nIf `mongosh` finds `.mongorc.js` on startup but doesn't find `.mongoshrc.js`, `mongosh` doesn't load the legacy `.mongorc.js` file and states you should rename `.mongorc.js` to `.mongoshrc.js`.\n\n## Example Usage\n\nYou can use the .mongoshrc file to customize `mongosh` startup behavior and add scripted functionality. For examples, see Execute Code From a Configuration File."} -{"chunk_id": "68a95c1b5e79d242619dd70a-0", "page_id": "68a95c1b5e79d242619dd70a", "source_name": "mongodb-shell", "product_name": "MongoDB Shell", "url": "https://mongodb.com/docs/mongodb-shell/run-commands", "title": "Run Commands", "text": "# Run Commands\n\nTo run commands in `mongosh`, you must first connect to a MongoDB deployment.\n\n## Format Input and Output\n\nBSONEJSONNode.js BSON parserJSON.parseJSON.stringify()`mongosh` uses the Node.js BSON parser parser to parse BSON data. You can use the parser's EJSON interface to transform your data when you work with `mongosh`.\n\nFor examples that use EJSON, see: EJSON.\n\n## Switch Databases\n\nTo display the database you are using, type `db`:\n\n```sh\ndb\n```\n\nThe operation should return `test`, which is the default database.\n\nTo switch databases, issue the `use ` helper, as in the following example:\n\n```javascript\nuse \n```\n\nTo access a different database from the current database without switching your current database context, see the `db.getSiblingDB()` method.\n\nTo list the databases available to the user, use the helper `show dbs`.\n\n### Create a New Database and Collection\n\nTo create a new database, issue the `use ` command with the database that you would like to create. For example, the following commands create both the database `myNewDatabase` and the collection `myCollection` using the `insertOne()` operation:\n\n```javascript\nuse myNewDatabase\ndb.myCollection.insertOne( { x: 1 } );\n```\n\nIf a collection does not exist, MongoDB creates the collection when you first store data for that collection.\n\n## Terminate a Running Command\n\nTo terminate a running command or query in `mongosh`, press `Ctrl + C`.\n\nWhen you enter `Ctrl + C`, `mongosh`:\n\n- interrupts the active command,\n\n- tries to terminate the ongoing, server-side operation, and\n\n- returns a command prompt.\n\nIf `mongosh` cannot cleanly terminate the running process, it issues a warning.\n\nPressing `Ctrl + C` in `mongosh` does not terminate asynchronous code. Asynchronous operations such as `setTimeout` or operations like `fs.readFile` continue to run.\n\nThere is no way to terminate asynchronous code in `mongosh`. This is the same behavior as in the Node.js REPL.\n\nPressing `Ctrl + C` once will not exit `mongosh`, press `Ctrl + C` twice to exit `mongosh`.\n\nYou can also terminate a script from within the script code by calling the `exit()` command. For more information, refer to Terminate a Script on Error.\n\n## Command Exceptions\n\nFor commands whose output includes `{ ok: 0 }`, `mongosh` returns a consistent exception and omits the server raw output. The legacy `mongo` shell returns output that varies for each command.\n\n## Clear the `mongosh` Console\n\nThe `cls` command clears the console. You can also clear the console with `Ctrl + L` and `console.clear()`."} -{"chunk_id": "68a95c1b5e79d242619dd714-0", "page_id": "68a95c1b5e79d242619dd714", "source_name": "mongodb-shell", "product_name": "MongoDB Shell", "url": "https://mongodb.com/docs/mongodb-shell/snippets/commands", "title": "Snippet Commands", "text": "# Snippet Commands\n\nThis feature is experimental. MongoDB does not provide support for Snippets. This feature may be changed or removed at any time without prior notice.\n\nBugs are not expected, however should you encounter one, please open an issue in the GitHub repository for this project.\n\nThis document provides an overview of the commands that are available to work with snippets.\n\n## Commands\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nCommand\n\n\nDescription\n\n
\n`help`\n\n\nShow the help text or information about a specific snippet. See an example.\n\n```shell\nsnippet help\nsnippet help \n```\n\n
\n`info`\n\n\nShow information about configured snippet repositories. See an example.\n\n```shell\nsnippet info\n```\n\n
\n`install`\n\n\nInstall a new snippet. See an example.\n\n```shell\nsnippet install \n```\n\n
\n`ls`\n\n\nList name and version of installed snippets. See an example\n\n```shell\nsnippet ls\n```\n\n
\n`load-all`\n\n\nLoad all installed snippets into the current environment.\n\n```shell\nsnippet load-all\n```\n\n
\n`outdated`\n\n\nList snippets that have updated registry versions.\n\n```shell\nsnippet outdated\n```\n\n
\n`refresh`\n\n\nClear and refresh the snippet metadata cache. See an example.\n\n```shell\nsnippet refresh\n```\n\n
\n`search`\n\n\nList available snippets, their version, and a brief description. See an example.\n\n```shell\nsnippet search\n```\n\n
\n`uninstall`\n\n\nRemove an installed snippet. See an example.\n\n```shell\nsnippet uninstall \n```\n\n
\n`update`\n\n\nGet the latest versions of installed snippets\n\n```shell\nsnippet update\n```\n\n
"} -{"chunk_id": "68a95c1b5e79d242619dd717-0", "page_id": "68a95c1b5e79d242619dd717", "source_name": "mongodb-shell", "product_name": "MongoDB Shell", "url": "https://mongodb.com/docs/mongodb-shell/snippets/registries-config", "title": "Registries and Registry Configuration", "text": "# Registries and Registry Configuration\n\nThis feature is experimental. MongoDB does not provide support for Snippets. This feature may be changed or removed at any time without prior notice.\n\nBugs are not expected, however should you encounter one, please open an issue in the GitHub repository for this project.\n\nThis page discusses different registries and how to configure your system to use them.\n\n## Types of Registry Configuration\n\nThe snippets feature uses the npm package manager to install snippets from a pre-specified registry. You can configure your local `mongosh` to use one or more registries:\n\n- The community registry that is maintained by MongoDB\n\n- A private registry that you maintain\n\n- Multiple registries used together\n\n### Using the MongoDB Registry\n\nThis is a public, community registry that is maintained by MongoDB.\n\nThe community registry is the default registry. It provides several useful snippets which can help you to get started. The snippets in the community registry are also good examples to use when you are ready to create your own snippets.\n\nMongoDB users are encouraged to contribute to this public registry. To learn how to share your code with other MongoDB users, see Contribute a Snippet Package to the MongoDB Community.\n\n### Using Private Snippet Registries\n\nYou can share code internally using a private registry.\n\nIf your snippets reveal proprietary or sensitive information, you can store them in a private, local registry instead of the public registry.\n\nTo create a private registry, see Define a New Registry.\n\n### Using Multiple Registries\n\nA private registry can also be used in conjunction with the community registry and other private registries. Using multiple registries allows you to benefit from snippets maintained by MongoDB or third parties while also maintaining control over code you don't want to share externally.\n\nTo configure multiple registries, see Connecting to Registries.\n\n## How to Configure a Registry\n\nTo use a private registry or multiple registries:\n\n- Define a New Registry.\n\n- Create a registry index file.\n\n- Update `snippetIndexSourceURLs` to contain a link to your registry index file.\n\n- Update `snippetRegistryURL` to point to your registry host (optional).\n\n### Define a New Registry\n\nThe npm public registry hosts the MongoDB snippets community registry. You can use npm to host your own public or private registry as well.\n\n#### Create A GitHub Repository.\n\nYou will push snippet packages from your GitHub repository to your npm registry.\n\nFollow the GitHub documentation to create a repository.\n\n#### Create An npm Registry.\n\nFollow the npm registry documentation to create a registry.\n\n#### Update `snippetIndexSourceURLs`.\n\nTo make the new registry available to your local `mongosh` installation, update the `snippetIndexSourceURLs` configuration settings.\n\n```\nconfig.set('snippetIndexSourceURLs',\n'https://github.com/YOUR_COMPANY/PATH_TO_YOUR_REPOSITORY/index.bson.br;'\n+ config.get('snippetIndexSourceURLs') )\n```\n\n#### Update `snippetRegistryURL`.\n\nIf you created a registry that is hosted outside npm, update `snippetRegistryURL` to point to the new registry.\n\n### Connecting to Registries\n\nYou can use a private registry in addition to, or instead of, the community MongoDB registry.\n\n`snippetIndexSourceURLs` ia a list of URLs. Each URL defines a path to an index file that contains metadata for the snippets in that registry.\n\nConfigure an additional registry by adding a URL to `snippetIndexSourceURLs`.\n\n```shell\nconfig.set('snippetIndexSourceURLs',\n 'https://github.com/YOUR_COMPANY/PATH_TO_YOUR_REPOSITORY/index.bson.br;'\n + config.get('snippetIndexSourceURLs')\n)\n```\n\nRestart `mongosh` for the update to take effect.\n\nIf two snippets with the same name appear in multiple registries, local system updates will be based on the entry in the first registry in the `snippetIndexSourceURLs` list.\n\nDo not reuse snippet names to avoid potential conflicts."} -{"chunk_id": "68a95c1b5e79d242619dd6dd-0", "page_id": "68a95c1b5e79d242619dd6dd", "source_name": "mongodb-shell", "product_name": "MongoDB Shell", "url": "https://mongodb.com/docs/mongodb-shell/reference/editor-mode", "title": "Use an Editor for Commands", "text": "# Use an Editor for Commands\n\nThe `mongosh` console is line oriented. However, you can also use an editor to work with multiline functions. There are two options:\n\n- Use the `edit` command with an external editor.\n\n- Use the `.editor` command, a built-in editor.\n\n## Using an External Editor\n\nThe `mongosh` `edit` command works with an external editor. You can configure an external editor in the shell that runs `mongosh` or from within `mongosh`.\n\nIf editors are configured in both locations, the editor configured within `mongosh` will take precedence.\n\nTo set an editor within `mongosh`, use the config.set() command.\n\n```javascript\nconfig.set( \"editor\", \"vi\" )\n```\n\nSee setting the external editor for more examples.\n\nYou can use `edit` in three ways:\n\n- Start a new Editing Session\n\n- Edit a Variable\n\n- Edit a Statement\n\n### Start a New Editing Session\n\nEnter `edit` by itself to start a new editing session.\n\n```javascript\nedit\n```\n\nIf you start an editing session without any arguments, the editor opens with the last edit loaded. See the example, Editing a Command.\n\n### Edit a Variable\n\nIf an argument exists in the console namespace, you can use `edit` to update it.\n\n```javascript\nvar albums = [ ];\nedit albums\n```\n\n- The variable `albums` is set in the first line.\n\n- The second line opens the external editor to edit the value of `albums`.\n\n### Edit a Statement\n\nTo edit a statement in the external editor, invoke `edit` with a statement such as `db.collection.insertMany()`.\n\n```javascript\nedit db.digits.insertMany( [] )\n```\n\nAfter editing `db.music.insertMany( [] )` and exiting the external editor, the `mongosh` console might look like this:\n\n```javascript\nprompt> db.digits.insertMany([{ \"zero\": 0 }, { \"one\": 1 }, { \"two\": 2 }])\n```\n\nWhen you exit the external editor, the statement is copied to the console input line, ready to run. It does not run automatically. Press `` to run the statement or ` + c` to cancel it.\n\n## Using the Built-in Editor\n\nThe `.editor` command provides basic multiline editing capabilities.\n\nThe editor does not save code. When you close the built-in editor, your edits are loaded into the global scope. If your edit calls any functions or commands, they will run when you close the editor.\n\nTo start the built-in editor:\n\n```javascript\n.editor\n```\n\nEnter ` + d` to exit and run your function.\n\nSee Using the Built-In Editor.\n\n## Examples\n\n### Set the External Editor\n\nIf the `EDITOR` environment variable is set in the shell running `mongosh`, the `edit` command will use that editor.\n\nIf the `mongosh` `editor` property is also set, `mongosh` will use that program instead. The `editor` property overrides the `EDITOR` environment variable.\n\n#### Set the `EDITOR` environment variable\n\nThe environment variable should be set before starting `mongosh`.\n\nSet an environment variable in `bash` or `zsh`:\n\n```shell\nexport EDITOR=vi\n```\n\nThe `vi` editor will open when you run `edit` in the `mongosh` console.\n\nYou can also set environment variables from within `mongosh` using `process.env.`.\n\nSet the EDITOR environment variable from `mongosh`:\n\n```javascript\nprocess.env.EDITOR = 'nano'\n```\n\nThe environment variable is only updated for the current `mongosh`. The update does not persist when `mongosh` exits.\n\n#### Set the `editor` Property\n\nTo set `nano` as the editor from within `mongosh`, use the config.set() command.\n\n```javascript\nconfig.set( \"editor\", \"nano\" )\n```\n\nThe `nano` editor will open when you run `edit` in the `mongosh` console.\n\n`mongosh` will attempt to use whatever program is configured. A program like `less` will work. Other programs, such as `grep`, may crash or have unexpected results.\n\n### Editing a Command\n\nUse `edit` to start an editing session. If the editor was already used in the current console session, the editor opens the last edit.\n\nThe following statement has a syntax error. The highlighted line is missing a comma:\n\n```javascript\n// WARNING: This code contains an error\n\ndb.users.insertMany( [\n { \"name\": \"Joey\", \"group\": \"sales\" }\n { \"name\": \"Marie\", \"group\": \"sales\" },\n { \"name\": \"Elton\", \"group\": \"accounting\" },\n { \"name\": \"Paola\", \"group\": \"marketing\" }\n] )\n```\n\nTo set up the example:\n\n1. Copy the example code.\n\n2. Enter `edit` to start an editing session.\n\n3. Paste the example code into the editor.\n\n4. Exit the editor.\n\n5. Press `enter`.\n\nWhen you exit the editor, it copies the example code to the command line. `mongosh` returns an error when the code runs.\n\nTo reload the example code, enter `edit` without any arguments.\n\n```javascript\n// WARNING: This code contains an error\n\ndb.users.insertMany([{\n \"name\": \"Joey\",\n \"group\": \"sales\"\n } {\n \"name\": \"Marie\",\n \"group\": \"sales\"\n },\n {\n \"name\": \"Elton\",\n \"group\": \"accounting\"\n },\n {\n \"name\": \"Paola\",\n \"group\": \"marketing\"\n }\n])\n```\n\nThe code is reformatted for easier editing. In this case the missing comma in the highlighted line causes the documents to be misaligned.\n\n### Using Visual Studio as an External Editor\n\nVisual Studio requires a special parameter to work as an external editor. Use `--wait` with Visual Studio.\n\nSet an environment variable:\n\n```javascript\nexport EDITOR=\"/usr/local/bin/code --wait\"\n```\n\nYou can also set the editor with config.set(). If Visual Studio is in your `PATH`, open `mongosh` and run:\n\n```javascript\nconfig.set(\"editor\", \"code --wait\")\n```\n\nIf you use Visual Studio, you can also use the MongoDB VS Code Extension.\n\n### Unset the External Editor\n\nUnset the `editor` variable in `mongosh`:\n\n```javascript\nconfig.set(\"editor\", null)\n```\n\nIf the `EDITOR` environment is configured, unset it as well. From `mongosh`, run:\n\n```javascript\nprocess.env.EDITOR = ''\n```\n\nIf you unset `EDITOR` using `process.env` the change will not persist after exiting `mongosh`. To make the change persistent, unset `EDITOR` from your shell.\n\n### Using the Built-In Editor\n\nStart the editor:\n\n```javascript\n.editor\n```\n\n`mongosh` enters editor mode. Enter your code:\n\n```javascript\n// Entering editor mode (^D to finish, ^C to cancel)\nvar albums =\n [\n { \"artist\": \"Beatles\", \"album\": \"Revolver\" },\n { \"artist\": \"The Monkees\", \"album\": \"Head\"}\n ]\n\ndb.music.insertMany( albums )\n```\n\nTo leave the editor,\n\n- Press ` + d` to exit and run your function\n\n- Press ` + c` to exit without running your function\n\nObjects which are declared using `.editor`, like `albums` in this example, are added to the global scope. They are available after `.editor` closes."} -{"chunk_id": "68a95c1b5e79d242619dd71e-0", "page_id": "68a95c1b5e79d242619dd71e", "source_name": "mongodb-shell", "product_name": "MongoDB Shell", "url": "https://mongodb.com/docs/mongodb-shell/reference/options", "title": "Options", "text": "# Options\n\nUse the following options to view and control various aspects of your MongoDB Shell.\n\n## General Options\n\n`mongosh`\n`--build-info`\nReturns a JSON-formatted document with information about your `mongosh` build and driver dependencies.\n\n**Example: View Build Information**\n\nYou can check the build information and driver dependencies of your `mongosh` binary by running the following command from your terminal:\n\n```sh\nmongosh --build-info\n```\n\nThis command returns the following JSON-formatted document:\n\n```javascript\n{\n version: '1.10.1',\n distributionKind: 'packaged',\n buildArch: 'x64',\n buildPlatform: 'linux',\n buildTarget: 'unknown',\n buildTime: '2023-06-21T09:49:37.225Z',\n gitVersion: '05ad91b4dd40382a13f27abe1ae8c3f9f52a38f7',\n nodeVersion: 'v16.20.1',\n opensslVersion: '3.1.1',\n sharedOpenssl: true,\n runtimeArch: 'x64',\n runtimePlatform: 'darwin',\n deps: {\n nodeDriverVersion: '5.6.0'\n }\n}\n```\n\n`--eval `\nEvaluates a JavaScript expression. You can use a single `--eval` argument or multiple `--eval` arguments together.\n\nAfter `mongosh` evaluates the `--eval` argument, it prints the results to your command line. If you use multiple `--eval` statements, `mongosh` only prints the results of the last `--eval`.\n\nYou can use the `--json` flag with `--eval` to return `mongosh` results in Extended JSON format. `mongosh` supports both `--json=canonical` and `--json=relaxed` modes. If you omit the mode, `mongosh` defaults to the `canonical` mode. The `--json` flag is mutually exclusive with `--shell`.\n\n**Example: Format Output**\n\nTo get output suitable for automated parsing, use `EJSON.stringify()`.\n\n```javascript\nmongosh --quiet --host rs0/centos1104 --port 27500 \\\n --eval \"EJSON.stringify(rs.status().members.map( \\\n m => ({'id':m._id, 'name':m.name, 'stateStr':m.stateStr})));\" \\\n| jq\n```\n\nAfter parsing with `jq`, the output resembles this:\n\n```javascript\n[\n {\n \"id\": 0,\n \"name\": \"centos1104:27500\",\n \"stateStr\": \"PRIMARY\"\n },\n {\n \"id\": 1,\n \"name\": \"centos1104:27502\",\n \"stateStr\": \"SECONDARY\"\n },\n {\n \"id\": 2,\n \"name\": \"centos1104:27503\",\n \"stateStr\": \"SECONDARY\"\n }\n]\n```\n\n`EJSON` has built in formatting options which may eliminate the need for a parser like `jq`. For example, the following code produces output that is formatted the same as above.\n\n```javascript\nmongosh --quiet --host rs0/centos1104 --port 27500 \\\n --eval \"EJSON.stringify( rs.status().members.map( \\\n ({ _id, name, stateStr }) => ({ _id, name, stateStr })), null, 2);\"\n```\n\n**Example: Multiple --eval Arguments**\n\nTo get a list of collections in the `moviesDatabase`, use multiple `--eval` statements:\n\n```javascript\nmongosh --quiet \\\n --eval 'use moviesDatabase' \\\n --eval 'show collections' \\\n mongodb://localhost/\n```\n\n**Example: --json Option**\n\nTo return statistics about a collection in Extended JSON format using multiple `--eval` statements:\n\n```sh\nmongosh --quiet --json=relaxed \\\n --eval 'use ' \\\n --eval 'db..stats()' \\\n mongodb://localhost/\n```\n\n`--file, -f `\n\nRuns a script from the command line without entering the MongoDB Shell console.\n\nFor additional details and an example, see Execute a Script From the Command Line.\n\n`--help, -h`\n\nReturns information on the options and use of the MongoDB Shell.\n\n`--nodb`\nPrevents the shell from connecting to any database instances.\n\n`--no-quiet`\nDisables the default `--quiet` option mode for non-interactive shell sessions. When specified, `mongosh` displays all messages during startup.\n\n`--norc`\nPrevents the shell from sourcing and evaluating `~/.mongoshrc.js` on startup.\n\n`--norc` also prevents the shell from loading any snippets you installed with the `snippet install` command. Instead, you can load snippets with the `snippet load-all` command. See Snippet Commands for more information.\n\n`--quiet`\nSkips all messages during startup (such as welcome messages and startup warnings) and goes directly to the prompt.\n\nFor non-interactive shell sessions, MongoDB enables `--quiet` by default. You can disable this behavior using `--no-quiet`.\n\n`--skipStartupWarnings`\nPrevents `mongosh` from displaying server startup warnings when creating a session. To suppress all startup messages, use the `--quiet` option.\n\n`--shell`\nEnables the shell interface. If you invoke the `mongosh` command and specify a JavaScript file as an argument, or use `--eval` to specify JavaScript on the command line, the `--shell` option provides the user with a shell prompt after the file finishes executing. The `--shell` flag is mutually exclusive with `--json`.\n\n`--verbose`\nIncreases the verbosity of the shell output during the connection process and when running commands.\n\n`--version`\nReturns the MongoDB Shell release number.\n\n## Stable API Options\n\n`--apiVersion `\nSpecifies the apiVersion. `\"1\"` is currently the only supported value.\n\n`--apiStrict`\nSpecifies that the server will respond with APIStrictError if your application uses a command or behavior outside of the Stable API.\n\nIf you specify `--apiStrict`, you must also specify `--apiVersion`.\n\n`--apiDeprecationErrors`\nSpecifies that the server will respond with APIDeprecationError if your application uses a command or behavior that is deprecated in the specified `apiVersion`.\n\nIf you specify `--apiDeprecationErrors`, you must also specify `--apiVersion`.\n\n## Connection Options\n\n`--host `\nSpecifies the name of the host machine where the `mongod` or `mongos` is running. If this is not specified, the MongoDB Shell attempts to connect to a MongoDB process running on the localhost.\n\nSpecify the `replica set name` and a seed list of set members. Use the following form:\n\n```none\n/<:port>,<:port>,<...>\n```\n\nThe MongoDB Shell verifies that the hostname (specified in the `--host` option or the connection string) matches the `SAN` (or, if `SAN` is not present, the `CN`) in the certificate presented by the `mongod` or `mongos`. If `SAN` is present, the MongoDB Shell does not match against the `CN`. If the hostname does not match the `SAN` (or `CN`), the MongoDB Shell shell fails to connect.\n\nSpecify the connection protocol as `mongodb+srv`, followed by the DNS SRV hostname record and any options. The `authSource` and `replicaSet` options, if included in the connection string, overrides any corresponding DNS-configured options set in the TXT record. Use of the `mongodb+srv:` connection string implicitly enables TLS (Transport Layer Security) / SSL (Secure Sockets Layer) (normally set with `tls=true`) for the client connection. The TLS (Transport Layer Security) option can be turned off by setting `tls=false` in the query string.\n\n```none\nmongodb+srv://server.example.com/?connectionTimeoutMS=3000\n```\n\n`--port `\nSpecifies the port where the `mongod` or `mongos` instance is listening. If `--port` is not specified, the MongoDB Shell attempts to connect to port `27017`."} -{"chunk_id": "68a95c1b5e79d242619dd71e-1", "page_id": "68a95c1b5e79d242619dd71e", "source_name": "mongodb-shell", "product_name": "MongoDB Shell", "url": "https://mongodb.com/docs/mongodb-shell/reference/options", "title": "Options", "text": "### TLS Options\n\n`--tls`\nEnables connection to a `mongod` or `mongos` that has TLS (Transport Layer Security) / SSL (Secure Sockets Layer) support enabled.\n\nTo learn more about TLS/SSL and MongoDB, see:\n\n- Configure mongod and mongos for TLS/SSL\n\n- TLS/SSL Configuration for Clients\n\n`--tlsCertificateKeyFile `\nSpecifies the .pem file that contains both the TLS (Transport Layer Security) / SSL (Secure Sockets Layer) certificate and key for `mongosh`. Specify the file name of the .pem file using relative or absolute paths.\n\nThis option is required when using the `--tls` option to connect to a `mongod` or `mongos` instance that requires client certificates. That is, the MongoDB Shell presents this certificate to the server.\n\nStarting in version 4.4, `mongod` / `mongos` logs a warning on connection if the presented X.509 certificate expires within `30` days of the `mongod/mongos` host system time.\n\nTo learn more about TLS/SSL and MongoDB, see:\n\n- Configure mongod and mongos for TLS/SSL\n\n- TLS/SSL Configuration for Clients\n\n`--tlsCertificateKeyFilePassword `\nSpecifies the password to de-crypt the certificate-key file (i.e. `--tlsCertificateKeyFile`).\n\nUse the `--tlsCertificateKeyFilePassword` option only if the certificate-key file is encrypted. In all cases, the MongoDB Shell redacts the password from all logging and reporting output.\n\nIf the private key in the PEM file is encrypted and you do not specify the `--tlsCertificateKeyFilePassword` option; the MongoDB Shell prompts for a passphrase.\n\nSee TLS/SSL Certificate Passphrase.\n\nTo learn more about TLS/SSL and MongoDB, see:\n\n- Configure mongod and mongos for TLS/SSL\n\n- TLS/SSL Configuration for Clients\n\n`--tlsCAFile `\nSpecifies the .pem file that contains the root certificate chain from the Certificate Authority. This file is used to validate the certificate presented by the `mongod` / `mongos` instance.\n\nSpecify the file name of the .pem file using relative or absolute paths.\n\nTo learn more about TLS/SSL and MongoDB, see:\n\n- Configure mongod and mongos for TLS/SSL\n\n- TLS/SSL Configuration for Clients\n\n`--tlsCRLFile `\nSpecifies the .pem file that contains the Certificate Revocation List. Specify the file name of the .pem file using relative or absolute paths.\n\nTo learn more about TLS/SSL and MongoDB, see:\n\n- Configure mongod and mongos for TLS/SSL\n\n- TLS/SSL Configuration for Clients\n\n`--tlsAllowInvalidHostnames`\nDisables the validation of the hostnames in the certificate presented by the `mongod` / `mongos` instance. Allows the MongoDB Shell to connect to MongoDB instances even if the hostname in the server certificates do not match the server's host.\n\nTo learn more about TLS/SSL and MongoDB, see:\n\n- Configure mongod and mongos for TLS/SSL\n\n- TLS/SSL Configuration for Clients\n\n`--tlsAllowInvalidCertificates`\nBypasses the validation checks for the certificates presented by the `mongod` / `mongos` instance and allows connections to servers that present invalid certificates.\n\nStarting in MongoDB 4.0, if you specify `--tlsAllowInvalidCertificates` when using x.509 authentication, an invalid certificate is only sufficient to establish a TLS (Transport Layer Security) / SSL (Secure Sockets Layer) connection but is *insufficient* for authentication.\n\nAlthough available, avoid using the `--tlsAllowInvalidCertificates` option if possible. If the use of `--tlsAllowInvalidCertificates` is necessary, only use the option on systems where intrusion is not possible.\n\nIf the MongoDB Shell shell (and other Connect to a TLS-Enabled Replica Set) runs with the `--tlsAllowInvalidCertificates` option, the shell (and other Connect to a TLS-Enabled Replica Set) do not attempt to validate the server certificates. This creates a vulnerability to expired `mongod` and `mongos` certificates as well as to foreign processes posing as valid `mongod` or `mongos` instances. If you only need to disable the validation of the hostname in the TLS (Transport Layer Security) / SSL (Secure Sockets Layer) certificates, see `--tlsAllowInvalidHostnames`.\n\nTo learn more about TLS/SSL and MongoDB, see:\n\n- Configure mongod and mongos for TLS/SSL\n\n- TLS/SSL Configuration for Clients\n\n`--tlsCertificateSelector =`\nAvailable on Windows and macOS as an alternative to `--tlsCertificateKeyFile`.\n\nWhen you import your private key, you must mark it as exportable. The Windows **Certificate Import Wizard** doesn't check this option by default.\n\nThe `--tlsCertificateKeyFile` and `--tlsCertificateSelector` options are mutually exclusive. You can only specify one.\n\nSpecifies a certificate property in order to select a matching certificate from the operating system's certificate store.\n\n`--tlsCertificateSelector` accepts an argument of the format `=` where the property can be one of the following:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nProperty\n\n\nValue type\n\n\nDescription\n\n
\n`subject`\n\n\nASCII string\n\n\nSubject name or common name on certificate\n\n
\n`thumbprint`\n\n\nhex string\n\n\nA sequence of bytes, expressed as hexadecimal, used to identify a public key by its SHA-1 digest.\n\nThe `thumbprint` is sometimes referred to as a `fingerprint`.\n\n
When using the system SSL certificate store, OCSP (Online Certificate Status Protocol) is used to validate the revocation status of certificates.\n\nStarting in version 4.4, `mongod` / `mongos` logs a warning on connection if the presented X.509 certificate expires within `30` days of the `mongod/mongos` host system time.\n\n`--tlsDisabledProtocols `\nDisables the specified TLS protocols. The option recognizes the following protocols:\n\n- `TLS1_0`\n\n- `TLS1_1`\n\n- `TLS1_2`\n\n- *(Starting in version 4.0.4, 3.6.9, 3.4.24)* `TLS1_3`\n\n- On macOS, you cannot disable `TLS1_1` and leave both `TLS1_0` and `TLS1_2` enabled. You must also disable at least one of the other two; for example, `TLS1_0,TLS1_1`.\n\n- To list multiple protocols, specify as a comma separated list of protocols. For example `TLS1_0,TLS1_1`.\n\n- The specified disabled protocols overrides any default disabled protocols.\n\nStarting in version 4.0, MongoDB disables the use of TLS 1.0 if TLS 1.1+ is available on the system. To enable the disabled TLS 1.0, specify `none` to `--tlsDisabledProtocols`.\n\n`--tlsUseSystemCA`\nAllows `mongosh` to load TLS certificates already available to the operating system's certificate authority without explicitly specifying the certificates to the shell. You cannot turn off this behavior. `--tlsUseSystemCA` can still be set for backward compatibility, but it has no effect.\n\nThis flag applies to both MongoDB connections and OIDC identity provider connections."} -{"chunk_id": "68a95c1b5e79d242619dd71e-2", "page_id": "68a95c1b5e79d242619dd71e", "source_name": "mongodb-shell", "product_name": "MongoDB Shell", "url": "https://mongodb.com/docs/mongodb-shell/reference/options", "title": "Options", "text": "## Authentication Options\n\n`--authenticationDatabase `\nSpecifies the authentication database where the specified `--username` has been created. See Authentication Database.\n\nIf you do not specify a value for `--authenticationDatabase`, the MongoDB Shell uses the database specified in the connection string.\n\n`--authenticationMechanism `\nSpecifies the authentication mechanism the MongoDB Shell uses to authenticate to the `mongod` or `mongos`. If you don't specify an `authenticationMechanism` but provide user credentials, the MongoDB Shell and drivers attempt to use SCRAM-SHA-256. If this fails, they fall back to SCRAM-SHA-1.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nValue\n\n\nDescription\n\n
\nSCRAM-SHA-1\n\n\nRFC 5802 standard Salted Challenge Response Authentication Mechanism using the SHA-1 hash function.\n\n
\nSCRAM-SHA-256\n\n\nRFC 7677 standard Salted Challenge Response Authentication Mechanism using the SHA-256 hash function.\n\nRequires featureCompatibilityVersion set to `4.0`.\n\n
\nMONGODB-X509\n\n\nMongoDB TLS (Transport Layer Security) / SSL (Secure Sockets Layer) certificate authentication.\n\n
\nGSSAPI (Kerberos)\n\n\nExternal authentication using Kerberos. This mechanism is available only in MongoDB Enterprise.\n\n
\nPLAIN (LDAP SASL)\n\n\nExternal authentication using LDAP. You can also use `PLAIN` for authenticating in-database users. `PLAIN` transmits passwords in plain text. This mechanism is available in MongoDB Enterprise and MongoDB Atlas.\n\n
\nMONGODB-OIDC (OpenID Connect)\n\n\nExternal authentication using OpenID Connect. This mechanism is available in MongoDB Enterprise and MongoDB Atlas.\n\n
\n`MONGODB-AWS` (AWS IAM)\n\n\nExternal authentication using Amazon Web Services Identity and Access Management (AWS IAM) credentials. This mechanism is available in MongoDB Enterprise and MongoDB Atlas.\n\n
`--gssapiServiceName`\nSpecify the name of the service using GSSAPI/Kerberos. Only required if the service does not use the default name of `mongodb`.\n\nThis option is available only in MongoDB Enterprise.\n\n`--sspiHostnameCanonicalization `\nSpecifies whether or not to use Hostname Canonicalization.\n\n`--sspiHostnameCanonicalization` has the same effect as setting the `CANONICALIZE_HOST_NAME:true|false` key-pair in the `authMechanismProperties` portion of the connection string.\n\nIf `--sspiHostnameCanonicalization` is set to:\n\n- `forwardAndReverse`, performs a forward DNS lookup and then a reverse lookup. New in `mongosh` 1.3.0.\n\n- `forward`, the effect is the same as setting `authMechanismProperties=CANONICALIZE_HOST_NAME:true`.\n\n- `none`, the effect is the same as setting `authMechanismProperties=CANONICALIZE_HOST_NAME:false`.\n\n`--oidcFlows`\nSpecifies OpenID Connect flows in a comma-separated list. The OpenID Connect flows specify how `mongosh` interacts with the identity provider for the authentication process. `mongosh` supports the following OpenID Connect flows:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nOpenID Connect Flow\n\n\nDescription\n\n
\n`auth-code`\n\n\nDefault. `mongosh` opens a browser and redirects you to the identity provider log-in screen.\n\n
\n`device-auth`\n\n\n`mongosh` provides you with a URL and code to finish authentication. This is considered a less secure OpenID Connect flow but can be used when `mongosh` is run in an environment in which it cannot open a browser.\n\n
To set `device-auth` as a fallback option to `auth-code`, see the following example:\n\n```bash\nmongosh 'mongodb://localhost/' --authenticationMechanism MONGODB-OIDC --oidcFlows=auth-code,device-auth\n```\n\n`--oidcDumpTokens`\nSpecifies whether `mongosh` prints tokens with extra debugging information. Use this option for debugging purposes only.\n\nThe `--oidcDumpTokens` option accepts the following values:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nValue\n\n\nDescription\n\n
\n`redacted`\n\n\nDefault when you only set `--oidcDumpTokens`. Prints token debugging information with sensitive data redacted.\n\n
\n`include-secrets`\n\n\nPrints token debugging information including credentials that can potentially authenticate to database servers.\n\n
The `include-secrets` value exposes credentials that attackers can use for authentication. Only use this option when unauthorized people cannot view the output of `mongosh` and the credentials are necessary for diagnostic purposes.\n\n`--oidcIdTokenAsAccessToken`\nSpecifies whether `mongosh` uses the ID token received from the identity provider instead of the access token. Use this option with identity providers that you can't configure to provide JWT (JSON Web Token) access tokens.\n\n`--oidcNoNonce`\nBy default, `mongosh` sends a nonce parameter during the OIDC (OpenID Connect) Authorization Code Flow.\n\nIf you set the `--oidcNoNonce` option, `mongosh` does not send a nonce parameter. Use this option if your identity provider does not support nonce values as part of authorization.\n\n`--oidcRedirectUri`\nSpecifies a URI where the identity provider redirects you after authentication. The URI must match the configuration of the identity provider. The default is `http://localhost:27097/redirect`.\n\n`--oidcTrustedEndpoint`\nIndicates that the current connection is to a trusted endpoint that is not Atlas or `localhost`. This ensures that access tokens are sent to the server. Only use this option when connecting to servers that you trust.\n\n`--browser`\nSpecifies the browser `mongosh` redirects you to when `MONGODB-OIDC` is enabled.\n\nThis option is run with the system shell.\n\nSet `--no-browser` to disable opening browsers entirely.\n\n`--password , -p `\n\nSpecifies a password with which to authenticate to a MongoDB database that uses authentication. Use in conjunction with the `--username` and `--authenticationDatabase` options.\n\nTo force the MongoDB Shell to prompt for a password, enter the `--password` option as the last option and leave out the argument.\n\n`--username , -u `\n\nSpecifies a username with which to authenticate to a MongoDB database that uses authentication. Use in conjunction with the `--password` and `--authenticationDatabase` options.\n\n## Session Options\n\n`--retryWrites`\nEnables Retryable Writes.\n\nBy default, retryable writes are:\n\n- enabled in `mongosh`\n\n- disabled in the legacy `mongo` shell\n\nTo disable retryable writes, use `--retryWrites=false`.\n\nFor more information on sessions, see Client Sessions and Causal Consistency Guarantees."} -{"chunk_id": "68a95c1b5e79d242619dd71e-3", "page_id": "68a95c1b5e79d242619dd71e", "source_name": "mongodb-shell", "product_name": "MongoDB Shell", "url": "https://mongodb.com/docs/mongodb-shell/reference/options", "title": "Options", "text": "## Field Level Encryption Options\n\n`--cryptSharedLibPath `\nThe path to the Automatic Encryption Shared Library. The library must be version 8.2.0 or higher. Required to use automatic encryption for the `mongosh` shell session.\n\n`--awsAccessKeyId `\nAn AWS Access Key associated with an IAM user who has `List` and `Read` permissions for the AWS Key Management Service (KMS). `mongosh` uses the specified `--awsAccessKeyId` to access the KMS.\n\n`--awsAccessKeyId` is required to enable Client-Side Field Level Encryption for the `mongosh` shell session. `--awsAccessKeyId` requires *both* of the following command line options:\n\n- `--awsSecretAccessKey`\n\n- `--keyVaultNamespace`\n\nIf `--awsAccessKeyId` is omitted, use the `Mongo()` constructor within the shell session to enable client-side field level encryption.\n\nTo mitigate the risk of leaking access keys into logs, consider specifying an environmental variable to `--awsAccessKeyId`.\n\n`--awsSecretAccessKey `\nAn AWS Secret Key associated to the specified `--awsAccessKeyId`.\n\n`--awsSecretAccessKey` is required to enable Client-Side Field Level Encryption for the `mongosh` session. `--awsSecretAccessKey` requires *both* of the following command line options:\n\n- `--awsAccessKeyId`\n\n- `--keyVaultNamespace`\n\nIf `--awsSecretAccessKey` and its supporting options are omitted, use `Mongo()` within the shell session to enable client-side field level encryption.\n\nTo mitigate the risk of leaking access keys into logs, consider specifying an environmental variable to `--awsSecretAccessKey`.\n\n`--awsSessionToken `\nAn AWS Session Token associated to the specified `--awsAccessKeyId`.\n\n`--awsSessionToken` is required to enable Client-Side Field Level Encryption for the `mongosh` shell session. `--awsSessionToken` requires *all* of the following command line options:\n\n- `--awsAccessKeyId`\n\n- `--awsSecretAccessKey`\n\n- `--keyVaultNamespace`\n\nIf `--awsSessionToken` and its supporting options are omitted, use `Mongo()` within the shell session to enable client-side field level encryption.\n\nTo mitigate the risk of leaking access keys into logs, consider specifying an environmental variable to `--awsSessionToken`.\n\n`--keyVaultNamespace `\nThe full namespace (`.`) of the collection used as a key vault for Client-Side Field Level Encryption. `--keyVaultNamespace` is required for enabling client-side field level encryption for the `mongosh` shell session. `mongosh` creates the specified namespace if it does not exist.\n\n`--keyVaultNamespace` requires *both* of the following command line options:\n\n- `--awsAccessKeyId`\n\n- `--awsSecretAccessKey`\n\nIf `--keyVaultNamespace` and its supporting options are omitted, use the `Mongo()` constructor within the shell session to enable client-side field level encryption."} -{"chunk_id": "68a95c1b5e79d242619dd71c-0", "page_id": "68a95c1b5e79d242619dd71c", "source_name": "mongodb-shell", "product_name": "MongoDB Shell", "url": "https://mongodb.com/docs/mongodb-shell/snippets", "title": "Snippets", "text": "# Snippets\n\nThis feature is experimental. MongoDB does not provide support for Snippets. This feature may be changed or removed at any time without prior notice.\n\nBugs are not expected, however should you encounter one, please open an issue in the GitHub repository for this project.\n\n## Introduction\n\nA `snippet` is a script that is packaged and stored in a registry to facilitate sharing and reuse.\n\nYou can write your own scripts in `mongosh` to manipulate data or to perform administrative tasks. Snippets are an improvement on locally stored scripts because they can be easily shared and maintained.\n\nThis page provides a high level introduction to working with snippets. The links in each section go deeper into writing, managing, and working with snippets.\n\n## Components\n\nThe Snippets feature has three main components:\n\n- **Scripts** are code that can be used with `mongosh`.\n\n- **Packages** are scripts that are bundled with metadata so they can be managed more easily.\n\n- **Registries** are collections of packages that can be shared.\n\nThere are also built in commands to help you work with snippets and utility scripts to help with packaging tasks.\n\n## Get Started\n\nThe fastest way to get started with snippets is to try one of the snippets in the community registry maintained by MongoDB.\n\nYou can also create your own snippets, package them for easier management, and configure a registry to share them.\n\n- **Try an Existing Snippet**.\n\n Install and run a snippet package from the community registry\n\n- **Create Your Own Snippet Package**.\n\n Write the snippet code and supporting files. Then, publish the snippet package.\n\n- **Configure Snippet Registries**.\n\n Use the community registry or configure a private registry."} -{"chunk_id": "68a95c1b5e79d242619dd6d8-0", "page_id": "68a95c1b5e79d242619dd6d8", "source_name": "mongodb-shell", "product_name": "MongoDB Shell", "url": "https://mongodb.com/docs/mongodb-shell/reference/configure-shell-settings-api", "title": "Configure Settings Using the API", "text": "# Configure Settings Using the API\n\nThe `config` API provides methods to examine and update the `mongosh` configuration. Updates made using the `config` API persist between sessions.\n\nThe `config` API can be used within the `mongosh` command line interface. It has no effect in the embedded Compass shell.\n\n## Syntax\n\nPrint the current `mongosh` configuration:\n\n```javascript\nconfig\n```\n\nReturn the current value for ``:\n\n```javascript\nconfig.get( \"\" )\n```\n\nChange the current setting of `` to ``:\n\n```javascript\nconfig.set( \"\", )\n```\n\nReset a `` to the default value:\n\n```javascript\nconfig.reset( \"\" )\n```"} -{"chunk_id": "68a95c1b5e79d242619dd6d8-1", "page_id": "68a95c1b5e79d242619dd6d8", "source_name": "mongodb-shell", "product_name": "MongoDB Shell", "url": "https://mongodb.com/docs/mongodb-shell/reference/configure-shell-settings-api", "title": "Configure Settings Using the API", "text": "### Supported property parameters\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nKey\n\n\nType\n\n\nDefault\n\n\nDescription\n\n
\n`browser`\n\n\nstring or boolean\n\n\nSystem default browser\n\n\nSpecifies the browser `mongosh` redirects you to when `MONGODB-OIDC` is enabled.\n\nThis option is run with the system shell.\n\nSet `browser` to `false` to disable opening browsers entirely.\n\n
\n`disableLogging`\n\n\nboolean\n\n\n`false`\n\n\nSpecifies whether MongoDB Shell writes log entries.\n\n
\n`disableSchemaSampling`\n\n\nboolean\n\n\n`false`\n\n\nBy default, MongoDB Shell samples your database schema to enable autocomplete suggestions.\n\nIf you set this setting to `true`, MongoDB Shell does not sample your database schema and autocomplete behaves as if the collection is empty.\n\n
\n`displayBatchSize`\n\n\ninteger\n\n\n20\n\n\nThe number of items displayed per cursor iteration\n\n
\n`enableTelemetry`\n\n\nboolean\n\n\n`true`\n\n\nEnables sending pseudo-anonymous tracking and diagnostic data to MongoDB during interactive and agentic sessions only.\n\n
\n`editor`\n\n\nstring\n\n\n`null`\n\n\nDesignates an editor to use within the `mongosh` console. Overrides the `EDITOR` environment variable if set.\n\n
\n`forceDisableTelemetry`\n\n\nboolean\n\n\n`false`\n\n\nOnly available in the global configuration file. When true, users cannot enable telemetry manually.\n\n
\n`historyLength`\n\n\ninteger\n\n\n1000\n\n\nThe number of items to store in `mongosh` REPL's history file.\n\n
\n`inspectCompact`\n\n\ninteger or boolean\n\n\n3\n\n\nThe level of inner elements that `mongosh` outputs on a single line. Short array elements are also grouped together on a single line.\n\nIf set to `false`, `mongosh` outputs each field on its own line.\n\n
\n`inspectDepth`\n\n\ninteger or Infinity\n\n\n6\n\n\nThe depth to which objects are printed. Setting `inspectDepth` to `Infinity` (the javascript object) prints all nested objects to their full depth.\n\n
\n`logCompressionEnabled`\n\n\nboolean\n\n\nfalse\n\n\nSpecifies whether MongoDB Shell compresses log files. When this value is `true`, MongoDB Shell uses gzip to compress logs. See Enable Log Compression.\n\n
\n`logLocation`\n\n\nstring\n\n\nDepends on your operating system. See View Shell Logs.\n\n\nDirectory where MongoDB Shell writes log files. Specify an absolute filepath. See Specify Log File Location.\n\n
\n`logMaxFileCount`\n\n\ninteger or Infinity\n\n\n100\n\n\nMaximum number of log files that the MongoDB Shell retains. After the MongoDB Shell reaches the maximum log file count, it starts deleting the oldest log files until the count is below the threshold. See Modify Maximum Log File Count.\n\n
\n`logRetentionDays`\n\n\ninteger or Infinity\n\n\n30\n\n\nNumber of days that MongoDB Shell log files are retained. If this value is set to `Infinity`, log files are not deleted based on age. To prevent log storage from growing too large, always specify at least one log retention criterion. See Log Retention.\n\n
\n`logRetentionGB`\n\n\nfloat or Infinity\n\n\nUnset\n\n\nMaximum amount of space in gigabytes used for MongoDB Shell logs. If the combined size of MongoDB Shell logs exceeds this value, log files are deleted starting with the oldest logs.\n\nIf this value is set to `Infinity`, log files are not deleted based on storage size. To prevent log storage from growing too large, always specify at least one log retention criterion. See Log Retention.\n\n
\n`oidcRedirectUri`\n\n\nstring\n\n\n`http://localhost:27097/redirect`\n\n\nSpecifies a URI where the identity provider redirects you after authentication. The URI must match the configuration of the identity provider. The default is `http://localhost:27097/redirect`.\n\n
\n`oidcTrustedEndpoints`\n\n\narray of strings\n\n\n`[]` (empty array)\n\n\nSpecifies an array of trusted endpoint hostnames, including possible wildcards, that are not Atlas or `localhost`. Access tokens are sent to these endpoints. Only configure endpoints that you trust.\n\n
\n`redactHistory`\n\n\nstring\n\n\n`remove`\n\n\nControls what information is recorded in the `mongosh` command history. You can access the `mongosh` command history via the up and down keys or Ctrl+R while inside the shell.\n\nMust be one of the following values:\n\n- `keep`: Retain all history.\n\n- `remove`: Remove lines that contain sensitive commands from the history. For example, `remove` removes calls to db.auth() or connect().\n\n- `remove-redact`: Remove lines that contain sensitive commands and redact specific strings in other history lines, such as file paths, email addresses, and URLs.\n\n
\n`showStackTraces`\n\n\nboolean\n\n\n`false`\n\n\nControls display of a stack trace along with error messages.\n\n
\n`snippetAutoload`\n\n\nboolean\n\n\n`true`\n\n\nIf `true`, automatically load installed snippets at startup.\n\n
\n`snippetIndexSourceURLs`\n\n\nstring\n\n\nMongoDB Repository\n\n\nA semicolon-separated list of URLs that link to a snippet registry.\n\n
\n`snippetRegistryURL`\n\n\nstring\n\n\nnpm Registry\n\n\nThe npm registry used by the `mongosh` npm client that installs snippet.\n\n
\n`updateURL`\n\n\nstring\n\n\n`https://downloads.mongodb.com/compass/mongosh.json`\n\n\nThe URL that MongoDB Shell checks for available updates at startup.\n\nTo disable update notifications and the associated outbound network request, set `updateURL` to an empty string.\n\n
\n\n## Behavior"} -{"chunk_id": "68a95c1b5e79d242619dd6d8-2", "page_id": "68a95c1b5e79d242619dd6d8", "source_name": "mongodb-shell", "product_name": "MongoDB Shell", "url": "https://mongodb.com/docs/mongodb-shell/reference/configure-shell-settings-api", "title": "Configure Settings Using the API", "text": "### Remove or Redact Sensitive Information From History\n\n`mongosh` makes \"best-effort\" attempts to match patterns that normally correspond to certain kinds of sensitive information.\n\nThere are patterns that match:\n\n- Certificates and keys\n\n- Email addresses\n\n- Generic user directories\n\n- HTTP(s) URLs\n\n- IP addresses\n\n- MongoDB connection strings\n\nCertain operations, such as `connect()`, are considered inherently sensitive. If `redactHistory` is set to `remove` or `remove-redact`, lines with these operations will be removed from the command line history.\n\nOther operations, like `find()`, sometimes have sensitive information like email addresses. The shell history will retain these lines as entered unless `redactHistory` is set to `remove-redact`.\n\n### Behavior with Configuration File\n\nSettings specified with the `config` API:\n\n- Override settings specified in the configuration file.\n\n- Persist across restarts.\n\nConsider the following configuration file that sets the `inspectDepth` setting to `20`:\n\n```yaml\nmongosh:\n inspectDepth: 20\n```\n\nDuring your `mongosh` session you run the following command to set `inspectDepth` to `10`:\n\n```javascript\nconfig.set( \"inspectDepth\", 10 )\n```\n\nThe value of `inspectDepth` becomes `10`, and will remain `10` even when `mongosh` is restarted.\n\n## Examples\n\n### Update Number of Items Returned by a Cursor\n\nConsider viewing a collection with a number of large documents. You can update the `batchSize` to limit the number of items returned by a cursor.\n\n```javascript\nconfig.set(\"displayBatchSize\", 3)\n```\n\nFuture `db.collection.find()` operations will only return 3 documents per cursor iteration.\n\n### Turn On Stack Traces\n\nEnable stack traces to see more detailed error reporting.\n\n```javascript\nconfig.set(\"showStackTraces\", true)\n```\n\nThe output differs like this:\n\n```javascript\n// showStackTraces set to 'false'\nEnterprise> db.orders.find( {}, { $thisWontWork: 1 } )\nMongoError: FieldPath field names may not start with '$'.\n\n// showStackTraces set to 'true'\nEnterprise> db.orders.find( {}, { $thisWontWork: 1 } )\nUncaught:\nMongoError: FieldPath field names may not start with '$'.\n at MessageStream.messageHandler (/usr/bin/mongosh:58878:20)\n at MessageStream.emit (events.js:315:20)\n at MessageStream.EventEmitter.emit (domain.js:548:15)\n at processIncomingData (/usr/bin/mongosh:57954:12)\n at MessageStream._write (/usr/bin/mongosh:57850:5)\n at writeOrBuffer (_stream_writable.js:352:12)\n at MessageStream.Writable.write (_stream_writable.js:303:10)\n at Socket.ondata (_stream_readable.js:719:22)\n at Socket.emit (events.js:315:20)\n at Socket.EventEmitter.emit (domain.js:548:15)\n```\n\n### Call config API from outside mongosh\n\nYou can call the `config` API from the command line using `--eval` with `mongosh`. In this case the `--nodb` option means `mongosh` will update without connecting to a MongoDB database.\n\nYou must use different quotation marks for the `--eval` expression and the `config` property. That is, single quotes for one and double quotes for the other.\n\n```\nmongosh --nodb --eval 'config.set(\"enableTelemetry\", true)'\n```\n\n`mongosh` returns additional information along with the result of the API call.\n\n```\nCurrent Mongosh Log ID: 609583b730e14918fa0d363f\nUsing MongoDB: undefined\nUsing Mongosh Beta: 0.12.1\n\nFor mongosh info see: https://www.mongodb.com/docs/mongodb-shell/\n\nSetting \"enableTelemetry\" has been changed\n```\n\n### Redact Sensitive Information\n\nCompare the recalled history when `redactHistory` is set to `remove-redact` or `remove`.\n\nSet `redactHistory` to `remove-redact` mode and enter a query containing an email address.\n\n```javascript\nconfig.set( \"redactHistory\", \"remove-redact\" )\ndb.contacts.find( {\"email\": \"customer@clients.com\" } )\n```\n\nWhen you press the `up arrow` to replay the last command the email address is redacted.\n\n```javascript\ndb.contacts.find( {\"email\": \"\" } ) // Redacted\n```\n\nSet `redactHistory` to `remove` mode and enter a query containing an email address.\n\n```javascript\nconfig.set( \"redactHistory\", \"remove\" )\ndb.contacts.find( {\"email\": \"customer@clients.com\" } )\n```\n\nWhen you press the `up arrow` to replay the last command the email address is present.\n\n```javascript\ndb.contacts.find( {\"email\": \"customer@clients.com\" } )\n```\n\nThe shell history reflects the changes. (Note that this stores the most recent input first.)\n\n```javascript\ndb.contacts.find( {\"email\": \"customer@clients.com\" } )\nconfig.set( \"redactHistory\", \"remove\" )\ndb.contacts.find( {\"email\": \"\" } )\nconfig.set( \"redactHistory\", \"remove-redact\" )\n```\n\n### Reset a Configuration Setting to the Default Value\n\nIf you modified a configuration setting and want to reset it to the default value, use `config.reset( \"\" )`.\n\n1. Change the value of the `historyLength` setting to `2000`:\n\n ```javascript\n config.set(\"historyLength\", 2000)\n ```\n\n2. Verify the updated value for `historyLength`:\n\n ```javascript\n config.get(\"historyLength\")\n ```\n\n3. Reset the `historyLength` setting to the default value of `1000`:\n\n ```javascript\n config.reset(\"historyLength\")\n ```\n\n4. Verify the updated value for `historyLength`:\n\n ```javascript\n config.get(\"historyLength\")\n ```"} -{"chunk_id": "68a95c1b5e79d242619dd6d5-0", "page_id": "68a95c1b5e79d242619dd6d5", "source_name": "mongodb-shell", "product_name": "MongoDB Shell", "url": "https://mongodb.com/docs/mongodb-shell/install", "title": "Install mongosh", "text": "# Install mongosh\n\nThis section describes how to install `mongosh` on Windows through the MSI installer.\n\nIf you already have `mongosh` installed and want to upgrade to the latest version, see Upgrade mongosh.\n\n## Prerequisites\n\nTo use the MongoDB Shell, you must have a MongoDB deployment to connect to.\n\n- For a free cloud-hosted deployment, you can use MongoDB Atlas.\n\n- To learn how to run a local MongoDB deployment, see Install MongoDB.\n\n### Supported MongoDB Versions\n\nYou can use the MongoDB Shell to connect to MongoDB version 7.0 or greater.\n\n## Supported Operating Systems\n\nYou can install MongoDB Shell on these Windows operating systems:\n\n- Microsoft Windows Server 2016+\n\n- Microsoft Windows 10+\n\n## Procedure\n\nOn Windows, `mongosh` preferences and configuration options are stored in the `%APPDATA%/mongodb/mongosh` directory.\n\n### Open the MongoDB Shell download page.\n\nOpen the MongoDB Download Center.\n\n### In the Platform dropdown, select Windows 64-bit (10+) (MSI)\n\n### Click Download.\n\n### Double-click the installer file.\n\n### Follow the prompts to install mongosh.\n\n### Confirm that mongosh installed successfully.\n\nTo confirm that `mongosh` installed successfully, open a command prompt and run the following command:\n\n```sh\nmongosh --version\n```\n\nThe command returns the version of `mongosh` you installed.\n\nThis section describes how to install `mongosh` on Windows through the .zip archive.\n\nIf you already have `mongosh` installed and want to upgrade to the latest version, see Upgrade mongosh.\n\n## Prerequisites\n\nTo use the MongoDB Shell, you must have a MongoDB deployment to connect to.\n\n- For a free cloud-hosted deployment, you can use MongoDB Atlas.\n\n- To learn how to run a local MongoDB deployment, see Install MongoDB.\n\n### Supported MongoDB Versions\n\nYou can use the MongoDB Shell to connect to MongoDB version 7.0 or greater.\n\n## Supported Operating Systems\n\nYou can install MongoDB Shell on these Windows operating systems:\n\n- Microsoft Windows Server 2016+\n\n- Microsoft Windows 10+\n\n## Procedure\n\nOn Windows, `mongosh` preferences and configuration options are stored in the `%APPDATA%/mongodb/mongosh` directory.\n\n### Open the MongoDB Shell download page.\n\nOpen the MongoDB Download Center.\n\n### Download the mongosh installation archive for your operating system.\n\nDownload `mongosh` from the MongoDB Download Center.\n\n### Extract the files from the downloaded archive.\n\nOpen a `cmd` terminal and run the following command from the directory that has the `mongosh` `.zip` archive:\n\n```sh\ntar -xf mongosh-2.13.0-win32-x64.zip\n```\n\nThe extracted archive has a `bin` folder that contains two files, `mongosh.exe` and `mongosh_crypt_v1.dll`.\n\n### Add the mongosh binary to your PATH environment variable.\n\nEnsure that the extracted MongoDB Shell binary is in the desired location in your filesystem, then add that location to your `PATH` environment variable.\n\nTo add the MongoDB Shell binary's location to your `PATH` environment variable:\n\n- Open the Control Panel.\n\n- In the System and Security category, click System.\n\n- Click Advanced system settings. The **System Properties** modal displays.\n\n- Click Environment Variables.\n\n- In the *System variables* section, select `Path` and click Edit. The **Edit environment variable** modal displays.\n\n- Click New and add the filepath to your `mongosh` binary.\n\n- Click OK to confirm your changes. On each other modal, click OK to confirm your changes.\n\nTo confirm that your `PATH` environment variable is correctly configured to find `mongosh`, open a command prompt and enter the `mongosh --help` command. If your `PATH` is configured correctly, a list of valid commands displays.\n\n### Confirm that mongosh installed successfully.\n\nTo confirm that `mongosh` installed successfully, open a command prompt and run the following command:\n\n```sh\nmongosh --version\n```\n\nThe command returns the version of `mongosh` you installed.\n\nThis section describes how to install `mongosh` on macOS through the Homebrew package manager. To learn how to manually install `mongosh` from an archive instead, select .zip file from the Installation Method menu at the top of this page.\n\nIn versions of `mongosh` older than 2.5.8, if you're using `Node.js` versions ^20.19.5, ^22.18.0, or ^24.3.0, the tab autocomplete may execute code up to and including potentially destructive operations. For example, `db.collection.deleteMany({}).`.\n\nIf you already have `mongosh` installed, to check your `mongosh` and Node.js versions, run:\n\n```sh\n --build-info\n```\n\n```javascript\n{\n \"version\": \"2.5.8\",\n \"distributionKind\": \"packaged\",\n \"buildArch\": \"x64\",\n \"buildPlatform\": \"linux\",\n \"buildTarget\": \"unknown\",\n \"buildTime\": \"2025-09-09T10:18:30.614Z\",\n \"gitVersion\": \"7b6bd25a97ce617f8d5bfa26c36db6d99dc92419\",\n \"nodeVersion\": \"v24.9.0\",\n \"opensslVersion\": \"3.6.0\",\n \"sharedOpenssl\": true,\n \"runtimeArch\": \"x64\",\n \"runtimePlatform\": \"darwin\",\n \"runtimeGlibcVersion\": \"N/A\",\n \"deps\": {\n \"nodeDriverVersion\": \"6.19.0\",\n \"kerberosVersion\": \"2.2.2\"\n }\n}\n```\n\nTo upgrade to the latest `mongosh` and Node.js versions, see Upgrade mongosh.\n\n`mongosh` installed with Homebrew does not provide the same stability and feature completeness guarantees as the official builds. For example, Homebrew `mongosh` installations don't support automatic client-side field level encryption.\n\n## Prerequisites\n\nTo use the MongoDB Shell, you must have a MongoDB deployment to connect to.\n\n- For a free cloud-hosted deployment, you can use MongoDB Atlas.\n\n- To learn how to run a local MongoDB deployment, see Install MongoDB.\n\n### Supported MongoDB Versions\n\nYou can use the MongoDB Shell to connect to MongoDB version 7.0 or greater.\n\n### Homebrew Requirements\n\nTo view the complete list of system requirements for Homebrew, see the Homebrew Website.\n\n## Supported Operating Systems\n\nYou can install MongoDB Shell on macOS 11 or greater (x64 or ARM64).\n\n## Procedure\n\nTo install `mongosh` with Homebrew:\n\n### Install Homebrew.\n\nRefer to the Homebrew website for the steps to install Homebrew on macOS.\n\n### Install the mongosh package.\n\nIssue the following command from the terminal to install the `mongosh` package:\n\n```sh\nbrew install mongosh\n```\n\n### Confirm that mongosh installed successfully.\n\nTo confirm that `mongosh` installed successfully, run the following command:\n\n```sh\nmongosh --version\n```\n\nThe command returns the version of `mongosh` you installed.\n\nThis section describes how to install `mongosh` on macOS using a downloaded `.zip` file.\n\nIf you already have `mongosh` installed and want to upgrade to the latest version, see Upgrade mongosh.\n\n## Supported Operating Systems\n\nYou can install MongoDB Shell on macOS 11 or greater (x64 or ARM64).\n\n## Procedure\n\nTo manually install `mongosh` using a downloaded `.zip` file:\n\n### Open the MongoDB Shell download page.\n\nOpen the MongoDB Download Center.\n\n### Download the mongosh installation archive for your operating system.\n\nDownload the appropriate version of `mongosh` for your operating system. MongoDB provides versions of `mongosh` for Intel and ARM architectures.\n\n### Extract the files from the downloaded archive.\n\nGo to the directory that contains the `mongosh` `.zip` archive, then unpack the `.zip` file.\n\nIf your computer is Intel based, run:\n\n```sh\nunzip mongosh-2.13.0-darwin-x64.zip\n```\n\nIf your computer is ARM based (M1 or M2), run:\n\n```sh\nunzip mongosh-2.13.0-darwin-arm64.zip\n```\n\nThe extracted archive has a `bin` folder that contains two files, `mongosh` and `mongosh_crypt_v1.dylib`.\n\nIf your web browser automatically extracts the archive as part of the download, or if you extract the archive without using the `unzip` command, you may need to make the binary executable.\n\nTo make the binary executable, run the following command in the directory where you extracted the archive:\n\n```sh\nchmod +x bin/mongosh\n```"} -{"chunk_id": "68a95c1b5e79d242619dd6d5-1", "page_id": "68a95c1b5e79d242619dd6d5", "source_name": "mongodb-shell", "product_name": "MongoDB Shell", "url": "https://mongodb.com/docs/mongodb-shell/install", "title": "Install mongosh", "text": "### Add the downloaded binaries to your PATH environment variable.\n\nYou can either:\n\n- Copy the `mongosh` binary into a directory listed in your `PATH` variable, such as `/usr/local/bin`. Run the following commands from the directory where you extracted the download file:\n\n ```sh\n sudo mkdir -p /usr/local/bin/\n sudo mkdir -p /usr/local/lib\n sudo cp mongosh /usr/local/bin/\n sudo cp mongosh_crypt_v1.dylib /usr/local/lib/\n ```\n\n- Create symbolic links to the `MongoDB Shell`. Switch to the directory where you extracted the files from the `.tgz` archive. Run the following command to create links to a directory already in your `PATH` such as `/usr/local/bin`.\n\n ```sh\n sudo ln -s $(pwd)/bin/* /usr/local/bin/\n ```\n\n### Allow macOS to run mongosh.\n\nmacOS may prevent `mongosh` from running after installation. If you receive a security error when starting `mongosh` indicating that the developer could not be identified or verified, perform the following actions:\n\n- Open *System Preferences*.\n\n- Select the *Security and Privacy* pane.\n\n- Under the *General* tab, click the button to the right of the message about `mongosh`, labelled either Open Anyway or Allow Anyway depending on your version of macOS.\n\n### Confirm that mongosh installed successfully.\n\nTo confirm that `mongosh` installed successfully, run the following command:\n\n```sh\nmongosh --version\n```\n\nThe command returns the version of `mongosh` you installed.\n\nThis section describes how to install `mongosh` on Ubuntu 24.04 (Noble).\n\nIf you already have `mongosh` installed and want to upgrade to the latest version, see Upgrade mongosh.\n\n## Supported Operating Systems\n\nMongoDB Shell is available as a PPA (Personal Package Archive) for these Ubuntu versions:\n\n- Ubuntu 24.04 (Noble)\n\n- Ubuntu 22.04 (Jammy)\n\n- Ubuntu 20.04 (Focal)\n\n- Ubuntu 18.04 (Bionic) (*Deprecated support*)\n\nIf you are running an older or unsupported Linux distribution, such as Red Hat Enterprise Linux (RHEL) 7, and do not see a matching package in the standard install flow, you can try searching for an archived `mongosh` release from the mongosh releases page on GitHub. However, MongoDB doesn't officially support or test these archived releases.\n\nWhen you choose an archived asset, select one that matches your:\n\n- Package format (`.rpm`, `.deb`, or archive)\n\n- CPU architecture (for example, `x86_64`/`amd64` or `arm64`)\n\n- Library or runtime requirements shown in the filename (for example, an OpenSSL version)\n\n## Procedure\n\n### Import the public key used by the package management system\n\nFrom a terminal, run the following command to import the MongoDB public GPG key from https://www.mongodb.org/static/pgp/server-8.0.asc:\n\n```sh\nwget -qO- https://www.mongodb.org/static/pgp/server-8.0.asc | sudo tee /etc/apt/trusted.gpg.d/server-8.0.asc\n```\n\nThe previous command writes the GPG key to your system's `/etc/apt/trusted.gpg.d` folder and displays the key in your terminal. You do not need to copy or save the key.\n\nIf you receive an error indicating that `gnupg` is not installed, perform the following steps:\n\n1. Install `gnupg` and its required libraries using the following command:\n\n ```sh\n sudo apt-get install gnupg\n ```\n\n2. Retry importing the key:\n\n ```sh\n wget -qO- https://www.mongodb.org/static/pgp/server-8.0.asc | sudo tee /etc/apt/trusted.gpg.d/server-8.0.asc\n ```\n\n### Create a list file for MongoDB\n\nCreate the list file `/etc/apt/sources.list.d/mongodb-org-8.3.list` for your version of Ubuntu:\n\n```sh\necho \"deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu noble/mongodb-org/8.3 multiverse\" | sudo tee /etc/apt/sources.list.d/mongodb-org-8.3.list\n```\n\n### Reload the local package database\n\n```sh\nsudo apt-get update\n```\n\n### Install the mongosh package\n\n`mongosh` supports OpenSSL. You can also configure `mongosh` to use your system's OpenSSL installation.\n\nTo install the latest stable version of `mongosh` with the included OpenSSL libraries:\n\n```sh\nsudo apt-get install -y mongodb-mongosh\n```\n\nTo install `mongosh` with your OpenSSL 1.1 libraries:\n\n```sh\nsudo apt-get install -y mongodb-mongosh-shared-openssl11\n```\n\nTo install `mongosh` with your OpenSSL 3.0 libraries:\n\n```sh\nsudo apt-get install -y mongodb-mongosh-shared-openssl3\n```\n\n### Confirm that mongosh installed successfully\n\nTo confirm that `mongosh` installed successfully, run the following command:\n\n```sh\nmongosh --version\n```\n\nThe command returns the version of `mongosh` you installed.\n\nThis section describes how to install `mongosh` on Ubuntu 22.04 (Jammy).\n\nIf you already have `mongosh` installed and want to upgrade to the latest version, see Upgrade mongosh.\n\n## Supported Operating Systems\n\nMongoDB Shell is available as a PPA (Personal Package Archive) for these Ubuntu versions:\n\n- Ubuntu 24.04 (Noble)\n\n- Ubuntu 22.04 (Jammy)\n\n- Ubuntu 20.04 (Focal)\n\n- Ubuntu 18.04 (Bionic) (*Deprecated support*)\n\nIf you are running an older or unsupported Linux distribution, such as Red Hat Enterprise Linux (RHEL) 7, and do not see a matching package in the standard install flow, you can try searching for an archived `mongosh` release from the mongosh releases page on GitHub. However, MongoDB doesn't officially support or test these archived releases.\n\nWhen you choose an archived asset, select one that matches your:\n\n- Package format (`.rpm`, `.deb`, or archive)\n\n- CPU architecture (for example, `x86_64`/`amd64` or `arm64`)\n\n- Library or runtime requirements shown in the filename (for example, an OpenSSL version)\n\n## Procedure\n\n### Import the public key used by the package management system\n\nFrom a terminal, run the following command to import the MongoDB public GPG key from https://www.mongodb.org/static/pgp/server-8.0.asc:\n\n```sh\nwget -qO- https://www.mongodb.org/static/pgp/server-8.0.asc | sudo tee /etc/apt/trusted.gpg.d/server-8.0.asc\n```\n\nThe previous command writes the GPG key to your system's `/etc/apt/trusted.gpg.d` folder and displays the key in your terminal. You do not need to copy or save the key.\n\nIf you receive an error indicating that `gnupg` is not installed, perform the following steps:\n\n1. Install `gnupg` and its required libraries using the following command:\n\n ```sh\n sudo apt-get install gnupg\n ```\n\n2. Retry importing the key:\n\n ```sh\n wget -qO- https://www.mongodb.org/static/pgp/server-8.0.asc | sudo tee /etc/apt/trusted.gpg.d/server-8.0.asc\n ```\n\n### Create a list file for MongoDB\n\nCreate the list file `/etc/apt/sources.list.d/mongodb-org-8.3.list` for your version of Ubuntu:\n\n```sh\necho \"deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/8.3 multiverse\" | sudo tee /etc/apt/sources.list.d/mongodb-org-8.3.list\n```\n\n### Reload the local package database\n\n```sh\nsudo apt-get update\n```\n\n### Install the mongosh package\n\n`mongosh` supports OpenSSL. You can also configure `mongosh` to use your system's OpenSSL installation.\n\nTo install the latest stable version of `mongosh` with the included OpenSSL libraries:\n\n```sh\nsudo apt-get install -y mongodb-mongosh\n```\n\nTo install `mongosh` with your OpenSSL 1.1 libraries:\n\n```sh\nsudo apt-get install -y mongodb-mongosh-shared-openssl11\n```\n\nTo install `mongosh` with your OpenSSL 3.0 libraries:\n\n```sh\nsudo apt-get install -y mongodb-mongosh-shared-openssl3\n```\n\n### Confirm that mongosh installed successfully\n\nTo confirm that `mongosh` installed successfully, run the following command:\n\n```sh\nmongosh --version\n```\n\nThe command returns the version of `mongosh` you installed.\n\nThis section describes how to install `mongosh` on Ubuntu 20.04 (Focal).\n\nIf you already have `mongosh` installed and want to upgrade to the latest version, see Upgrade mongosh."} -{"chunk_id": "68a95c1b5e79d242619dd6d5-2", "page_id": "68a95c1b5e79d242619dd6d5", "source_name": "mongodb-shell", "product_name": "MongoDB Shell", "url": "https://mongodb.com/docs/mongodb-shell/install", "title": "Install mongosh", "text": "## Supported Operating Systems\n\nMongoDB Shell is available as a PPA (Personal Package Archive) for these Ubuntu versions:\n\n- Ubuntu 24.04 (Noble)\n\n- Ubuntu 22.04 (Jammy)\n\n- Ubuntu 20.04 (Focal)\n\n- Ubuntu 18.04 (Bionic) (*Deprecated support*)\n\nIf you are running an older or unsupported Linux distribution, such as Red Hat Enterprise Linux (RHEL) 7, and do not see a matching package in the standard install flow, you can try searching for an archived `mongosh` release from the mongosh releases page on GitHub. However, MongoDB doesn't officially support or test these archived releases.\n\nWhen you choose an archived asset, select one that matches your:\n\n- Package format (`.rpm`, `.deb`, or archive)\n\n- CPU architecture (for example, `x86_64`/`amd64` or `arm64`)\n\n- Library or runtime requirements shown in the filename (for example, an OpenSSL version)\n\n## Procedure\n\n### Import the public key used by the package management system\n\nFrom a terminal, run the following command to import the MongoDB public GPG key from https://www.mongodb.org/static/pgp/server-8.0.asc:\n\n```sh\nwget -qO- https://www.mongodb.org/static/pgp/server-8.0.asc | sudo tee /etc/apt/trusted.gpg.d/server-8.0.asc\n```\n\nThe previous command writes the GPG key to your system's `/etc/apt/trusted.gpg.d` folder and displays the key in your terminal. You do not need to copy or save the key.\n\nIf you receive an error indicating that `gnupg` is not installed, perform the following steps:\n\n1. Install `gnupg` and its required libraries using the following command:\n\n ```sh\n sudo apt-get install gnupg\n ```\n\n2. Retry importing the key:\n\n ```sh\n wget -qO- https://www.mongodb.org/static/pgp/server-8.0.asc | sudo tee /etc/apt/trusted.gpg.d/server-8.0.asc\n ```\n\n### Create a list file for MongoDB\n\nCreate the list file `/etc/apt/sources.list.d/mongodb-org-8.3.list` for your version of Ubuntu:\n\n```sh\necho \"deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/8.3 multiverse\" | sudo tee /etc/apt/sources.list.d/mongodb-org-8.3.list\n```\n\n### Reload the local package database\n\n```sh\nsudo apt-get update\n```\n\n### Install the mongosh package\n\n`mongosh` supports OpenSSL. You can also configure `mongosh` to use your system's OpenSSL installation.\n\nTo install the latest stable version of `mongosh` with the included OpenSSL libraries:\n\n```sh\nsudo apt-get install -y mongodb-mongosh\n```\n\nTo install `mongosh` with your OpenSSL 1.1 libraries:\n\n```sh\nsudo apt-get install -y mongodb-mongosh-shared-openssl11\n```\n\nTo install `mongosh` with your OpenSSL 3.0 libraries:\n\n```sh\nsudo apt-get install -y mongodb-mongosh-shared-openssl3\n```\n\n### Confirm that mongosh installed successfully\n\nTo confirm that `mongosh` installed successfully, run the following command:\n\n```sh\nmongosh --version\n```\n\nThe command returns the version of `mongosh` you installed.\n\nThis section describes how to install `mongosh` on Ubuntu 18.04 (Bionic).\n\nIf you already have `mongosh` installed and want to upgrade to the latest version, see Upgrade mongosh.\n\nSupport for Ubuntu 18.04 (Bionic) is deprecated.\n\n## Supported Operating Systems\n\nMongoDB Shell is available as a PPA (Personal Package Archive) for these Ubuntu versions:\n\n- Ubuntu 24.04 (Noble)\n\n- Ubuntu 22.04 (Jammy)\n\n- Ubuntu 20.04 (Focal)\n\n- Ubuntu 18.04 (Bionic) (*Deprecated support*)\n\nIf you are running an older or unsupported Linux distribution, such as Red Hat Enterprise Linux (RHEL) 7, and do not see a matching package in the standard install flow, you can try searching for an archived `mongosh` release from the mongosh releases page on GitHub. However, MongoDB doesn't officially support or test these archived releases.\n\nWhen you choose an archived asset, select one that matches your:\n\n- Package format (`.rpm`, `.deb`, or archive)\n\n- CPU architecture (for example, `x86_64`/`amd64` or `arm64`)\n\n- Library or runtime requirements shown in the filename (for example, an OpenSSL version)\n\n## Procedure\n\n### Import the public key used by the package management system\n\nFrom a terminal, run the following command to import the MongoDB public GPG key from https://www.mongodb.org/static/pgp/server-7.0.asc:\n\n```sh\nwget -qO- https://www.mongodb.org/static/pgp/server-7.0.asc | sudo tee /etc/apt/trusted.gpg.d/server-7.0.asc\n```\n\nThe previous command writes the GPG key to your system's `/etc/apt/trusted.gpg.d` folder and displays the key in your terminal. You do not need to copy or save the key.\n\nIf you receive an error indicating that `gnupg` is not installed, perform the following steps:\n\n1. Install `gnupg` and its required libraries using the following command:\n\n ```sh\n sudo apt-get install gnupg\n ```\n\n2. Retry importing the key:\n\n ```sh\n wget -qO- https://www.mongodb.org/static/pgp/server-7.0.asc | sudo tee /etc/apt/trusted.gpg.d/server-7.0.asc\n ```\n\n### Create a list file for MongoDB\n\nCreate the list file `/etc/apt/sources.list.d/mongodb-org-7.0.list` for your version of Ubuntu:\n\n```sh\necho \"deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/7.0 multiverse\" | sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list\n```\n\n### Reload the local package database\n\n```sh\nsudo apt-get update\n```\n\n### Install the mongosh package\n\n`mongosh` supports OpenSSL. You can also configure `mongosh` to use your system's OpenSSL installation.\n\nTo install the latest stable version of `mongosh` with the included OpenSSL libraries:\n\n```sh\nsudo apt-get install -y mongodb-mongosh\n```\n\nTo install `mongosh` with your OpenSSL 1.1 libraries:\n\n```sh\nsudo apt-get install -y mongodb-mongosh-shared-openssl11\n```\n\nTo install `mongosh` with your OpenSSL 3.0 libraries:\n\n```sh\nsudo apt-get install -y mongodb-mongosh-shared-openssl3\n```\n\n### Confirm that mongosh installed successfully\n\nTo confirm that `mongosh` installed successfully, run the following command:\n\n```sh\nmongosh --version\n```\n\nThe command returns the version of `mongosh` you installed.\n\nThis section describes how to install `mongosh` on Debian 13 (Trixie).\n\nIf you already have `mongosh` installed and want to upgrade to the latest version, see Upgrade mongosh.\n\n## Supported Operating Systems\n\nMongoDB Shell is supported on Debian versions 11 and greater.\n\n## Procedure\n\n### Import the public key used by the package management system\n\nFrom a terminal, run the following command to import the MongoDB public GPG key from https://www.mongodb.org/static/pgp/server-8.0.asc:\n\n```sh\nwget -qO- https://www.mongodb.org/static/pgp/server-8.0.asc | sudo tee /etc/apt/trusted.gpg.d/server-8.0.asc\n```\n\nThe previous command writes the GPG key to your system's `/etc/apt/trusted.gpg.d` folder and displays the key in your terminal. You do not need to copy or save the key.\n\nIf you receive an error indicating that `gnupg` is not installed, perform the following steps:\n\n1. Install `gnupg` and its required libraries using the following command:\n\n ```sh\n sudo apt-get install gnupg\n ```\n\n2. Retry importing the key:\n\n ```sh\n wget -qO- https://www.mongodb.org/static/pgp/server-8.0.asc | sudo tee /etc/apt/trusted.gpg.d/server-8.0.asc\n ```\n\n### Create a list file for MongoDB\n\nCreate the list file `/etc/apt/sources.list.d/mongodb-org-8.3.list` for your version of Debian:\n\n```sh\necho \"deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/debian trixie/mongodb-org/8.3 main\" | sudo tee /etc/apt/sources.list.d/mongodb-org-8.3.list\n```\n\n### Reload the local package database\n\n```sh\nsudo apt-get update\n```"} -{"chunk_id": "68a95c1b5e79d242619dd6d5-3", "page_id": "68a95c1b5e79d242619dd6d5", "source_name": "mongodb-shell", "product_name": "MongoDB Shell", "url": "https://mongodb.com/docs/mongodb-shell/install", "title": "Install mongosh", "text": "### Install the mongosh package\n\n`mongosh` supports OpenSSL. You can also configure `mongosh` to use your system's OpenSSL installation.\n\nTo install the latest stable version of `mongosh` with its bundled OpenSSL libraries, run the following command. This build is self-contained and does not depend on the OpenSSL version installed on your system:\n\n```sh\nsudo apt-get install -y mongodb-mongosh\n```\n\nAlternatively, you can install a build of `mongosh` that uses your system's OpenSSL libraries. Choose the package that matches your system's OpenSSL version. In Debian 13 (Trixie), the default OpenSSL version is 3.0.\n\nTo use your system's OpenSSL 3.0 libraries:\n\n```sh\nsudo apt-get install -y mongodb-mongosh-shared-openssl3\n```\n\nTo use your system's OpenSSL 1.1 libraries:\n\n```sh\nsudo apt-get install -y mongodb-mongosh-shared-openssl11\n```\n\n### Confirm that mongosh installed successfully\n\nTo confirm that `mongosh` installed successfully, run the following command:\n\n```sh\nmongosh --version\n```\n\nThe command returns the version of `mongosh` you installed.\n\nThis section describes how to install `mongosh` on Debian 12 (Bookworm).\n\nIf you already have `mongosh` installed and want to upgrade to the latest version, see Upgrade mongosh.\n\n## Supported Operating Systems\n\nMongoDB Shell is supported on Debian versions 11 and greater.\n\nIf you are running an older or unsupported Linux distribution, such as Red Hat Enterprise Linux (RHEL) 7, and do not see a matching package in the standard install flow, you can try searching for an archived `mongosh` release from the mongosh releases page on GitHub. However, MongoDB doesn't officially support or test these archived releases.\n\nWhen you choose an archived asset, select one that matches your:\n\n- Package format (`.rpm`, `.deb`, or archive)\n\n- CPU architecture (for example, `x86_64`/`amd64` or `arm64`)\n\n- Library or runtime requirements shown in the filename (for example, an OpenSSL version)\n\n## Procedure\n\n### Import the public key used by the package management system\n\nFrom a terminal, run the following command to import the MongoDB public GPG key from https://www.mongodb.org/static/pgp/server-8.0.asc:\n\n```sh\nwget -qO- https://www.mongodb.org/static/pgp/server-8.0.asc | sudo tee /etc/apt/trusted.gpg.d/server-8.0.asc\n```\n\nThe previous command writes the GPG key to your system's `/etc/apt/trusted.gpg.d` folder and displays the key in your terminal. You do not need to copy or save the key.\n\nIf you receive an error indicating that `gnupg` is not installed, perform the following steps:\n\n1. Install `gnupg` and its required libraries using the following command:\n\n ```sh\n sudo apt-get install gnupg\n ```\n\n2. Retry importing the key:\n\n ```sh\n wget -qO- https://www.mongodb.org/static/pgp/server-8.0.asc | sudo tee /etc/apt/trusted.gpg.d/server-8.0.asc\n ```\n\n### Create a list file for MongoDB\n\nCreate the list file `/etc/apt/sources.list.d/mongodb-org-8.3.list` for your version of Debian:\n\n```sh\necho \"deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/debian bookworm/mongodb-org/8.3 main\" | sudo tee /etc/apt/sources.list.d/mongodb-org-8.3.list\n```\n\n### Reload the local package database\n\n```sh\nsudo apt-get update\n```\n\n### Install the mongosh package\n\n`mongosh` supports OpenSSL. You can also configure `mongosh` to use your system's OpenSSL installation.\n\nTo install the latest stable version of `mongosh` with its bundled OpenSSL libraries, run the following command. This build is self-contained and does not depend on the OpenSSL version installed on your system:\n\n```sh\nsudo apt-get install -y mongodb-mongosh\n```\n\nAlternatively, you can install a build of `mongosh` that uses your system's OpenSSL libraries. Choose the package that matches your system's OpenSSL version. In Debian 12 (Bookworm), the default OpenSSL version is 3.0.\n\nTo use your system's OpenSSL 3.0 libraries:\n\n```sh\nsudo apt-get install -y mongodb-mongosh-shared-openssl3\n```\n\nTo use your system's OpenSSL 1.1 libraries:\n\n```sh\nsudo apt-get install -y mongodb-mongosh-shared-openssl11\n```\n\n### Confirm that mongosh installed successfully\n\nTo confirm that `mongosh` installed successfully, run the following command:\n\n```sh\nmongosh --version\n```\n\nThe command returns the version of `mongosh` you installed.\n\nThis section describes how to install `mongosh` on Debian 11 (Bullseye).\n\nIf you already have `mongosh` installed and want to upgrade to the latest version, see Upgrade mongosh.\n\n## Supported Operating Systems\n\nMongoDB Shell is supported on Debian versions 11 and greater.\n\nIf you are running an older or unsupported Linux distribution, such as Red Hat Enterprise Linux (RHEL) 7, and do not see a matching package in the standard install flow, you can try searching for an archived `mongosh` release from the mongosh releases page on GitHub. However, MongoDB doesn't officially support or test these archived releases.\n\nWhen you choose an archived asset, select one that matches your:\n\n- Package format (`.rpm`, `.deb`, or archive)\n\n- CPU architecture (for example, `x86_64`/`amd64` or `arm64`)\n\n- Library or runtime requirements shown in the filename (for example, an OpenSSL version)\n\n## Procedure\n\n### Import the public key used by the package management system\n\nFrom a terminal, run the following command to import the MongoDB public GPG key from https://www.mongodb.org/static/pgp/server-8.0.asc:\n\n```sh\nwget -qO- https://www.mongodb.org/static/pgp/server-8.0.asc | sudo tee /etc/apt/trusted.gpg.d/server-8.0.asc\n```\n\nThe previous command writes the GPG key to your system's `/etc/apt/trusted.gpg.d` folder and displays the key in your terminal. You do not need to copy or save the key.\n\nIf you receive an error indicating that `gnupg` is not installed, perform the following steps:\n\n1. Install `gnupg` and its required libraries using the following command:\n\n ```sh\n sudo apt-get install gnupg\n ```\n\n2. Retry importing the key:\n\n ```sh\n wget -qO- https://www.mongodb.org/static/pgp/server-8.0.asc | sudo tee /etc/apt/trusted.gpg.d/server-8.0.asc\n ```\n\n### Create a list file for MongoDB\n\nCreate the list file `/etc/apt/sources.list.d/mongodb-org-8.3.list` for your version of Debian:\n\n```sh\necho \"deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/debian bullseye/mongodb-org/8.3 main\" | sudo tee /etc/apt/sources.list.d/mongodb-org-8.3.list\n```\n\n### Reload the local package database\n\n```sh\nsudo apt-get update\n```\n\n### Install the mongosh package\n\n`mongosh` supports OpenSSL. You can also configure `mongosh` to use your system's OpenSSL installation.\n\nTo install the latest stable version of `mongosh` with its bundled OpenSSL libraries, run the following command. This build is self-contained and does not depend on the OpenSSL version installed on your system:\n\n```sh\nsudo apt-get install -y mongodb-mongosh\n```\n\nAlternatively, you can install a build of `mongosh` that uses your system's OpenSSL libraries. Choose the package that matches your system's OpenSSL version. In Debian 11 (Bullseye), the default OpenSSL version is 1.1.\n\nTo use your system's OpenSSL 3.0 libraries:\n\n```sh\nsudo apt-get install -y mongodb-mongosh-shared-openssl3\n```\n\nTo use your system's OpenSSL 1.1 libraries:\n\n```sh\nsudo apt-get install -y mongodb-mongosh-shared-openssl11\n```\n\n### Confirm that mongosh installed successfully\n\nTo confirm that `mongosh` installed successfully, run the following command:\n\n```sh\nmongosh --version\n```\n\nThe command returns the version of `mongosh` you installed.\n\nThis section describes how to install `mongosh` on Red Hat Enterprise Linux 10 or Oracle Linux 10 using the `yum` package manager.\n\nIf you already have `mongosh` installed and want to upgrade to the latest version, see Upgrade mongosh."} -{"chunk_id": "68a95c1b5e79d242619dd6d5-4", "page_id": "68a95c1b5e79d242619dd6d5", "source_name": "mongodb-shell", "product_name": "MongoDB Shell", "url": "https://mongodb.com/docs/mongodb-shell/install", "title": "Install mongosh", "text": "## Supported Operating Systems\n\n`mongosh` is available as `yum` package for the following RHEL (Red Hat Enterprise Linux) platforms:\n\n- RHEL (Red Hat Enterprise Linux) 8+ (x64, ARM64, ppc64le, and s390x)\n\n- Oracle Linux 8+ running the Red Hat Compatible Kernel (RHCK).\n\n MongoDB Shell does not support the Unbreakable Enterprise Kernel (UEK).\n\n## Procedure\n\n### Configure the package management system (yum)\n\nCreate a `/etc/yum.repos.d/mongodb-org-8.3.repo` file with the following contents:\n\n```none\n[mongodb-org-8.3]\nname=MongoDB Repository\nbaseurl=https://repo.mongodb.org/yum/redhat/10/mongodb-org/8.3/$basearch/\ngpgcheck=1\nenabled=1\ngpgkey=https://www.mongodb.org/static/pgp/server-8.0.asc\n```\n\nYou can also download the `.rpm` files directly from the MongoDB repository. Downloads are organized in the following order:\n\n1. Red Hat or CentOS version (for example, `10`)\n\n2. MongoDB edition (for example, `mongodb-enterprise`)\n\n3. MongoDB release version (for example, `8.3`)\n\n4. Architecture (for example, `x86_64`)\n\n### Install mongosh\n\n`mongosh` supports OpenSSL. You can also configure `mongosh` to use your system's OpenSSL installation.\n\nIf the MongoDB Shell fails to start with the following error on RHEL 9+ and derivatives such as Amazon Linux 2023, install the `mongodb-mongosh-shared-openssl3` package:\n\n```none\nmongosh: OpenSSL configuration error: ...:error:030000A9:digital\nenvelope routines:alg_module_init:unknown\noption:../deps/openssl/openssl/crypto/evp/evp_cnf.c:61:name=rh-allow-sha1-signatures,\nvalue=yes\n```\n\nTo install the latest stable version of `mongosh` with the included OpenSSL libraries:\n\n```sh\nsudo yum install -y mongodb-mongosh\n```\n\nTo install `mongosh` with your OpenSSL 1.1 libraries:\n\n```sh\nsudo yum install -y mongodb-mongosh-shared-openssl11\n```\n\nTo install `mongosh` with your OpenSSL 3.0 libraries:\n\n```sh\nsudo yum install -y mongodb-mongosh-shared-openssl3\n```\n\nThis section describes how to install `mongosh` on Red Hat Enterprise Linux 9 or Oracle Linux 9 using the `yum` package manager.\n\nIf you already have `mongosh` installed and want to upgrade to the latest version, see Upgrade mongosh.\n\n## Supported Operating Systems\n\n`mongosh` is available as `yum` package for the following RHEL (Red Hat Enterprise Linux) platforms:\n\n- RHEL (Red Hat Enterprise Linux) 8+ (x64, ARM64, ppc64le, and s390x)\n\n- Oracle Linux 8+ running the Red Hat Compatible Kernel (RHCK).\n\n MongoDB Shell does not support the Unbreakable Enterprise Kernel (UEK).\n\nIf you are running an older or unsupported Linux distribution, such as Red Hat Enterprise Linux (RHEL) 7, and do not see a matching package in the standard install flow, you can try searching for an archived `mongosh` release from the mongosh releases page on GitHub. However, MongoDB doesn't officially support or test these archived releases.\n\nWhen you choose an archived asset, select one that matches your:\n\n- Package format (`.rpm`, `.deb`, or archive)\n\n- CPU architecture (for example, `x86_64`/`amd64` or `arm64`)\n\n- Library or runtime requirements shown in the filename (for example, an OpenSSL version)\n\n## Procedure\n\n### Configure the package management system (yum)\n\nCreate a `/etc/yum.repos.d/mongodb-org-8.3.repo` file with the following contents:\n\n```none\n[mongodb-org-8.3]\nname=MongoDB Repository\nbaseurl=https://repo.mongodb.org/yum/redhat/9/mongodb-org/8.3/$basearch/\ngpgcheck=1\nenabled=1\ngpgkey=https://www.mongodb.org/static/pgp/server-8.0.asc\n```\n\nYou can also download the `.rpm` files directly from the MongoDB repository. Downloads are organized in the following order:\n\n1. Red Hat or CentOS version (for example, `9`)\n\n2. MongoDB edition (for example, `mongodb-enterprise`)\n\n3. MongoDB release version (for example, `8.3`)\n\n4. Architecture (for example, `x86_64`)\n\n### Install mongosh\n\n`mongosh` supports OpenSSL. You can also configure `mongosh` to use your system's OpenSSL installation.\n\nIf the MongoDB Shell fails to start with the following error on RHEL 9+ and derivatives such as Amazon Linux 2023, install the `mongodb-mongosh-shared-openssl3` package:\n\n```none\nmongosh: OpenSSL configuration error: ...:error:030000A9:digital\nenvelope routines:alg_module_init:unknown\noption:../deps/openssl/openssl/crypto/evp/evp_cnf.c:61:name=rh-allow-sha1-signatures,\nvalue=yes\n```\n\nTo install the latest stable version of `mongosh` with the included OpenSSL libraries:\n\n```sh\nsudo yum install -y mongodb-mongosh\n```\n\nTo install `mongosh` with your OpenSSL 1.1 libraries:\n\n```sh\nsudo yum install -y mongodb-mongosh-shared-openssl11\n```\n\nTo install `mongosh` with your OpenSSL 3.0 libraries:\n\n```sh\nsudo yum install -y mongodb-mongosh-shared-openssl3\n```\n\n### Confirm that mongosh installed successfully\n\nTo confirm that `mongosh` installed successfully, run the following command:\n\n```sh\nmongosh --version\n```\n\nThe command returns the version of `mongosh` you installed.\n\nThis section describes how to install `mongosh` on Red Hat Enterprise Linux 8 or Oracle Linux 8 using the `yum` package manager.\n\nIf you already have `mongosh` installed and want to upgrade to the latest version, see Upgrade mongosh.\n\n## Supported Operating Systems\n\n`mongosh` is available as `yum` package for the following RHEL (Red Hat Enterprise Linux) platforms:\n\n- RHEL (Red Hat Enterprise Linux) 8+ (x64, ARM64, ppc64le, and s390x)\n\n- Oracle Linux 8+ running the Red Hat Compatible Kernel (RHCK).\n\n MongoDB Shell does not support the Unbreakable Enterprise Kernel (UEK).\n\nIf you are running an older or unsupported Linux distribution, such as Red Hat Enterprise Linux (RHEL) 7, and do not see a matching package in the standard install flow, you can try searching for an archived `mongosh` release from the mongosh releases page on GitHub. However, MongoDB doesn't officially support or test these archived releases.\n\nWhen you choose an archived asset, select one that matches your:\n\n- Package format (`.rpm`, `.deb`, or archive)\n\n- CPU architecture (for example, `x86_64`/`amd64` or `arm64`)\n\n- Library or runtime requirements shown in the filename (for example, an OpenSSL version)\n\n## Procedure\n\n### Configure the package management system (yum)\n\nCreate a `/etc/yum.repos.d/mongodb-org-8.3.repo` file with the following contents:\n\n```none\n[mongodb-org-8.3]\nname=MongoDB Repository\nbaseurl=https://repo.mongodb.org/yum/redhat/8/mongodb-org/8.3/$basearch/\ngpgcheck=1\nenabled=1\ngpgkey=https://www.mongodb.org/static/pgp/server-8.0.asc\n```\n\nYou can also download the `.rpm` files directly from the MongoDB repository. Downloads are organized in the following order:\n\n1. Red Hat or CentOS version (for example, `8`)\n\n2. MongoDB edition (for example, `mongodb-enterprise`)\n\n3. MongoDB release version (for example, `8.3`)\n\n4. Architecture (for example, `x86_64`)\n\n### Install mongosh\n\n`mongosh` supports OpenSSL. You can also configure `mongosh` to use your system's OpenSSL installation.\n\nTo install the latest stable version of `mongosh` with the included OpenSSL libraries:\n\n```sh\nsudo yum install -y mongodb-mongosh\n```\n\nTo install `mongosh` with your OpenSSL 1.1 libraries:\n\n```sh\nsudo yum install -y mongodb-mongosh-shared-openssl11\n```\n\nTo install `mongosh` with your OpenSSL 3.0 libraries:\n\n```sh\nsudo yum install -y mongodb-mongosh-shared-openssl3\n```\n\n### Confirm that mongosh installed successfully\n\nTo confirm that `mongosh` installed successfully, run the following command:\n\n```sh\nmongosh --version\n```\n\nThe command returns the version of `mongosh` you installed.\n\nThis section describes how to install `mongosh` on Amazon Linux 2023 using the `yum` package manager.\n\nIf you already have `mongosh` installed and want to upgrade to the latest version, see Upgrade mongosh."} -{"chunk_id": "68a95c1b5e79d242619dd6d5-5", "page_id": "68a95c1b5e79d242619dd6d5", "source_name": "mongodb-shell", "product_name": "MongoDB Shell", "url": "https://mongodb.com/docs/mongodb-shell/install", "title": "Install mongosh", "text": "## Supported Operating Systems\n\n`mongosh` is available as `yum` package for the following Amazon Linux platforms:\n\n- Amazon Linux 2023 (x64 and ARM64)\n\n- Amazon Linux 2 (x64 and ARM64)\n\nIf you are running an older or unsupported Linux distribution, such as Red Hat Enterprise Linux (RHEL) 7, and do not see a matching package in the standard install flow, you can try searching for an archived `mongosh` release from the mongosh releases page on GitHub. However, MongoDB doesn't officially support or test these archived releases.\n\nWhen you choose an archived asset, select one that matches your:\n\n- Package format (`.rpm`, `.deb`, or archive)\n\n- CPU architecture (for example, `x86_64`/`amd64` or `arm64`)\n\n- Library or runtime requirements shown in the filename (for example, an OpenSSL version)\n\n## Procedure\n\n### Configure the package management system (yum)\n\nCreate a `/etc/yum.repos.d/mongodb-org-8.3.repo` file with the following contents:\n\n```none\n[mongodb-org-8.3]\nname=MongoDB Repository\nbaseurl=https://repo.mongodb.org/yum/amazon/2023/mongodb-org/8.3/$basearch/\ngpgcheck=1\nenabled=1\ngpgkey=https://www.mongodb.org/static/pgp/server-8.0.asc\n```\n\nYou can also download the `.rpm` files directly from the MongoDB repository. Downloads are organized in the following order:\n\n1. Amazon Linux version (for example, `2023`)\n\n2. MongoDB release version (for example, `8.3`)\n\n3. Architecture (for example, `x86_64`)\n\n### Install mongosh\n\n`mongosh` supports OpenSSL. You can also configure `mongosh` to use your system's OpenSSL installation.\n\nIf the MongoDB Shell fails to start with the following error on RHEL 9+ and derivatives such as Amazon Linux 2023, install the `mongodb-mongosh-shared-openssl3` package:\n\n```none\nmongosh: OpenSSL configuration error: ...:error:030000A9:digital\nenvelope routines:alg_module_init:unknown\noption:../deps/openssl/openssl/crypto/evp/evp_cnf.c:61:name=rh-allow-sha1-signatures,\nvalue=yes\n```\n\nTo install the latest stable version of `mongosh` with the included OpenSSL libraries:\n\n```sh\nsudo yum install -y mongodb-mongosh\n```\n\nTo install `mongosh` with your OpenSSL 1.1 libraries:\n\n```sh\nsudo yum install -y mongodb-mongosh-shared-openssl11\n```\n\nTo install `mongosh` with your OpenSSL 3.0 libraries:\n\n```sh\nsudo yum install -y mongodb-mongosh-shared-openssl3\n```\n\n### Confirm that mongosh installed successfully\n\nTo confirm that `mongosh` installed successfully, run the following command:\n\n```sh\nmongosh --version\n```\n\nThe command returns the version of `mongosh` you installed.\n\nThis section describes how to install `mongosh` on Amazon Linux 2 using the `yum` package manager.\n\nIf you already have `mongosh` installed and want to upgrade to the latest version, see Upgrade mongosh.\n\n## Supported Operating Systems\n\n`mongosh` is available as `yum` package for the following Amazon Linux platforms:\n\n- Amazon Linux 2023 (x64 and ARM64)\n\n- Amazon Linux 2 (x64 and ARM64)\n\nIf you are running an older or unsupported Linux distribution, such as Red Hat Enterprise Linux (RHEL) 7, and do not see a matching package in the standard install flow, you can try searching for an archived `mongosh` release from the mongosh releases page on GitHub. However, MongoDB doesn't officially support or test these archived releases.\n\nWhen you choose an archived asset, select one that matches your:\n\n- Package format (`.rpm`, `.deb`, or archive)\n\n- CPU architecture (for example, `x86_64`/`amd64` or `arm64`)\n\n- Library or runtime requirements shown in the filename (for example, an OpenSSL version)\n\n## Procedure\n\n### Configure the package management system (yum)\n\nCreate a `/etc/yum.repos.d/mongodb-org-8.3.repo` file with the following contents:\n\n```none\n[mongodb-org-8.3]\nname=MongoDB Repository\nbaseurl=https://repo.mongodb.org/yum/amazon/2/mongodb-org/8.3/$basearch/\ngpgcheck=1\nenabled=1\ngpgkey=https://www.mongodb.org/static/pgp/server-8.0.asc\n```\n\nYou can also download the `.rpm` files directly from the MongoDB repository. Downloads are organized in the following order:\n\n1. Amazon Linux version (for example, `2023`)\n\n2. MongoDB release version (for example, `8.3`)\n\n3. Architecture (for example, `x86_64`)\n\n### Install mongosh\n\n`mongosh` supports OpenSSL. You can also configure `mongosh` to use your system's OpenSSL installation.\n\nTo install the latest stable version of `mongosh` with the included OpenSSL libraries:\n\n```sh\nsudo yum install -y mongodb-mongosh\n```\n\nTo install `mongosh` with your OpenSSL 1.1 libraries:\n\n```sh\nsudo yum install -y mongodb-mongosh-shared-openssl11\n```\n\nTo install `mongosh` with your OpenSSL 3.0 libraries:\n\n```sh\nsudo yum install -y mongodb-mongosh-shared-openssl3\n```\n\n### Confirm that mongosh installed successfully\n\nTo confirm that `mongosh` installed successfully, run the following command:\n\n```sh\nmongosh --version\n```\n\nThe command returns the version of `mongosh` you installed.\n\nThis section describes how to install `mongosh` on Linux distributions using a `.tgz` archive.\n\nIf you already have `mongosh` installed and want to upgrade to the latest version, see Upgrade mongosh.\n\n## Supported Operating Systems\n\nMongoDB Shell is supported on the following Linux versions:\n\n- Amazon Linux 2023 (x64 and ARM64)\n\n- Amazon Linux 2 (x64 and ARM64)\n\n- Debian 11+\n\n- Oracle Linux 8+ running the Red Hat Compatible Kernel (RHCK). MongoDB Shell does not support the Unbreakable Enterprise Kernel (UEK).\n\n- Red Hat Enterprise Linux (RHEL) 8+ (x64, ARM64, ppc64le, and s390x)\n\n- SLES 15\n\n- Ubuntu 20.04+ (x64 and ARM64)\n\nIf you are running an older or unsupported Linux distribution, such as Red Hat Enterprise Linux (RHEL) 7, and do not see a matching package in the standard install flow, you can try searching for an archived `mongosh` release from the mongosh releases page on GitHub. However, MongoDB doesn't officially support or test these archived releases.\n\nWhen you choose an archived asset, select one that matches your:\n\n- Package format (`.rpm`, `.deb`, or archive)\n\n- CPU architecture (for example, `x86_64`/`amd64` or `arm64`)\n\n- Library or runtime requirements shown in the filename (for example, an OpenSSL version)\n\n## Procedure\n\n### Open the MongoDB Shell download page.\n\nOpen the MongoDB Download Center.\n\n### Download the Linux 64-bit .tgz package.\n\nDownload the appropriate version of `mongosh` for your operating system. MongoDB also provides versions of `mongosh` that use your system's OpenSSL installation.\n\nSee the MongoDB Download Center.\n\n### Extract the files from the downloaded archive.\n\nGo to the directory that contains the `.tgz` archive, then unpack the archive.\n\nThe name of the `.tgz` package varies depending on the version you downloaded. Replace the `.tgz` package name in the following command with the name of the package you downloaded and run the command.\n\n```sh\ntar -zxvf mongosh-2.13.0-linux-x64.tgz\n```\n\nThe extracted archive has a `bin` folder that contains two files, `mongosh` and `mongosh_crypt_v1.so`.\n\nIf your web browser automatically extracts the archive as part of the download, or if you extract the archive without using the `tar` command, you may need to make the binary executable.\n\nTo make the binary executable, run the following command in the directory where you extracted the archive:\n\n```sh\nchmod +x bin/mongosh\n```\n\n### Add the downloaded binaries to your PATH environment variable.\n\nYou can either:\n\n- Copy the `mongosh` binary into a directory listed in your `PATH` variable, such as `/usr/local/bin`. Run the following commands from the directory where you extracted the download file:\n\n ```sh\n sudo mkdir -p /usr/local/bin/\n sudo mkdir -p /usr/local/lib\n sudo cp mongosh /usr/local/bin/\n sudo cp mongosh_crypt_v1.dylib /usr/local/lib/\n ```\n\n- Create symbolic links to the `MongoDB Shell`. Switch to the directory where you extracted the files from the `.tgz` archive. Run the following command to create links to a directory already in your `PATH` such as `/usr/local/bin`.\n\n ```sh\n sudo ln -s $(pwd)/bin/* /usr/local/bin/\n ```"} -{"chunk_id": "68a95c1b5e79d242619dd6d5-6", "page_id": "68a95c1b5e79d242619dd6d5", "source_name": "mongodb-shell", "product_name": "MongoDB Shell", "url": "https://mongodb.com/docs/mongodb-shell/install", "title": "Install mongosh", "text": "### Confirm that mongosh installed successfully.\n\nTo confirm that `mongosh` installed successfully, run the following command:\n\n```sh\nmongosh --version\n```\n\nThe command returns the version of `mongosh` you installed.\n\n## Next Steps\n\nNow that you've installed `mongosh`, your next step is to connect to a MongoDB deployment. To learn how to connect `mongosh` to a local or Atlas deployment, see Connect to a Deployment.\n\nMongoDB provides a programmatically accessible list of `mongosh`\ndownloads that can be accessed through your application."} -{"chunk_id": "68a95c1c5e79d242619dd764-0", "page_id": "68a95c1c5e79d242619dd764", "source_name": "mongodb-vscode", "product_name": "MongoDB for VS Code", "url": "https://mongodb.com/docs/mongodb-vscode/copilot-export-test", "title": "Export and Test Queries", "text": "# Export and Test Queries\n\nYou can use the MongoDB Extension for Github Copilot to export and test your application queries in playgrounds.\n\nThe Export Code to Playground feature is only available if you enable MongoDB Extension for Github Copilot.\n\n## Export to Playground\n\nUse the following steps to test your application code in a playground:\n\n### Open the project file that contains the MongoDB query that you want to export.\n\n### Highlight the query that you want to test.\n\n### Right-click to select Export Code to Playground.\n\nRight-click your selected code to open the options menu. Click MongoDB Copilot Extension > Export Code to Playground.\n\nWhen you click Export Code to Playground, Visual Studio Code opens a new playground with your selected code in MongoDB shell syntax.\n\nOnce you export your code to a playground, you can click on the top right of your window to run your query.\n\nYou can also convert your code to a driver language with the Export to Language feature.\n\n- Explore Your Data with Playgrounds\n\n- MongoDB Extension for Github Copilot"} -{"chunk_id": "68a95c1c5e79d242619dd772-0", "page_id": "68a95c1c5e79d242619dd772", "source_name": "mongodb-vscode", "product_name": "MongoDB for VS Code", "url": "https://mongodb.com/docs/mongodb-vscode/create-cluster-terraform", "title": "Create an Atlas Cluster from a Template using Terraform", "text": "# Create an Atlas Cluster from a Template using Terraform\n\nThis page outlines how to use the Atlas template for Terraform files included with the MongoDB Extension for Visual Studio Code to create Flex clusters.\n\nAfter loading the template, you configure the cluster and provide details about your Atlas account. You then use Terraform commands to plan, apply, and destroy your Atlas cluster.\n\n## Prerequisites\n\nBefore you use the Atlas template for Terraform files included with the MongoDB Extension for Visual Studio Code, you must:\n\n- Install MongoDB for VS Code Extension\n\n- Install Terraform\n\n- Have an Atlas account.\n\n- Have an Atlas organization.\n\n- Have a service account in an |service| organization with the `Organization Owner` or `Organization Project Creator`\n role.\n\n## Procedures\n\n### Create an Atlas Terraform File using the Template\n\nUse the Atlas template for Terraform files included with the VS Code Extension to configure an Atlas cluster:\n\n#### In Visual Studio Code, create a new file.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nOperating System\n\n\nMethod\n\n\nActions\n\n
\nAny\n\n\nVisual Studio Code Menu\n\n\nFile > New File\n\n
\nMacOS\n\n\nKeyboard Shortcut\n\n\nPress `Command` + `N`\n\n
\nWindows and Linux\n\n\nKeyboard Shortcut\n\n\nPress `Control` + `N`\n\n
\n\n#### Save the file. Name it `main.tf`.\n\n`main.tf` is the recommended filename for the entry point to a Terraform module.\n\n#### In the `main.tf` file, type `atlas`, then press the **Enter** or **Return** key.\n\nThe MongoDB Extension for VSCode populates the file with an example configuration using the MongoDB Atlas Terraform provider to create a Flex cluster.\n\n#### Update the Atlas Terraform configuration to configure your cluster.\n\nThe cursor moves to select the value of the `name` argument of the `mongodbatlas_project` resource.\n\nProvide values for the following arguments to configure your cluster:\n\nPress the **Tab** key to select to the next argument in the template that you should update.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nAttribute\n\n\nValue\n\n
\n`mongodbatlas_project``.name`\n\n\nName of the Atlas project that this configuration creates.\n\n
\n`mongodbatlas_advanced_cluster``.name`\n\n\nName of the Atlas Flex cluster that this configuration creates.\n\n
\n`mongodbatlas_advanced_cluster``.replication_specs.``region_configs.``backing_provider_name`\n\n\nProvider on which the Atlas Flex cluster that this configuration creates is hosted. Choose one of the following accepted values:\n\n- `AWS`\n\n- `AZURE`\n\n- `GCP`\n\n
\n`mongodbatlas_advanced_cluster``.replication_specs.``region_configs.``region_name`\n\n\nRegion to which the Atlas Flex cluster that this configuration creates is deployed. Ensure that the region you chose supports Flex clusters.\n\nFor details about the regions that each provider supports, see the following sections in the Atlas documentation:\n\n- Amazon Web Services\n\n- Google Cloud Platform\n\n- Microsoft Azure\n\n
\n\n#### Update the `local` variables.\n\nThe `local` variables contain sensitive information. **Do not** check these values in to a repository that is available publicly.\n\nProvide values for the following `local` variables:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nVariable\n\n\nValue\n\n
\n`mongodb_atlas_client_id`\n\n\nAtlas service account client ID.\n\n
\n`mongodb_atlas_client_secret`\n\n\nAtlas service account client secret.\n\n
\n`mongodb_atlas_org_id`\n\n\nAtlas organization ID in which you want to create a project.\n\n
\n`mongodb_atlas_database_username`\n\n\nUsername of the MongoDB database user that Atlas creates for your cluster.\n\n
\n`mongodb_atlas_database_user_password`\n\n\nPassword for the MongoDB database user named in `mongodb_atlas_database_username`.\n\n
\n`mongodb_atlas_accesslistip`\n\n\nIP address or CIDR block from which your Atlas cluster is accessible.\n\n
The template authenticates to Atlas with a service account. API keys are also supported, but service accounts are the recommended authentication method. To learn about both methods, see the MongoDB Atlas Terraform Provider authentication guide.\n\nTo maximize security, consider taking the following steps:\n\n- Define the `local` variables in an input variables file.\n\n ```none\n variable \"mongodb_atlas_client_id\" {\n default = \"my-client-id\"\n }\n\n variable \"mongodb_atlas_client_secret\" {\n default = \"my-client-secret\"\n }\n ```\n\n- Exclude the input variables file from your repository. For example, add the filename to the `.gitignore` file for your repository.\n\n- Reference variables from the input variables file in the `main.tf` file by prefacing them with `var.`.\n\n ```none\n provider \"mongodbatlas\" {\n client_id = var.mongodb_atlas_client_id\n client_secret = var.mongodb_atlas_client_secret\n }\n ```\n\n#### Add optional configuration options to the `main.tf` file.\n\nFor a complete list of supported configuration options, see the MongoDB Atlas Terraform Provider documentation.\n\nFor production deployments, consider the official MongoDB Atlas Cluster module, which bundles the cluster resource with production best-practice defaults.\n\nFlex clusters don't support all configurations available with the MongoDB Atlas Terraform provider. For a list of unsupported configurations, see the Atlas documentation.\n\n#### Save the `main.tf` file."} -{"chunk_id": "68a95c1c5e79d242619dd772-1", "page_id": "68a95c1c5e79d242619dd772", "source_name": "mongodb-vscode", "product_name": "MongoDB for VS Code", "url": "https://mongodb.com/docs/mongodb-vscode/create-cluster-terraform", "title": "Create an Atlas Cluster from a Template using Terraform", "text": "### Create the Atlas Cluster using Terraform\n\nAfter you create a Terraform file using the template, create the Atlas cluster:\n\n#### Navigate to the directory in which you saved your `main.tf` file.\n\n#### Run the `terraform init` command to install the required providers.\n\nThe following output indicates that the MongoDB Atlas Terraform Provider is installed and ready for use:\n\n```bash\nterraform init\n```\n\n```none\nInitializing the backend...\n\nInitializing provider plugins...\n- Finding mongodb/mongodbatlas versions matching \"~> 2.0\"...\n- Installing mongodb/mongodbatlas v2.18.0...\n- Installed mongodb/mongodbatlas v2.18.0 (signed by a HashiCorp partner, key ID 2A32ED1F3AD25ABF)\nPartner and community providers are signed by their developers.\nIf you'd like to know more about provider signing, you can read about it here:\nhttps://developer.hashicorp.com/terraform/cli/plugins/signing\nTerraform has created a lock file .terraform.lock.hcl to record the provider\nselections it made above. Include this file in your version control repository\nso Terraform can guarantee to make the same selections by default when you run\n\"terraform init\" in the future.\n\nTerraform has been successfully initialized!\n\nYou may now begin working with Terraform. Try running \"terraform plan\" to see\nany changes that are required for your infrastructure. All Terraform commands\nshould now work.\n\nIf you ever set or change modules or backend configuration, rerun this command\nto reinitialize your working directory. If you forget, other commands will\ndetect it and remind you to do so if necessary.\n\n```\n\n#### Run the `terraform plan` command to view what happens when you apply the configuration.\n\nThe following output shows what happens when you apply the Terraform configuration:\n\n```bash\nterraform plan\n```\n\n```none\nTerraform used the selected providers to generate the following execution\nplan. Resource actions are indicated with the following symbols:\n + create\n\nTerraform will perform the following actions:\n\n # mongodbatlas_advanced_cluster.my_cluster will be created\n + resource \"mongodbatlas_advanced_cluster\" \"my_cluster\" {\n + advanced_configuration = (known after apply)\n + backup_enabled = (known after apply)\n + bi_connector_config = (known after apply)\n + cluster_id = (known after apply)\n + cluster_type = \"REPLICASET\"\n + config_server_management_mode = (known after apply)\n + config_server_type = (known after apply)\n + connection_strings = (known after apply)\n + create_date = (known after apply)\n + delete_on_create_timeout = true\n + encryption_at_rest_provider = (known after apply)\n + global_cluster_self_managed_sharding = (known after apply)\n + mongo_db_major_version = (known after apply)\n + mongo_db_version = (known after apply)\n + name = \"atlasClusterName\"\n + paused = (known after apply)\n + pit_enabled = (known after apply)\n + project_id = (known after apply)\n + redact_client_log_data = (known after apply)\n + replica_set_scaling_strategy = (known after apply)\n + replication_specs = [\n + {\n + container_id = (known after apply)\n + external_id = (known after apply)\n + region_configs = [\n + {\n + analytics_auto_scaling = (known after apply)\n + analytics_specs = (known after apply)\n + auto_scaling = (known after apply)\n + backing_provider_name = \"AWS\"\n + electable_specs = (known after apply)\n + priority = 7\n + provider_name = \"FLEX\"\n + read_only_specs = (known after apply)\n + region_name = \"US_EAST_1\"\n },\n ]\n + zone_id = (known after apply)\n + zone_name = (known after apply)\n },\n ]\n + root_cert_type = (known after apply)\n + state_name = (known after apply)\n + termination_protection_enabled = (known after apply)\n + use_aws_time_based_snapshot_copy_for_fast_initial_sync = (known after apply)\n + version_release_system = (known after apply)\n }\n\n # mongodbatlas_database_user.my_user will be created\n + resource \"mongodbatlas_database_user\" \"my_user\" {\n + auth_database_name = \"admin\"\n + aws_iam_type = \"NONE\"\n + id = (known after apply)\n + ldap_auth_type = \"NONE\"\n + oidc_auth_type = \"NONE\"\n + password = (sensitive value)\n + password_wo = (write-only attribute)\n + project_id = (known after apply)\n + username = \"myUser\"\n + x509_type = \"NONE\"\n\n + roles {\n + database_name = \"admin\"\n + role_name = \"atlasAdmin\"\n }\n }\n\n # mongodbatlas_project.my_project will be created\n + resource \"mongodbatlas_project\" \"my_project\" {\n + cluster_count = (known after apply)\n + created = (known after apply)\n + id = (known after apply)\n + ip_addresses = (known after apply)\n + is_cluster_ai_assistant_enabled = (known after apply)\n + is_collect_database_specifics_statistics_enabled = (known after apply)\n + is_data_explorer_enabled = (known after apply)\n + is_data_explorer_gen_ai_features_enabled = (known after apply)\n + is_data_explorer_gen_ai_sample_document_passing_enabled = (known after apply)\n + is_extended_storage_sizes_enabled = (known after apply)\n + is_native_reranking_enabled = (known after apply)\n + is_performance_advisor_enabled = (known after apply)\n + is_realtime_performance_panel_enabled = (known after apply)\n + is_schema_advisor_enabled = (known after apply)\n + is_slow_operation_thresholding_enabled = (known after apply)\n + name = \"atlasProjectName\"\n + org_id = \"5d3716bfcf09a21576d7983e\"\n + region_usage_restrictions = (known after apply)\n + with_default_alerts_settings = true\n }"} -{"chunk_id": "68a95c1c5e79d242619dd772-2", "page_id": "68a95c1c5e79d242619dd772", "source_name": "mongodb-vscode", "product_name": "MongoDB for VS Code", "url": "https://mongodb.com/docs/mongodb-vscode/create-cluster-terraform", "title": "Create an Atlas Cluster from a Template using Terraform", "text": " # mongodbatlas_project_ip_access_list.my_ipaddress will be created\n + resource \"mongodbatlas_project_ip_access_list\" \"my_ipaddress\" {\n + aws_security_group = (known after apply)\n + cidr_block = (known after apply)\n + comment = \"My IP Address\"\n + id = (known after apply)\n + ip_address = \"203.0.113.10\"\n + project_id = (known after apply)\n }\n\nPlan: 4 to add, 0 to change, 0 to destroy.\n\nChanges to Outputs:\n + connection_strings = (known after apply)\n\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nNote: You didn't use the -out option to save this plan, so Terraform can't\nguarantee to take exactly these actions if you run \"terraform apply\" now.\n\n```\n\nProceed to the next step if the information is correct.\n\n#### Run the `terraform apply` command to create an Atlas cluster from the Terraform configuration.\n\nType `yes` when prompted to confirm that you want to apply the configuration.\n\nThe `terraform apply` command might take several minutes to complete.\n\nThe following output indicates that your Atlas cluster is created. You can create a connection to this deployment using the VS Code Extension with the displayed connection string:\n\n```bash\nterraform apply\n```\n\n```none\nApply complete! Resources: 4 added, 0 changed, 0 destroyed.\n\nOutputs:\n\nconnection_strings = \"mongodb+srv://atlasClusterName.xxxxx.mongodb.net\"\n\n```\n\n### Delete the Atlas Cluster using Terraform\n\nDeleting a cluster destroys databases, collections, and documents stored on it **and** all other resources defined in the Terraform configuration in which you configured the cluster.\n\nProceed with caution.\n\nTo delete the Atlas cluster:\n\n#### Navigate to the directory in which you saved your `main.tf` file.\n\n#### Run the `terraform destroy` command to delete the resources defined in the configuration.\n\n```sh\nterraform destroy\n```\n\nType `yes` when prompted to confirm that you want to destroy the resources defined in the configuration.\n\nThe `terraform destroy` command might take several minutes to complete.\n\nThe following output indicates that the Atlas cluster and all associated resources are deleted:\n\n```sh\nDestroy complete! Resources: 4 destroyed.\n```"} -{"chunk_id": "68a95c1c5e79d242619dd796-0", "page_id": "68a95c1c5e79d242619dd796", "source_name": "mongodb-vscode", "product_name": "MongoDB for VS Code", "url": "https://mongodb.com/docs/mongodb-vscode/update-document-playground", "title": "Update Documents with VS Code", "text": "# Update Documents with VS Code\n\nYou can update documents in a collection using the MongoDB CRUD Operators in a MongoDB Playground:\n\n- Use the updateOne() method to update one document.\n\n- Use the updateMany() method to update more than one document.\n\n## Prerequisites\n\nIf you have not done so already, you must complete the following prerequisites before you can update documents with a MongoDB Playground:\n\n- Create a connection to a MongoDB deployment.\n\n- Activate the connection to the MongoDB deployment.\n\n- Open a MongoDB Playground.\n\n- Create Documents with VS Code or create documents in a collection using a different method.\n\n## Update One Document\n\nTo update one document, use the following syntax in your Playground:\n\n```javascript\ndb.collection.updateOne(\n ,\n ,\n {\n upsert: ,\n writeConcern: ,\n collation: ,\n arrayFilters: [ , ... ],\n hint: \n }\n)\n```\n\nFor a detailed description of this method's parameters, see updateOne() in the MongoDB Manual.\n\nTo run your Playground, press the button at the top right corner of the Playground View. VS Code Extension splits your Playground and outputs the results of your Playground in the Playground Results pane. If you disabled split-view, VS Code Extension outputs the results of your Playground in a new tab.\n\n### Example\n\nThe following example:\n\n1. Switches to the `test` database.\n\n2. Updates one document in the `test.sales` collection that matches the filter.\n\n```javascript\n :copyable: false\n use(\"test\");\n\ndb.sales.updateOne(\n { \"_id\" : 1},\n { $inc: { \"quantity\" : 1 }}\n);\n```\n\nWhen you press the button, VS Code Extension splits your Playground and outputs the following document in the Playground Result pane. If you disabled split-view, VS Code Extension outputs the following document in a new tab. If you manually move your playground results, VS Code Extension displays the results in that tab.\n\n```javascript\n{\n acknowledged: 1,\n matchedCount: 1,\n modifiedCount: 1,\n upsertedCount: 0,\n insertedId: null\n}\n```\n\n## Update Many Documents\n\nTo update many documents, use the following syntax in your Playground:\n\n```javascript\ndb.collection.updateMany(\n ,\n ,\n {\n upsert: ,\n writeConcern: ,\n collation: ,\n arrayFilters: [ , ... ],\n hint: \n }\n)\n```\n\nFor a detailed description of this method's parameters, see updateMany() in the MongoDB Manual.\n\nTo run your Playground, press the button at the top right corner of the Playground View. VS Code Extension splits your Playground and outputs the results of your Playground in the Playground Results pane. If you disabled split-view, VS Code Extension outputs the results of your Playground in a new tab.\n\n### Example\n\nThe following example:\n\n1. Switches to the `test` database.\n\n2. Updates all documents in the `test.sales` collection that match the filter.\n\n```javascript\nuse(\"test\");\n\ndb.sales.updateMany(\n { \"item\" : \"abc\" },\n { $set: { \"price\": 9 }}\n);\n```\n\nWhen you press the button, VS Code Extension splits your Playground and outputs the following document in the Playground Result pane. If you disabled split-view, VS Code Extension outputs the following document in a new tab. If you manually move your playground results, VS Code Extension displays the results in that tab.\n\n```javascript\n{\n acknowledged: 1,\n matchedCount: 3,\n modifiedCount: 3,\n upsertedCount: 0,\n insertedId: null\n}\n```"} -{"chunk_id": "69cb67f936a2a5baa36abade-0", "page_id": "69cb67f936a2a5baa36abade", "source_name": "mongodb-vscode", "product_name": "MongoDB for VS Code", "url": "https://mongodb.com/docs/mongodb-vscode/agent-skills", "title": "MongoDB Agent Skills in MongoDB VS Code Extension", "text": "# MongoDB Agent Skills in MongoDB VS Code Extension\n\nMongoDB for VS Code Extension includes the official MongoDB Agent Skills so you can perform common MongoDB tasks using AI agents.\n\nTo learn more about the MongoDB Agent Skills, see the MongoDB Agent Skills documentation.\n\n## Overview\n\nMongoDB Agent Skills are pre-built, reusable instructions that help AI coding agents perform common MongoDB tasks efficiently. These skills provide agents with expert knowledge about MongoDB best practices, enabling them to help you build applications faster and with fewer errors.\n\n## What are Agent Skills?\n\nAgent skills are specialized instructions that teach AI coding agents how to:\n\n- Set up and configure MongoDB connections\n\n- Design and implement database schemas\n\n- Write efficient queries and aggregations\n\nWhen you install MongoDB agent skills, your AI coding agent gains access to MongoDB-specific knowledge and can provide more accurate, context-aware assistance for your MongoDB development tasks.\n\n## Available Skills\n\nThe MongoDB agent skills collection includes several skills. To view the current list of available skills, see the MongoDB Agent Skills documentation.\n\n## Manage the MCP Server\n\nThe VS Code Extension bundles the MongoDB MCP Server, so skills that access a live database work out of the box. You can also use skills focused on design, tuning, and best-practices guidance without it, although some of these skills provide a richer experience with MCP enabled.\n\nTo manage the MongoDB MCP server from the VS Code Extension, see the MCP Server settings."} -{"chunk_id": "68fb1a413b754f1e0c7ead8a-0", "page_id": "68fb1a413b754f1e0c7ead8a", "source_name": "mongodb-vscode", "product_name": "MongoDB for VS Code", "url": "https://mongodb.com/docs/mongodb-vscode/logs", "title": "View MongoDB VSCode Extension Logs", "text": "# View MongoDB VSCode Extension Logs\n\nYou can view logs for MongoDB for VS Code Extension to troubleshoot extension issues.\n\n## Steps\n\nOpen the Command Palette (Ctrl+Shift+P or Cmd+Shift+P)\n\nRun the Developer: Open Log... command\n\nSelect MongoDB Extension from the list of log files\n\n## Examples\n\n### Insert\n\nThe following example shows log messages that appear after you use a playground to insert a document into a collection:\n\n```sh\n2025-10-23 14:36:24.130 [info] [telemetry] Telemetry sent [\n {\n anonymousId: '414615cf-8328-427a-bb18-23416389a7ec',\n event: 'Playground Created',\n properties: {\n extension_version: '1.14.2',\n device_id: 'unknown',\n playground_type: 'insertDocument'\n }\n }\n]\n2025-10-23 14:36:26.019 [info] [language server controller] Running a playground... [\n {\n connectionId: '6e213121-77a7-4d43-a14c-1fde0e6ac06e',\n filePath: '/Users/jeff/github/docs-mongodb-internal/playground-3.mongodb.js',\n inputLength: 254\n }\n]\n2025-10-23 14:36:26.705 [info] [language server controller] Evaluate response [\n {\n namespace: 'test.products',\n type: 'InsertOneResult',\n outputLength: 39,\n language: 'json'\n }\n]\n2025-10-23 14:36:36.672 [info] [telemetry] Telemetry sent [\n {\n anonymousId: '414615cf-8328-427a-bb18-23416389a7ec',\n event: 'Command Run',\n properties: {\n extension_version: '1.14.2',\n device_id: 'unknown',\n command: 'mdb.runPlayground'\n }\n }\n]\n2025-10-23 14:36:36.672 [info] [telemetry] Telemetry sent [\n {\n anonymousId: '414615cf-8328-427a-bb18-23416389a7ec',\n event: 'Playground Code Executed',\n properties: {\n extension_version: '1.14.2',\n device_id: 'unknown',\n type: 'insert',\n partial: false,\n error: false\n }\n }\n]\n```\n\n### Read\n\nThe following example shows log messages that appear after you run a playground to read data from a collection:\n\n```sh\n2025-10-23 14:12:27.424 [info] [telemetry] Telemetry sent [\n {\n anonymousId: '414615cf-8328-427a-bb18-23416389a7ec',\n event: 'Playground Created',\n properties: {\n extension_version: '1.14.2',\n device_id: 'unknown',\n playground_type: 'search'\n }\n }\n]\n2025-10-23 14:12:27.424 [info] [telemetry] Telemetry sent [\n {\n anonymousId: '414615cf-8328-427a-bb18-23416389a7ec',\n event: 'Command Run',\n properties: {\n extension_version: '1.14.2',\n device_id: 'unknown',\n command: 'mdb.runPlayground'\n }\n }\n]\n2025-10-23 14:12:37.446 [info] [telemetry] Telemetry sent [\n {\n anonymousId: '414615cf-8328-427a-bb18-23416389a7ec',\n event: 'Playground Code Executed',\n properties: {\n extension_version: '1.14.2',\n device_id: 'unknown',\n type: 'query',\n partial: false,\n error: false\n }\n }\n]\n```"} -{"chunk_id": "68a95c1c5e79d242619dd794-0", "page_id": "68a95c1c5e79d242619dd794", "source_name": "mongodb-vscode", "product_name": "MongoDB for VS Code", "url": "https://mongodb.com/docs/mongodb-vscode/require-playgrounds", "title": "Use require() in Playgrounds", "text": "# Use require() in Playgrounds\n\nYou can use the require() function in your playgrounds to reuse code in your playgrounds. The code you include with `require()` can be either:\n\n- A native Node module (such as fs)\n\n- An external Node module downloaded from npm\n\n- A local JavaScript file\n\n## Use Cases\n\nUsing `require()` to import code helps keep your playgrounds organized. If you are often performing the same tasks in your playgrounds, you can use `require()` to reuse code and avoid writing full functions in each of your playgrounds.\n\nFor example, consider the following scenarios where reusing code can simplify logic and improve productivity:\n\n- You need to ensure that documents are inserted with a consistent structure. You can import a JavaScript file to validate the data format before the playground script performs the insert.\n\n- You store monetary data and want to convert values between different currencies. You can import a JavaScript function to perform conversion calculations.\n\n- You need to import data from files on your local computer. You can use the native Node module `fs` to read data from local files.\n\n## Get Started\n\nTo learn how to use `require()` in your playgrounds, see the following tutorials:\n\n- Use require() to Include Node.js Modules\n\n- Use require() to Load Local Files"} -{"chunk_id": "68a95c1c5e79d242619dd751-0", "page_id": "68a95c1c5e79d242619dd751", "source_name": "mongodb-vscode", "product_name": "MongoDB for VS Code", "url": "https://mongodb.com/docs/mongodb-vscode/install/verify-plugin", "title": "Verify MongoDB for VSCode Plugin", "text": "# Verify MongoDB for VSCode Plugin\n\nThe MongoDB release team digitally signs VS Code Extension releases to certify that the plugin is a valid and unaltered MongoDB release. You can use the digital signature to validate the plugin and ensure that it is a trusted installation.\n\n## Before you Begin\n\nIf you don't have VS Code Extension installed, download the VS Code Extension plugin from the GitHub Releases page or the Visual Studio Code extension marketplace.\n\n## Steps\n\n### Download the VS Code Extension signature file\n\nGo to the MongoDB VS Code Releases page and download the `.sig` file for your version of VS Code Extension.\n\n### Import the VS Code Extension public key\n\n```sh\ncurl https://pgp.mongodb.com/mongodb-vscode.asc | gpg --import\n```\n\nIf the key imports successfully, the command returns:\n\n```sh\ngpg: key A8130EC3F9F5F923: public key \"MongoDB VS Code Signing Key \" imported\ngpg: Total number processed: 1\ngpg: imported: 1\n```\n\nIf you have previously imported the key, the command returns:\n\n```sh\ngpg: key A8130EC3F9F5F923: public key \"MongoDB VS Code Signing Key \" not changed\ngpg: Total number processed: 1\ngpg: unchanged: 1\n```\n\n### Verify the plugin\n\n```sh\ngpg --verify \n```\n\nIf the plugin is signed by MongoDB, the command returns:\n\n```sh\ngpg: Signature made Mon Jan 8 19:30:04 2024 CET\ngpg: using RSA key A505CECC78EC9A688A4811505D55DCA8B92B7040\ngpg: Good signature from \"MongoDB VS Code Signing Key \" [unknown]\n```\n\nIf the package is signed but the signing key is not added to your local `trustdb`, the command returns:\n\n```sh\ngpg: WARNING: This key is not certified with a trusted signature!\ngpg: There is no indication that the signature belongs to the owner.\n```\n\nIf the package is not signed properly, the command returns an error message:\n\n```sh\ngpg: Signature made Mon Jan 22 10:22:53 2024 CET\ngpg: using RSA key AB1B92FFBE0D3740425DAD16A8130EC3F9F5F923\ngpg: BAD signature from \"MongoDB VS Code Signing Key \" [unknown]\n```"} -{"chunk_id": "68a95c1c5e79d242619dd79a-0", "page_id": "68a95c1c5e79d242619dd79a", "source_name": "mongodb-vscode", "product_name": "MongoDB for VS Code", "url": "https://mongodb.com/docs/mongodb-vscode/run-agg-pipelines", "title": "Run Aggregation Pipelines with VS Code", "text": "# Run Aggregation Pipelines with VS Code\n\nYou can run aggregation pipelines on your collections in VS Code Extension. Aggregation pipelines consist of stages that process your data and return computed results.\n\nCommon uses for aggregation include:\n\n- Grouping data by a given expression.\n\n- Calculating results based on multiple fields and storing those results in a new field.\n\n- Filtering data to return a subset that matches a given criteria.\n\n- Sorting data.\n\nWhen you run an aggregation, VS Code Extension conveniently outputs the results directly within Visual Studio Code.\n\n## Open a Playground to Run Aggregation Pipelines\n\nYou can run aggregation pipelines in a MongoDB Playground. MongoDB Playgrounds are JavaScript environments where you can prototype queries, aggregations, and MongoDB commands with helpful syntax highlighting.\n\nTo open a new MongoDB Playground:\n\n### Open the Visual Studio Code Command Palette.\n\nIn Visual Studio Code, press one of the following key combinations:\n\n- Control + Shift + P on Windows or Linux.\n\n- Command + Shift + P on macOS.\n\nThe Command Palette provides quick access to commands and keyboard shortcuts.\n\n### Find and run the \"Create MongoDB Playground\" command.\n\nUse the Command Palette search bar to search for commands. All commands related to VS Code Extension are prefaced with MongoDB:.\n\nWhen you run the MongoDB: Create MongoDB Playground command, VS Code Extension opens a default playground template pre-configured with a few commands.\n\nTo load new Playgrounds without the template, disable the Use Default Template For Playground setting. To learn more about VS Code Extension settings, see Visual Studio Code Settings.\n\n## Create and Run an Aggregation Pipeline\n\nTo create an aggregation pipeline, use the following syntax in your Playground:\n\n```\ndb..aggregate([\n {\n <$stage1>\n },\n {\n <$stage2>\n }\n ...\n])\n```\n\nTo run your Playground, press the button at the top right corner of the Playground View. VS Code Extension splits your Playground and outputs the results of your Playground in the Playground Results pane. If you disabled split-view, VS Code Extension outputs the results of your Playground in a new tab.\n\n### Example\n\nTo run this example, **start with a blank MongoDB Playground** by clearing the template Playground if it is loaded.\n\nConsider the following playground which inserts sample data into a collection and aggregates that data:\n\n```javascript\nuse(\"test\");\n\ndb.sales.insertMany([\n { \"_id\" : 1, \"item\" : \"abc\", \"price\" : 10, \"quantity\" : 2, \"date\" : new Date(\"2014-03-01T08:00:00Z\") },\n { \"_id\" : 2, \"item\" : \"jkl\", \"price\" : 20, \"quantity\" : 1, \"date\" : new Date(\"2014-03-01T09:00:00Z\") },\n { \"_id\" : 3, \"item\" : \"xyz\", \"price\" : 5, \"quantity\" : 10, \"date\" : new Date(\"2014-03-15T09:00:00Z\") },\n { \"_id\" : 4, \"item\" : \"xyz\", \"price\" : 5, \"quantity\" : 20, \"date\" : new Date(\"2014-04-04T11:21:39.736Z\") },\n { \"_id\" : 5, \"item\" : \"abc\", \"price\" : 10, \"quantity\" : 10, \"date\" : new Date(\"2014-04-04T21:23:13.331Z\") },\n { \"_id\" : 6, \"item\" : \"def\", \"price\" : 7.5, \"quantity\": 5, \"date\" : new Date(\"2015-06-04T05:08:13Z\") },\n { \"_id\" : 7, \"item\" : \"def\", \"price\" : 7.5, \"quantity\": 10, \"date\" : new Date(\"2015-09-10T08:43:00Z\") },\n { \"_id\" : 8, \"item\" : \"abc\", \"price\" : 10, \"quantity\" : 5, \"date\" : new Date(\"2016-02-06T20:20:13Z\") }\n])\n\ndb.sales.aggregate([\n { $match: { date: { $gte: new Date(\"2014-01-01\"), $lt: new Date(\"2015-01-01\") } } },\n { $group: { _id: \"$item\", totalSaleAmount: { $sum: { $multiply: [ \"$price\", \"$quantity\" ] } } } }\n])\n```\n\nThis pipeline:\n\n1. Switches to the `test` database.\n\n2. Inserts eight documents into the `test.sales` collection.\n\n3. Performs an aggregation in two stages:\n\n The `$match` stage filters the data such that only sales from the year 2014 are passed to the next stage.\n\n The `$group` stage groups the data by item. The stage adds a new field to the output called `totalSaleAmount`, which is the culmination of the item's `price` and `quantity`.\n\nWhen you press the Play Button, VS Code Extension splits your playground and outputs the following document in the Playground Results.json pane. If you disabled split-view, VS Code Extension outputs the following document in a new tab:\n\n```javascript\n[\n {\n _id: 'abc',\n totalSaleAmount: 120\n },\n {\n _id: 'jkl',\n totalSaleAmount: 20\n },\n {\n _id: 'xyz',\n totalSaleAmount: 150\n }\n]\n```\n\n- To learn more about the available aggregation stages, see Aggregation Stages.\n\n- To learn more about the available aggregation operators you can use within stages, see Expressions."} -{"chunk_id": "68a95c1c5e79d242619dd77b-0", "page_id": "68a95c1c5e79d242619dd77b", "source_name": "mongodb-vscode", "product_name": "MongoDB for VS Code", "url": "https://mongodb.com/docs/mongodb-vscode/create-document-playground", "title": "Create Documents with VS Code", "text": "# Create Documents with VS Code\n\nYou can create documents in a collection using the MongoDB CRUD Operators in a MongoDB Playground:\n\n- Use the insertOne() method to insert one document.\n\n- Use the insertMany() method to insert more than one document.\n\n## Prerequisites\n\nIf you have not done so already, you must complete the following prerequisites before you can create documents with a MongoDB Playground:\n\n- Create a connection to a MongoDB deployment.\n\n- Activate the connection to the MongoDB deployment.\n\n- Open a MongoDB Playground.\n\n## Create One Document\n\nTo create one document, use the following syntax in your Playground:\n\n```javascript\ndb.collection.insertOne(\n ,\n {\n writeConcern: \n }\n)\n```\n\nIf the database doesn't exist, insert operations will create it.\n\nFor a detailed description of this method's parameters, see insertOne() in the MongoDB Manual.\n\nTo run your Playground, press the button at the top right corner of the Playground View. VS Code Extension splits your Playground and outputs the results of your Playground in the Playground Results pane. If you disabled split-view, VS Code Extension outputs the results of your Playground in a new tab.\n\n### Example\n\nTo run this example, **start with a blank MongoDB Playground** by clearing the template Playground if it is loaded.\n\nThe following example:\n\n1. Switches to the `test` database.\n\n2. Inserts eight documents into the `test.sales` collection.\n\n```javascript\nuse(\"test\");\n\ndb.sales.insertOne(\n { \"_id\" : 1, \"item\" : \"abc\", \"price\" : 10, \"quantity\" : 2, \"date\" : new Date(\"2014-03-01T08:00:00Z\")}\n);\n```\n\nWhen you press the button, VS Code Extension splits your Playground and outputs the following document in the Playground Result pane. If you disabled split-view, VS Code Extension outputs the following document in a new tab. If you manually move your playground results, VS Code Extension displays the results in that tab.\n\n```javascript\n{\n acknowledged: 1,\n insertedId: 1\n}\n```\n\n## Create Many Documents\n\nTo create many documents, use the following syntax in your Playground:\n\n```javascript\ndb.collection.insertMany(\n [ , , ... ],\n {\n writeConcern: ,\n ordered: \n }\n)\n```\n\nIf the database doesn't exist, insert operations will create it.\n\nFor a detailed description of this method's parameters, see insertMany() in the MongoDB Manual.\n\nTo run your Playground, press the button at the top right corner of the Playground View. VS Code Extension splits your Playground and outputs the results of your Playground in the Playground Results pane. If you disabled split-view, VS Code Extension outputs the results of your Playground in a new tab.\n\n### Example\n\nTo run this example, **start with a blank MongoDB Playground** by clearing the template Playground if it is loaded.\n\nThe following example:\n\n1. Switches to the `test` database.\n\n2. Inserts eight documents into the `test.sales` collection.\n\n```javascript\nuse(\"test\");\n\ndb.sales.insertMany([\n { \"_id\" : 2, \"item\" : \"abc\", \"price\" : 10, \"quantity\" : 2, \"date\" : new Date(\"2014-03-01T08:00:00Z\") },\n { \"_id\" : 3, \"item\" : \"jkl\", \"price\" : 20, \"quantity\" : 1, \"date\" : new Date(\"2014-03-01T09:00:00Z\") },\n { \"_id\" : 4, \"item\" : \"xyz\", \"price\" : 5, \"quantity\" : 10, \"date\" : new Date(\"2014-03-15T09:00:00Z\") },\n { \"_id\" : 5, \"item\" : \"xyz\", \"price\" : 5, \"quantity\" : 20, \"date\" : new Date(\"2014-04-04T11:21:39.736Z\") },\n { \"_id\" : 6, \"item\" : \"abc\", \"price\" : 10, \"quantity\" : 10, \"date\" : new Date(\"2014-04-04T21:23:13.331Z\") },\n { \"_id\" : 7, \"item\" : \"def\", \"price\" : 7.5, \"quantity\": 5, \"date\" : new Date(\"2015-06-04T05:08:13Z\") },\n { \"_id\" : 8, \"item\" : \"def\", \"price\" : 7.5, \"quantity\": 10, \"date\" : new Date(\"2015-09-10T08:43:00Z\") },\n { \"_id\" : 9, \"item\" : \"abc\", \"price\" : 10, \"quantity\" : 5, \"date\" : new Date(\"2016-02-06T20:20:13Z\") },\n]);\n```\n\nWhen you press the button, VS Code Extension splits your Playground and outputs the following document in the Playground Result pane. If you disabled split-view, VS Code Extension outputs the following document in a new tab. If you manually move your playground results, VS Code Extension displays the results in that tab.\n\n```javascript\n{\n acknowledged: 1,\n insertedIds: {\n '0': 2,\n '1': 3,\n '2': 4,\n '3': 5,\n '4': 6,\n '5': 7,\n '6': 8,\n '7': 9\n }\n}\n```"} -{"chunk_id": "68a95c1c5e79d242619dd78e-0", "page_id": "68a95c1c5e79d242619dd78e", "source_name": "mongodb-vscode", "product_name": "MongoDB for VS Code", "url": "https://mongodb.com/docs/mongodb-vscode/read-document-playground", "title": "Read Documents with VS Code", "text": "# Read Documents with VS Code\n\nfindOne()find()You can read documents in a collection using the MongoDB CRUD Operators in a MongoDB Playground:\n\n- Use the findOne() method to read one document.\n\n- Use the find() method to read more than one document.\n\nYou can open a JavaScript Playground pre-configured to search a collection by hovering over the Documents label in the navigation panel and clicking the icon that appears.\n\n## Prerequisites\n\nIf you have not done so already, you must complete the following prerequisites before you can read documents with a MongoDB Playground:\n\n- Create a connection to a MongoDB deployment.\n\n- Activate the connection to the MongoDB deployment.\n\n- Open a MongoDB Playground.\n\n- Create Documents with VS Code or create documents in a collection using a different method.\n\n## Read One Document\n\nTo read one document, use the following syntax in your Playground:\n\n```javascript\ndb.collection.findOne(\n { },\n { }\n)\n```\n\nIf multiple documents satisfy the query, this method returns the first document according to the natural order which reflects the order of documents on the disk.\n\nTo learn more about this method's parameters, see findOne() in the MongoDB Manual.\n\nTo run your Playground, press the button at the top right corner of the Playground View. VS Code Extension splits your Playground and outputs the results of your Playground in the Playground Results pane. If you disabled split-view, VS Code Extension outputs the results of your Playground in a new tab.\n\nYou may edit any JSON (Javascript Object Notation) document returned from a findOne() or find() operation.\n\n### Click Edit Document\n\nAt the top of this document, click Edit Document. VS Code Extension opens it as an editable EJSON (Extended Javascript Object Notation) document titled `.:\"<_id>\"`.\n\nMake any necessary edits to the dcument.\n\n### Save the edited document\n\nPress Ctrl + S (Windows/Linux) or Cmd + S to save the edited document to the MongoDB database.\n\nIf the update succeeds, VS Code Extension confirms that the database has stored the change. If the update results in an error, VS Code Extension displays the error.\n\n### Example\n\nTo run this example, **start with a blank MongoDB Playground** by clearing the template Playground if it is loaded.\n\nThe following example:\n\n1. Switches to the `test` database.\n\n2. Reads one document in the `test.sales` collection that matches the query.\n\n```javascript\nuse(\"test\");\n\ndb.sales.findOne(\n { \"_id\" : 1 },\n { \"_id\" : 0 }\n);\n```\n\nWhen you press the button, VS Code Extension splits your Playground and outputs the following document in the Playground Result pane. If you disabled split-view, VS Code Extension outputs the following document in a new tab. If you manually move your playground results, VS Code Extension displays the results in that tab.\n\n```javascript\n{\n item: 'abc',\n price: 10,\n quantity: 2,\n date: 2014-03-01T08:00:00.000Z\n}\n```\n\n## Read Many Documents\n\nTo read many documents, use the following syntax in your Playground:\n\n```javascript\ndb.collection.find(\n { },\n { }\n)\n```\n\nFor a detailed description of this method's parameters, see find() in the MongoDB Manual.\n\nTo run your Playground, press the button at the top right corner of the Playground View. VS Code Extension splits your Playground and outputs the results of your Playground in the Playground Results pane. If you disabled split-view, VS Code Extension outputs the results of your Playground in a new tab.\n\n### Example\n\nTo run this example, **start with a blank MongoDB Playground** by clearing the template Playground if it is loaded.\n\nThe following example:\n\n1. Switches to the `test` database.\n\n2. Reads all documents in the `test.sales` collection that match the query.\n\n```javascript\nuse(\"test\");\n\ndb.sales.find(\n { \"item\" : \"abc\" },\n { \"price\" : 1 }\n);\n```\n\nWhen you press the button, VS Code Extension splits your Playground and outputs the following document in the Playground Result pane. If you disabled split-view, VS Code Extension outputs the following document in a new tab. If you manually move your playground results, VS Code Extension displays the results in that tab.\n\n```javascript\n[\n {\n _id: 2,\n price: 10\n },\n {\n _id: 6,\n price: 10\n },\n {\n _id: 9,\n price: 10\n },\n {\n _id: 1,\n price: 10\n }\n]\n```\n\n## Read Documents with a Cursor\n\nWhen the last expression in your Playground evaluates to a cursor, such as a `db.collection.find()` or `db.collection.aggregate()` call, Visual Studio Code opens the results in the cursor results document browser view.\n\nIn this view, you can:\n\n- Page through results with the pagination controls at the top of the view.\n\n- View each document in a table-like list. Documents appear in shell syntax by default.\n\nVisual Studio Code still uses the regular results editor for operations that don't produce a cursor with a list of documents, such as aggregations ending with `$out` or `$merge`, or results that are not documents, such as strings, numbers, or other scalar values.\n\n### Example\n\nTo run this example, **start with a blank MongoDB Playground** by clearing the template Playground if it is loaded.\n\nThe following example:\n\n1. Switches to the `test` database.\n\n2. Reads all documents from the `test.sales` collection that match the query.\n\n3. Returns a cursor as the last expression.\n\n```javascript\nuse(\"test\");\n\ndb.sales.find(\n { \"price\": { $gte: 10 } },\n { \"price\": 1 }\n);\n```\n\nWhen you click the button, Visual Studio Code opens a document browser tab that shows the documents the cursor returned with pagination controls at the top of the view.\n\n### Return the Entire Cursor as an Array\n\nIf you prefer to convert a cursor to an array and view it directly in the Playground Results editor instead of the document browser, call `toArray()` on the cursor as the last expression in your Playground:\n\n```javascript\nlet cursor = db.collection.find({ });\n\ncursor.toArray();\n```\n\nWhen you press the button, VS Code Extension splits your Playground and outputs the following document in the Playground Result pane. If you disabled split-view, VS Code Extension outputs the following document in a new tab. If you manually move your playground results, VS Code Extension displays the results in that tab.\n\n```javascript\n[\n {\n \"_id\": 2,\n \"price\": 10\n },\n {\n \"_id\": 3,\n \"price\": 20\n },\n {\n \"_id\": 6,\n \"price\": 10\n },\n {\n \"_id\": 9,\n \"price\": 10\n }\n]\n```\n\n## Learn More\n\nFor more detailed documentation on cursor methods and behaviors, see:\n\n- MongoDB Cursors Overview\n\n- Iterate a Cursor"} -{"chunk_id": "69c37e657cce4b2a565938e0-0", "page_id": "69c37e657cce4b2a565938e0", "source_name": "mongoid", "product_name": "Mongoid ODM", "url": "https://mongodb.com/docs/mongoid/current/connect/forking-server-config", "title": "Configure a Forking Server", "text": "# Configure a Forking Server\n\n## Overview\n\nIn this guide, you can learn about configuring your application to use a forking web server.\n\nWhen using Mongoid with a forking web server, adhere to the following guidelines:\n\n- If possible, do not perform any MongoDB operations in the parent process before forking.\n\n- You can avoid connection errors such as `Mongo::Error::SocketError` and `Mongo::Error::NoServerAvailable` by performing the following actions:\n\n 1. Disconnect MongoDB clients in the parent Ruby process immediately *before* forking by using the `Mongoid.disconnect_clients` method. This ensures that the parent and child processes do not accidentally reuse the same sockets and have I/O conflicts. `Mongoid.disconnect_clients` does not disrupt any in-flight MongoDB operations, and automatically reconnects when you perform new operations.\n\n 2. Reconnect your MongoDB clients in the child Ruby process immediately *after* forking by using the `Mongoid.reconnect_clients` method. This is required to respawn the driver's monitoring threads in the child process.\n\nMost web servers provide hooks that your application can use to perform actions when the worker processes are forked. The following sections provide configuration examples for some common Ruby web servers.\n\n## Puma\n\nSelect the tab that corresponds to your version of Puma:\n\n\n\n\n\nUse the `on_worker_boot` hook to reconnect clients in the worker processes. Use the `before_fork` and `on_refork` hooks to close clients in the parent process.\n\nThe following code uses the `on_worker_boot`, `before_fork`, and `on_refork` hooks in a sample Puma configuration file:\n\n```ruby\n# Runs in the Puma master process before it forks a child worker.\nbefore_fork do\n Mongoid.disconnect_clients\nend\n\n# Required when using Puma's fork_worker option. Runs in the\n# child worker 0 process before it forks grandchild worker processes.\non_refork do\n Mongoid.disconnect_clients\nend\n\n# Runs in each Puma child process after it forks from its parent.\non_worker_boot do\n Mongoid.reconnect_clients\nend\n```\n\n\n\n\n\nUse the `before_worker_boot` hook to reconnect clients in the worker processes. Use the `before_fork` and `before_refork` hooks to close clients in the parent process. To learn more about these hooks, see Cluster mode hooks in the Puma API documentation.\n\nThe following code uses the `before_worker_boot`, `before_fork`, and `before_refork` hooks in a sample Puma configuration file:\n\n```ruby\n# Runs in the Puma master process before it forks a child worker.\nbefore_fork do\n Mongoid.disconnect_clients\nend\n\n# Required when using Puma's fork_worker option. Runs in the\n# child worker 0 process before it forks grandchild worker processes.\nbefore_refork do\n Mongoid.disconnect_clients\nend\n\n# Runs in each Puma child process after it forks from its parent.\nbefore_worker_boot do\n Mongoid.reconnect_clients\nend\n```\n\n\n\n\n\n## Unicorn\n\nUse the `before_fork` hook to close clients in the parent process. Use the `after_fork` hook to reconnect clients in the worker processes. To learn more about these hooks, see Configurator in the Unicorn API documentation.\n\nThe following code uses the `before_fork` and `after_fork` hooks in a sample Unicorn configuration file:\n\n```ruby\nbefore_fork do |_server, _worker|\n Mongoid.disconnect_clients\nend\n\nafter_fork do |_server, _worker|\n Mongoid.reconnect_clients\nend\n```\n\n## Passenger\n\nUse the `starting_worker_process` hook to reconnect clients in the worker processes. To learn more about this hook, see Smart spawning hooks in the Passenger documentation.\n\nPassenger does have a hook that is invoked in the parent process before the worker processes are forked.\n\nThe following code uses the `starting_worker_process` hook to reconnect clients:\n\n```ruby\nif defined?(PhusionPassenger)\n PhusionPassenger.on_event(:starting_worker_process) do |forked|\n Mongoid.reconnect_clients if forked\n end\nend\n```"} -{"chunk_id": "69c37e657cce4b2a56593907-0", "page_id": "69c37e657cce4b2a56593907", "source_name": "mongoid", "product_name": "Mongoid ODM", "url": "https://mongodb.com/docs/mongoid/current/logging-config", "title": "Logging Configuration", "text": "# Logging Configuration\n\n## Overview\n\nIn this guide, you can learn how to configure logging in your Mongoid application. When configuring logging, note that Mongoid provides a model layer on top of the Ruby driver, and the *driver* dispatches data operations to MongoDB. Therefore, some logging output in an application that uses Mongoid comes from Mongoid itself, and some comes from the driver.\n\n## Driver Logger\n\nThe Mongoid client is a Ruby driver client instance, so the logger of a Mongoid client is the Ruby driver logger, not the Mongoid logger. The following code creates a Mongoid client logger:\n\n```ruby\nMongoid.client(:default).logger\n```\n\nDepending on your application framework and how you configure Mongoid and the Ruby driver, they may use the same logger instance or different instances, potentially with different configurations.\n\n### Ruby on Rails Configuration\n\nWhen used in a Ruby on Rails application, Mongoid by default inherits the logger and the log level from Rails. Mongoid sets the driver's logger to the same logger instance:\n\n```ruby\nRails.logger === Mongoid.logger\n# => true\n\nMongoid.logger === Mongo::Logger.logger\n# => true\n```\n\nTo change the log level, use the standard Rails configuration. Place the following block in one of your environment configuration files, such as `config/environments/production.rb`:\n\n```ruby\nRails.application.configure do\n config.log_level = :debug\nend\n```\n\nThe `log_level` Mongoid configuration option is not used when Mongoid operates in a Rails application, because Mongoid inherits Rails' log level.\n\nTo configure either the Mongoid or driver logger differently from the Rails logger, use an initializer as shown in the following code:\n\n```ruby\nRails.application.configure do\n config.after_initialize do\n # Change Mongoid log destination and level\n Mongoid.logger = Logger.new(STDERR).tap do |logger|\n logger.level = Logger::DEBUG\n end\n\n # Change driver log destination and level\n Mongo::Logger.logger = Logger.new(STDERR).tap do |logger|\n logger.level = Logger::DEBUG\n end\n end\nend\n```\n\nThere is no provision in the Ruby standard library `Logger` to return the log device, such as the `IO` object, that a logger is using.\n\nTo make, for example, Mongoid or the Ruby driver log to the standard Rails log file (`log/development.log`) with a different level from standard Rails logger (`Rails.logger`), you must open the file separately and pass the resulting `IO` object to the `Logger` constructor.\n\nBecause Mongoid sets its own logger and the driver's logger to the same instance as the Rails logger, modifying any of the instances affects all the loggers. For example, the following code changes the log level for all three loggers:\n\n```ruby\nMongoid::Logger.logger.level = Logger::DEBUG\n```\n\n### Standalone Configuration\n\nWhen not loaded in a Ruby on Rails application, Mongoid respects the `log_level` top-level configuration option:\n\n```yaml\ndevelopment:\n clients:\n default:\n ...\n options:\n log_level: :debug\n```\n\nYou can also configure the log level in-line:\n\n```ruby\nMongoid.configure do |config|\n config.log_level = :debug\nend\n```\n\nThe default log destination is standard error. To change the log destination, create a new logger instance as shown in the following code:\n\n```ruby\nMongoid.logger = Logger.new(STDERR).tap do |logger|\n logger.level = Logger::DEBUG\nend\n```\n\nTo change the Ruby driver log level or destination, add the following block to your application file:\n\n```ruby\nMongo::Logger.logger = Logger.new(STDERR).tap do |logger|\n logger.level = Logger::DEBUG\nend\n```\n\nMongoid does not change the driver's logger when running in standalone mode."} -{"chunk_id": "68a95c1f5e79d242619dd965-0", "page_id": "68a95c1f5e79d242619dd965", "source_name": "mongoid", "product_name": "Mongoid ODM", "url": "https://mongodb.com/docs/mongoid/current/interact-data/query-persistence", "title": "Persist Data from Queries", "text": "# Persist Data from Queries\n\n## Overview\n\nIn this guide, you can learn how how to persist data off of your queries in Mongoid. Mongoid supports persistence operations off of criteria in a limited capacity, allowing you to to expressively perform multi-document insert, update, and delete operations.\n\nTo learn more about creating filter criteria, see the Specify a Document Query guide.\n\nTo learn more about performing CRUD operations, see the CRUD Operations guide.\n\n## Persistence Methods\n\nThis section describes methods that you can chain to your queries to create, update, and delete data in your MongoDB collections.\n\n### Create a Document\n\nYou can use the following methods to create new documents from your query criteria:\n\n- `create`: Saves a model instance to MongoDB\n\n - Example: `Band.where(name: 'Daft Punk').create`\n\n- `create!`: Saves a model instance to MongoDB or raises an exception if a validation error occurs\n\n - Example: `Band.where(name: 'Daft Punk').create!`\n\n- `build`: Creates an unsaved model instance\n\n - Example: `Band.where(name: 'Daft Punk').build`\n\n- `new`: Creates an unsaved model instance\n\n - Example: `Band.where(name: 'Daft Punk').new`\n\n### Update Documents\n\nYou can use the following methods to update documents based on your query criteria:\n\n- `update`: Updates attributes of the first matching document\n\n - Example: `Band.where(name: 'Sundown').update(label: 'ABC Records')`\n\n- `update_all`: Updates attributes of all matching documents\n\n - Example: `Band.where(country: 'Canada').update_all(label: 'ABC Records')`\n\n- `add_to_set`: Adds a value to a specified array in all matching documents\n\n - Example: `Band.where(name: 'Sun Down').add_to_set(label: 'ABC Records')`\n\n- `bit`: Performs a bitwise update of a field\n\n - Example: `Band.where(name: 'Sun Down').bit(likes: { and: 14, or: 4 })`\n\n- `inc`: Increments the value of a field\n\n - Example: `Band.where(name: 'Sun Down').inc(likes: 14)`\n\n- `pop`: Removes the first or last element of an array field\n\n - Example: `Band.where(name: 'Sun Down').pop(members: -1)`\n\n- `pull`: Removes all instances of a value or values that match a specified condition from an array field\n\n - Example: `Band.where(name: 'Sun Down').pull(members: 'Jonah Larsen')`\n\n- `pull_all`: Removes all instances of the specified values from an array field\n\n - Example: `Band.where(name: 'Sun Down').pull_all(:members, [ 'Jonah Larsen', 'Dan Jones' ])`\n\n- `push`: Appends a specified value to an array field\n\n - Example: `Band.where(name: 'Sun Down').push(members: 'Jonah Larsen')`\n\n- `push_all`: Appends a specified value by using the `$each` operator in an array field\n\n - Example: `Band.where(name: 'Sun Down').push_all(members: [ 'Jonah Larsen', 'Dan Jones' ])`\n\n- `rename`: Renames a field in all matching documents\n\n - Example: `Band.where(name: 'Sun Down').rename(name: :title)`\n\n- `set`: Sets a new value for a specified field in all matching documents\n\n - Example: `Band.where(name: 'Sun Down').set(likes: 10000)`\n\n- `unset`: Deletes a particular field in all matching documents\n\n - Example: `Band.where(name: 'Sun Down').unset(:likes)`\n\n### Delete Documents\n\nYou can use the following methods to delete documents based on your query criteria:\n\n- `delete`: Deletes all matching documents.\n\n - Example: `Band.where(label: 'ABC Records').delete`\n\n- `destroy`: Deletes all matching documents while running callbacks. This method loads all documents into memory.\n\n - Example: `Band.where(label: 'ABC Records').destroy`\n\n## Additional Information\n\nTo learn how to customize your persistence target, see the Persistence Configuration guide."} -{"chunk_id": "68a95c1f5e79d242619dd96e-0", "page_id": "68a95c1f5e79d242619dd96e", "source_name": "mongoid", "product_name": "Mongoid ODM", "url": "https://mongodb.com/docs/mongoid/current/interact-data/specify-query", "title": "Specify a Document Query", "text": "# Specify a Document Query\n\n## Overview\n\nIn this guide, you can learn how to specify a **query** by using Mongoid.\n\nYou can refine the set of documents that a query returns by creating a **query filter**. A query filter is an expression that specifies the search criteria MongoDB uses to match documents in a read or write operation. When creating a query filter, you can prompt the driver to search for documents with an exact match to your query, or you can compose query filters to express more complex matching criteria.\n\nMongoid provides a query domain-specific language (DSL) similar to the one used in Active Record.\n\n### Sample Data\n\nThe examples in this guide use the `Band` model, which represents a band or musical group. The definition of the `Band` model might be different for each section to demonstrate different query functionalities. Some sections might use other models to demonstrate query functionality.\n\n## Queries in Mongoid\n\nMongoid query methods return `Mongoid::Criteria` objects, which are chainable and lazily evaluated wrappers for the MongoDB Query API. The queries are executed when you iterate through the results. The following example demonstrates the return type for a simple query:\n\n```ruby\n# Creates a simple query\nBand.where(name: \"Deftones\")\n\n# Returns a Criteria object\n# => #\"Deftones\"}\n# options: {}\n# class: Band\n# embedded: false>\n\n# Evaluate the query by converting to JSON\nBand.where(name: \"Deftones\").to_json\n\n# Returns matching documents\n# => [{\"_id\":\"...\",\"name\":\"Deftones\"}]\n```\n\nYou can use methods such as `first` and `last` to return individual documents. You can also iterate a `Criteria` object by using methods such as `each` or `map` to retrieve documents from the server. You can use `to_json` to convert a `Criteria` object to JSON.\n\nIf you chain other query methods on an existing `Criteria` object, Mongoid merges the filter criteria.\n\n## Create a Query Filter\n\nThis section describes the syntax patterns that you can use to create filter criteria. You can specify queries in Mongoid by using any of the following syntax patterns:\n\n- Field syntax\n\n- Query API syntax\n\n- Symbol operator syntax\n\nThese syntaxes support querying embedded documents by using dot notation. The syntaxes also respect field aliases and field types, if the field being queried is defined in the model class.\n\nThe examples in this section use the following model definition:\n\n```ruby\nclass Band\n include Mongoid::Document\n\n field :name, type: String\n field :founded, type: Integer\n field :m, as: :member_count, type: Integer\n\n embeds_one :manager\nend\n\nclass Manager\n include Mongoid::Document\n\n embedded_in :band\n\n field :name, type: String\nend\n```\n\n### Field Syntax\n\nThe field querying syntax uses the basic Ruby hashes. The keys can be symbols or strings and correspond to field names in MongoDB documents.\n\nThe following code shows two equivalent queries that use field querying syntax to retrieve documents in which the `name` field value is `'Depeche Mode'`:\n\n```ruby\nBand.where(name: 'Depeche Mode')\nBand.where('name' => 'Depeche Mode')\n```\n\n### Query API Syntax\n\nYou can specify a Query API operator on any field by using the hash syntax, as shown by the following equivalent queries:\n\n```ruby\nBand.where(founded: {'$gt' => 1980})\nBand.where('founded' => {'$gt' => 1980})\n```\n\n### Symbol Operator Syntax\n\nYou can specify Query API operators as methods on symbols for the respective field name, as shown in the following code:\n\n```ruby\nBand.where(:founded.gt => 1980)\n```\n\n## Query on Different Field Types\n\nThis section describes how to perform queries on fields with different types of values.\n\n### Defined Fields\n\nTo query on a field, the field does not need to be in the the model class definition. However, if a field is defined in the model class, Mongoid coerces query values to match the defined field types when constructing the query.\n\nThe following code specifies a string value when querying on the `founded` field. Because the `founded` field is defined in the model class to have `Integer` values, Mongoid coerces the string `'2020'` to `2020` when performing the query:\n\n```ruby\nBand.where(founded: '2020')\n```\n\nTo learn more about defining fields in Mongoid, see the Use BSON Field Types guide.\n\n### Raw Values\n\nTo bypass Mongoid's query type coercion behavior and query directly for the raw-typed value in the database, wrap the query value in the `Mongoid::RawValue` class, as shown in the following code:\n\n```ruby\nBand.where(founded: Mongoid::RawValue('2020'))\n```\n\n### Field Aliases\n\nQueries follow the storage field names and field aliases that you might have set in your model class definition.\n\nThe `id` and `_id` fields are aliases, so you can use either field name in queries:\n\n```ruby\nBand.where(id: '5ebdeddfe1b83265a376a760')\nBand.where(_id: '5ebdeddfe1b83265a376a760')\n```\n\n### Embedded Documents\n\nTo query on values of fields of embedded documents, you can use dot notation. The following code retrieves documents in which the `name` field of the embedded `Manager` document is `'Smith'`:\n\n```ruby\nBand.where('manager.name' => 'Smith')\n```\n\nThe following code demonstrates how to use a symbol operator when querying on an embedded field:\n\n```ruby\nBand.where(:'manager.name'.ne => 'Smith')\n```\n\nQueries always return top-level model instances, even if all the conditions reference embedded document fields.\n\n## Logical Operations\n\nMongoid supports the following logical operations on `Criteria` objects:\n\n- `and`\n\n- `or`\n\n- `nor`\n\n- `not`\n\nThese methods take one or more hashes of conditions or another `Criteria` object as their arguments. The `not` operation has an argument-free version.\n\nThe following code demonstrates how to use the logical operations in queries:\n\n```ruby\n# Uses \"and\" to combine criteria\nBand.where(label: 'Trust in Trance').and(name: 'Astral Projection')\n\n# Uses \"or\" to specify criteria\nBand.where(label: 'Trust in Trance').or(Band.where(name: 'Astral Projection'))\n\n# Uses \"not\" to specify criteria\nBand.not(label: 'Trust in Trance', name: 'Astral Projection')\n\n# Uses \"not\" without arguments\nBand.not.where(label: 'Trust in Trance', name: 'Astral Projection')\n```\n\nTo ensure backwards compatibility with earlier Mongoid versions, the logical operation methods accept arrays of parameters, which are flattened to obtain the criteria.\n\nPassing arrays to logical operations is deprecated and might be removed in a future version.\n\nThe following queries produce the same conditions:\n\n```ruby\n# Conditions passed to separate \"and\" calls\nBand.and(name: 'Sun Kil Moon').and(member_count: 2)\n\n# Multiple conditions in the same \"and\" call\nBand.and({name: 'Sun Kil Moon'}, {member_count: 2})\n\n# Multiple conditions in an array - Deprecated\nBand.and([{name: 'Sun Kil Moon'}, {member_count: 2}])\n\n# Condition in \"where\" and a scope\nBand.where(name: 'Sun Kil Moon').and(Band.where(member_count: 2))\n\n# Condition in \"and\" and a scope\nBand.and({name: 'Sun Kil Moon'}, Band.where(member_count: 2))\n\n# Scope as an array element, nested arrays - Deprecated\nBand.and([Band.where(name: 'Sun Kil Moon'), [{member_count: 2}]])\n```"} -{"chunk_id": "68a95c1f5e79d242619dd96e-1", "page_id": "68a95c1f5e79d242619dd96e", "source_name": "mongoid", "product_name": "Mongoid ODM", "url": "https://mongodb.com/docs/mongoid/current/interact-data/specify-query", "title": "Specify a Document Query", "text": "### Operator Combinations\n\nThe logical operators have the the same semantics as those from Active Record.\n\nWhen conditions are specified on the same field multiple times, all conditions are added to the criteria, as shown by the queries in the following code:\n\n```ruby\n# Combines as \"and\"\nBand.where(name: 'Swans').where(name: 'Feist')\n\n# Combines as \"or\"\nBand.where(name: 'Swans').or(name: 'Feist')\n```\n\nThe `any_of`, `none_of`, `nor`, and `not` operations behave similarly.\n\nWhen you use `and`, `or`, and `nor` logical operators, they operate on the criteria built up to that point:\n\n```ruby\n# \"or\" applies to the first condition, and the second is combined\n# as \"and\"\nBand.or(name: 'Sun').where(label: 'Trust')\n\n# Same as previous example - \"where\" and \"and\" are aliases\nBand.or(name: 'Sun').and(label: 'Trust')\n\n# Same operator can be stacked any number of times\nBand.or(name: 'Sun').or(label: 'Trust')\n\n# The last label condition is added to the top level as \"and\"\nBand.where(name: 'Sun').or(label: 'Trust').where(label: 'Feist')\n# Interpreted query:\n# {\"$or\"=>[{\"name\"=>\"Sun\"}, {\"label\"=>\"Trust\"}], \"label\"=>\"Feist\"}\n```\n\n### not Behavior\n\nYou can use the `not` method without arguments, in which case it negates the next condition that is specified. The `not` method can be called with one or more hash conditions or `Criteria` objects, which are all negated and added to the criteria.\n\nThe following examples demonstrate the behavior of `not`:\n\n```ruby\n# \"not\" negates \"where\"\nBand.not.where(name: 'Best')\n\n# The second \"where\" is added as \"$and\"\nBand.not.where(name: 'Best').where(label: /Records/)\n\n# \"not\" negates its argument\nBand.not(name: 'Best')\n```\n\nYou cannot use the `$not` operator in MongoDB with a string argument. Mongoid uses the `$ne` operator to achieve negation:\n\n```ruby\n# String negation - uses \"$ne\"\nBand.not.where(name: 'Best')\n\n# Regex negation - uses \"$not\"\nBand.not.where(name: /Best/)\n```\n\nSimilarly to `and`, the `not` operation negates individual conditions for simple field criteria. For complex conditions and when a field already has a condition defined on it, Mongoid emulates `$not` by using an `{'$and' => [{'$nor' => ...}]}` construct, because MongoDB supports the `$not` operator only on a per-field basis rather than globally:\n\n```ruby\n# Simple condition\nBand.not(name: /Best/)\n\n# Complex conditions\nBand.where(name: /Best/).not(name: 'Astral Projection')\n\n# Symbol operator syntax\nBand.not(:name.ne => 'Astral Projection')\n```\n\nIf you are using `not` with arrays or regular expressions, view the limitations of `$not` in the Server manual.\n\n## Incremental Query Construction\n\nBy default, when you add conditions to a query, Mongoid considers each condition complete and independent from any other conditions present in the query. For example, calling `in` twice adds two separate `$in` conditions:\n\n```ruby\nBand.in(name: ['a']).in(name: ['b'])\n# Interpreted query:\n# {\"name\"=>{\"$in\"=>[\"a\"]}, \"$and\"=>[{\"name\"=>{\"$in\"=>[\"b\"]}}]}\n```\n\nSome operator methods support building the condition incrementally. When you add a condition which uses one of the supported operators, Mongoid sees if there already is a condition on the same field using the same operator. If so, the operator expressions are combined according to the specified *merge strategy*. The following section describes the available merge strategies.\n\n### Merge Strategies\n\nMongoid provides the following merge strategies:\n\n- **Override**: The new operator instance replaces any existing conditions on the same field by using the same operator.\n\n- **Intersect**: If there already is a condition using the same operator on the same field, the values of the existing condition are intersected with the values of the new condition and the result is stored as the operator value.\n\n- **Union**: If there already is a condition using the same operator on the same field, the values of the new condition are added to the values of the existing condition and the result is stored as the operator value.\n\nThe following code demonstrates how the merge strategies produce criteria by using `in` as the example operator:\n\n```ruby\nBand.in(name: ['a']).override.in(name: ['b'])\n# Interpreted query:\n# {\"name\"=>{\"$in\"=>[\"b\"]}}\n\nBand.in(name: ['a', 'b']).intersect.in(name: ['b', 'c'])\n# Interpreted query:\n# {\"name\"=>{\"$in\"=>[\"b\"]}}\n\nBand.in(name: ['a']).union.in(name: ['b'])\n# Interpreted query:\n# {\"name\"=>{\"$in\"=>[\"a\", \"b\"]}}\n```\n\nThe strategy is requested by calling `override`, `intersect` or `union` on a `Criteria` instance. The requested strategy applies to the next condition method called on the query. If the next condition method called does not support merge strategies, the strategy is reset, as shown in the following example:\n\n```ruby\nBand.in(name: ['a']).union.ne(name: 'c').in(name: ['b'])\n# Interpreted query:\n# {\"name\"=>{\"$in\"=>[\"a\"], \"$ne\"=>\"c\"}, \"$and\"=>[{\"name\"=>{\"$in\"=>[\"b\"]}}]}\n```\n\nBecause `ne` does not support merge strategies, the `union` strategy is ignored and reset. Then, when `in` is invoked the second time, there is no active strategy.\n\nMerge strategies assume that the previous conditions have been added to the top level of the query. However, this is not always the case, as conditions might be nested under an `$and` clause. Using merge strategies with complex criteria can generate incorrect queries.\n\n### Supported Operator Methods\n\nThe following operator methods support merge strategies:\n\n- `all`\n\n- `in`\n\n- `nin`\n\nThe set of methods might be expanded in future releases of Mongoid. To ensure future compatibility, invoke a strategy method only when the next method call is an operator that supports merge strategies.\n\nMerge strategies are applied only when conditions are added through the designated methods. In the following example, the merge strategy is not applied because the second condition is added as `where`, not by using `in`:\n\n```ruby\nBand.in(name: ['a']).union.where(name: {'$in' => 'b'})\n# Interpreted query:\n# {\"foo\"=>{\"$in\"=>[\"a\"]}, \"$and\"=>[{\"foo\"=>{\"$in\"=>\"b\"}}]}\n```\n\n### Operator Value Expansion\n\nOperator methods that support merge strategies take `Array` as their value type. Mongoid expands `Array`-compatible types, such as a `Range`, when they are used with these operator methods.\n\nThe following example demonstrates how you can pass a `Range` object as the query value when using the `in` method:\n\n```ruby\nBand.in(year: 1950..1960)\n# Interpreted query:\n# {\"year\"=>{\"$in\"=>[1950, 1951, 1952, 1953, 1954, 1955, 1956, 1957, 1958, 1959, 1960]}}\n```\n\nMongoid wraps non-`Array` values in arrays, as the shown in the following example:\n\n```ruby\nBand.in(year: 1950)\n# Interpreted query: {\"year\"=>{\"$in\"=>[1950]}}\n```\n\n## Element Match\n\nYou can use the `elem_match` method to match documents that contain an array field with at least one element that matches all the specified query criteria.\n\nThe following example creates a sample document that contains an array field. Then, it uses the `elem_match` method to match documents in which the `tour` array field contains an entry in which the `city` value is `'London'`:\n\n```ruby\naerosmith = Band.create!(name: 'Aerosmith', tours: [\n {city: 'London', year: 1995},\n {city: 'New York', year: 1999},\n])\n\nswans = Band.create!(name: 'Swans', tours: [\n {city: 'Milan', year: 2014},\n {city: 'Montreal', year: 2015},\n])\n\n# Returns only \"Aerosmith\"\nBand.elem_match(tours: {city: 'London'})\n```"} -{"chunk_id": "68a95c1f5e79d242619dd96e-2", "page_id": "68a95c1f5e79d242619dd96e", "source_name": "mongoid", "product_name": "Mongoid ODM", "url": "https://mongodb.com/docs/mongoid/current/interact-data/specify-query", "title": "Specify a Document Query", "text": "### Associations\n\nYou can use the `elem_match` method to match embedded associations.\n\nThis example uses the following models that define an embedded association between `Band` and `Tour`:\n\n```ruby\nclass Band\n include Mongoid::Document\n field :name, type: String\n embeds_many :tours\nend\n\nclass Tour\n include Mongoid::Document\n field :city, type: String\n field :year, type: Integer\n embedded_in :band\nend\n```\n\nThe following code creates a `Band` object and embedded `Tour` objects, then uses the `elem_match` method to query on the `city` field:\n\n```ruby\naerosmith = Band.create!(name: 'Aerosmith')\n\nTour.create!(band: aerosmith, city: 'London', year: 1995)\nTour.create!(band: aerosmith, city: 'New York', year: 1999)\n\n# Returns the \"Aerosmith\" document\nBand.elem_match(tours: {city: 'London'})\n```\n\nYou cannot use `elem_match` on non-embedded associations because MongoDB does not perform a join operation on the collections. If you perform this query, the conditions are added to the collection that is the source of the non-embedded association rather than the collection of the association.\n\nYou can use `elem_match` to query recursively embedded associations, as shown in the following example:\n\n```ruby\nclass Tag\n include Mongoid::Document\n\n field name:, type: String\n recursively_embeds_many\nend\n\n# Creates the root Tag\nroot = Tag.create!(name: 'root')\n\n# Adds embedded Tags\nsub1 = Tag.new(name: 'sub_tag_1', child_tags: [Tag.new(name: 'sub_sub_tag_1')])\n\nroot.child_tags << sub1\nroot.child_tags << Tag.new(name: 'sub_tag_2')\nroot.save!\n\n# Searches for Tag in which one child Tag tame is \"sub_tag_1\"\nTag.elem_match(child_tags: {name: 'sub_tag_1'})\n\n# Searches for a child Tag in which one child Tag tame is \"sub_sub_tag_1\"\nroot.child_tags.elem_match(child_tags: {name: 'sub_sub_tag_1'})\n```\n\nTo learn more about associations, see the Referenced Associations and Embedded Associations guides.\n\n## Querying by _id Value\n\nMongoid provides the `find` method, which allows you to query documents by their `_id` values.\n\nThe following example uses the `find` method to match a document with the specified `_id` field value:\n\n```ruby\nBand.find('6725342d4cb3e161059f91d7')\n```\n\nWhen you pass an ID value to the `find` method, the method converts it to the data type declared for the `_id` field in the model. By default, the `_id` field is defined as a `BSON::ObjectId` type.\n\nThe preceding example is equivalent to the following code, which passes an `BSON::ObjectId` instance as the argument to `find`:\n\n```ruby\nBand.find(BSON::ObjectId.from_string('5f0e41d92c97a64a26aabd10'))\n```\n\nIf you use the Ruby driver to query on the `_id` field, `find` does not internally perform the type conversion.\n\nThe `find` method accepts multiple arguments, or an array of arguments. Mongoid interprets each argument or array element as an `_id` value, and returns documents with all the specified `_id` values in an array, as shown in the following example:\n\n```ruby\n# Equivalent ways to match multiple documents\nBand.find('5f0e41d92c97a64a26aabd10', '5f0e41b02c97a64a26aabd0e')\nBand.find(['5f0e41d92c97a64a26aabd10', '5f0e41b02c97a64a26aabd0e'])\n```\n\nThe `find` method exhibits the following behavior:\n\n- If you provide the same `_id` value more than once, Mongoid returns only one document, if one exists.\n\n- Mongoid does not return documents in an ordered way. Documents might be returned in different order from the order of the provided `_id` values.\n\n- If any of the `_id` values are not found in the database, the result depends on the value of the `raise_not_found_error` configuration option.\n\n If you set the `raise_not_found_error` option to `true`, `find` raises a `Mongoid::Errors::DocumentNotFound` error if any of the `_id` values are not found.\n\n If you set the `raise_not_found_error` option to `false` and query for a single `_id` value, `find` returns `nil` if Mongoid does not match a document. If you pass multiple `_id` values and some or all are not matched, the return value is an array of any documents that match, or an empty array if no documents match.\n\n## find Variations\n\nThis section describes methods that are similar to the `find` method described in the preceding section.\n\nYou can use the `find_by` method to retrieve documents based on the provided criteria. If no documents are found, it raises an error or returns `nil` depending on how you set the `raise_not_found_error` configuration option.\n\nThe following code demonstrates how to use the `find_by` method:\n\n```ruby\n# Simple equality query\nBand.find_by(name: \"Photek\")\n\n# Performs an action on each returned result\nBand.find_by(name: \"Tool\") do |band|\n band.fans += 1\nend\n```\n\nYou can use the `find_or_create_by` method to retrieve documents based on the provided criteria. If no documents are found, it creates and returns an instance that is saved to MongoDB.\n\nThe following code demonstrates how to use the `find_or_create_by` method:\n\n```ruby\n# If no matches, creates a Band with just the \"name\" field\nBand.find_or_create_by(name: \"Photek\")\n\n# If no matches, creates a Band with just the \"name\" field because the\n# query condition is not a literal\nBand.where(:likes.gt => 10).find_or_create_by(name: \"Photek\")\n\n# Creates a Band in which the name is Aerosmith because there is no\n# document in which \"name\" is Photek and Aerosmith at the same time\nBand.where(name: \"Photek\").find_or_create_by(name: \"Aerosmith\")\n```\n\nYou can use the `find_or_initialize_by` method to retrieve documents based on the provided criteria. If no documents are found, it returns a new one, without persisting it to MongoDB. Use the same syntax for `find_or_initialize_by` as you do for the `find_or_create_by` method.\n\n## Regular Expressions\n\nMongoid allows you to query documents by using regular expressions in your filter criteria.\n\nThe following code creates a sample `Band` model:\n\n```ruby\nBand.create!(name: 'Tame Impala', description: \"Tame\\nImpala is an American band\")\n```\n\nYou can perform queries by using Ruby regular expressions, as shown in the following code:\n\n```ruby\n# Matches documents in which the \"name\" field includes the string \"impala\"\nBand.where(name: /impala/i)\n# => Returns sample document\n```\n\nYou can also perform queries by using Perl Compatible Regular Expression (PCRE) syntax and `BSON::Regexp::Raw` objects:\n\n```ruby\n# Matches \"description\" values that start exactly with \"Impala\"\nBand.where(description: /\\AImpala/)\n# => nil\n\n# Matches \"description\" values that start exactly with \"Impala\"\nBand.where(description: BSON::Regexp::Raw.new('^Impala'))\n# => nil\n\n# Matches \"description\" values that start exactly with \"Impala\" with\n# the multiline option\nBand.where(description: BSON::Regexp::Raw.new('^Impala', 'm'))\n# => Returns sample document\n```"} -{"chunk_id": "68a95c1f5e79d242619dd96e-3", "page_id": "68a95c1f5e79d242619dd96e", "source_name": "mongoid", "product_name": "Mongoid ODM", "url": "https://mongodb.com/docs/mongoid/current/interact-data/specify-query", "title": "Specify a Document Query", "text": "## Field Type Query Conversions\n\nWhen you specify a query on a field defined in a model, if the field has a *specified data type*, Mongoid converts the query value based on how the field is defined.\n\nConsider the following `Album` model definition that contains a `Date`-valued field, a `Time`-valued field, and an implicit `Object`-valued field. The model also intentionally *does not define* a field named `last_reviewed`:\n\n```ruby\nclass Album\n include Mongoid::Document\n\n field :release_date, type: Date\n field :last_commented, type: Time\n field :last_purchased\nend\n```\n\nYou can query on the `release_date` and `last_commented` fields by using `Date` and `Time` values, as shown in the following code:\n\n```ruby\nAlbum.where(release_date: Date.today)\n# Interpreted query:\n# {\"release_date\"=>2024-11-05 00:00:00 UTC}\n\nAlbum.where(last_commented: Time.now)\n# Interpreted query:\n# {\"last_commented\"=>2024-11-04 17:20:47.329472 UTC}\n```\n\nHowever, if you query by using only `Date` values on fields defined as other types, the generated queries display the default conversion behavior, as shown in the following example:\n\n```ruby\nAlbum.where(last_commented: Date.today)\n# Interpreted query:\n# {\"last_commented\"=>Mon, 04 Nov 2024 00:00:00.000000000 EST -05:00}\n\nAlbum.where(last_purchased: Date.today)\n# Interpreted query:\n# {\"last_purchased\"=>\"2024-11-04\"}\n\nAlbum.where(last_reviewed: Date.today)\n# Interpreted query:\n# {\"last_reviewed\"=>2024-11-04 00:00:00 UTC}\n```\n\nIn the preceding example, the following conversions apply:\n\n- When using a `Date` value to query the `Time`-valued `last_commented` field, Mongoid interprets the date to be in local time and applies the configured time zone.\n\n- When querying on the `last_purchased` field, which has no explicit type, the date is used unmodified in the constructed query.\n\n- When querying on the undefined `last_reviewed` field, Mongoid interprets the `Date` to be in UTC and converts to a time, matching the behavior of querying a `Date`-valued field such as `release_date`.\n\n## Additional Query Methods\n\nThis section describes more query methods that you can use in Mongoid.\n\n### Count Documents\n\nYou can use the `count` and `estimated_count` methods to count the number of documents in a collection.\n\nYou can count the number of documents that match filter criteria by using the `count` method:\n\n```ruby\n# Counts all documents in collection\nBand.count\n\n# Counts documents that match criteria\nBand.where(country: 'England').count\n```\n\nYou can also use the `length` or `size` method to count documents. These methods cache subsequent calls to the database, which might produce performance improvements.\n\nYou can get an approximate number of documents in the collection from the collection metadata by using the `estimated_count` method:\n\n```ruby\nBand.estimated_count\n```\n\nThe `estimated_count` method does not accept query conditions, including conditions set by a scope on the model. If you are calling this method on a model that has a default scope, you must first call the `unscoped` method to disable the scope.\n\n### Ordinal Methods\n\nThe methods described in the following list allow you to select a specific result from the list of returned documents based on its position.\n\n- `first`: Returns the first matching document. You can get the first `n` documents by passing an integer-valued parameter. This method automatically uses a sort on the `_id` field. *See lines 1-8 in the following code for examples.*\n\n- `last`: Returns the last matching document. You can get the last `n` documents by passing an integer-valued parameter. This method automatically uses a sort on the `_id` field. *See line 11 in the following code for an example.*\n\n- `first_or_create`: Returns the first matching document. If no document matches, creates and returns a newly saved one.\n\n- `first_or_initialize`: Returns the first matching document. If no document matches, returns a new one.\n\n- `second`: Returns the second matching document. Automatically uses a sort on the `_id` field.\n\n- `third`: Returns the third matching document. Automatically uses a sort on the `_id` field.\n\n- `fourth`: Returns the fourth matching document. Automatically uses a sort on the `_id` field.\n\n- `fifth`: Returns the fifth matching document. Automatically uses a sort on the `_id` field.\n\n- `second_to_last`: Returns the second-to-last matching document. Automatically uses a sort on the `_id` field. *See line 14 in the following code for an example.*\n\n- `third_to_last`: Returns the third-to-last matching document. Automatically uses a sort on the `_id` field.\n\nThe following code demonstrates how to use some methods described in the preceding list:\n\n```ruby\n# Returns the first document in the collection\nBand.first\n\n# Returns the first matching document\nBand.where(founded: {'$gt' => 1980}).first\n\n# Returns the first two matching documents\nBand.first(2)\n\n# Returns the last matching document\nBand.where(founded: {'$gt' => 1980}).last\n\n# Returns the second to last document\nBand.second_to_last\n```\n\nEach method described in this section has a variation that is suffixed with `!` that returns an error if Mongoid doesn't match any documents. For example, to implement error handling in your application when your query returns no results, use the `first!` method instead of `first`.\n\n### Survey Field Values\n\nTo inspect the values of specified fields of documents in a collection, you can use the following methods:\n\n- `distinct`: Gets a list of distinct values for a single field. *See lines 1-7 in the following code for examples.*\n\n- `pick`: Gets the values from one document for the provided fields. Returns `nil` for unset fields and for non-existent fields. *See line 10 in the following code for an example.*\n\n- `pluck`: Gets all values for the provided field. Returns `nil` for unset fields and for non-existent fields. *See line 13 in the following code for an example.*\n\n- `tally`: Gets a mapping of values to counts for the specified field. *See line 16 in the following code for an example.*\n\nThe preceding methods accept field names referenced by using dot notation, which allows you to reference fields in embedded associations. They also respect field aliases, including those defined in embedded documents.\n\nThe following code demonstrates how to use these methods:\n\n```ruby\nBand.distinct(:name)\n# Example output: \"Ghost Mountain\" \"Hello Goodbye\" \"She Said\"\n\nBand.where(:members.gt => 2).distinct(:name)\n# Example output: \"Arctic Monkeys\" \"The Smiths\"\n\nBand.distinct('tours.city')\n# Example output: \"London\" \"Sydney\" \"Amsterdam\"\n\nBand.all.pick(:name)\n# Example output: \"The Smiths\"\n\nBand.all.pluck(:country)\n# Example output: \"England\" \"Spain\" \"England\" \"Japan\"\n\nBand.all.tally(:country)\n# Example output: [\"England\",2] [\"Italy\",3]\n```\n\n### Miscellaneous\n\nThe following list describes Mongoid methods that do not fit into another category:\n\n- `each`: Iterates over all matching documents.\n\n```ruby\n# Print each matching document \"name\" to console\nBand.where(:members.gt => 1).each do |band|\n p band.name\nend\n```\n\n- `exists?`: Determines if any matching documents exist, returning `true` if at least one matching document is found.\n\n```ruby\n# Checks existence of any document\nBand.exists?\n\n# Checks existence based on query\nBand.where(name: \"Le Tigre\").exists?\nBand.exists?(name: \"Le Tigre\")\n\n# Checks existence based on \"_id\" value\nBand.exists?('6320d96a3282a48cfce9e72c')\n\n# Always returns false\nBand.exists?(false)\nBand.exists?(nil)\n```\n\n## Additional Information\n\nTo learn how to modify the way that Mongoid returns results to you, see Modify Query Results.\n\nTo learn more about defining scopes on your models, see Scoping.\n\nTo learn about methods that you can chain to your queries to persist data, see Persist Data from Queries.\n\nTo learn about the query cache feature, see Query Cache.\n\nTo learn about performing asynchronous queries, see Asynchronous Queries."} -{"chunk_id": "68a95c1f5e79d242619dd96f-0", "page_id": "68a95c1f5e79d242619dd96f", "source_name": "mongoid", "product_name": "Mongoid ODM", "url": "https://mongodb.com/docs/mongoid/current/interact-data/text-search", "title": "Run a Text Query", "text": "# Run a Text Query\n\n## Overview\n\nIn this guide, you can learn how to use Mongoid to run a **text search**. A text query allows you to efficiently query fields that have string values.\n\nMongoDB provides text indexes to support text queries on fields that have string values or values that are arrays of string elements. To learn more about text indexes, see Text Indexes on Self-Managed Deployments in the Server manual.\n\nThis guide focuses on text queries. If your database is hosted on MongoDB Atlas, you can use the MongoDB Search feature to perform more powerful and flexible full-text searches. To learn more about MongoDB Search, see the MongoDB Search Overview in the Atlas documentation.\n\nYou can run a text query by performing the following steps:\n\n1. Define a text index on a model.\n\n2. Create the text index on the target collection.\n\n3. Perform a text query.\n\nThe following sections describe how to perform each of these actions.\n\n## Define a Text Index on Your Model\n\nUse the `index` macro to specify the text index in your model definition. The following code creates a `Dish` model class that includes a text index on the `description` field:\n\n```ruby\nclass Dish\n include Mongoid::Document\n\n field :name, type: String\n field :description, type: String\n\n index description: 'text'\nend\n```\n\nYou must specify the index type as a string, as shown by `'text'` in the preceding code.\n\n## Create the Text Index\n\nNext, you must create the text index in your collection. You can create the index by using an interface such as the Atlas UI or Compass. If you are using the Rails framework to develop your application, you can run the following Rake task to create the index based on your model specification:\n\n```bash\nbundle exec rake db:mongoid:create_indexes\n```\n\nTo learn more about using indexes with Mongoid, see the Indexes for Query Optimization guide.\n\n## Perform Text Queries\n\nTo perform a text query, use the `$text` evaluation query operator, followed by the `$search` field in your query filter. The `$text` operator performs a text query on the text indexed fields. The `$search` field specifies the text to search in the text indexed fields. To learn more about this operator, see the $text reference in the Server manual.\n\n### Search by a Term\n\nTo search for a term, specify the term as a string in your query filter. To search for multiple terms, separate each term with spaces in the string.\n\nWhen searching for multiple terms, Mongoid returns documents with at least one of the terms in text indexed fields.\n\nSuppose you search by using the string `'cake coffee cream'`. The following list describes values that match this text query:\n\n- `'Has strong coffee notes.'`\n\n- `'Good for creamy coffee fans.'`\n\n- `'A rich but light cake.'`\n\n- `'A creamy coffee cake with cranberries.'`\n\nThe following example runs a text query for `description` values that contain the term `'herb'`:\n\n```rust\nDish.where('$text' => {'$search' => 'herb'})\n```\n\n```none\n# Sample output\n{\"_id\":\"...\",\"description\":\"A bright, herb-based salad. A perfect starter for vegetarians and vegans.\",\"name\":\"Kale Tabbouleh\"}\n{\"_id\":\"...\",\"description\":\"Grilled whole fish stuffed with herbs and pomegranate seeds. Serves 3-4.\",\"name\":\"Herbed Whole Branzino\"}\n```\n\nAlthough the search term was `'herb'`, the method also matches descriptions containing `'herbs'` because a MongoDB text index uses *suffix stemming* to match similar words. To learn more about how MongoDB matches terms, see Text Index Properties in the {+server-manual}.\n\n### Search by a Phrase\n\nTo search for a phrase, specify the phrase with escaped quotes as a string in your query filter. If you don't add escaped quotes around the phrase, Mongoid runs a term search.\n\nEscaped quotes are a backslash character (`\\`) followed by a double quote character (`\"`).\n\nThe following example runs a text query for `description` values that contain the phrase `\"serves 2\"`:\n\n```rust\nDish.where('$text' => {'$search' => \"\\\"serves 2\\\"\"})\n```\n\n```none\n# Sample output\n{\"_id\":\"...\",\"description\":\"A vegetarian take on the classic dish that uses lentils as a base. Serves 2.\",\"name\":\"Shepherd\u2019s Pie\"}\n{\"_id\":\"...\",\"description\":\"Baked trout seasoned with garlic, lemon, dill, and, of course, butter. Serves 2.\",\"name\":\"Garlic Butter Trout\"}\n```\n\n### Search with Excluded Terms\n\nFor each term or phrase to exclude from your text query, specify the term or phrase prefixed with a minus sign (`-`) as a string in your query filter.\n\nYou must search for at least one term to exclude terms from your search. If you don't search for any terms, Mongoid doesn't return any documents.\n\nThe following example runs a text query for `description` values that contain the term `'vegan'`, but do not contain the term `'tofu'`:\n\n```rust\nDish.where('$text' => {'$search' => 'vegan -tofu'})\n```\n\n```none\n# Sample output\n{\"_id\":\"...\",\"description\":\"A bright, herb-based salad. A perfect starter for vegetarians and vegans.\",\"name\":\"Kale Tabbouleh\"}\n```\n\n## Additional Information\n\nTo learn more about constructing query filters, see Specify a Document Query.\n\nTo learn more about performing CRUD operations, see the CRUD Operations guide."} -{"chunk_id": "68a95c1f5e79d242619dd91e-0", "page_id": "68a95c1f5e79d242619dd91e", "source_name": "mongoid", "product_name": "Mongoid ODM", "url": "https://mongodb.com/docs/mongoid/current/data-modeling/documents", "title": "Use the Document Module in Your Model", "text": "# Use the Document Module in Your Model\n\n## Overview\n\nIn this guide, you can learn about the `Mongoid::Document` module in Mongoid. The `Document` module is a Ruby implementation of a MongoDB document, which stores data in field-and-value pairs. To learn more about the terminology, structure, and limitations of MongoDB documents, see Documents in the Server manual.\n\nYou must include the `Mongoid::Document` module in any class that you want to persist to MongoDB. By including the `Document` module in your model class, you can use its methods on instances of your model class.\n\nThe following code demonstrates how to include the `Document` module in a sample `Person` model class:\n\n```ruby\nclass Person\n include Mongoid::Document\n\n field :name, type: String\nend\n```\n\nYou can find more information about the `Document` module in the API documentation.\n\n## Work with Documents\n\nYou can store instances of your models directly in a collection, or you can embed them in other classes that use the `Document` module. When you save a `Document` instance to MongoDB, it is converted to a BSON object that is similar to a Ruby hash or JSON object.\n\nThe following code creates an instance of the `Person` model defined in the preceding section:\n\n```ruby\nPerson.create(name: 'Meena Kumar')\n```\n\nThe document appears in MongoDB as follows:\n\n```json\n{\n \"_id\": {\n \"$oid\": \"673b6dce61700598c24a72b0\"\n },\n \"name\": \"Meena Kumar\"\n}\n```\n\nWhen you persist an instance of a model to the database, MongoDB automatically adds an `_id` field that has a unique value even if you do not explicitly define this field in your model.\n\nTo learn more about this field, see the ObjectId reference in the Server manual.\n\n## Additional Information\n\nTo learn more about the field types that you can use in Mongoid models, see the Use BSON Field Types guide.\n\nTo learn how to access and change your MongoDB data, see CRUD Operations."} -{"chunk_id": "68a95c1f5e79d242619dd9a8-0", "page_id": "68a95c1f5e79d242619dd9a8", "source_name": "mongoid", "product_name": "Mongoid ODM", "url": "https://mongodb.com/docs/mongoid/current/reference/release-notes", "title": "Release Notes", "text": "# Release Notes\n\nLearn what's new in:\n\n- Version 9.1.1\n\n- Version 9.1\n\n- Version 9.0.12\n\n- Version 9.0.11\n\n- Version 9.0.7\n\n- Version 9.0\n\nTo view a list of releases and detailed release notes, see Mongoid Releases on GitHub.\n\n## What's New in 9.1.1\n\nThe 9.1.1 release includes the following changes:\n\nMongoid v9.1.1 includes fixes for the following security issues:\n\n- CVE-2026-93758\n\n- CVE-2026-93759\n\n- CVE-2026-93760\n\n- CVE-2026-93761\n\n- CVE-2026-93762\n\n- CVE-2026-93763\n\n- CVE-2026-93764\n\n- CVE-2026-93765\n\nFor the latest information about MongoDB security updates, see MongoDB Security Bulletins.\n\nFor more information about this release, see the v9.1.1 release notes on GitHub.\n\n## What's New in 9.1\n\nThe 9.1 release includes the following new features, improvements, and fixes:\n\n- Adds the `Criteria#raw` method that allows you to retrieve results as raw hashes. To learn more, see the Return Raw Data section of the Modify Query Results guide.\n\n- Improves caching functionality by modifying the behavior of `cache_key` to *not* embed a timestamp when `cache_version` returns a non-nil value. Instead, the timestamp is used as the version for the entry to reduce key churn.\n\n This change also adds the `cache_version` method to the `Mongoid::Document` module. If the cache key format introduced in this version poses an issue in your application, you can revert to the original format by defining the `cache_version` method as `nil`:\n\n ```ruby\n module Mongoid\n module Document\n def cache_version = nil\n end\n end\n ```\n\n- Updates the `serializable_hash` method to include a new `Mongoid::Config.serializable_hash_with_legacy_only` option, which defaults to `true`. When this option is enabled, the Ruby driver uses the pre-existing legacy `serializable_hash` behavior. This behavior returns all keys when you pass an empty array for the `:only` option. Mongoid will deprecate this legacy behavior in v10.0.\n\n- Adds the `Mongoid.isolation_level` property, which allows you to configure the default isolation level for concurrent operations. The default isolation level is `:rails`, which inherits the isolation level from `ActiveSupport::IsolatedExecutionState`. You can also specify the `:thread` option for the pre-existing thread-local isolation level functionality or the `:fiber` option to inherit the internal state from any parent fiber.\n\n- Adds the `any?`, `one?`, and `many?` enumerable methods to the `Criteria` class and delegates them to `scoped` at the class level. These methods use the MongoDB `count` function rather than loading documents into memory, which improves performance when documents have not already been fetched. The following example shows how to use these methods:\n\n ```ruby\n User.any? # Returns true if any user documents exist\n User.one? # Returns true if exactly one user document exists in the criteria\n User.many? # Returns true if more than one user document exists in the criteria\n ```\n\n- Adds the `Criteria#to_mql` method, which returns the MongoDB Query Language (MQL) representation of a query. Use this method to inspect the queries that Mongoid generates. The following example returns the MQL for a `Person` query:\n\n ```ruby\n Person.where(age: { '$gt' => 18 }).to_mql\n ```\n\n- Adds the `Criteria#eager_load` method for loading associations using an aggregation pipeline. Unlike `includes`, `eager_load` issues a single query to the database. This method performs better on `has_many` and `has_and_belongs_to_many` associations and on queries that join multiple `belongs_to` or `has_one` associations. If you use `eager_load` on an embedded association, Mongoid falls back to `includes`. The following example eager-loads the `employer` and `partner` associations for active persons:\n\n ```ruby\n Person.where(active: true).eager_load(:employer, :partner)\n ```\n\n- Adds MongoDB Vector Search support. Define a MongoDB Vector Search index by using the `vector_field` macro or the `vector_search_index` method, and then call `vector_search` to query for semantically similar documents. To learn more, see the MongoDB Vector Search overview and the MongoDB Vector Search guide. The following example defines a MongoDB Vector Search index on an `Article` model and queries for similar documents:\n\n ```ruby\n class Article\n include Mongoid::Document\n\n vector_field :embedding, dimensions: 1536\n end\n\n articles = Article.vector_search(query_vector, limit: 5)\n ```\n\n- Adds the `auto_embed_field` macro, which enables auto-embedding in MongoDB Vector Search support. Mongoid uses the configured embedding model to automatically index the field. To learn more, see MongoDB Vector Search Quick Start in the MongoDB Vector Search documentation. The following example defines an auto-embedding field and queries for similar articles:\n\n ```ruby\n class Article\n include Mongoid::Document\n\n auto_embed_field :body\n end\n\n articles = Article.auto_embed_search('machine learning', limit: 5)\n ```\n\n- Adds support for specifying the associated document type when calling `build_` or `create_` on `embeds_one`, `has_one`, and `belongs_to` associations. The following example builds a `HeadlessRunner` for a `Job` association:\n\n ```ruby\n job = Job.create\n job.build_runner({ name: 'My Runner' }, HeadlessRunner)\n ```\n\n- Adds the `Mongoid.allow_short_circuit_queries` configuration option. When set to `true`, a top-level `$in` condition with an empty array returns an empty result without querying the database. This option defaults to `false`. The following example enables the option:\n\n ```ruby\n Mongoid.allow_short_circuit_queries = true\n Document.in(ids: []) # Returns [], no database query issued\n ```\n\n- Updates duplicate index declaration behavior. Mongoid now ignores index declarations that differ only in their options, including the index name. To allow near-identical index declarations to be sent to the server, set `Mongoid.allow_duplicate_index_declarations = true`.\n\n- Deprecates the `Criteria#max_scan` method.\n\n- Changes the default of `Mongoid::Config.allow_reparenting_via_nested_attributes` to `false`. Set this option to `true` to restore the earlier behavior. This option will be removed in Mongoid v10.\n\n- Changes the default of `Mongoid.autosave_saves_unchanged_documents` to `false`. Set this option to `true` to restore the earlier behavior. This option will be removed in Mongoid v10.\n\n## What's New in 9.0.12\n\nThe 9.0.12 release includes the following changes:\n\nMongoid v9.0.12 includes fixes for the following security issues:\n\n- CVE-2026-93758\n\n- CVE-2026-93759\n\n- CVE-2026-93760\n\n- CVE-2026-93761\n\n- CVE-2026-93762\n\n- CVE-2026-93763\n\n- CVE-2026-93764\n\n- CVE-2026-93765\n\nFor the latest information about MongoDB security updates, see MongoDB Security Bulletins.\n\nFor more information about this release, see the v9.0.12 release notes on GitHub.\n\n## What's New in 9.0.11\n\nThe 9.0.11 release includes the following new features:\n\n### `allow_reparenting_via_nested_attributes` Configuration\n\nMongoid v9.0.11 introduces the `Mongoid::Config.allow_reparenting_via_nested_attributes` configuration option. This option controls whether dependent `has_many` records can be reparented through nested attributes.\n\nThe option defaults to `true`, preserving the legacy behavior. To prevent reparenting through nested attributes, set this option to `false`:\n\n```ruby\nMongoid::Config.allow_reparenting_via_nested_attributes = false\n```\n\nIn Mongoid v9.1, this option will default to `false`. The option will be removed in Mongoid v10."} -{"chunk_id": "68a95c1f5e79d242619dd9a8-1", "page_id": "68a95c1f5e79d242619dd9a8", "source_name": "mongoid", "product_name": "Mongoid ODM", "url": "https://mongodb.com/docs/mongoid/current/reference/release-notes", "title": "Release Notes", "text": "### Autosave Behavior for Unchanged Subtrees\n\nMongoid v9.0.11 introduces the `Mongoid.autosave_saves_unchanged_documents` configuration option. This option controls whether Mongoid autosaves all documents in an association subtree when any document in the subtree has `autosave: true`.\n\nIn earlier Mongoid versions, associations with `autosave: true` caused Mongoid to invoke `#save` on all child documents and recursively invoke all corresponding `after_save` hooks, regardless of whether those documents had changed.\n\nThe option defaults to `true`, preserving the legacy behavior. To autosave only subtrees that contain changed documents, set this option to `false`:\n\n```ruby\nMongoid.autosave_saves_unchanged_documents = false\n```\n\nIn Mongoid v9.1, this option will default to `false`. The option will be removed in Mongoid v10.\n\n### Support for Ruby 4.0\n\nMongoid v9.0.11 adds official support for Ruby 4.0.\n\n## What's New in 9.0.7\n\nThe 9.0.7 release includes breaking changes.\n\nThe 9.0.7 release includes the following changes:\n\n- A previous Mongoid version fixed a bug where child callbacks that depended on parent state were no longer invoked if the child had not changed. Because the fix introduced a performance regression, this patch version restores the earlier functionality. Child callbacks are now invoked only if the child itself has changed. This introduces breaking changes for apps that depend on callbacks being invoked on unmodified children (for example, when a child callback depends on the parent having changed state).\n\n The following code sample shows how to invoke child callbacks in response to parent changes:\n\n ```ruby\n class Parent\n include Mongoid::Document\n has_many :children\n after_save { children.each(&:parent_changed_callback) }\n end\n\n class Child\n include Mongoid::Document\n belongs_to :parent\n\n def parent_changed_callback\n # ...\n end\n end\n ```\n\n## What's New in 9.0\n\nThe 9.0 release includes the following new features, improvements, and fixes:\n\n### Railsmdb\n\nAlongside the release of Mongoid v9.0, `railsmdb`, a command-line utility for creating, updating, managing, and maintaining Rails applications, is generally available.\n\n`railsmdb` makes it easier to work with MongoDB from the command line through common generators that Ruby on Rails developers are already familiar with.\n\nFor example, you can use `railsmdb` to generate stubs for new Mongoid models:\n\n```sh\nbin/railsmdb generate model person\n```\n\nThis will create a new model at `app/models/person.rb`:\n\n```ruby\nclass Person\n include Mongoid::Document\n include Mongoid::Timestamp\nend\n```\n\nYou can specify the fields of the model:\n\n```sh\nbin/railsmdb generate model person name:string birth:date\n```\n\n```ruby\nclass Person\n include Mongoid::Document\n include Mongoid::Timestamp\n field :name, type: String\n field :birth, type: Date\nend\n```\n\nYou can instruct the generator to make the new model a subclass of another, by passing the `--parent` option:\n\n```sh\nbin/railsmdb generate model student --parent=person\n```\n\n```ruby\nclass Student < Person\n include Mongoid::Timestamp\nend\n```\n\nIf you need to store your models in a different collection than can be inferred from the model name, you can specify `--collection`:\n\n```sh\nbin/railsmdb generate model course --collection=classes\n```\n\n```ruby\nclass Course\n include Mongoid::Document\n include Mongoid::Timestamp\n store_in collection: 'classes'\nend\n```\n\nFor more information see the mongoid-railsmdb repository on GitHub.\n\n### Removal of Support for Ruby 2.6 and JRuby 9.3\n\nMongoid v9.0 requires Ruby 2.7 or newer or JRuby 9.4. Earlier Ruby and JRuby versions are not supported.\n\n### Removal of Support for Rails 5\n\nMongoid v9.0 requires Rails 6.0 or newer. Earlier Rails versions are not supported.\n\n### Removal of Deprecated Class `Mongoid::Errors::InvalidStorageParent`\n\nThe deprecated class `Mongoid::Errors::InvalidStorageParent` has been removed.\n\n### `around_*` Callbacks for Embedded Documents are Ignored by Default\n\nMongoid v8.x and older allows users to define `around_*` callbacks for embedded documents. Starting in v9.0, by default these callbacks are ignored and will not be executed. A warning will be printed to the console if such callbacks are defined.\n\nIf you want to restore the old behavior, you can set `Mongoid.around_callbacks_for_embeds` to `true` in your application.\n\nEnabling `around_*` callbacks for embedded documents is not recommended as it may cause `SystemStackError` exceptions when a document has many embedded documents. See MONGOID-5658 for more details.\n\n### `for_js` Method is Deprecated\n\nThe `for_js` method is deprecated and will be removed in Mongoid v10.0.\n\n### Removal of Deprecated Options\n\n**Breaking change:** The following config options are removed in Mongoid v9.0. Please ensure you have removed all references to these from your app. If you were using `config.load_defaults 8.1` before upgrading, you will not experience any behavior change. Refer to earlier release notes for the meaning of each option.\n\n- `:use_activesupport_time_zone`\n\n- `:broken_aggregables`\n\n- `:broken_alias_handling`\n\n- `:broken_and`\n\n- `:broken_scoping`\n\n- `:broken_updates`\n\n- `:compare_time_by_ms`\n\n- `:legacy_attributes`\n\n- `:legacy_pluck_distinct`\n\n- `:legacy_triple_equals`\n\n- `:object_id_as_json_oid`\n\n- `:overwrite_chained_operators`\n\nIn addition, support for `config.load_defaults` versions v7.5 and prior has been dropped (you must use a minimum of version v8.0.)\n\n### Removal of Deprecated Functionality\n\n**Breaking change:** The following deprecated functionality is now removed:\n\n- The `Mongoid::QueryCache` module has been removed. Please replace any usages 1-for-1 with `Mongo::QueryCache`. The method `Mongoid::QueryCache#clear_cache` should be replaced with `Mongo::QueryCache#clear`. All other methods and submodules are identically named.\n\n- `Object#blank_criteria?` method is removed (previously deprecated).\n\n- `Document#as_json :compact` option is removed. Please call ``#compact` on the returned `Hash` object instead.\n\n- The deprecated class `Mongoid::Errors::InvalidStorageParent` has been removed.\n\n### Get and Set Thread-Local Variables\n\nYou can use the Mongoid::Threaded.get and Mongoid::Threaded.set methods to query and modify thread-local variables. To learn when to use these methods, see the Thread-Local Variables section of the Callbacks guide.\n\n### Index Verification Configuration\n\nYou can use the `Mongoid.allow_duplicate_index_declarations` configuration option to send index verification to the server. If a duplicate index is declared, the server raises an error. To learn more, see the Configuration Options section of the Application Configuration guide.\n\n### `touch` Method Clears Changed State\n\nIn Mongoid v8.x and older, the `touch` method leaves models in the changed state:\n\n```ruby\n# v8.x behaviour\nband = Band.create!\nband.touch\nband.changed? # => true\nband.changes\n# => {\"updated_at\"=>[2023-01-30 13:12:57.477191135 UTC, 2023-01-30 13:13:11.482975646 UTC]}\n```\n\nStarting in v9.0, Mongoid now correctly clears changed state after using the `touch` method.\n\n```ruby\n# v9.0 behavior\nband = Band.create!\nband.touch\nband.changed? # => false\nband.changes # => {}\n```\n\n### Sandbox Mode for Rails Console\n\nMongoid now supports Rails console sandbox mode. If the Rails console started with `--sandbox` flag, Mongoid starts a transaction on the `:default` client before opening the console. This transaction won't be committed. Therefore, all the commands executed in the console using the `:default` client won't be persisted in the database.\n\nIf you execute commands in the sandbox mode *using any other client than default*, these changes will be persisted as usual."} -{"chunk_id": "68a95c1f5e79d242619dd9a8-2", "page_id": "68a95c1f5e79d242619dd9a8", "source_name": "mongoid", "product_name": "Mongoid ODM", "url": "https://mongodb.com/docs/mongoid/current/reference/release-notes", "title": "Release Notes", "text": "### New Transactions API\n\nMongoid 9.0 introduces new transactions API that is inspired by Active Record:\n\n```ruby\nBand.transaction do\n Band.create(title: 'Led Zeppelin')\nend\n\nband = Band.create(title: 'Deep Purple')\nband.transaction do\n band.active = false\n band.save!\nend\n```\n\nTo learn more, see the Transactions and Sessions guide.\n\n### Embedded Documents Always Use Parent Persistence Context\n\nMongoid v8.x and older allow user to specify persistence context for an embedded document (using `store_in` macro). In Mongoid v9.0 these settings are ignored for embedded documents. An embedded document now always uses the persistence context of its parent.\n\n### Support for Passing Raw Values into Queries\n\nWhen performing queries, it is now possible to skip Mongoid's type coercion logic by using the `Mongoid::RawValue` wrapper class. This can be useful when legacy data in the database is of a different type than the field definition.\n\n```ruby\nclass Person\n include Mongoid::Document\n field :age, type: Integer\nend\n\n# Query for the string \"42\", not the integer 42\nPerson.where(age: Mongoid::RawValue(\"42\"))\n```\n\n### Raise `AttributeNotLoaded` Error When Accessing Fields Omitted from Query Projection\n\nWhen attempting to access a field on a model instance which was excluded with the `only` or `without` query projections methods when the instance was loaded, Mongoid will now raise a `Mongoid::Errors::AttributeNotLoaded` error.\n\n```ruby\nBand.only(:name).first.label\n#=> raises Mongoid::Errors::AttributeNotLoaded\n\nBand.without(:label).first.label = 'Sub Pop Records'\n#=> raises Mongoid::Errors::AttributeNotLoaded\n```\n\nIn earlier Mongoid versions, the same conditions would raise an `ActiveModel::MissingAttributeError`. Please check your code for any Mongoid-specific usages of this class, and change them to `Mongoid::Errors::AttributeNotLoaded`. Note additionally that `AttributeNotLoaded` inherits from `Mongoid::Errors::MongoidError`, while `ActiveModel::MissingAttributeError` does not.\n\n### Use Configured Time Zone to Typecast `Date` to `Time` in Queries\n\nWhen querying for a Time field using a Date value, Mongoid now correctly considers `Time.zone` to perform type conversion.\n\n```ruby\nclass Magazine\n include Mongoid::Document\n\n field :published_at, type: Time\nend\n\nTime.zone = 'Asia/Tokyo'\n\nMagazine.gte(published_at: Date.parse('2022-09-26'))\n#=> will return all results on or after Sept 26th, 2022\n# at 0:00 in Asia/Tokyo time zone.\n```\n\nIn prior Mongoid versions, the above code would ignore the `Time.zone` (irrespective of the now-removed `:use_activesupport_time_zone` setting) and would always use the system time zone to perform the type conversion.\n\nNote that in prior Mongoid versions, typecasting `Date` to `Time` during persistence operations was already correctly using time zone.\n\n### `touch` Method on Embedded Documents Correctly Handles `touch: false` Option\n\nWhen the `touch: false` option is set on an `embedded_in` relation, calling the `touch` method on an embedded child document will not invoke `touch` on its parent document.\n\n```ruby\nclass Address\n include Mongoid::Document\n include Mongoid::Timestamps\n\n embedded_in :mall, touch: false\nend\n\nclass Mall\n include Mongoid::Document\n include Mongoid::Timestamps\n\n embeds_many :addresses\nend\n\nmall = Mall.create!\naddress = mall.addresses.create!\n\naddress.touch\n#=> updates address.updated_at but not mall.updated_at\n```\n\nIn addition, the `touch` method has been optimized to perform one persistence operation per parent document, even when using multiple levels of nested embedded documents.\n\n### `embedded_in` Associations Default to `touch: true`\n\nUpdating an embedded sub-document will now automatically touch the parent, unless you explicitly set `touch: false` on the relation:\n\n```ruby\nclass Address\n include Mongoid::Document\n include Mongoid::Timestamps\n\n embedded_in :mall, touch: false\nend\n```\n\nFor all other associations, the default remains `touch: false`.\n\n### Flipped Default for `:replace` Option in `upsert`\n\nMongoid v8.1 added the `:replace` option to the `upsert` method. This option was used to specify whether or not the existing document should be updated or replaced.\n\nMongoid v9.0 flips the default of this flag from `true` to `false`. This means that, by default, Mongoid v9.0 updates the existing document and does not replace it.\n\n### Immutability of the `_id` Field Enforced\n\nBefore Mongoid v9.0, mutating the `_id` field behaved inconsistently depending on whether the document was top-level or embedded, and depending on how the update was performed. In v9.0, changing the `_id` field will now raise an exception when the document is saved, if the document had been previously persisted.\n\nMongoid 9.0 also introduces a new feature flag, `immutable_ids`, which defaults to `true`.\n\n```ruby\nMongoid::Config.immutable_ids = true\n```\n\nWhen set to `false`, the older, inconsistent behavior is restored.\n\n### Support for Field Aliases on Index Options\n\nSupport has been added to use aliased field names in the following options of the `index` macro: `partial_filter_expression`, `weights`, `wildcard_projection`.\n\n```ruby\nclass Person\n include Mongoid::Document\n field :a, as: :age\n index({ age: 1 }, { partial_filter_expression: { age: { '$gte' => 20 } })\nend\n```\n\nThe expansion of field name aliases in index options such as `partial_filter_expression` is performed according to the behavior of MongoDB server 6.0. Future server versions may change how they interpret these options, and Mongoid's functionality may not support such changes.\n\n### BSON 5 and `BSON::Decimal128` Fields\n\nWhen BSON 4 or earlier is present, any field declared as `BSON::Decimal128` will return a `BSON::Decimal128` value. When BSON 5 is present, however, any field declared as `BSON::Decimal128` will return a `BigDecimal` value by default.\n\n```ruby\nclass Model\n include Mongoid::Document\n\n field :decimal_field, type: BSON::Decimal128\nend\n\n# under BSON <= 4\nModel.first.decimal_field.class #=> BSON::Decimal128\n\n# under BSON >= 5\nModel.first.decimal_field.class #=> BigDecimal\n```\n\nIf you need literal `BSON::Decimal128` values with BSON 5, you may instruct Mongoid to allow literal `BSON::Decimal128` fields:\n\n```ruby\nModel.first.decimal_field.class #=> BigDecimal\n\nMongoid.allow_bson5_decimal128 = true\nModel.first.decimal_field.class #=> BSON::Decimal128\n```\n\nThe `allow_bson5_decimal128` option only has any effect under BSON 5 and later. BSON 4 and earlier ignore the setting entirely.\n\n### Search Index Management for MongoDB Atlas\n\nWhen connected to MongoDB Atlas, Mongoid now supports creating and removing search indexes. You may do so programmatically, via the `Mongoid::SearchIndexable` API:\n\n```ruby\nclass SearchablePerson\n include Mongoid::Document\n\n search_index { ... } # define the search index here\nend\n\n# create the declared search indexes; this returns immediately, but the\n# search indexes may take several minutes before they are available.\nSearchablePerson.create_search_indexes\n\n# query the available search indexes\nSearchablePerson.search_indexes.each do |index|\n # ...\nend\n\n# remove all search indexes from the model's collection\nSearchablePerson.remove_search_indexes\n```\n\nIf you are not connected to MongoDB Atlas, the search index definitions are ignored. Trying to create, enumerate, or remove search indexes will result in an error.\n\nThere are also rake tasks available, for convenience:\n\n```bash\n# create search indexes for all models; waits for indexes to be created\n# and shows progress on the terminal.\n$ rake mongoid:db:create_search_indexes\n\n# as above, but returns immediately and lets the indexes be created in the\n# background\n$ rake WAIT_FOR_SEARCH_INDEXES=0 mongoid:db:create_search_indexes\n\n# removes search indexes from all models\n$ rake mongoid:db:remove_search_indexes\n```"} -{"chunk_id": "68a95c1f5e79d242619dd9a8-3", "page_id": "68a95c1f5e79d242619dd9a8", "source_name": "mongoid", "product_name": "Mongoid ODM", "url": "https://mongodb.com/docs/mongoid/current/reference/release-notes", "title": "Release Notes", "text": "### Removal of `Time.configured`\n\n`Time.configured` returned either the time object wrapping the configured time zone, or the standard Ruby `Time` class. This allowed you to query a time value even if no time zone had been configured.\n\nMongoid now requires that you set a time zone if you intend to do anything with time values (including using timestamps in your documents). Any uses of `Time.configured` must be replaced with `Time.zone`.\n\n```ruby\n# before:\nputs Time.configured.now\n\n# after:\nputs Time.zone.now\n\n# or, better for finding the current Time specifically:\nputs Time.current\n```\n\nIf you do not set a time zone, you will see errors in your code related to `nil` values. If you are using Rails, the default time zone is already set to UTC. If you are not using Rails, you may set a time zone at the start of your program like this:\n\n```ruby\nTime.zone = 'UTC'\n```\n\nThis will set the time zone to UTC. You can see all available time zone names by running the following command:\n\n```bash\n$ ruby -ractive_support/values/time_zone \\\n -e 'puts ActiveSupport::TimeZone::MAPPING.keys'\n```\n\n### Records Remember Persistence Context of Creation\n\nConsider the following code:\n\n```ruby\nrecord = Model.with(collection: 'other_collection') { Model.first }\nrecord.update(field: 'value')\n```\n\nBefore Mongoid v9.0, the preceding code silently fails to execute the update, because the storage options (here, the specification of an alternate collection for the model) would not be remembered by the record. Thus, the record would be loaded from `other_collection`, but when updated, would attempt to look for and update the document in the default collection for Model. To make this work, you would have had to specify the collection explicitly for every update.\n\nAs of Mongoid v9.0, records that are created or loaded under explicit storage options, will remember those options (including a named client, a different database, or a different collection).\n\nIf you need the legacy (pre-v9.0) behavior, you can enable it with the following flag:\n\n```ruby\nMongoid.legacy_persistence_context_behavior = true\n```\n\nThis flag defaults to false in Mongoid v9.0."} -{"chunk_id": "68a95c1f5e79d242619dd9a1-0", "page_id": "68a95c1f5e79d242619dd9a1", "source_name": "mongoid", "product_name": "Mongoid ODM", "url": "https://mongodb.com/docs/mongoid/current/quick-start-rails", "title": "Integrate Mongoid with Ruby on Rails", "text": "# Integrate Mongoid with Ruby on Rails\n\n## Overview\n\nIn this guide, you can learn how to create a **Ruby** web application that uses **Ruby on Rails 8** as the web framework. Ruby on Rails is a full-stack web application framework for Ruby that follows the model-view-controller (MVC) architecture pattern for building applications.\n\nThe application in this tutorial consists of the following layers:\n\n- **Database layer**: MongoDB provides data storage and retrieval.\n\n- **Application layer**: Rails handles HTTP requests, routing, and logic processing.\n\n- **Presentation layer**: Emebdded Ruby templates and CSS render restaurant data on web pages.\n\nTo learn how to integrate Mongoid into an existing application, see the Add Mongoid to an Existing Application guide.\n\n### Why Use MongoDB with Ruby and Rails?\n\nBy integrating MongoDB with Ruby and Rails, you can use Mongoid's Object-Document Mapper (ODM) to interact with MongoDB's flexible document model. Mongoid replaces Rails' default Active Record ORM, and you can leverage MongoDB's schema flexibility while using Rails to easily control how your data is modeled and displayed.\n\n## Quick Start Tutorial\n\nThis tutorial shows you how to build a web application that uses Ruby and Rails. The application accesses sample restaurant data, queries the data, and displays the results on a locally hosted site. The tutorial also includes instructions for connecting to a MongoDB cluster hosted on MongoDB Atlas and accessing and displaying data from your database.\n\nIf you prefer to connect to MongoDB by using the Ruby driver without Mongoid, follow the Get Started with the Ruby Driver tutorial.\n\n### Set Up Your Project\n\nFollow the steps in this section to install the project dependencies, create an Atlas cluster, and set up the application structure.\n\n#### Verify the prerequisites.\n\nBefore you create the Quick Start application, install the following software in your development environment:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nPrerequisite\n\n\nNotes\n\n
\nRuby\n\n\nUse version 3.1 or later.\n\n
\nRubyGems\n\n\nThis is a package manager for Ruby.\n\n
\nCode editor\n\n\nThis tutorial uses Visual Studio Code with the Ruby extension, but you can use the editor of your choice.\n\n
\nTerminal app and shell\n\n\nFor MacOS users, use Terminal or a similar app. For Windows users, use PowerShell.\n\n
\n\n#### Create a MongoDB Atlas cluster.\n\nMongoDB Atlas is a fully managed cloud database service that hosts your MongoDB deployments. If you do not have a MongoDB deployment, you can create a MongoDB cluster for free (no credit card required) by completing the MongoDB Get Started tutorial. The MongoDB Get Started tutorial also demonstrates how to load sample datasets into your cluster, including the `sample_restaurants` database that is used in this tutorial.\n\nTo connect to your MongoDB cluster, you must use a **connection URI**. To learn how to retrieve your connection URI, see the Add your connection string section of the MongoDB Get Started tutorial.\n\nSave your connection string in a secure location.\n\n#### Specify the target database in your connection string.\n\nWhen connecting to an Atlas cluster, you must specify the database that you want to interact with as the default database in your connection string. You must add the database name to your connection string *after the hostname* and *before the connection options*.\n\nThe following example specifies the `sample_restaurants` target database in a sample connection string:\n\n```none\nmongodb+srv://user0:pass123@mongo0.example.com/sample_restaurants?retryWrites=true&w=majority\n```\n\n#### Install Rails.\n\nInstall the `rails` gem, which provides a command-line interface to create a basic application structure and application components.\n\nRun the following command to install `rails`:\n\n```bash\ngem install rails\n```\n\n#### Create a Rails app with default scaffolding.\n\nRun the following commands to create a new Rails application directory with default scaffolding and enter the application:\n\n```bash\nrails new my-rails-app --skip-active-record\ncd my-rails-app\n```\n\nThe `--skip-active-record` flag instructs Rails to not add Active Record as a dependency. You don't need this dependency because you will use Mongoid instead.\n\n#### Configure your project dependencies.\n\nNavigate to the `my-rails-app` directory and run the following commands to install the Mongoid and the dependencies:\n\n```bash\nbundle add mongoid\nbundle install\n```\n\n#### Generate the Mongoid configuration.\n\nRun the following command to generate the Mongoid configuration file:\n\n```bash\nrails generate mongoid:config\n```\n\nThis command creates a `config/mongoid.yml` file to configure the connection to your MongoDB deployment\n\n### Configure the Back End\n\nAfter setting up the project structure and dependencies, follow the steps in this section to connect to MongoDB and set up your data models.\n\n#### Configure your MongoDB connection.\n\nNavigate to the `config/mongoid.yml` file and replace its contents with the following code:\n\n```yaml\ndevelopment:\n clients:\n default:\n uri: \n```\n\nReplace the `` placeholder with the connection URI that you saved in a previous step. Ensure that the URI includes the `sample_restaurants` database name.\n\n#### Create a data model.\n\nGenerate a `Restaurant` model with `name`, `cuisine`, and `borough` fields by running the following command:\n\n```bash\nbin/rails g scaffold Restaurant name:string cuisine:string borough:string\n```\n\nThe `Restaurant` model represents the `restaurants` collection in the `sample_restaurants` database. The preceding command also creates the controller and view files for the `Restaurant` model. You can find the directories that contain these files in the `app` directory of your application.\n\n#### Configure routes and add custom actions.\n\nNavigate to the `config/routes.rb` file and replace its contents with the following code:\n\n```ruby\nRails.application.routes.draw do\n resources :restaurants\n get \"browse\" => \"restaurants#browse\"\n\n # Defines the root path route (\"/\")\n root \"restaurants#index\"\nend\n```\n\nThen, add the following method to the `app/controllers/restaurants_controller.rb` file:\n\n```ruby\n # GET /browse\n def browse\n @restaurants = Restaurant\n .where(name: /Moon/i).and(borough: \"Queens\")\n end\n```\n\nThis method queries for restaurants in Queens that have `\"Moon\"` in their name by using a case-insensitive regular expression match."} -{"chunk_id": "68a95c1f5e79d242619dd9a1-1", "page_id": "68a95c1f5e79d242619dd9a1", "source_name": "mongoid", "product_name": "Mongoid ODM", "url": "https://mongodb.com/docs/mongoid/current/quick-start-rails", "title": "Integrate Mongoid with Ruby on Rails", "text": "### Configure the Front End\n\nAfter setting up the data layer, follow the steps in this section to create templates and styling for the user interface.\n\n#### Update the main layout.\n\nNavigate to the `app/views/layouts/application.html.erb` file and replace its contents with the following code:\n\n```erb\n\n\n \n <%= content_for(:title) || \"Restaurant Directory\" %>\n \n <%= csrf_meta_tags %>\n <%= csp_meta_tag %>\n\n <%= stylesheet_link_tag :app, \"data-turbo-track\": \"reload\" %>\n <%= javascript_importmap_tags %>\n \n\n \n
\n \n <%= yield %>\n
\n \n\n```\n\nThis file is the main template wrapper for all pages in your application. It includes navigation links, page titles, and the necessary Rails helper tags for security and asset loading.\n\n#### Create the restaurant list view.\n\nNavigate to the `app/views/restaurants/index.html.erb` file and replace its contents with the following code:\n\n```erb\n<% content_for :title, \"Restaurant Directory\" %>\n\n
\n

Restaurant Directory

\n
\n\n
\n

All Restaurants

\n <%= link_to \"New Restaurant\", new_restaurant_path, class: \"btn btn-success\" %>\n
\n\n
\n <% @restaurants.each do |restaurant| %>\n
\n
<%= restaurant.name %>
\n
\n Borough: <%= restaurant.borough %>\n
\n
<%= restaurant.cuisine %>
\n
\n <%= link_to \"View\", restaurant, class: \"btn\" %>\n <%= link_to \"Edit\", edit_restaurant_path(restaurant), class: \"btn btn-secondary\" %>\n <%= link_to \"Delete\", restaurant_path(restaurant), method: :delete,\n confirm: \"Are you sure?\", class: \"btn btn-danger\" %>\n
\n
\n <% end %>\n
\n\n```\n\nThis view file displays all restaurants in a grid layout and includes action buttons for viewing, editing, and deleting each restaurant.\n\n#### Create the filtered view.\n\nCreate a new file named `app/views/restaurants/browse.html.erb` and paste the following code:\n\n```erb\n<% content_for :title, \"Browse Restaurants\" %>\n\n
\n

Browse Restaurants

\n
Restaurants in Queens with \"Moon\" in the name
\n
\n\n
\n

Filtered Results

\n
\n <%= link_to \"New Restaurant\", new_restaurant_path, class: \"btn btn-success\" %>\n <%= link_to \"All Restaurants\", root_path, class: \"btn\" %>\n
\n
\n\n
\n<% @restaurants.each do |restaurant| %>\n
\n
<%= restaurant.name %>
\n
\n Borough: <%= restaurant.borough %>\n
\n
<%= restaurant.cuisine %>
\n
\n <%= link_to \"View\", restaurant, class: \"btn\" %>\n <%= link_to \"Edit\", edit_restaurant_path(restaurant), class: \"btn btn-secondary\" %>\n <%= link_to \"Delete\", restaurant_path(restaurant), method: :delete,\n confirm: \"Are you sure?\", class: \"btn btn-danger\" %>\n
\n
\n<% end %>\n
\n```\n\nThis view file displays the filtered restaurant results, showing only restaurants from the custom `browse` controller action.\n\n#### Add CSS styling.\n\nAdd the following code to the `app/assets/stylesheets/application.css` file:\n\n```css\n* {\n margin: 0;\n padding: 0;\n box-sizing: border-box;\n}\n\nbody {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;\n line-height: 1.6;\n color: #333;\n background: rgb(198, 240, 209);\n min-height: 100vh;\n}\n\n.container {\n max-width: 1200px;\n margin: 0 auto;\n padding: 20px;\n}\n\nheader {\n text-align: center;\n margin-bottom: 40px;\n color: rgb(0, 0, 0);\n}\n\nh1 {\n font-size: 3rem;\n margin-bottom: 10px;\n}\n\n.subtitle {\n font-size: 1.2rem;\n opacity: 0.9;\n}\n\n.controls {\n display: flex;\n justify-content: center;\n gap: 20px;\n margin-bottom: 30px;\n}\n\n.btn {\n background: white;\n color: #0d8958;\n border: none;\n padding: 12px 24px;\n border-radius: 25px;\n font-weight: 600;\n text-decoration: none;\n cursor: pointer;\n transition: all 0.3s ease;\n box-shadow: 0 4px 15px rgba(0,0,0,0.2);\n display: inline-block;\n}\n\n.btn:hover {\n transform: translateY(-2px);\n box-shadow: 0 6px 20px rgba(0,0,0,0.3);\n color: #0d8958;\n text-decoration: none;\n}\n\n.btn.btn-success {\n background: #0d8958;\n color: white;\n}\n\n.btn.btn-success:hover {\n background: #0a6b44;\n color: white;\n}\n\n.btn.btn-danger {\n background: #dc3545;\n color: white;\n}\n\n.btn.btn-danger:hover {\n background: #c82333;\n color: white;\n}\n\n.btn.btn-secondary {\n background: #6c757d;\n color: white;\n}\n\n.btn.btn-secondary:hover {\n background: #5a6268;\n color: white;\n}\n\n.restaurants-grid {\n display: grid;\n grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));\n gap: 20px;\n margin-top: 20px;\n}\n\n.restaurant-card {\n background: white;\n border-radius: 15px;\n padding: 20px;\n box-shadow: 0 8px 25px rgba(0,0,0,0.1);\n transition: transform 0.3s ease, box-shadow 0.3s ease;\n}\n\n.restaurant-card:hover {\n transform: translateY(-5px);\n box-shadow: 0 12px 35px rgba(0,0,0,0.15);\n}\n\n.restaurant-name {\n font-size: 1.4rem;\n font-weight: 700;\n color: #000000;\n margin-bottom: 10px;\n}\n\n.restaurant-info {\n margin-bottom: 8px;\n}\n\n.restaurant-info strong {\n color: #555;\n}\n\n.cuisine-tag {\n display: inline-block;\n background: #0d8958;\n color: white;\n padding: 4px 12px;\n border-radius: 15px;\n font-size: 0.85rem;\n font-weight: 600;\n margin-top: 10px;\n}\n\n.btn-group {\n display: flex;\n gap: 10px;\n margin-top: 15px;\n}\n\n.btn-group .btn {\n padding: 8px 16px;\n font-size: 0.9rem;\n}\n\n.notice {\n background: white;\n color: #0d8958;\n padding: 15px 20px;\n border-radius: 15px;\n margin-bottom: 20px;\n box-shadow: 0 4px 15px rgba(0,0,0,0.1);\n text-align: center;\n font-weight: 600;\n}\n\n.form-container {\n background: white;\n border-radius: 15px;\n padding: 30px;\n box-shadow: 0 8px 25px rgba(0,0,0,0.1);\n max-width: 600px;\n margin: 0 auto;\n}\n\n.form-group {\n margin-bottom: 20px;\n}\n\n.form-label {\n display: block;\n margin-bottom: 8px;\n font-weight: 600;\n color: #333;\n}\n\n.form-input {\n width: 100%;\n padding: 12px 16px;\n border: 2px solid #e9ecef;\n border-radius: 12px;\n font-size: 1rem;\n transition: border-color 0.3s ease;\n}\n\n.form-input:focus {\n outline: none;\n border-color: #0d8958;\n}\n\n.form-actions {\n display: flex;\n gap: 15px;\n justify-content: center;\n margin-top: 25px;\n}\n\n.page-header {\n text-align: center;\n margin-bottom: 30px;\n}\n\n.actions-header {\n display: flex;\n justify-content: space-between;\n align-items: center;\n margin-bottom: 30px;\n background: white;\n padding: 20px;\n border-radius: 15px;\n box-shadow: 0 4px 15px rgba(0,0,0,0.1);\n}\n\n.actions-header h1 {\n font-size: 2rem;\n color: #0d8958;\n margin: 0;\n}\n\n@media (max-width: 768px) {\n .container {\n padding: 10px;\n }\n\n h1 {\n font-size: 2rem;\n }\n\n .controls {\n flex-direction: column;\n align-items: center;\n }\n\n .restaurants-grid {\n grid-template-columns: 1fr;\n }\n\n .actions-header {\n flex-direction: column;\n gap: 15px;\n }"} -{"chunk_id": "68a95c1f5e79d242619dd9a1-2", "page_id": "68a95c1f5e79d242619dd9a1", "source_name": "mongoid", "product_name": "Mongoid ODM", "url": "https://mongodb.com/docs/mongoid/current/quick-start-rails", "title": "Integrate Mongoid with Ruby on Rails", "text": " .form-actions {\n flex-direction: column;\n }\n}\n```\n\nThis CSS file adds styling to the site's grid layout.\n\n### Run Your Application\n\nFinally, follow the steps in this section to run your web application and explore the restaurant data by using the browser interface.\n\n#### Start the Rails application.\n\nNavigate to your project directory and run the following command:\n\n```bash\nbin/rails s\n```\n\nIf successful, the command output resembles the following example:\n\n```bash\n=> Booting Puma\n=> Rails 8.0.1 application starting in development\n=> Run `bin/rails server --help` for more startup options\nPuma starting in single mode...\n* Puma version: 6.4.3 (ruby 3.2.5-p208) (\"The Eagle of Durango\")\n* Min threads: 3\n* Max threads: 3\n* Environment: development\n* PID: 66973\n* Listening on http://127.0.0.1:3000\n* Listening on http://[::1]:3000\n* Listening on http://127.0.2.2:3000\n* Listening on http://127.0.2.3:3000\nUse Ctrl-C to stop\n```\n\n#### Open the web application.\n\nOpen http://127.0.0.1:3000 in your web browser. The initial landing page displays all restaurants in the `sample_restaurants.restaurants` collection:\n\nThen, click the Browse Filtered button to view restaurants in Queens that have `\"Moon\"` in their name:\n\n#### Explore CRUD functionality.\n\nRails automatically provides complete CRUD (Create, Read, Update, Delete) functionality for your restaurants. You can perform the following actions:\n\n- **Create**: Click New Restaurant to add a new restaurant to the `restaurants` collection.\n\n- **Read**: Click View on any restaurant card to see detailed information.\n\n- **Update**: Click Edit on any restaurant card to modify the restaurant's information.\n\n- **Delete**: Click Delete on any restaurant card to remove it from the collection.\n\nCongratulations on completing the Quick Start tutorial! After you complete these steps, you have a Ruby and Rails web application that connects to your MongoDB deployment, runs queries on sample restaurant data, and displays the results on a locally hosted web interface with full CRUD capabilities.\n\n## Additional Resources\n\nTo learn more about Ruby, Rails, Mongoid, and MongoDB, view the following resources:\n\n- Ruby on Rails documentation\n\n- Ruby Driver Documentation\n\n- Ruby language documentation\n\nIf you prefer to use Sinatra as your web framework, see the Integrate Mongoid with Sinatra guide."} -{"chunk_id": "6a0ea46a44288d4d5b181bfe-0", "page_id": "6a0ea46a44288d4d5b181bfe", "source_name": "mongoid", "product_name": "Mongoid ODM", "url": "https://mongodb.com/docs/mongoid/current/data-modeling/associations/association-metadata", "title": "Association Metadata", "text": "# Association Metadata\n\n## Overview\n\nAssociations in Mongoid allow you to create relationships between models. When you define an association, Mongoid stores metadata about that association. You can access the metadata by calling the `reflect_on_association` method on a model class or document, or by directly accessing the metadata on a specific document. The following example shows how to access metadata by using the `reflect_on_association` method and by direct access:\n\n```ruby\n# Get the metadata for a named association from the class or document\nModel.reflect_on_association(:)\n\n# Directly access metadata on a document\nmodel.associations[:]\n```\n\nReplace `` in the preceding example with the name of your association.\n\n## Attributes\n\nAll associations contain attributes that store information about the associated document. Associations contain the following attributes:\n\n- `_target`: The proxied document or documents\n\n- `_base`: The document on which the association is defined\n\n- `_association`: Information about the association\n\nThe following example accesses each of the preceding attributes:\n\n```ruby\nclass Band\n include Mongoid::Document\n\n embeds_many :songs\nend\n\nBand.songs = [ song ]\nBand.songs._target # returns [ song ]\nBand.songs._base # returns band\nBand.songs._association # returns the association metadata\n```\n\nThe following table shows the information stored in the `_association` attribute:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nMethod\n\n\nDescription\n\n
\n`Association#as`\n\n\nThe name of the parent to a polymorphic child.\n\n
\n`Association#as?`\n\n\nReturns whether an `as` option exists.\n\n
\n`Association#autobuilding?`\n\n\nReturns whether the association is autobuilding.\n\n
\n`Association#autosaving?`\n\n\nReturns whether the association is autosaving.\n\n
\n`Association#cascading_callbacks?`\n\n\nReturns whether the association has callbacks cascaded down from the parent.\n\n
\n`Association#class_name`\n\n\nThe class name of the proxied document.\n\n
\n`Association#cyclic?`\n\n\nReturns whether the association is a cyclic association.\n\n
\n`Association#dependent`\n\n\nThe association's dependent option.\n\n
\n`Association#destructive?`\n\n\nReturns `true` if the association has a dependent delete or destroy method.\n\n
\n`Association#embedded?`\n\n\nReturns whether the association is embedded in another document.\n\n
\n`Association#forced_nil_inverse?`\n\n\nReturns whether the association has a `nil` inverse defined.\n\n
\n`Association#foreign_key`\n\n\nThe name of the foreign-key field.\n\n
\n`Association#foreign_key_check`\n\n\nThe name of the foreign-key field's dirty-check method.\n\n
\n`Association#foreign_key_setter`\n\n\nThe name of the foreign-key field's setter.\n\n
\n`Association#indexed?`\n\n\nReturns whether the foreign key is auto indexed.\n\n
\n`Association#inverses`\n\n\nThe names of all inverse associations.\n\n
\n`Association#inverse`\n\n\nThe name of a single inverse association.\n\n
\n`Association#inverse_class_name`\n\n\nThe class name of the association on the inverse side.\n\n
\n`Association#inverse_foreign_key`\n\n\nThe name of the foreign-key field on the inverse side.\n\n
\n`Association#inverse_klass`\n\n\nThe class of the association on the inverse side.\n\n
\n`Association#inverse_association`\n\n\nThe metadata of the association on the inverse side.\n\n
\n`Association#inverse_of`\n\n\nThe explicitly defined name of the inverse association.\n\n
\n`Association#inverse_setter`\n\n\nThe name of the method used to set the inverse.\n\n
\n`Association#inverse_type`\n\n\nThe name of the polymorphic-type field of the inverse.\n\n
\n`Association#inverse_type_setter`\n\n\nThe name of the polymorphic-type field's setter of the inverse.\n\n
\n`Association#key`\n\n\nThe name of the field in the attribute's hash that is used to get the association.\n\n
\n`Association#klass`\n\n\nThe class of the proxied documents in the association.\n\n
\n`Association#name`\n\n\nThe association name.\n\n
\n`Association#options`\n\n\nReturns `self`, for API compatibility with ActiveRecord.\n\n
\n`Association#order`\n\n\nThe custom sorting options on the association.\n\n
\n`Association#polymorphic?`\n\n\nReturns whether the association is polymorphic.\n\n
\n`Association#setter`\n\n\nThe name of the field to set the association.\n\n
\n`Association#store_as`\n\n\nThe name of the attribute in which to store an embedded association.\n\n
\n`Association#touchable?`\n\n\nReturns whether the association has a touch option.\n\n
\n`Association#type`\n\n\nThe name of the field to get the polymorphic type.\n\n
\n`Association#type_setter`\n\n\nThe name of the field to set the polymorphic type.\n\n
\n`Association#validate?`\n\n\nReturns whether the association has an associated validation.\n\n
"} -{"chunk_id": "68a95c1f5e79d242619dd921-0", "page_id": "68a95c1f5e79d242619dd921", "source_name": "mongoid", "product_name": "Mongoid ODM", "url": "https://mongodb.com/docs/mongoid/current/data-modeling/field-behaviors", "title": "Customize Field Behaviors", "text": "# Customize Field Behaviors\n\n## Overview\n\nIn this guide, you can learn how to customize the behavior of fields in Mongoid models.\n\n## Specify Default Values\n\nYou can configure fields to have default values by using the `default` option. Default field values can be either fixed or `Proc` values.\n\nThe following example specifies a fixed default value for the `state` field:\n\n```ruby\nclass Order\n include Mongoid::Document\n\n field :state, type: String, default: 'created'\nend\n```\n\nThe following example specifies a `Proc` default value for the `fulfill_by` field:\n\n```ruby\nclass Order\n include Mongoid::Document\n\n field :fulfill_by, type: Time, default: ->{ Time.now + 3.days }\nend\n```\n\nThe driver evaluates default values that are not `Proc` instances when the class *loads*. The driver evaluates `Proc` values when the document is *instantiated*. The following default field values do not produce equivalent outcomes:\n\n```ruby\n# Time.now is set to the time the class is loaded\nfield :submitted_at, type: Time, default: Time.now\n\n# Time.now is set to the time the document is instantiated\nfield :submitted_at, type: Time, default: ->{ Time.now }\n```\n\nYou can set a default value that depends on the document's state by using the `self` keyword in a `Proc` instance. The following example sets the `fulfill_by` default value to depend on the state of the `submitted_at` field:\n\n```ruby\nfield :fulfill_by, type: Time, default: ->{\n self.submitted_at + 4.hours\n}\n```\n\nBy default, Mongoid applies `Proc` default values after setting and initializing all other attributes. To apply the default before setting the other attributes, set the `pre_processed` option to `true`, as shown in the following example:\n\n```ruby\nfield :fulfill_by, type: Time, default: ->{ Time.now + 3.days },\n pre_processed: true\n```\n\nAlways set the `pre-processed` option to `true` to set a default `Proc` value for the `_id` field.\n\n## Specify Storage Names\n\nYou can specify a separate field name to store in the database, while still referring to the field by its original name in your application. This can save storage space, because MongoDB stores all field information along with every document.\n\nYou can set an alternate storage name by using the `as:` keyword. The following example creates a field called `name` that Mongoid stores in the database as `n`:\n\n```ruby\nclass Band\n include Mongoid::Document\n field :n, as: :name, type: String\nend\n```\n\nMongoid stores the `name` field as `\"n\"`, but you can still access the field as `name` in your application.\n\n## Field Aliases\n\nYou can create an alias for your field by using the `alias_attribute` option. Specifying an alias does not change how Mongoid stores the field in the database, but it allows you to access the field by a different name in your application.\n\nThe following example specifies an alias for the `name` field:\n\n```ruby\nclass Band\n include Mongoid::Document\n field :name, type: String\n alias_attribute :n, :name\nend\n```\n\nTo remove a field alias, you can use the `unalias_attribute` option. The following example removes the alias for the `name` field:\n\n```ruby\nclass Band\n unalias_attribute :n\nend\n```\n\nYou can also use `unalias_attribute` to remove the predefined `id` alias from the `_id` field. This can be used to store different values in the `_id` field and an `id` field.\n\n## Field Redefinition\n\nBy default, Mongoid allows you to redefine fields on a model. To raise an error when a field is redefined, set the `duplicate_fields_exception` configuration option in your `mongoid.yml` file to `true`.\n\nIf the `duplicate_fields_exception` option is set to `true`, you can still redefine a specific field by setting the `overwrite` option to `true` when you define the field. The following example defines the `name` field, and then redefines the field by using the `overwrite` option:\n\n```ruby\nclass Person\n include Mongoid::Document\n field :name\n field :name, type: String, overwrite: true\nend\n```\n\n## Custom ID Field\n\nBy default, Mongoid defines the `_id` field on documents to contain a `BSON::ObjectId` value that Mongoid generates automatically. You can customize the type or specify the default value of the `_id` field by specifying it in your model.\n\nThe following example creates a `Band` class with a custom `_id` field:\n\n```ruby\nclass Band\n include Mongoid::Document\n field :name, type: String\n field :_id, type: String, default: ->{ name }\nend\n```\n\nYou can omit the default value for the `_id` field. If you don't specify a default value for the field, Mongoid persists the document without an `_id` value. For top-level documents, the MongoDB server automatically assigns an `_id` value. However, for embedded documents, the server does not assign an `_id` value.\n\nWhen you don't specify a value for the `_id` field, Mongoid does not retrieve the automatically assigned value from the server. Because of this, you cannot retrieve the document from the database by using the `_id` value.\n\n## Uncastable Values\n\nA value is considered **uncastable** if it cannot be converted to the specified field type. For example, an array is considered uncastable when assigned to an `Integer` field.\n\nIn v8.0 and later, Mongoid assigns `nil` to values that are uncastable. The original uncastable value is stored in the `attributes_before_type_cast` hash with their field names.\n\n## Custom Getters and Setters\n\nYou can override the default getter and setter methods for a field by specifying a method with the same name as the field and calling the `read_attribute` or `write_attribute` method to operate on the raw attribute value.\n\nThe following example creates a custom getter and setter for the `name` field of a `Person` class:\n\n```ruby\nclass Person\n include Mongoid::Document\n field :name, type: String\n\n # Custom getter for 'name' to return the name in uppercase\n def name\n read_attribute(:name).upcase if read_attribute(:name)\n end\n\n # Custom setter for 'name' to store the name in lowercase\n def name=(value)\n write_attribute(:name, value.downcase)\n end\nend\n```\n\n## Read-Only Attributes\n\nYou can specify a field to be read-only by specifying the `attr_readonly` option. This allows you to create documents with the attributes, but not update them.\n\nThe following example creates a `Band` class and specifies the `name` field as read-only:\n\n```ruby\nclass Band\n include Mongoid::Document\n field :name, type: String\n field :origin, type: String\n\n attr_readonly :name\nend\n```\n\nIf you call a mass-update method, such as `update_attributes`, and pass in a read-only field, Mongoid ignores the read-only field and updates all others. If you attempt to explicitly update a read-only field, Mongoid raises a `ReadonlyAttribute` exception.\n\nCalls to atomic persistence operators, such as `bit` and `inc`, still persist changes to the read-only field.\n\nTo learn about specifying entire models as read-only, see the Read-only Documents section of the Perform Data Operations guide."} -{"chunk_id": "68a95c1f5e79d242619dd921-1", "page_id": "68a95c1f5e79d242619dd921", "source_name": "mongoid", "product_name": "Mongoid ODM", "url": "https://mongodb.com/docs/mongoid/current/data-modeling/field-behaviors", "title": "Customize Field Behaviors", "text": "## Localize Fields\n\nMongoid supports localized fields by using the i18n gem. When you localize a field, Mongoid stores the field as a hash of locale keys and values. Accessing the fields behaves in the same way as a string value. You can localize fields of any field type.\n\nThe following example creates a `Product` class with a localized `review` field:\n\n```ruby\nclass Product\n include Mongoid::Document\n field :review, type: String, localize: true\nend\n\nI18n.default_locale = :en\nproduct = Product.new\nproduct.review = \"Marvelous!\"\nI18n.locale = :de\nproduct.review = \"Fantastisch!\"\n\nproduct.attributes\n# Outputs: { \"review\" => { \"en\" => \"Marvelous!\", \"de\" => \"Fantastisch!\" }\n```\n\nYou can get and set all translations at once by calling the `_translations` method:\n\n```ruby\nproduct.review_translations\n# Outputs: { \"en\" => \"Marvelous!\", \"de\" => \"Fantastisch!\" }\nproduct.review_translations =\n { \"en\" => \"Marvelous!\", \"de\" => \"Wunderbar!\" }\n```\n\nYou can specify fallbacks for localized fields by enabling the i18n fallbacks feature.\n\nEnable fallbacks in a Rails application by setting the `config.i18n.fallbacks` configuration setting in your environment and setting the fallback languages:\n\n```ruby\nconfig.i18n.fallbacks = true\nconfig.after_initialize do\n I18n.fallbacks[:de] = [ :en, :es ]\nend\n```\n\nEnable fallbacks in non-Rails applications by including the module into the i18n backend and setting the fallback languages:\n\n```ruby\nrequire \"i18n/backend/fallbacks\"\nI18n::Backend::Simple.send(:include, I18n::Backend::Fallbacks)\nI18n.fallbacks[:de] = [ :en, :es ]\n```\n\nAfter enabling fallbacks, if an active language does not have have a translation, it is looked up in the specified fallback language.\n\nYou can disable fallback languages for a specified field by setting the `fallbacks` option to false when defining the field:\n\n```ruby\nclass Product\n include Mongoid::Document\n field :review, type: String, localize: true, fallbacks: false\nend\n```\n\nWhen querying localized fields, Mongoid automatically alters the query criteria to match the current locale. The following example queries the `Product` class for a review in the `en` locale:\n\n```ruby\n# Match all products with Marvelous as the review. The current locale is :en.\nProduct.where(review: \"Marvelous!\")\n# The resulting MongoDB query filter: { \"review.en\" : \"Marvelous!\" }\n```\n\nIf you want to query extensively on localized fields, we recommend indexing each locale that you want to query on."} -{"chunk_id": "69746408fe5a47168d5fcb78-0", "page_id": "69746408fe5a47168d5fcb78", "source_name": "mongosync", "product_name": "Mongosync", "url": "https://mongodb.com/docs/mongosync/current/installation/verify/gpg", "title": "Verify Packages with GPG (Linux)", "text": "# Verify Packages with GPG (Linux)\n\nThe MongoDB release team digitally signs `mongosync` packages to certify that the packages are a valid and unaltered MongoDB release. Before you install `mongosync`, you can use the digital signature to validate the package.\n\nThis page describes how to use GPG to verify Linux packages.\n\n## Before you Begin\n\nIf you don't have `mongosync` installed, download the `mongosync` package from the Download Center.\n\n## Steps\n\n### Import the MongoDB Server Tools public key.\n\n```shell\ncurl https://pgp.mongodb.com/server-Tools.asc | gpg --import\n\n```\n\nIf the key imports successfully, the command returns:\n\n```shell\ngpg: key 3132835C1D925D5B: public key \"MongoDB CLI Tools Release Signing Key \" imported\ngpg: Total number processed: 1\ngpg: imported: 1\n\n```\n\nIf you have previously imported the key, the command returns:\n\n```shell\ngpg: key 3132835C1D925D5B: \"MongoDB CLI Tools Release Signing Key \" not changed\ngpg: Total number processed: 1\ngpg: unchanged: 1\n\n```\n\n### Download the Mongosync public signature.\n\nTo download the `mongosync` public signature, run the following command, replacing the placeholder values with your platform, architecture, and `mongosync` version:\n\n```shell\ncurl -LO https://s3.amazonaws.com/downloads.mongodb.org/tools/mongosync/mongosync---.tgz.sig\n\n```\n\nThe following URL contains the signature file for `mongosync` on Amazon Linux 2023, version 1.22.0:\n\n`https://s3.amazonaws.com/downloads.mongodb.org/tools/mongosync/mongosync-amazon2023-x86_64-1.22.0.tgz.sig`\n\n### Verify the package.\n\n```shell\ngpg --verify \n\n```\n\nIf the package is signed by MongoDB, the command returns:\n\n```shell\ngpg: Signature made Wed 19 Feb 2025 02:19:15 PM EST\ngpg: using RSA key D4E45C292A5C94962F0D10E13132835C1D925D5B\ngpg: Good signature from \"MongoDB CLI Tools Release Signing Key \" [unknown]\n\n```\n\nIf the package is signed but the signing key is not added to your local `trustdb`, the command returns:\n\n```shell\ngpg: WARNING: This key is not certified with a trusted signature!\ngpg: There is no indication that the signature belongs to the owner.\n\n```\n\nIf the package is not properly signed, the command returns an error message:\n\n```shell\ngpg: Signature made Wed 19 Feb 2025 02:19:15 PM EST\ngpg: using RSA key D4E45C292A5C94962F0D10E13132835C1D925D5B\ngpg: BAD signature from \"MongoDB CLI Tools Release Signing Key \" [unknown]\n\n```"} -{"chunk_id": "69746408fe5a47168d5fcbd3-0", "page_id": "69746408fe5a47168d5fcbd3", "source_name": "mongosync", "product_name": "Mongosync", "url": "https://mongodb.com/docs/mongosync/current/topologies/rs-to-sharded", "title": "Sync a Replica Set to a Sharded Cluster", "text": "# Sync a Replica Set to a Sharded Cluster\n\nThis page outlines the procedure to synchronize data from a replica set to a sharded cluster using `mongosync`.\n\n`mongosync` doesn't support syncing from a sharded cluster to a replica set.\n\n## Before You Begin\n\n- Define your source replica set and destination sharded cluster.\n\n- Define an administrative user that has permissions in both clusters.\n\n- Download and install `mongosync`.\n\nTo learn more, see the mongosync setup instructions.\n\n## Steps\n\n### Connect the replica set and sharded cluster\n\n`mongosync` must create an initial connection between the source replica set and the destination sharded cluster before you can start to sync data.\n\nTo connect `cluster0` to `cluster1` with `mongosync`, enter the following command:\n\n```shell\nmongosync \\\n --cluster0 \"\" \\\n --cluster1 \"\"\n\n```\n\nFollow the connection instructions for your cluster architecture to format your connection strings and connect to the `mongos` instance in your cluster.\n\n### Start synchronization\n\nCall the start endpoint to initiate data synchronization.\n\nTo sync from a replica set to a sharded cluster, set the `sharding` option for the `start` command to shard collections on the destination cluster. For more information, see Sharding Parameters.\n\nUse the `sharding.shardingEntries` parameter to specify the collections to shard. Collections that you do not list in this array replicate as unsharded. For more information, see Shard Replica Sets and Choose a Shard Key.\n\nThe following example starts a sync from a replica set to a sharded cluster:\n\n#### Request\n\n```\ncurl localhost:27182/api/v1/start -XPOST \\\n--data '\n {\n \"source\": \"cluster0\",\n \"destination\": \"cluster1\",\n \"sharding\": {\n \"createSupportingIndexes\": true,\n \"shardingEntries\": [\n {\n \"database\": \"accounts\",\n \"collection\": \"us_east\",\n \"shardCollection\": {\n \"key\": [\n { \"location\": 1 },\n { \"region\": 1 }\n ]\n }\n }\n ]\n }\n } '\n\n```\n\n#### Response\n\n```json\n{\"success\":true}\n\n```\n\n## Next Steps\n\nYou can finalize a migration and transfer your application workload from the source to the destination cluster using the `mongosync`\ncutover process.\n\n## Limitations\n\n- You cannot use the reverse endpoint between a replica set and a sharded cluster.\n\n- `mongosync` allows users to rename collections that the `sharding.shardingEntries` option includes during sync with some limitations. For details, see Renaming During Sync.\n\n- If you use the `sharding.createSupportingIndexes` option, the indexes are automatically created on the destination cluster during the sync. You cannot create these indexes afterwards on the source cluster.\n\n- If you want to create an index to support shard keys manually, you must create the index before `mongosync` starts or after the migration is complete and `mongosync` has stopped.\n\n- If the source replica set has arbiters, the source replica set must have more than 2 non-arbiter nodes and you must sync from a non-arbiter node.\n\nFor more details, see mongosync Migration Limitations.\n\n## Learn More\n\n- Mongosync Quickstart\n\n- Sync Sharded Clusters\n\n- About mongosync\n\n- mongosync\n\n- mongosync States"} -{"chunk_id": "69746408fe5a47168d5fcadc-0", "page_id": "69746408fe5a47168d5fcadc", "source_name": "mongosync", "product_name": "Mongosync", "url": "https://mongodb.com/docs/mongosync/current/reference/mongosync-states", "title": "`mongosync` States", "text": "# `mongosync` States\n\n`mongosync` enters different states depending on the requests it receives. `mongosync` can only be in a single state at a given time. The current `mongosync` states determines which API operations you can run.\n\nMost state transitions happen as the result of an API call. The exceptions are:\n\n- The transition from `COMMITTING` to `COMMITTED`. For more information, see Finalizing Sync.\n\n- The transition from `REVERSING` to `RUNNING`. For more information, see Reversing Sync.\n\nThis page describes `mongosync` states.\n\n## View the Current State\n\nTo view the current state of `mongosync`, use the /progress. endpoint. The /progress endpoint returns the state in the `state` field.\n\nStarting in `mongosync` 1.7.3, `mongosync` can take at least two minutes to respond when you resume or restart a sync operation. During this time, any calls to the `progress` endpoint might fail. If a `progress` call fails, it is safe to retry.\n\n## State Descriptions\n\nThe following table describes each state and lists the permitted operations in that state.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nState\n\n\nDescription\n\n\nPossible API Operations\n\n
\n`INITIALIZING`\n\n\nThe sync process is initializing and not ready for `/start`.\n\n\n- `GET` /progress\n\n
\n`IDLE`\n\n\n`mongosync` is initialized and ready for a sync job to begin.\n\n\n- `POST` /start\n\n- `GET` /progress\n\n
\n`RUNNING`\n\n\nThe sync process is currently running. In this state, data is initially synced to the destination cluster. Subsequent writes to the source cluster are applied to the destination cluster.\n\n\n- `POST` /pause\n\n- `POST` /commit\n\n- `GET` /progress\n\n
\n`PAUSED`\n\n\nThe sync process is paused. To resume the sync process, send a request to the /resume endpoint.\n\n\n- `POST` /resume\n\n- `GET` /progress\n\n
\n`COMMITTING`\n\n\nThe cutover for the sync process has started. The time it takes to transition to the `COMMITTED` phase depends on `lag.overallLagSeconds`. To monitor `lag.overallLagSeconds` or to see if `mongosync` has finished committing, use the /progress endpoint.\n\n\n- `GET` /progress\n\n
\n`COMMITTED`\n\n\nThe cutover for the sync process is complete.\n\n\n- `GET` /progress\n\n- `POST` /reverse\n\n
\n`REVERSING`\n\n\nThe sync process copies metadata from the destination cluster to the source cluster. Then, MongoDB swaps the source and destination clusters and resumes applying change events.\n\nTo start the cutover process during reverse migration, use the /commit endpoint.\n\n\n- `GET` /progress\n\n
"} -{"chunk_id": "69746408fe5a47168d5fcdeb-0", "page_id": "69746408fe5a47168d5fcdeb", "source_name": "mongosync", "product_name": "Mongosync", "url": "https://mongodb.com/docs/mongosync/current/release-notes/1.14", "title": "Release Notes for mongosync 1.14", "text": "# Release Notes for mongosync 1.14\n\nThis page describes changes and new features introduced in MongoDB Mongosync 1.14.\n\n## 1.14.0 Release\n\n**June 5, 2025**\n\n### API Changes\n\n- Adds the `estimatedSecondsToCEACatchup` field to the `progress` endpoint response.\n\n- `mongosync` errors on indexes that are inconsistent or missing on some data-bearing shards, instead of ignoring them.\n\n- Adds the `\"excludeHashed\"` option to the `buildIndexes` parameter in the `start` endpoint.\n\n### Live Upgrades\n\nLive upgrades to 1.14 are not supported.\n\n### Fixed Issues\n\n- Fixes a bug where `mongosync` exited during collection copy upon seeing a transient error. Now, `mongosync` will retry on retryable errors.\n\n- Fixes a bug where the embedded verifier could have caused long downtime during `commit` if the source cluster has a lot of unique or hidden indexes.\n\n### Other Notes\n\n- Fixes a case where `mongosync` exited unexpectedly without printing a fatal log error. Now, if `mongosync` exits unexpectedly, it prints a log error.\n\n- Fixes a bug introduced in `mongosync` version 1.10 where the `progress` endpoint overcounted the verifier's `estimatedDocumentCount`.\n\n- If the verifier finds checksum mismatches, it might re-fetch some documents from the source or destination cluster to check if the mismatch is due to differences in field order. This might lead to cutover taking slightly longer.\n\n## Minimum Supported Version\n\nFor information on minimum supported versions, see MongoDB Server Version Compatibility.\n\nFor best performance, upgrade your source and destination clusters to the most recent MongoDB Server patch release prior to migration. For more information, see Upgrade to the Latest Self-Managed Patch Release of MongoDB."} -{"chunk_id": "69746408fe5a47168d5fca7f-0", "page_id": "69746408fe5a47168d5fca7f", "source_name": "mongosync", "product_name": "Mongosync", "url": "https://mongodb.com/docs/mongosync/current/reference/api/progress", "title": "`progress`", "text": "# `progress`\n\n## Description\n\nReturns either an updated status of the synchronization process or an error.\n\n## Request\n\n```http\nGET /api/v1/progress\n\n```\n\n## Response\n\nThe `progress` endpoint returns either an updated status or an error."} -{"chunk_id": "69746408fe5a47168d5fca7f-1", "page_id": "69746408fe5a47168d5fca7f", "source_name": "mongosync", "product_name": "Mongosync", "url": "https://mongodb.com/docs/mongosync/current/reference/api/progress", "title": "`progress`", "text": "### Successful Response\n\nThe response object contains 2 top-level fields, `success` and `progress`.\n\nThe `success` field contains the status of the `progress` command. Value is `true` if the command succeeds and `false` if the command fails.\n\nIf `mongosync` successfully gets the status of the sync process, all response fields are wrapped in the top-level `progress` object with the following fields:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nField\n\n\nType\n\n\nDescription\n\n
\n`state`\n\n\nstring\n\n\nThe current state of `mongosync`. For information on the possible states, see State Descriptions.\n\n
\n`canCommit`\n\n\nboolean\n\n\nIf `true`, indicates that a commit request succeeds. This also means that:\n\n- The initial sync has completed and is applying change events.\n\n- The embedded verifier is in an appropriate state for commit.\n\n- The lag for `mongosync` and the embedded verifier is 30 seconds or less.\n\nIf you set buildIndexes to `\"afterDataCopy\"` or `\"excludeHashedAfterCopy\"` when calling `start`, `{canCommit: true}` also indicates that index builds are complete.\n\n`canCommit` is `false` when `mongosync` or the embedded verifier reports more than 30 seconds of lag.\n\n
\n`canWrite`\n\n\nboolean\n\n\nIf `true`, indicates that writes are permitted on the destination cluster. Do not write to the destination cluster while `canWrite` is `false`.\n\nIndex validation continues until the commit is complete.\n\n
\n`indexBuilding`\n\n\nobject\n\n\nShows real-time progress of index builds on the destination cluster if you set `buildIndexes` to `afterDataCopy` or `excludeHashedAfterCopy` when calling `start`. This object is only displayed during the Change Event Application phase.\n\nIMPORTANT: Because `mongosync` creates indexes for the largest collections first, the percentage of indexes built might not linearly correspond to the percentage of time elapsed.\n\n
\n`indexBuilding.indexesBuilt`\n\n\ninteger\n\n\nThe number of indexes that `mongosync` has finished building.\n\n
\n`indexBuilding.totalIndexesToBuild`\n\n\ninteger\n\n\nThe total number of indexes that `mongosync` needs to build, including those that it has finished building.\n\n
\n`indexBuilding.collectionsFinished`\n\n\ninteger\n\n\nThe number of collections that `mongosync` has completed index builds for.\n\n
\n`indexBuilding.collectionsTotal`\n\n\ninteger\n\n\nThe total number of collections that `mongosync` needs to build indexes for, including those that have been completed.\n\n
\n`info`\n\n\nstring\n\n\nProvides extra information on the synchronization progress. Possible `info` values include:\n\n- `\"collection copy\"`\n\n- `\"change event application\"`\n\n- `\"waiting for commit to complete\"`\n\n- `\"commit completed\"`\n\n
\n`ceaStage`\n\n\nstring\n\n\nStage of the Change Event Application (CEA) phase. Only appears when `mongosync` is in CEA. This field can be one of the following values:\n\n- `\"collection copy drain\"`: `mongosync` is still draining the change events that accumulated during collection copy.\n\n- `\"steady state\"`: `mongosync` finished draining the collection copy backlog and is processing change events from the change stream closer to real time.\n\nUse this field to interpret synchronization lag. For more information, see Change Event Application Stages.\n\n
\n`lag`\n\n\nobject\n\n\nReports synchronization lag broken down by component. The `lag` object is `null` when `mongosync` is in the `IDLE` or `PAUSED` state.\n\n
\n`lag.overallLagSeconds`\n\n\ninteger\n\n\nTime difference in seconds between the latest event timestamp that `mongosync` applied to the destination cluster and the latest timestamp on the source cluster. Equals `lagTimeSeconds` in all states.\n\n
\n`lag.crudLagSeconds`\n\n\ninteger\n\n\nCRUD component of the synchronization lag in seconds. This field is `null` when `mongosync` has not yet set the source timestamp for CRUD operations.\n\n
\n`lag.ddlLagSeconds`\n\n\ninteger\n\n\nDDL component of the synchronization lag in seconds. This field is `null` when the DDL applier is disabled (for example, when the source server version is earlier than 6.0) or when no DDL event has been applied yet.\n\n
\n`lagTimeSeconds`\n\n\ninteger\n\n\n*Deprecated in Mongosync 1.21.* Use `lag.overallLagSeconds` instead. This field may be removed in a future version.\n\nTime difference in seconds between the latest event timestamp that `mongosync` applied to the destination cluster and the latest timestamp on the source cluster for this instance of `mongosync`.\n\n`mongosync` performs periodic no-op writes on the source cluster, which may prevent the value of the `lagTimeSeconds` field from reaching zero until `mongosync` commits the migration.\n\nDue to constant no-ops on the source cluster, the time difference is often a few seconds above zero, even if there are no real writes on the source cluster. The time difference becomes zero when `mongosync` commits the migration.\n\nAs of version 1.9, `/progress` also reports verifier lag. See `verification.source.lagTimeSeconds` and `verification.destination.lagTimeSeconds` in this table.\n\n
\n`totalEventsApplied`\n\n\ninteger\n\n\nThe approximate number of change events this instance of `mongosync` has applied to the destination cluster.\n\nThis value may not be an accurate representation of the total number of events because it is not persisted and it omits certain events from the count.\n\n
\n`collectionCopy`\n\n\nobject\n\n\nEstimates the total amount of data being copied from collections and the amount that has already been copied to the destination cluster\n\n
\n`collectionCopy`\n`.estimatedTotalBytes`\n\n\ninteger\n\n\nEstimated total number of bytes to be copied globally by all `mongosync` instances during the initial copying of collections.\n\n`mongosync` calculates this value before collection copy begins. During collection copy, this value only changes if `estimatedCopiedBytes` exceeds it, in which case `mongosync` raises `estimatedTotalBytes` to equal `estimatedCopiedBytes`. After collection copy completes, `estimatedTotalBytes` equals `estimatedCopiedBytes`. This value is a best-effort estimate.\n\n
\n`collectionCopy`\n`.estimatedCopiedBytes`\n\n\ninteger\n\n\nEstimated number of bytes copied to the destination cluster by this `mongosync` instance during the initial copying of collections.\n\nTo calculate total estimated progress as a percentage:"} -{"chunk_id": "69746408fe5a47168d5fca7f-2", "page_id": "69746408fe5a47168d5fca7f", "source_name": "mongosync", "product_name": "Mongosync", "url": "https://mongodb.com/docs/mongosync/current/reference/api/progress", "title": "`progress`", "text": "1. Add the `estimatedCopiedBytes` value for each `mongosync` instance.\n\n2. Divide the result by `estimatedTotalBytes`.\n\n3. Multiply the result by 100.\n\nBoth values are best-effort estimates and may not accurately reflect actual migration progress.\n\n
\n`destination.` `pingLatencyMs`\n\n\ninteger\n\n\nProvides the last-known ping latency, in milliseconds, from `mongosync` to the destination cluster. This field is refreshed every 30 seconds while replication is still in progress and reported in the response. If latency is less than `1` millisecond or `mongosync` has not performed the ping yet, this field is absent. This field has a value of `-1` if the last ping attempt failed.\n\n
\n`directionMapping`\n\n\nobject\n\n\nDescribes the mapping direction for the synchronization, namely the source and destination clusters.\n\n
\n`directionMapping`\n`.Source`\n\n\nstring\n\n\nSource cluster. Returned in the form `: :`.\n\n
\n`directionMapping`\n`.Destination`\n\n\nstring\n\n\nDestination cluster. Returned in the form `: :`.\n\n
\n`estimatedOplogTimeRemaining`\n\n\nstring\n\n\nShows estimate of the oplog time available on the source cluster. Possible values include a duration (for example, `\"12 hours\"`, `\"4 hours\"`, or `\"45 minutes\"`) and special cases such as `\"more than 72 hours\"`, `\"less than 15 minutes\"`, and `\"not checked yet\"`.\n\n`mongosync` calculates `estimatedOplogTimeRemaining` as the time window between the oldest available oplog entry on the source cluster and the oldest oplog entry that `mongosync` still needs to complete successfully. `mongosync` updates this value every five minutes.\n\nIMPORTANT: If you increase the oplog size on the source cluster, `estimatedOplogTimeRemaining` might not increase immediately. As `mongosync` processes the source oplog, the available oplog window typically increases.\n\n`mongosync` reports `estimatedOplogTimeRemaining` only while it checks oplog time. `mongosync` includes this field only when it is in the `RUNNING` state and only before the `/progress` endpoint returns `canWrite=true`.\n\n
\n`estimatedSecondsToCEACatchup`\n\n\ninteger\n\n\nEstimated time in seconds remaining in the Change Event Application (CEA) phase, based on how much `lag.overallLagSeconds` has decreased over a recent interval.\n\n`/progress` does not report `estimatedSecondsToCEACatchup` if `mongosync` is not in CEA, or if `lag.overallLagSeconds` has increased or stayed the same over the most recent interval. In this case, wait 30 minutes and then try again.\n\n
\n`mongosyncID`\n\n\nstring\n\n\nIdentifier string for the `mongosync` instance.\n\n
\n`coordinatorID`\n\n\nstring\n\n\nIdentifier string for the coordinator instance.\n\n- When `mongosync` is coordinated by another instance, this field shows the identifier string for the coordinator instance.\n\n- When `mongosync` is a coordinator or runs alone, this field returns the same value as its `mongosyncID` field.\n\n- When `mongosync` starts up, this field returns `null` until `mongosync` identifies the coordinator.\n\n
\n`source.` `pingLatencyMs`\n\n\ninteger\n\n\nProvides the last-known ping latency, in milliseconds, from `mongosync` to the source cluster. This field is refreshed every 30 seconds while replication is still in progress and reported in the response. If latency is less than `1` millisecond or `mongosync` has not performed the ping yet, this field is absent. This field has a value of `-1` if the last ping attempt failed.\n\n
\n`verification`\n\n\ndocument\n\n\nProvides information on the phase and progress of verification checks performed by the embedded verifier.\n\n
\n`verification.source`\n\n\ndocument\n\n\nProvides information on the phase and progress of verification checks running on the source cluster.\n\n
\n`verification.source.` `estimatedDocumentCount`\n\n\ninteger\n\n\nEstimated number of documents on the source cluster.\n\n
\n`verification.source.` `hashedDocumentCount`\n\n\ninteger\n\n\nNumber of documents hashed by the verifier on the source cluster.\n\n
\n`verification.source.` `lagTimeSeconds`\n\n\ninteger\n\n\nTime in seconds after the last verification check was performed on the source cluster.\n\n
\n`verification.source.` `phase`\n\n\nstring\n\n\nCurrent phase of the verification process on the source cluster. This can be one of three values:\n\n- `\"not started\"`: The verifier has not started any initial collection scans for this cluster.\n\n- `\"initial hashing\"`: The verifier is doing its initial scan for at least one collection in the cluster.\n\n- `\"stream hashing\"`: The verifier has finished its initial scan for the cluster and is now following its change stream.\n\nIf the verifier needs to re-scan a collection, the verifier can go back to the `\"initial hashing\"` phase even if the endpoint previously reported the `\"stream hashing\"` phase.\n\nStarting in `mongosync` 1.22, the verifier reports `\"not started\"` until `mongosync` reaches the Change Event Application phase.\n\n
\n`verification.source.` `scannedCollectionCount`\n\n\ninteger\n\n\nNumber of collections scanned by the embedded verifier on the source cluster.\n\n
\n`verification.source.` `totalCollectionCount`\n\n\ninteger\n\n\nNumber of collections on the source cluster to include in verification checks.\n\n
\n`verification.destination`\n\n\ndocument\n\n\nProvides information on the phase and progress of verification checks running on the destination cluster.\n\n
\n`verification.destination.` `estimatedDocumentCount`\n\n\ninteger\n\n\nEstimated number of documents on the destination cluster.\n\n
\n`verification.destination.` `hashedDocumentCount`\n\n\ninteger\n\n\nNumber of documents hashed by the verifier on the destination cluster.\n\n
\n`verification.destination.` `lagTimeSeconds`\n\n\ninteger\n\n\nTime in seconds since the last verification check performed on the destination cluster.\n\n
\n`verification.destination.` `phase`\n\n\nstring\n\n\nCurrent phase of the verification process on the destination cluster. This can be one of three values:\n\n- `\"not started\"`: The verifier has not started any initial collection scans for this cluster."} -{"chunk_id": "69746408fe5a47168d5fca7f-3", "page_id": "69746408fe5a47168d5fca7f", "source_name": "mongosync", "product_name": "Mongosync", "url": "https://mongodb.com/docs/mongosync/current/reference/api/progress", "title": "`progress`", "text": "- `\"initial hashing\"`: The verifier is doing its initial scan for at least one collection in the cluster.\n\n- `\"stream hashing\"`: The verifier has finished its initial scan for the cluster and is now following its change stream.\n\nIf the verifier needs to re-scan a collection, the verifier can go back to the `\"initial hashing\"` phase even if the endpoint previously reported the `\"stream hashing\"` phase.\n\nStarting in `mongosync` 1.22, the verifier reports `\"not started\"` until `mongosync` reaches the Change Event Application phase.\n\n
\n`verification.destination.` `scannedCollectionCount`\n\n\ninteger\n\n\nNumber of collections scanned by the embedded verifier on the destination cluster.\n\n
\n`verification.destination.` `totalCollectionCount`\n\n\ninteger\n\n\nNumber of collections on the destination cluster to include in verification checks.\n\n
\n`warnings`\n\n\narray of strings\n\n\nWarning messages that `mongosync` detects. If `mongosync` detects no warnings, it omits this field.\n\nIf the estimated oplog time remaining is very low, `mongosync` adds a warning that describes the issue and links to the documentation. For example:\n\n```json\n\"warnings\": [\n \"The amount of available oplog on the source cluster is too small for mongosync to complete successfully.\n For more details, see https://www.mongodb.com/docs/cluster-to-cluster-sync/current/reference/oplog-sizing/.\"\n]\n```\n\nFor more details, see oplog Sizing.\n\nIf `mongosync` blocks user writes on the source cluster, `mongosync` adds a warning to the `warnings` field. To learn more, see Write Blocking.\n\n
\n\n### Error Response\n\nIf `mongosync` encounters an error, the `progress` endpoint returns the following fields:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nField\n\n\nType\n\n\nDescription\n\n
\n`success`\n\n\nboolean\n\n\nStatus of the `progress` command. Value is `true` if the command succeeds and `false` if the command fails.\n\n
\n`error`\n\n\nstring\n\n\nType of error.\n\n
\n`errorDescription`\n\n\nstring\n\n\nDetailed description of the error.\n\n
\n\n## Behavior\n\n- When `mongosync` is in the `IDLE` state, all output fields except `state` and `canCommit` are `null`.\n\n- When `mongosync` is in the `PAUSED` state, the `lag` object is `null` and the deprecated `lagTimeSeconds` field is `null`.\n\n- When `mongosync` is in the `INITIALIZING` state, `mongosync` rejects `/start` requests. Once initialization completes, `mongosync` returns `IDLE` and accepts `/start` requests.\n\n If `mongosync` resumes or restarts after a crash, once initialization completes, the `/progress` response returns the `state` before the crash.\n\n- The endpoint does not auto-refresh. To get updated status, call the `progress` endpoint again.\n\n- Calls to `/progress` before `mongosync` reaches the collection copy phase return 0 for `estimatedCopiedBytes` and 1 for `estimatedTotalBytes`.\n\n- During collection copy, `estimatedTotalBytes` only changes if `estimatedCopiedBytes` exceeds it. In that case, `mongosync` raises `estimatedTotalBytes` to equal `estimatedCopiedBytes`.\n\n- At the end of collection copy, `estimatedTotalBytes` equals `estimatedCopiedBytes`. `mongosync` uses the total bytes copied as the source of truth. Both values are best-effort estimates.\n\n### Change Event Application Stages\n\nThe `ceaStage` field reports how far `mongosync` has progressed through the Change Event Application (CEA) phase. `ceaStage` can help you interpret `mongosync` lag.\n\nDuring `\"collection copy drain\"`, `mongosync` applies change events accumulated during collection copy. Because collection copy might have already copied a document whose insert remains queued in the backlog, replaying that insert can produce an expected duplicate key error. Handling these errors can temporarily reduce CEA throughput, so lag may increase during this stage without indicating a problem.\n\nWhen `ceaStage` is `\"steady state\"`, `mongosync` processes only source writes that occur after collection copy finishes. If `mongosync` throughput exceeds the source write rate, lag should decrease.\n\nIf lag continues to increase while `ceaStage` is `\"steady state\"`, `mongosync` is not keeping up with the source cluster. Unless the source write rate decreases or the CEA throughput increases, `mongosync` cannot catch up and complete the migration. In this case, you can do one of the following:\n\n- Increase the `--loadLevel` value, if CPU usage permits.\n\n- Size up the destination cluster to add more CPU capacity.\n\n- Lower the source cluster's write rate, if possible.\n\n### Endpoint Protection\n\n`progress``mongosync` does not protect the `progress` endpoint. However, by default the API binds to localhost only and does not accept calls from other sources. Additionally, the `progress` call does not expose connection credentials or user data.\n\n## Example\n\nThe following example returns the status of the synchronization process.\n\n### Request\n\n```shell\ncurl localhost:27182/api/v1/progress -XGET\n\n```\n\n### Response\n\n```json\n{\n \"progress\":\n {\n \"state\":\"RUNNING\",\n \"canCommit\":true,\n \"canWrite\":false,\n \"info\":\"change event application\",\n \"ceaStage\":\"steady state\",\n \"lag\": {\n \"overallLagSeconds\": 0,\n \"crudLagSeconds\": 0,\n \"ddlLagSeconds\": null\n },\n \"lagTimeSeconds\":0,\n \"collectionCopy\":\n {\n \"estimatedTotalBytes\":694,\n \"estimatedCopiedBytes\":694\n },\n \"directionMapping\":\n {\n \"Source\":\"cluster0: localhost:27017\",\n \"Destination\":\"cluster1: localhost:27018\"\n },\n \"source\":\n {\n \"pingLatencyMs\":250\n },\n \"destination\":\n {\n \"pingLatencyMs\":-1\n },\n \"verification\":\n {\n \"source\":\n {\n \"estimatedDocumentCount\": 42,\n \"hashedDocumentCount\": 42,\n \"lagTimeSeconds\": 2,\n \"totalCollectionCount\": 42,\n \"scannedCollectionCount\": 10,\n \"phase\": \"stream hashing\"\n\n },\n \"destination\": {\n \"estimatedDocumentCount\": 42,\n \"hashedDocumentCount\": 42,\n \"lagTimeSeconds\": 2,\n \"totalCollectionCount\": 42,\n \"scannedCollectionCount\": 10,\n \"phase\": \"stream hashing\"\n }\n }\n },\n \"success\": true\n}\n\n```"} -{"chunk_id": "69746408fe5a47168d5fcae2-0", "page_id": "69746408fe5a47168d5fcae2", "source_name": "mongosync", "product_name": "Mongosync", "url": "https://mongodb.com/docs/mongosync/current/reference/oplog-sizing", "title": "oplog Sizing", "text": "# oplog Sizing\n\nThe mongosync program uses change streams to synchronize data between source and destination clusters. `mongosync` does not access the oplog directly, but when a change stream returns events from the past, the events must be within the `oplog` time range.\n\n`mongosync` applies operations in the `oplog` on the source cluster to the data on the destination cluster after the collection copy phase. When operations that `mongosync` has not applied roll off the `oplog` on the source cluster, the sync fails and `mongosync` exits.\n\n`mongosync` does not replicate `applyOps` operations made on the source cluster during sync to the destination cluster.\n\nIf you anticipate syncing a large data set, or if you plan to pause synchronization for an extended period of time, you might exceed the oplog window. Use the `oplogSizeMB` setting to increase the size of the `oplog` on the source cluster.\n\n## Considerations\n\nThe destination cluster must have enough disk storage to accommodate the logical data size being migrated and the destination oplog entries from the initial sync. For example, to migrate 10 GB of data, the destination cluster must have at least 10 GB available for the data and another 10 GB for the insert oplog entries from the initial sync.\n\nTo use embedded verification, you must have a larger oplog on the destination. If you enable the embedded verifier and reduce the size of the destination oplog, the embedded verifier might not be able to keep up, causing `mongosync` to error.\n\nIf you need to reduce the overhead of the destination oplog entries and the embedded verifier is disabled, you can:\n\n- Use the `oplogSizeMB` setting to lower the destination cluster's oplog size.\n\n- Use to `oplogMinRetentionHours` setting to lower or remove the destination cluster's minimum oplog retention period.\n\n## Monitor oplog Size Needed for Initial Sync\n\n### Determine oplog window.\n\nTo get the difference in seconds between the first and last entry in the `oplog` run `db.getReplicationInfo()`. If you are replicating a sharded cluster, run the command on each shard.\n\n```javascript\ndb.getReplicationInfo().timeDiff\n\n```\n\nThe value returned is the minimum `oplog` window of the cluster. If there are multiple shards, the smallest number is the minimum `oplog` window.\n\n### Determine `mongosync` replication lag.\n\nTo get the `lag.overallLagSeconds` value, run the /progress command. The lag time is the time in seconds between the last event applied by `mongosync` and time of the current latest event on the source cluster.\n\nIt is a measure of how far behind the source cluster `mongosync` is.\n\n### Validate oplog size.\n\nIf the lag time approaches the minimum `oplog` window, make one of the following changes:\n\n- Increase the `oplog` window. Use `replSetResizeOplog` to set `minRetentionHours` greater than the current `oplog` window.\n\n `replSetResizeOplog` is unsupported in Atlas. To resize the oplog in Atlas, see Set Minimum Oplog Window.\n\n- Scale up the `mongosync` instance. Add CPU or memory to scale up the `mongosync` node so that it has a higher copy rate.\n\nThe oplog window and rate of change for replication lag may vary during synchronization. Repeat these steps during a migration to monitor the progress."} -{"chunk_id": "69746408fe5a47168d5fca5a-0", "page_id": "69746408fe5a47168d5fca5a", "source_name": "mongosync", "product_name": "Mongosync", "url": "https://mongodb.com/docs/mongosync/current/faq", "title": "Frequently Asked Questions", "text": "# Frequently Asked Questions\n\nThis page provides answers to some frequently asked questions we have encountered. If you have additional questions please contact MongoDB Support.\n\n## Can I change the load level while `mongosync` is syncing?\n\nYes, you can adjust the cluster workload level during a migration by following the steps in Reconfigure `mongosync` During Synchronization.\n\n## Can I perform reads or writes to my destination cluster while `mongosync` is syncing?\n\n`mongosync` combines and reorders writes from the source to the destination during synchronization, and temporarily modifies collection characteristics. As a result, `mongosync` can't guarantee that the destination matches the source, including a stale version of the source, at any point in time when the sync is running, even if the sync is paused. To safely accept traffic to the migrated collections on the destination cluster, wait for the migration to `commit`. To learn more, see Mid-sync Considerations.\n\nPerforming writes to your migrated collections on the destination cluster during synchronization might cause one or more of the following issues:\n\n- If verification is enabled, writes to the migrated collections on the destination cluster during synchronization might cause the verification phase to fail.\n\n- If verification is disabled, writes to the migrated collections on the destination cluster during synchronization might cause `mongosync` to fail.\n\n- If `mongosync` does not fail, writes to the migrated collections on the destination cluster can conflict with `mongosync` writes. These conflicts might overwrite either the user or `mongosync` writes and leave the destination cluster with inconsistent data, even if `mongosync` commits successfully.\n\n`mongosync` blocks writes on the destination cluster by default. To learn more about write-blocking, see Write Blocking and `start`.\n\nUpon commit, it is only safe to write to your migrated collections on the destination cluster when `canWrite` is `true`. To check the value of `canWrite`, run the `progress` endpoint.\n\nTo learn more about permissable reads and writes during synchronization, see Reads and Writes.\n\nIndex builds on the destination cluster are treated as writes while `mongosync` is syncing.\n\n## Can I use `mongosync` for continuous synchronization between two MongoDB clusters?\n\nFor example, can I maintain a secondary cluster for Disaster Recovery, Analytics, or other similar use cases?\n\nNo, `mongosync` is designed to support one-time migrations. `mongosync` must `commit` in order to safely accept read or write traffic to the migrated collections on the destination cluster. Therefore, Disaster Recovery, Analytics, and other similar use cases are not supported workflows for `mongosync`.\n\nFor more information, see Can I perform reads or writes to my destination cluster while `mongosync` is syncing?.\n\n## Why are the destination cluster indexes larger than the source cluster indexes?\n\nThe following factors may contribute to an increase in index size on destination clusters:\n\n- `mongosync` inserts and removes data during a migration, which can cause data to be stored inefficiently on disk.\n\n- By default, `mongosync` builds indexes before copying data. `mongosync` copies data in `_id` order. If an index is not correlated with `_id`, the index size can become large. For more information, see the MongoDB Manual FAQ: Indexes page.\n\nUse the following methods to mitigate an increase in index size:\n\n- Restart the migration with the `buildIndexes`\n parameter set to `never`. When the migration finishes, manually build indexes on the destination cluster.\n\n- After the migration, perform a rolling initial sync on the destination cluster.\n\n- After the migration, run compact (database command) on the destination cluster. This rebuilds indexes and releases unneeded disk space to the OS, but may impact cluster performance.\n\n## Can `mongosync` run on its own hardware?\n\nYes, `mongosync` can run on its own hardware. `mongosync` does not have to run on the servers that host your MongoDB instances. When `mongosync` runs on its own hardware, it can use an operating system (OS) that is different than the OS on the source or destination clusters.\n\n## What hardware specifications should the destination cluster have?\n\nFor most migrations, the destination cluster should have higher hardware specifications than the source cluster, including the following properties:\n\n- CPU\n\n- Memory\n\n- Disk I/O\n\nThese hardware specifications ensure that the destination cluster can handle `mongosync` writes and that the sync can keep up with the source cluster's workload.\n\nThe destination cluster must have enough disk storage to accommodate the logical data size being migrated and the destination oplog entries from the initial sync. For example, to migrate 10 GB of data, the destination cluster must have at least 10 GB available for the data and another 10 GB for the insert oplog entries from the initial sync.\n\nTo use embedded verification, you must have a larger oplog on the destination. If you enable the embedded verifier and reduce the size of the destination oplog, the embedded verifier might not be able to keep up, causing `mongosync` to error.\n\nIf you need to reduce the overhead of the destination oplog entries and the embedded verifier is disabled, you can:\n\n- Use the `oplogSizeMB` setting to lower the destination cluster's oplog size.\n\n- Use to `oplogMinRetentionHours` setting to lower or remove the destination cluster's minimum oplog retention period.\n\n## Should I increase the size of the `oplog` in the source cluster?\n\n`mongosync` applies operations in the `oplog` on the source cluster to the data on the destination cluster after the collection copy phase. When operations that `mongosync` has not applied roll off the `oplog` on the source cluster, the sync fails and `mongosync` exits.\n\n`mongosync` does not replicate `applyOps` operations made on the source cluster during sync to the destination cluster.\n\nIf you anticipate syncing a large data set, or if you plan to pause synchronization for an extended period of time, you might exceed the oplog window. Use the `oplogSizeMB` setting to increase the size of the `oplog` on the source cluster.\n\n## Which connection string options does `mongosync` allow?\n\n`mongosync` requires readConcern: \"majority\" and writeConcern: \"majority\".\n\nIf the `readConcern` is not `majority`, `mongosync` returns an error:\n\n```shell\nInvalid URI option, read concern must be majority\n\n```\n\nIf the `writeConcern` is not `majority`, `mongosync` returns an error:\n\n```shell\nInvalid URI option, write concern must be majority\n\n```\n\n`mongosync` accepts all other connection string options.\n\n## Does `mongosync` support network compression?\n\n`mongosync` supports network compression and enables it by default. However, your cluster configurations must share at least one common compressor.\n\nFor more information about network compression configuration options, see the `--networkMessageCompressors` option in the Database Manual.\n\n## Which security and authentication options are supported?\n\n`mongosync` uses a standard MongoDB connection string to connect to the source and destination clusters.\n\nLDAP and X509 are supported. For available authentication options, see Authentication on Self-Managed Deployments."} -{"chunk_id": "69746408fe5a47168d5fca5a-1", "page_id": "69746408fe5a47168d5fca5a", "source_name": "mongosync", "product_name": "Mongosync", "url": "https://mongodb.com/docs/mongosync/current/faq", "title": "Frequently Asked Questions", "text": "## Does `mongosync` automatically restart on error?\n\n`mongosync` does not automatically restart on error. However, you can write a script or use your operating system's process managers, `systemd` for example, to restart the `mongosync` process.\n\nThe `mongosync` binary is stateless. The metadata for restarting is stored on the destination cluster.\n\nA `mongosync` operation can be resumed if `mongosync` becomes unavailable during synchronization. When `mongosync` becomes available again, restart the `mongosync` process with the same parameters. `mongosync` resumes the operation from where it stopped when `mongosync` became unavailable.\n\nStarting in `mongosync` 1.7.3, `mongosync` can take at least two minutes to respond when you resume or restart a sync operation. During this time, any calls to the `progress` endpoint might fail. If a `progress` call fails, it is safe to retry.\n\n## Can the source or destination be a replica set with arbiters?\n\nYes, the replica set can have arbiters. The source replica set must have more than 2 non-arbiter nodes and you must sync from a non-arbiter node. Use the source cluster's connection string to specify a read preference for a non-arbiter, data-bearing node.\n\n## What if I see a Slow Operation Warning?\n\nSlow operation warnings can occur during the initial sync or the application of a change event when there is a slow read operation on the source cluster or a slow write operation on the destination cluster. The warning may indicate network congestion or resource strain on the source or destination cluster.\n\nWhile these warnings do not indicate failures in themselves, slow operations can cause operation timeout errors in `mongosync` and migration failures.\n\nIf you see slow operation warnings, check CPU, memory, and network usage on the source and destination clusters. If the clusters are underprovisioned for your needs, consider upgrading the cluster hardware.\n\n## Should I stop a migration if the logs contain the word \"error\" or \"failure\"?\n\nNo, logs that contain the word \"error\" or \"failure\" show non-fatal errors and do not signal that you need to stop `mongosync` early. These logs do not indicate that `mongosync` is failing or corrupting data. If a fatal error occurs, `mongosync` stops the sync and writes a fatal log entry.\n\n## What if I see a lot of duplicate key errors in the logs?\n\nDuplicate key errors are a normal part of the sync process. These errors can occur if:\n\n- You insert a document on the source cluster after `mongosync` starts. `mongosync` may directly copy the document and redundantly apply the insert change event for the document later.\n\n- You stop and resume `mongosync`. This can lead to duplicate insertions when `mongosync` restarts.\n\n- `mongosync` encounters a transient error and reattempts an insertion that may have already succeeded.\n\n## What should I do if `mongosync` returns a fatal error?\n\nA fatal error indicates a problem that must be corrected and requires the migration to be restarted. After addressing the error, delete all migrated data on the destination cluster, including the `__mdb_internal_mongosync` database. Then, relaunch `mongosync` and start a new migration.\n\n## Does `mongosync` Support TTL Indexes?\n\nMongosync supports syncing TTL Indexes from the source to the destination cluster.\n\n## Can I customize chunk distributions when syncing into a sharded cluster?\n\nNo, you can't configure `mongosync` to customize chunk distributions on a destination sharded cluster. `mongosync` samples each collection during initialization to determine how to distribute documents efficiently across the destination cluster\u2019s shards after migration.\n\n## Where can I find the `mongosync` license?\n\nThe `mongosync` download includes the `mongosync` license. After you extract the downloaded archive, find the `LICENSE` file in the `mongosync` installation directory."} -{"chunk_id": "69746408fe5a47168d5fca69-0", "page_id": "69746408fe5a47168d5fca69", "source_name": "mongosync", "product_name": "Mongosync", "url": "https://mongodb.com/docs/mongosync/current/installation/verify/rpm", "title": "Verify RPM Packages (RHEL)", "text": "# Verify RPM Packages (RHEL)\n\nThe MongoDB release team digitally signs `mongosync` packages to certify that the packages are a valid and unaltered MongoDB release. Before you install `mongosync`, you can use the digital signature to validate the package.\n\nThis page describes how to verify `.rpm` packages on RHEL operating systems.\n\n## Before you Begin\n\nIf you don't have `mongosync` installed, download the `mongosync` package from the Download Center.\n\n## Steps\n\n### Import the MongoDB Server Tools public key in gpg and rpm\n\n```shell\ncurl https://pgp.mongodb.com/server-Tools.asc | gpg --import\n\nrpm --import https://pgp.mongodb.com/server-Tools.asc\n\n```\n\nIf the key imports successfully, the command returns:\n\n```shell\ngpg: key 3132835C1D925D5B: public key \"MongoDB CLI Tools Release Signing Key \" imported\ngpg: Total number processed: 1\ngpg: imported: 1\n\n```\n\nIf you have previously imported the key, the command returns:\n\n```shell\ngpg: key 3132835C1D925D5B: \"MongoDB CLI Tools Release Signing Key \" not changed\ngpg: Total number processed: 1\ngpg: unchanged: 1\n\n```\n\n### Verify the rpm file\n\n```shell\nrpm --checksig \n\n```\n\nIf the file is signed, the command returns:\n\n```shell\n digests signatures OK\n\n```"} -{"chunk_id": "69746408fe5a47168d5fcb7f-0", "page_id": "69746408fe5a47168d5fcb7f", "source_name": "mongosync", "product_name": "Mongosync", "url": "https://mongodb.com/docs/mongosync/current/release-notes/1.16", "title": "Release Notes for mongosync 1.16", "text": "# Release Notes for mongosync 1.16\n\nThis page describes changes and new features introduced in MongoDB Mongosync 1.16.\n\n## 1.16.0 Release\n\n**August 12, 2025**\n\n### New Features\n\n#### Natural Scan Capability\n\nStarting in version 1.16.0, `mongosync` supports copy in natural sort order for databases and collections to the destination cluster with the `copyInNaturalOrder` parameter in the /start API endpoint.\n\nFor more information, see /start Request Body Parameters.\n\n#### Build Indexes After Data Copy\n\nAdds new options for the `buildIndexes` parameter in the /start API endpoint:\n\n- `afterDataCopy` option causes `mongosync` to build indexes on the destination cluster after collection copy, reducing migration time.\n\n- `excludeHashedAfterCopy` option causes `mongosync` to build non-hashed indexes on the destination cluster after collection copy.\n\nFor more information, see /start Request Body Parameters.\n\n#### OTel Metrics Logs\n\nAdds new configuration options for OpenTelemetry (OTel) metrics logging when running the `mongosync` binary:\n\n- `disableMetricsLogging` to disable the default metrics logging behavior.\n\n- `metricsLoggingFilepath` to specify the file path for metrics logging.\n\nFor more information, see Mongosync Metrics.\n\n### Live Upgrades\n\nLive upgrades to 1.16 are not supported.\n\n## Minimum Supported Version\n\nFor information on minimum supported versions, see MongoDB Server Version Compatibility.\n\nFor best performance, upgrade your source and destination clusters to the most recent MongoDB Server patch release prior to migration. For more information, see Upgrade to the Latest Self-Managed Patch Release of MongoDB."} -{"chunk_id": "69746408fe5a47168d5fcb37-0", "page_id": "69746408fe5a47168d5fcb37", "source_name": "mongosync", "product_name": "Mongosync", "url": "https://mongodb.com/docs/mongosync/current/reference/versioning", "title": "`mongosync` Versioning", "text": "# `mongosync` Versioning\n\nMongosync uses Semantic Versioning 2.0.0. Version numbers have the form `X.Y.Z`, where `X` is the major version, `Y` is the minor version, and `Z` is the patch version.\n\nMongoDB uses the following guidelines to determine when to increment the version number for Mongosync:\n\n- Major number: The release breaks backwards compatibility.\n\n- Minor number: The release includes significant new features that are backwards compatible.\n\n- Patch number: This release only includes small, backwards compatible changes.\n\n## Currently Supported Versions\n\nMongoDB only supports the latest patch release of each major version. For example, `mongosync` 1.22.0 is the latest patch release of 1.22. If you are using an unsupported version of `mongosync`, you might be asked to upgrade in order to receive support.\n\nMongoDB supports `mongosync` with the latest MongoDB Server patch release. For example, once MongoDB Server v8.0.2 is released support is no longer provided for `mongosync` with MongoDB Server v8.0.1.\n\n## Version-Related Considerations\n\nMongosync has the following version related considerations:\n\n### Support Lifecycle\n\n- Major releases are supported for at least one year from the first release in that series.\n\n- If a version of Mongosync only works with an unsupported version of MongoDB Server, that version of Mongosync is also unsupported.\n\n### Patch Releases\n\nOnly the latest version in each major release series receives new patch releases. For example, when version Mongosync 2.1.0 is released, version 2.0 would no longer receive patch releases. At the same time, version 1.3 would continue to receive patches until version 1.4 was released.\n\n### Live Upgrades\n\nStarting in `mongosync` 1.7.0, you can upgrade `mongosync` without restarting data synchronization operations from the beginning.\n\n`mongosync` does not support live upgrades to all versions. To see if you can live upgrade to a specific version, check that version's release notes and see the **Live Upgrades** section.\n\nAfter the live upgrade, `mongosync` continues operations that were in progress before the upgrade.\n\nTo live upgrade `mongosync`, perform these steps:\n\n#### (Optional) Pause the `mongosync` processes\n\nTo pause `mongosync`, run `pause` on each running `mongosync` process.\n\nYou can resume the `mongosync` processes later from the paused state, as shown in the final step.\n\nIf you don't want to immediately resume data synchronization operations after live upgrade, consider pausing the `mongosync` processes. This is useful if you're coordinating operations from multiple `mongosync` processes.\n\n#### Stop the `mongosync` processes\n\nUse your operating system to stop each running `mongosync` process. To stop a process, see your operating system documentation for the specific steps.\n\n#### Download and install the new `mongosync` binaries\n\nTo download and install the new `mongosync` binaries, see download and install mongosync.\n\n#### Initialize the `mongosync` processes\n\nTo initialize the `mongosync` processes, see Quickstart. During initialization after a live upgrade, `mongosync` updates the persistent metadata.\n\n#### Resume the `mongosync` processes\n\nIf you paused any `mongosync` processes earlier in the optional first step, run `resume` on all `mongosync` processes.\n\nIf a data synchronization operation was already in progress before the live upgrade, new features added in the latest `mongosync` version may not all be supported after the live upgrade. Performance improvements and bug fixes are always supported after the live upgrade.\n\n### Persistent Metadata\n\nDuring normal operation, `mongosync` creates metadata that is persisted to disk in the destination database. This metadata is not versioned and may change at any time.\n\n### Log Messages\n\nLog message formats are not versioned and may change at any time. This includes changes to the message text, as well as the presence, absence, or contents of other fields in the message.\n\nUser scripts and applications should not rely on logging output. Scripts and applications should use the monitoring API to determine the current state of `mongosync`.\n\n## Examples\n\nThe following examples illustrate the kinds of changes that would result in each type of version number update.\n\n### Major Releases\n\n- Changes that make the new and old versions of `mongosync` produce different results on the destination cluster for the same set of inputs. Except:\n\n - Bug fixes for cases where the older version of `mongosync` fails to replicate data.\n\n - When the earlier behavior is explicitly documented as unsupported.\n\n- Changes to documented CLI parameters or configuration keys such that `mongosync` rejects formerly valid input. Except:\n\n - Bug fixes such as parsing or type errors.\n\n - Even though CLI parameters or configuration keys may be deprecated, the meaning of documented CLI parameters or configuration keys will never change. If needed, new parameters or keys will replace the older, deprecated entities.\n\n- Changes that break compatibility with a supported version of MongoDB Server.\n\n- Dropping a version of the REST API. `mongosync` may drop all older endpoints in favor of a new version of the API. There will never be any other types of backwards incompatible changes in the REST API.\n\n- Removing support for a previously supported MongoDB Server feature if `mongosync` still supports a version of MongoDB Server that supports the feature.\n\n- If `mongosync` already supports a major version of MongoDB Server, changes that require new access privileges in order to continue supporting that version of MongoDB Server.\n\n### Minor Releases\n\n- Adding support for a previously incompatible MongoDB Server version.\n\n- Requiring new access privileges for a previously unsupported major release of MongoDB Server.\n\n- Adding support for previously unsupported collection types.\n\n- Adding support for previously unsupported index types.\n\n- Adding new endpoints, new fields, or new accepted inputs in the REST API.\n\n- Adding new documented CLI options.\n\n- Adding new configuration keys or accepted values.\n\n### Patch Releases\n\n- Backwards compatible bug fixes.\n\n- Performance regression fixes.\n\n- Performance improvements.\n\n- Changes to help text strings.\n\n- Changes to log text strings.\n\n- Changes to informational text in API responses, but not changes to enum-style string fields like \"state\".\n\n- Typo fixes."} -{"chunk_id": "68b144e0d523194d210635a1-0", "page_id": "68b144e0d523194d210635a1", "source_name": "node", "product_name": "Node.js Driver", "url": "https://mongodb.com/docs/drivers/node/current/security/authentication/scram", "title": "SCRAM Authentication Mechanisms", "text": "# SCRAM Authentication Mechanisms\n\n## Overview\n\n**Salted Challenge Response Authentication Mechanism (SCRAM)** is a family of authentication mechanisms that use a challenge-response mechanism to authenticate the user. SCRAM-SHA-256, which uses the SHA-256 algorithm to hash your password, is the default authentication mechanism in MongoDB Server version 4.0 and later. SCRAM-SHA-1, which uses the SHA-1 algorithm instead, is the default authentication mechanism in MongoDB Server versions earlier than 4.0.\n\nYou can use SCRAM to authenticate to MongoDB Atlas, MongoDB Enterprise Advanced, and MongoDB Community Edition.\n\nTo learn more about the SCRAM family of authentication mechanisms, see RFC 5802 and Salted Challenge Response Authentication Mechanism on Wikipedia.\n\nFor more information about the MongoDB implementation of SCRAM, see SCRAM in the MongoDB Server manual.\n\n### Code Placeholders\n\nThe code examples on this page use the following placeholders:\n\n- ``: The MongoDB username of the user to authenticate.\n\n- ``: The MongoDB password of the user to authenticate.\n\n- ``: The network address of your MongoDB deployment.\n\nTo use the code examples, replace these placeholders with your own values.\n\n## Default Authentication Mechanism\n\nThe `DEFAULT` authentication mechanism is a fallback setting that instructs the driver to negotiate the first authentication mechanism supported by the server in the following order of preference:\n\n1. `SCRAM-SHA-256`\n\n2. `SCRAM-SHA-1`\n\n3. `MONGODB-CR`\n\nIf the `DEFAULT` option is specified, the driver first attempts to authenticate using `SCRAM-SHA-256`. If the version of the MongoDB instance does not support that mechanism, the driver attempts to authenticate using `SCRAM-SHA-1`. If the instance does not support that mechanism either, the driver attempts to authenticate using `MONGODB-CR`.\n\nYou can specify the default authentication mechanism by setting the `authMechanism` parameter to `DEFAULT` in the connection string, or by omitting the parameter since it is the default value.\n\nThe following example shows how to set the authentication mechanism to the default by setting `authMechanism` to `DEFAULT` in the connection string:\n\nAlways **URI encode** the username and password using the `encodeURIComponent` method to ensure they are correctly parsed.\n\n```javascript\nconst { MongoClient } = require(\"mongodb\");\n\n// Replace the following with values for your environment.\nconst username = encodeURIComponent(\"\");\nconst password = encodeURIComponent(\"\");\nconst clusterUrl = \"\";\n\nconst authMechanism = \"DEFAULT\";\n\n// Replace the following with your MongoDB deployment's connection string.\nconst uri =\n `mongodb+srv://${username}:${password}@${clusterUrl}/?authMechanism=${authMechanism}`;\n\n// Create a new MongoClient\nconst client = new MongoClient(uri);\n\n// Function to connect to the server\nasync function run() {\n try {\n // Establish and verify connection\n await client.db(\"admin\").command({ ping: 1 });\n console.log(\"Connected successfully to server\");\n } finally {\n // Ensures that the client will close when you finish/error\n await client.close();\n }\n}\nrun().catch(console.dir);\n\n```\n\nTo learn more about the SCRAM version that MongoDB supports, see the SCRAM section of the MongoDB Server manual.\n\n## SCRAM-SHA-256\n\n`SCRAM-SHA-256` is the default authentication method for MongoDB starting in version 4.0\n\n`SCRAM-SHA-256` is a SCRAM version that uses your username and password, encrypted with the `SHA-256` algorithm to authenticate your user.\n\nYou can specify this authentication mechanism by setting the `authMechanism` to the value `SCRAM-SHA-256` in the connection string as shown in the following sample code.\n\nAlways **URI encode** the username and password using the `encodeURIComponent` method to ensure they are correctly parsed.\n\n```javascript\nconst { MongoClient } = require(\"mongodb\");\n\n// Replace the following with values for your environment.\nconst username = encodeURIComponent(\"\");\nconst password = encodeURIComponent(\"\");\nconst clusterUrl = \"\";\n\nconst authMechanism = \"SCRAM-SHA-256\";\n\n// Replace the following with your MongoDB deployment's connection string.\nconst uri =\n `mongodb+srv://${username}:${password}@${clusterUrl}/?authMechanism=${authMechanism}`;\n\n// Create a new MongoClient\nconst client = new MongoClient(uri);\n\n// Function to connect to the server\nasync function run() {\n try {\n // Establish and verify connection\n await client.db(\"admin\").command({ ping: 1 });\n console.log(\"Connected successfully to server\");\n } finally {\n // Ensures that the client will close when you finish/error\n await client.close();\n }\n}\nrun().catch(console.dir);\n\n```\n\n## SCRAM-SHA-1\n\n`SCRAM-SHA-1` is the default authentication method for MongoDB versions 3.0, 3.2, 3.4, and 3.6.\n\n`SCRAM-SHA-1` is a SCRAM version that uses your username and password, encrypted with the `SHA-1` algorithm to authenticate your user.\n\nYou can specify this authentication mechanism by setting the `authMechanism` parameter to the value `SCRAM-SHA-1` in the connection string as shown in the following sample code.\n\nAlways **URI encode** the username and password using the `encodeURIComponent` method to ensure they are correctly parsed.\n\n```javascript\nconst { MongoClient } = require(\"mongodb\");\n\n// Replace the following with values for your environment.\nconst username = encodeURIComponent(\"\");\nconst password = encodeURIComponent(\"\");\nconst clusterUrl = \"\";\n\nconst authMechanism = \"SCRAM-SHA-1\";\n\n// Replace the following with your MongoDB deployment's connection string.\nconst uri =\n `mongodb+srv://${username}:${password}@${clusterUrl}/?authMechanism=${authMechanism}`;\n\n// Create a new MongoClient\nconst client = new MongoClient(uri);\n\n// Function to connect to the server\nasync function run() {\n try {\n // Establish and verify connection\n await client.db(\"admin\").command({ ping: 1 });\n console.log(\"Connected successfully to server\");\n } finally {\n // Ensures that the client will close when you finish/error\n await client.close();\n }\n}\nrun().catch(console.dir);\n\n```\n\n## API Documentation\n\nTo learn more about any of the methods or types discussed on this page, see the following API documentation:\n\n- MongoClient"} -{"chunk_id": "693a629b6857b32b32660f2e-0", "page_id": "693a629b6857b32b32660f2e", "source_name": "node", "product_name": "Node.js Driver", "url": "https://mongodb.com/docs/drivers/node/current/data-formats/bson/utf8-validation", "title": "UTF-8 Validation", "text": "# UTF-8 Validation\n\n## Overview\n\nIn this guide, you can learn how to enable or disable the Node.js driver's **UTF-8** validation feature. UTF-8 is a character encoding specification that ensures compatibility and consistent presentation across most operating systems, applications, and language character sets.\n\nIf you *enable* validation, the driver throws an error when it attempts to convert data that contains invalid UTF-8 characters. The validation adds processing overhead since it needs to check the data.\n\nIf you *disable* validation, your application avoids the validation processing overhead, but cannot guarantee consistent presentation of invalid UTF-8 data.\n\nBy default, the driver enables UTF-8 validation on data from MongoDB. It checks incoming documents for any characters that are not encoded in a valid UTF-8 format when it parses data sent from MongoDB to your application.\n\nThis version of the Node.js driver automatically substitutes invalid lone surrogates with the replacement character before validation when you send data to MongoDB. Therefore, the validation only throws an error when the setting is enabled and the driver receives invalid UTF-8 document data from MongoDB.\n\nRead the sections below to learn how to set UTF-8 validation using the Node.js driver.\n\n## Specify the UTF-8 Validation Setting\n\nYou can specify whether the driver performs UTF-8 validation by defining the `enableUtf8Validation` setting in the options parameter when you create a client, reference a database or collection, or call a CRUD operation. If you omit the setting, the driver enables UTF-8 validation.\n\nSee the following for code examples that demonstrate how to disable UTF-8 validation on the client, database, collection, or CRUD operation:\n\n```javascript\n// disable UTF-8 validation on the client\nnew MongoClient('', { enableUtf8Validation: false });\n\n// disable UTF-8 validation on the database\nclient.db('', { enableUtf8Validation: false });\n\n// disable UTF-8 validation on the collection\ndb.collection('', { enableUtf8Validation: false });\n\n// disable UTF-8 validation on a specific operation call\nawait myColl.findOne({ title: 'Cam Jansen'}, { enableUtf8Validation: false });\n```\n\nIf your application reads invalid UTF-8 from MongoDB while the `enableUtf8Validation` option is enabled, it throws a `BSONError` that contains the following message:\n\n```\nInvalid UTF-8 string in BSON document\n```\n\n### Set the Validation Scope\n\nThe `enableUtf8Validation` setting automatically applies to the scope of the object instance on which you included it, and any other objects created by calls on that instance.\n\nFor example, if you include the option on the call to instantiate a database object, any collection instance you construct from that object inherits the setting. Any operations you call on that collection instance also inherit the setting.\n\n```javascript\nconst database = client.db('books', { enableUtf8Validation: false });\n\n// The collection inherits the UTF-8 validation disabled setting from the database\nconst myColl = database.collection('mystery');\n\n// CRUD operation runs with UTF-8 validation disabled\nawait myColl.findOne({ title: 'Encyclopedia Brown' });\n```\n\nYou can override the setting at any level of scope by including it when constructing the object instance or when calling an operation.\n\nFor example, if you disable validation on the collection object, you can override the setting in individual CRUD operation calls on that collection.\n\n```javascript\nconst collection = database.collection('mystery', { enableUtf8Validation: false });\n\n// CRUD operation runs with UTF-8 validation enabled\nawait myColl.findOne({ title: 'Trixie Belden' }, { enableUtf8Validation: true });\n\n// CRUD operation runs with UTF-8 validation disabled\nawait myColl.findOne({ title: 'Enola Holmes' });\n```"} -{"chunk_id": "68b144e0d523194d2106353f-0", "page_id": "68b144e0d523194d2106353f", "source_name": "node", "product_name": "Node.js Driver", "url": "https://mongodb.com/docs/drivers/node/current/crud/transactions/transaction-core", "title": "Use the Core API", "text": "# Use the Core API\n\nYou can perform a transaction to run a series of operations that do not change any data until the entire transaction is committed. This usage example uses the **Core API** to perform a transaction.\n\nTo learn more about the performing transactions in the Node.js driver, see the Transactions guide.\n\nThe Node.js driver also provides the Convenient Transaction API to perform transactions. To learn more about the Convenient Transaction API, see the Use the Convenient Transaction API usage example.\n\n## Example\n\nConsider a situation in which a customer purchases items from your online shop. To record the purchase, your application must update your inventory and the customer's orders. Your application also needs to save the order details.\n\nThe following table describes the collections that store purchase data and how a purchase changes the data in each collection.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nCollection\n\n\nOperation\n\n\nDescription of the Change\n\n
\n`orders`\n\n\ninsert\n\n\nInserts a document that describes the order\n\n
\n`customers`\n\n\nupdate or upsert\n\n\nAppends the `_id` from the order document to the order history in the customer document\n\n
\n`inventory`\n\n\nupdate\n\n\nUpdates the quantities of items available after a purchase\n\n
### Sample Data\n\nThe code examples use the following sample data in the `testdb` database:\n\n- Documents in the `customers` collection that describe customers and their past orders\n\n- Documents in the `inventory` collection that include quantities and descriptions of all items\n\nThe following document is in the `customers` collection:\n\n```json\n{ _id: 98765, orders: [] }\n```\n\nThe `inventory` collection contains the following documents:\n\n```json\n{ item: \"sunblock\", item_id: 5432, qty: 85 },\n{ item: \"beach towel\", item_id: 7865, qty: 41 }\n```\n\nYou store purchase records in the `orders` collection of the `testdb` database. This collection is empty, as there have been no purchases.\n\nThe code examples use the `cart` and `payment` variables to represent a sample list of items purchased and the order payment details. The following code describes the contents of the `cart` and `payment` variables:\n\n```javascript\nconst cart = [\n { item: 'sunblock', item_id: 5432, qty: 1, price: 5.19 },\n { item: 'beach towel', item_id: 7865, qty: 2, price: 15.99 }\n];\nconst payment = { customer: 98765, total: 37.17 };\n```\n\n### Implementation\n\nThe code example in this section demonstrates how to use the Core API to perform a multi-document transaction in a session. In this example, the transaction makes the changes needed when a customer purchases items from your shop.\n\nThis example code performs a transaction through the following actions:\n\n1. Calls the `startSession()` method to create a new session\n\n2. Calls the `startTransaction()` method with an options parameter to create a new transaction\n\n3. Performs the following operations within the transaction:\n\n - Inserts a document to the `orders` collection that contains information about the purchase and customer\n\n - Updates the `inventory` collection if there is sufficient inventory to fulfill the purchase\n\n - Ends the transaction and throws an exception if there isn't sufficient inventory for any item in the order\n\n - Adds the ID of the order to the list of past orders for the customer\n\n - Returns a message acknowledging that the transaction committed successfully with a copy of the purchase record\n\n4. Calls the `commitTransaction()` method to commit the transaction if all operations complete successfully\n\n5. Implements a `catch` block that contains error-handling logic\n\n6. Calls the `abortTransaction()` method to end the transaction\n\n7. Calls the `endSession()` method to end the session\n\n```javascript\nasync function placeOrder(client, cart, payment) {\n const transactionOptions = {\n readConcern: { level: 'snapshot' },\n writeConcern: { w: 'majority' },\n readPreference: 'primary'\n };\n\n // Start the session\n const session = client.startSession();\n try {\n // Start the transaction in the session, specifying the transaction options\n session.startTransaction(transactionOptions);\n\n const ordersCollection = client.db('testdb').collection('orders');\n /* Within the session, insert an order that contains information about the\n customer, items purchased, and the total payment */\n const orderResult = await ordersCollection.insertOne(\n {\n customer: payment.customer,\n items: cart,\n total: payment.total,\n },\n { session }\n );\n\n const inventoryCollection = client.db('testdb').collection('inventory');\n\n for (const item of order) {\n /* Update the inventory for the purchased items. End the\n transaction if the quantity of an item in the inventory is\n insufficient to complete the purchase. */\n const inStock = await inventoryCollection.findOneAndUpdate(\n {\n item_id: item.item_id,\n item_id: { $gte: item.qty }\n },\n { $inc: { 'qty': -item.qty }},\n { session }\n )\n if (inStock === null) {\n throw new Error('Insufficient quantity or item ID not found.');\n }\n }\n\n const customerCollection = client.db('testdb').collection('customers');\n\n // Within the session, add the order details to the \"orders\" array of the customer document\n await customerCollection.updateOne(\n { _id: payment.customer },\n { $push: { orders: orderResult.insertedId }},\n { session }\n );\n\n // Commit the transaction to apply all updates performed within it\n await session.commitTransaction();\n console.log('Transaction successfully committed.');\n\n } catch (error) {\n /*\n Handle any exceptions thrown during the transaction and end the\n transaction. Roll back all the updates performed in the transaction.\n */\n if (error instanceof MongoError && error.hasErrorLabel('UnknownTransactionCommitResult')) {\n // Add your logic to retry or handle the error\n }\n else if (error instanceof MongoError && error.hasErrorLabel('TransientTransactionError')) {\n // Add your logic to retry or handle the error\n } else {\n console.log('An error occured in the transaction, performing a data rollback:' + error);\n }\n await session.abortTransaction();\n } finally {\n // End the session\n await session.endSession();\n }\n}\n```\n\nThe Node.js driver natively supports explicit resource management for `MongoClient`, `ClientSession`, `ChangeStreams`, and cursors. This feature is experimental and subject to change. To learn how to use explicit resource management, see the v6.9 Release Notes."} -{"chunk_id": "68b144e0d523194d2106353f-1", "page_id": "68b144e0d523194d2106353f", "source_name": "node", "product_name": "Node.js Driver", "url": "https://mongodb.com/docs/drivers/node/current/crud/transactions/transaction-core", "title": "Use the Core API", "text": "### Transaction Results\n\nThis section describes the data changes created by the transaction.\n\nThe `customers` collection contains the customer document with an order `_id` appended to the orders field:\n\n```json\n{\n \"_id\": 98765,\n \"orders\": [\n \"61dc...\"\n ]\n}\n```\n\nThe `inventory` collection contains updated quantities for the items `\"sunblock\"` and `\"beach towel\"`:\n\n```json\n[\n {\n \"_id\": ...,\n \"item\": \"sunblock\",\n \"item_id\": 5432,\n \"qty\": 84\n },\n {\n \"_id\": ...,\n \"item\": \"beach towel\",\n \"item_id\": 7865,\n \"qty\": 39\n }\n]\n```\n\nThe `orders` collection contains the order and payment information:\n\n```json\n[\n {\n \"_id\": \"...\",\n \"customer\": 98765,\n \"items\": [\n {\n \"item\": \"sunblock\",\n \"item_id\": 5432,\n \"qty\": 1,\n \"price\": 5.19\n },\n {\n \"item\": \"beach towel\",\n \"item_id\": 7865,\n \"qty\": 2,\n \"price\": 15.99\n }\n ],\n \"total\": 37.17\n }\n]\n```\n\n## API Documentation\n\nTo learn more about any of the methods or types discussed in this usage example, see the following API Documentation:\n\n- TransactionOptions\n\n- ClientSession\n\n- startSession()\n\n- startTransaction()\n\n- commitTransaction()\n\n- abortTransaction()\n\n- endSession()"} -{"chunk_id": "68b144e0d523194d21063530-0", "page_id": "68b144e0d523194d21063530", "source_name": "node", "product_name": "Node.js Driver", "url": "https://mongodb.com/docs/drivers/node/current/crud/query/project", "title": "Specify Which Fields to Return", "text": "# Specify Which Fields to Return\n\n## Overview\n\nUse a projection to control which fields appear in the documents returned by read operations. Many requests only require certain fields, so projections can help you limit unnecessary network bandwidth usage. Projections work in two ways:\n\n- Explicitly include fields with a value of `1`. This has the side-effect of implicitly excluding all unspecified fields.\n\n- Implicitly exclude fields with a value of `0`. This has the side-effect of implicitly including all unspecified fields.\n\nThese two methods of projection are mutually exclusive: if you explicitly include fields, you cannot explicitly exclude fields, and vice versa.\n\n### Sample Documents\n\nTo follow the examples in this guide, use the following code snippet to insert documents that describe fruits into the `myDB.fruits` collection:\n\n```javascript\nconst myDB = client.db(\"myDB\");\nconst myColl = myDB.collection(\"fruits\");\n\nawait myColl.insertMany([\n { \"_id\": 1, \"name\": \"apples\", \"qty\": 5, \"rating\": 3 },\n { \"_id\": 2, \"name\": \"bananas\", \"qty\": 7, \"rating\": 1 },\n { \"_id\": 3, \"name\": \"oranges\", \"qty\": 6, \"rating\": 2 },\n { \"_id\": 4, \"name\": \"avocados\", \"qty\": 3, \"rating\": 5 },\n]);\n```\n\nYour query operation may return a reference to a cursor that contains matching documents. To learn how to examine data stored in the cursor, see the Access Data From a Cursor page.\n\n## Single Field\n\nIn the following query, pass the projection to only return the `name` field of each document:\n\n```javascript\n// return only* the name field\nconst projectFields = { name: 1 };\nconst cursor = myColl.find().project(projectFields);\nfor await (const doc of cursor) {\n console.dir(doc);\n}\n```\n\nThe projection document specifies a value of `1` for `name`. This instructs the operation to *include* the `name` field of each returned document in the results and *exclude* the `qty` and `rating` fields. Passing this projection to `find()` with an empty query document and no sort document yields the following results:\n\n```json\n{ \"_id\": 1, \"name\": \"apples\" }\n{ \"_id\": 2, \"name\": \"bananas\" }\n{ \"_id\": 3, \"name\": \"oranges\" }\n{ \"_id\": 4, \"name\": \"avocados\" }\n```\n\nAlthough this projection only explicitly included the `name` field, the query returned the `_id` field as well.\n\nThe `_id` field is a special case because it is always included in every query unless explicitly specified otherwise. This is because `_id` is a unique identifier for each document, a property that is often used when constructing queries. The `movies` collection data demonstrates why this property is necessary: two or more movies can share the same title, such as movie remakes. Because of this, you need a unique `_id` value to reliably reference a specific movie. `_id` is the only exception to the mutually exclusive include-exclude behavior in projections: you *can* explicitly exclude `_id` even when explicitly including other fields if you do not want `_id` to be present in returned documents.\n\n```javascript\n// return only the name field\nconst projectFields = { _id: 0, name: 1 };\nconst cursor = myColl.find().project(projectFields);\nfor await (const doc of cursor) {\n console.dir(doc);\n}\n```\n\nThe projection document specifies a value of `1` for `name` and `0` for `_id`. This instructs the operation to *include* the `name` field of each returned document in the results and *exclude* the `_id`, `qty`, and `rating` fields. Passing this projection to `find()` with an empty query document and no sort document yields the following results:\n\n```json\n{ \"name\": \"apples\" }\n{ \"name\": \"bananas\" }\n{ \"name\": \"oranges\" }\n{ \"name\": \"avocados\" }\n```\n\n## Multiple Fields\n\nYou can also specify multiple fields to include in your projection. Note: the order in which you specify the fields in the projection does not alter the order in which they are returned.\n\n```javascript\nconst projectFields = { _id: 0, rating: 1, name: 1 };\nconst cursor = myColl.find().project(projectFields);\nfor await (const doc of cursor) {\n console.dir(doc);\n}\n```\n\nThis example that identifies two fields to include in the projection yields the following results:\n\n```json\n { \"name\": \"apples\", \"rating\": 3 }\n { \"name\": \"bananas\", \"rating\": 1 }\n { \"name\": \"oranges\", \"rating\": 2 }\n { \"name\": \"avocados\", \"rating\": 5 }\n```\n\nFor more projection examples, see the MongoDB Manual page on Project Fields to Return from Query.\n\nYou must chain a cursor method such as `sort()`, `limit()`, `skip()`, or `project()` to a read operation before iterating the cursor. If you specify a cursor method after iterating the cursor, the setting does not apply to the read operation."} -{"chunk_id": "68b144e0d523194d210635ad-0", "page_id": "68b144e0d523194d210635ad", "source_name": "node", "product_name": "Node.js Driver", "url": "https://mongodb.com/docs/drivers/node/current/security/tls", "title": "Enable TLS on a Connection", "text": "# Enable TLS on a Connection\n\n## Overview\n\nIn this guide, you can learn how to connect to MongoDB instances with the TLS security protocol.\n\nTo configure your connection to use TLS, enable the TLS option and provide your certificates for validation.\n\nTo learn more about TLS, see the Wikipedia entry on Transport Layer Security.\n\n## Enable TLS\n\nYou can enable TLS on a connection to your MongoDB instance in the following ways:\n\n- Setting the `tls` option to `true` in your `MongoClientOptions` object\n\n- Setting the `tls` option to `true` in your connection string\n\n\n\n\n\nA `MongoClient` instance can connect with TLS if you set `tls` to `true` in your `MongoClientOptions` object:\n\n```js\nconst client = new MongoClient(uri, { tls: true });\n```\n\n\n\n\n\nA `MongoClient` instance can connect with TLS if you set the `tls` option to `true` in your connection string:\n\n```js\nconst uri = \"mongodb://:?tls=true\";\nconst client = new MongoClient(uri, myClientSettings);\n```\n\n\n\n\n\nIf you use a DNS SRV record when connecting to MongoDB by specifying the `+srv` modification in your connection string, you enable TLS on your connection by default. To disable it, set the `tls` or `ssl` parameter value to `false` in your connection string or `MongoClientOptions` object.\n\nTo learn more about connection behavior when you use a DNS seedlist, see the SRV Connection Format section in the Server manual.\n\nThe Node.js driver depends on OpenSSL by default. Outdated SSL proxies can cause an `unsafe legacy renegotiation disabled` error in environments using OpenSSL 3.0 or later. You can resolve this error by setting the `SSL_OP_LEGACY_SERVER_CONNECT` option, as shown in the following example:\n\n```js\nimport { MongoClient } from 'mongodb';\nimport crypto from 'crypto';\n\nconst client = new MongoClient(\"mongodb+srv://...\", {\n secureContext: {\n secureOptions: crypto.constants.SSL_OP_LEGACY_SERVER_CONNECT\n }\n});\n```\n\nIn addition to the `tls` client option, the driver provides more options to configure TLS on your connection. For **testing purposes**, you can set the `tlsAllowInvalidHostnames`, `tlsAllowInvalidCertificates`, and `tlsInsecure` client options.\n\nSetting the `tlsAllowInvalidHostnames` option to `true` disables hostname verification, and setting the `tlsAllowInvalidCertificates` to `true` disables certificate validation. Setting the `tlsInsecure` option to `true` disables both certificate and hostname validation.\n\nSpecifying any of these options in a production environment makes your application insecure and potentially vulnerable to expired certificates and to foreign processes posing as valid client instances.\n\nFor a full list of client options, see Specify Connection Options.\n\n## Configure Certificates\n\nTo successfully initiate a TLS request, an application must prove its identity by referencing cryptographic certificates. To connect to MongoDB with TLS, your certificates must be stored as PEM files.\n\nFor production use, we recommend that your MongoDB deployment use valid certificates generated and signed by the same certificate authority. For testing, you can use self-signed certificates.\n\nThe following list describes the components required to establish a connection with TLS:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nTLS Component\n\n\nDescription\n\n
\nCertificate Authority (CA)\n\n\nOne or more certificate authorities to trust when making a TLS connection.\n\n
\nClient Certificate\n\n\nA digital certificate and key that allow the server to verify the identity of your application to establish an encrypted network connection.\n\n
\nCertificate Key\n\n\nThe client certificate private key file. This key is often included within the certificate file itself.\n\n
\nPassphrase\n\n\nThe password to decrypt the private client key if it is encrypted.\n\n
To learn more about the PEM format, see the Wikipedia entry on Privacy-Enhanced Mail.\n\n## Reference Certificates in a Client\n\nYou must reference your certificates in your `MongoClientOptions` object so that the server can validate them before the client connects. You can reference your certificates in the following ways:\n\n- Create a `SecureContext` object to store certificates *(Recommended)*\n\n- Provide filepath strings that point to your certificates\n\n- Create `Buffer` objects to store certificates\n\n### Create a SecureContext Object to Store Certificates\n\nWe recommend that you use the `secureContext` option to configure your TLS connection. `SecureContext` objects are native to Node.js and allow you to keep all your TLS options in a single reusable object.\n\nTo create a `SecureContext` object, import the `createSecureContext()` method from the `tls` module. Next, call the `createSecureContext()` method and pass the contents of your certificates in the options parameter. This method returns a `SecureContext` object that you can use in your `MongoClientOptions` object.\n\nThe following code shows how to create a `SecureContext` object and pass it to your client:\n\n```js\n// Create a SecureContext object\nconst secureContext = tls.createSecureContext({\n ca: fs.readFileSync(``),\n cert: fs.readFileSync(``),\n key: fs.readFileSync(``),\n});\n\n// Pass the SecureContext as a client option\nconst client = new MongoClient(uri, { tls: true, secureContext });\n```\n\nTo learn more about the `createSecureContext()` method and the `tls` package, see the Node.js TLS API documentation.\n\nFor a runnable example that uses a `SecureContext` object, see the SecureContext Example.\n\n### Provide Certificate Filepaths\n\nYou can include the filepaths for your certificates as client options to retrieve your certificates while connecting with TLS. The driver reads these files when you call the `connect()` method on your `MongoClient` instance.\n\nThe following code shows how to provide certificate filepaths as options in your `MongoClient`:\n\n```js\n// Pass filepaths as client options\nconst client = new MongoClient(uri, {\n tls: true,\n tlsCAFile: ``,\n tlsCertificateKeyFile: ``,\n});\n```\n\nYour TLS configuration might require that you present a certificate revocation list (CRL) when connecting to MongoDB. Starting in version 6.0 of the driver, you can pass the filepath of your CRL file to the `tlsCRLFile` option in your connection string or your `MongoClientOptions` instance.\n\n### Create Buffer Objects to Store Certificates\n\nYou can pass the contents of your certificate files as `Buffer` objects in your client options to connect with TLS.\n\nThe following code shows how to read the contents of your certificate files and pass the resulting `Buffer` objects as options in your `MongoClient`:\n\n```js\n// Read file contents\nconst ca = fs.readFileSync(``);\nconst cert = fs.readFileSync(``);\nconst key = fs.readFileSync(``);\n\n// Pass Buffers as client options\nconst client = new MongoClient(uri, { tls: true, ca, cert, key });\n```"} -{"chunk_id": "68b144e0d523194d210635ad-1", "page_id": "68b144e0d523194d210635ad", "source_name": "node", "product_name": "Node.js Driver", "url": "https://mongodb.com/docs/drivers/node/current/security/tls", "title": "Enable TLS on a Connection", "text": "## SecureContext Example\n\nThis example shows how to create a `SecureContext` object and a `MongoClient` instance that includes TLS options. The example connects to MongoDB and executes a find query:\n\n```js\nimport { MongoClient } from \"mongodb\";\nimport * as fs from \"fs\";\nimport * as tls from \"tls\";\n\n// Replace the uri string with your connection string.\nconst uri = \"\";\n\n// Replace the filepaths with your certificate filepaths.\nconst secureContext = tls.createSecureContext({\n ca: fs.readFileSync(``),\n cert: fs.readFileSync(``),\n key: fs.readFileSync(``),\n});\n\n// Create a client with the secureContext option\nconst client = new MongoClient(uri, { tls: true, secureContext });\n\nasync function run() {\n try {\n const db = client.db(\"myDB\");\n const myColl = db.collection(\"myColl\");\n const doc = await myColl.findOne({});\n console.log(doc);\n } finally {\n await client.close();\n }\n}\nrun().catch(console.dir);\n```\n\n## Additional Information\n\nFor more information about enabling TLS on a connection, see the following Server manual documentation:\n\n- TLS/SSL (Transport Encryption)\n\n- TLS/SSL Configuration for Clients\n\n### API Documentation\n\n- MongoClientOptions\n\n- MongoClient\n\n- tlsAllowInvalidHostnames client option\n\n- tlsAllowInvalidCertificates client option\n\n- secureContext client option\n\n- tlsCAFile client option\n\n- tlsCertificateKeyFile client option\n\n- ca client option\n\n- cert client option\n\n- key client option"} -{"chunk_id": "68b144e0d523194d21063542-0", "page_id": "68b144e0d523194d21063542", "source_name": "node", "product_name": "Node.js Driver", "url": "https://mongodb.com/docs/drivers/node/current/crud/query/text", "title": "Query Text", "text": "# Query Text\n\n## Overview\n\nText queries let you query string type fields in your collection for specified words or phrases. You can perform a text query by using the `$text` operator, which performs a logical `OR` on each term separated by a space in the query string. You can also specify more options to the operator to handle case sensitivity, stop words, and word stemming (such as plural forms or other tenses) for a supported language. This is often used for unstructured text such as transcripts, essays, or web pages.\n\nThe `$text` query operator requires that you specify the query field in a **text index** on your collection. See the examples below for sample code for creating a text index and using the `$text` query operator.\n\nMongoDB Search helps you build fast, relevance-based search capabilities on top of your MongoDB data. Try it today on MongoDB Atlas, our fully managed database as a service.\n\n## Examples\n\nThe following examples use sample data from the `movies` collection in the `sample_mflix` database. To enable text queries on the `title` field, create a **text index** by using the following command:\n\n```javascript\nawait db.movies.createIndex({ title: \"text\" });\n```\n\nWe use a single field text index for the examples in this guide, but you can create a compound text index that broadens your text queries to multiple fields. The following command creates a text index on two fields in the `movies` collection:\n\n```javascript\nawait db.movies.createIndex({ title: \"text\", plot: \"text\" });\n```\n\nWhen creating a compound text index, you can specify a weight option to prioritize certain text fields in your index. When you execute a text query, the field weights influence how MongoDB calculates the text query score for each matching document.\n\nTo learn more about specifying field weights when creating a text index, see the Text Indexes section in the Indexes guide.\n\nYou can only create *one* text index per collection. Every text query searches all the fields specified in that index for matches.\n\nTo learn more about text indexes, see Text Indexes in the Server manual.\n\n### Query for Words\n\nThis example queries for Star Trek movies by searching for titles containing the word \"trek\". If you want to query using multiple words, separate your words with spaces to query for documents that match any of the search terms (logical `OR`).\n\n```javascript\n // Create a query that searches for the string \"trek\"\n const query = { $text: { $search: \"trek\" } };\n\n // Return only the `title` of each matched document\n const projection = {\n _id: 0,\n title: 1,\n };\n\n // Find documents based on our query and projection\n const cursor = movies.find(query).project(projection);\n```\n\nThis operation returns the following documents:\n\n```javascript\n{ title: 'Trek Nation' }\n{ title: 'Star Trek' }\n{ title: 'Star Trek Into Darkness' }\n{ title: 'Star Trek: Nemesis' }\n{ title: 'Star Trek: Insurrection' }\n{ title: 'Star Trek: Generations' }\n{ title: 'Star Trek: First Contact' }\n{ title: 'Star Trek: The Motion Picture' }\n{ title: 'Star Trek VI: The Undiscovered Country' }\n{ title: 'Star Trek V: The Final Frontier' }\n{ title: 'Star Trek IV: The Voyage Home' }\n{ title: 'Star Trek III: The Search for Spock' }\n{ title: 'Star Trek II: The Wrath of Khan' }\n```\n\nSuccess! The query found every document in the `movies` collection with a title including the word \"trek\". Unfortunately, the search included one unintended item: \"Trek Nation,\" which is a movie about Star Trek and not part of the Star Trek movie series. To solve this, we can query with a more specific **phrase**.\n\n### Query By Phrase\n\nTo make your query more specific, try using the phrase \"star trek\" instead of just the word \"trek\". To search by phrase, surround your multi-word phrase with escaped quotes (`\\\"\\\"`):\n\n```javascript\n // Create a query that searches for the phrase \"star trek\"\n const query = { $text: { $search: \"\\\"star trek\\\"\" } };\n\n // Return only the `title` of each matched document\n const projection = {\n _id: 0,\n title: 1,\n };\n\n // Find documents based on the query and projection\n const cursor = movies.find(query).project(projection);\n```\n\nQuerying by the phrase `\"star trek\"` instead of just the term `\"trek\"` matches the following documents:\n\n```javascript\n{ title: 'Star Trek' }\n{ title: 'Star Trek Into Darkness' }\n{ title: 'Star Trek: Nemesis' }\n{ title: 'Star Trek: Insurrection' }\n{ title: 'Star Trek: Generations' }\n{ title: 'Star Trek: First Contact' }\n{ title: 'Star Trek: The Motion Picture' }\n{ title: 'Star Trek VI: The Undiscovered Country' }\n{ title: 'Star Trek V: The Final Frontier' }\n{ title: 'Star Trek IV: The Voyage Home' }\n{ title: 'Star Trek III: The Search for Spock' }\n{ title: 'Star Trek II: The Wrath of Khan' }\n```\n\nThese results include all movies in the database that contain the phrase `\"star trek\"`, which in this case results in only fictional Star Trek movies. Unfortunately, this query returned `\"Star Trek Into Darkness\"`, a movie that was not part of the original series of movies. To resolve this issue, we can omit that document with a **negation**.\n\n### Query with Negations\n\nTo use a negated term, place a negative sign, `-`, in front of the term you to omit from the result set. The query operation omits any documents that contain this term from the search result. Since this query includes two distinct terms, separate them with a space.\n\n```javascript\n // Create a query that searches for the phrase \"star trek\" while omitting \"into darkness\"\n const query = { $text: { $search: \"\\\"star trek\\\" -\\\"into darkness\\\"\" } };\n\n // Include only the `title` field of each matched document\n const projection = {\n _id: 0,\n title: 1,\n };\n\n // Find documents based on the query and projection\n const cursor = movies.find(query).project(projection);\n```\n\nQuerying with the negated term yields the following documents:\n\n```javascript\n{ title: 'Star Trek' }\n{ title: 'Star Trek: Nemesis' }\n{ title: 'Star Trek: Insurrection' }\n{ title: 'Star Trek: Generations' }\n{ title: 'Star Trek: First Contact' }\n{ title: 'Star Trek: The Motion Picture' }\n{ title: 'Star Trek VI: The Undiscovered Country' }\n{ title: 'Star Trek V: The Final Frontier' }\n{ title: 'Star Trek IV: The Voyage Home' }\n{ title: 'Star Trek III: The Search for Spock' }\n{ title: 'Star Trek II: The Wrath of Khan' }\n```\n\nYour query operation may return a reference to a cursor that contains matching documents. To learn how to examine data stored in the cursor, see the Access Data From a Cursor page."} -{"chunk_id": "68b144e0d523194d21063542-1", "page_id": "68b144e0d523194d21063542", "source_name": "node", "product_name": "Node.js Driver", "url": "https://mongodb.com/docs/drivers/node/current/crud/query/text", "title": "Query Text", "text": "### Sort by Relevance\n\nNow that the result set reflects the desired results, you can use the text query `textScore`, accessed using the $meta operator in the query projection, to order the results by relevance:\n\n```javascript\n // Create a query that searches for the phrase \"star trek\" while omitting \"into darkness\"r\n const query = { $text: { $search: \"\\\"star trek\\\" -\\\"into darkness\\\"\" } };\n\n // Sort returned documents by descending text relevance score\n const sort = { score: { $meta: \"textScore\" } };\n\n // Include only the `title` and `score` fields in each returned document\n const projection = {\n _id: 0,\n title: 1,\n score: { $meta: \"textScore\" },\n };\n\n // Find documents based on the query, sort, and projection\n const cursor = movies\n .find(query)\n .sort(sort)\n .project(projection);\n```\n\nQuerying in this way returns the following documents in the following order. In general, text relevance increases as a string matches more terms and decreases as the unmatched portion of the string lengthens.\n\n```javascript\n{ title: 'Star Trek', score: 1.5 }\n{ title: 'Star Trek: Generations', score: 1.3333333333333333 }\n{ title: 'Star Trek: Insurrection', score: 1.3333333333333333 }\n{ title: 'Star Trek: Nemesis', score: 1.3333333333333333 }\n{ title: 'Star Trek: The Motion Picture', score: 1.25 }\n{ title: 'Star Trek: First Contact', score: 1.25 }\n{ title: 'Star Trek II: The Wrath of Khan', score: 1.2 }\n{ title: 'Star Trek III: The Search for Spock', score: 1.2 }\n{ title: 'Star Trek IV: The Voyage Home', score: 1.2 }\n{ title: 'Star Trek V: The Final Frontier', score: 1.2 }\n{ title: 'Star Trek VI: The Undiscovered Country', score: 1.2 }\n```\n\nFor more information about the $text operator and its options, see the manual entry."} -{"chunk_id": "68b144e0d523194d210635aa-0", "page_id": "68b144e0d523194d210635aa", "source_name": "node", "product_name": "Node.js Driver", "url": "https://mongodb.com/docs/drivers/node/current/security/socks", "title": "Enable SOCKS5 Proxy Support", "text": "# Enable SOCKS5 Proxy Support\n\n## Overview\n\nIn this guide, you can learn how to connect to MongoDB instances by using a SOCKS5 proxy. SOCKS5 is a standardized protocol for connecting to network services through a proxy server.\n\nTo learn more about the SOCKS5 protocol, see the Wikipedia entry on SOCKS.\n\n## Install the socks Package\n\nStarting in version 6.0 of the Node.js driver, you must install the `socks` package to use SOCKS5 proxy support in your application. You can install `socks` by running the following command in your shell:\n\n```bash\nnpm i socks\n```\n\n## SOCKS5 Client Options\n\nYou can set options in your `MongoClientOptions` instance or in your connection URI to configure SOCKS5 proxy support for your connection. The following table describes the client options related to SOCKS5:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nAccepted Values\n\n\nDefault Value\n\n\nDescription\n\n
\n**proxyHost**\n\n\nstring\n\n\n`null`\n\n\nSpecifies the SOCKS5 proxy IPv4 address, IPv6 address, or domain name.\n\n
\n**proxyPort**\n\n\nnon-negative integer\n\n\n`null`\n\n\nSpecifies the TCP port number of the SOCKS5 proxy server. If you set the `proxyHost` option, the value of this option defaults to `1080`.\n\n
\n**proxyUsername**\n\n\nstring\n\n\n`null`\n\n\nSpecifies the username for authentication to the SOCKS5 proxy server. If you set this option to a zero-length string, the driver ignores it.\n\n
\n**proxyPassword**\n\n\nstring\n\n\n`null`\n\n\nSpecifies the password for authentication to the SOCKS5 proxy server. If you set this option to a zero-length string, the driver ignores it.\n\n
The driver throws an error if you set the `proxyPort`, `proxyUsername`, or `proxyPassword` options without setting the `proxyHost` option.\n\n## Example\n\nThis example shows how to instantiate a `MongoClient` that uses SOCKS5 proxy support. The following example code specifies proxy server options and connects to MongoDB:\n\n```javascript\n// Replace the placeholder with your connection string\nconst uri = \"\";\n\n// Replace the placeholders with your SOCKS5 proxy server details\nconst socksOptions = {\n proxyHost: \"\",\n proxyPort: 1080,\n proxyUsername: \"\",\n proxyPassword: \"\",\n};\n\n// Create a new client with the proxy server details\nconst client = new MongoClient(uri, socksOptions);\n```\n\nThe preceding sample code uses placeholders for the connection URI and proxy server details. To run this code, you must replace these placeholders with the information for your deployment and proxy server.\n\n## Additional Information\n\nFor more information about SOCKS5 proxy support, see the MongoDB SOCKS5 specification.\n\n### API Documentation\n\nTo learn more about the methods and types discussed in this guide, see the following API Documentation:\n\n- MongoClientOptions\n\n- MongoClient\n\n- ProxyOptions"} -{"chunk_id": "698c1f7b8ef09cee81a660fc-0", "page_id": "698c1f7b8ef09cee81a660fc", "source_name": "node", "product_name": "Node.js Driver", "url": "https://mongodb.com/docs/drivers/node/current/integrations/next-vercel", "title": "Tutorial: Deploy a Next.js Application on Vercel", "text": "# Tutorial: Deploy a Next.js Application on Vercel\n\n## Overview\n\nIn this tutorial, you learn how to create a Next.js application that connects to MongoDB. You also learn how to deploy the application on Vercel, a platform that hosts Next.js applications.\n\nThis tutorial uses the Next.js Pages Router instead of the App Router that Next.js introduced in version 13.\n\n### Prerequisites\n\nBefore you begin, complete the following steps:\n\n- Complete the MongoDB Get Started guide to set up a new Atlas account and load sample data into a new free cluster.\n\n- Get the connection string for your cluster and save it to use later in this tutorial.\n\n- Create a Vercel account by visiting the Vercel website.\n\n- Download Node.js version 18 or later.\n\n- Ensure you have npm and npx installed.\n\n## Tutorial\n\nThis tutorial guides you through the following steps:\n\n- Create a Next.js application.\n\n- Connect MongoDB to Next.js.\n\n- Query MongoDB from Next.js.\n\n- Deploy your application on Vercel.\n\n### Create a Next.js Application\n\nYou can create a Next.js application with MongoDB integration by using the **with-mongodb** example template.\n\nTo create a new Next.js application with MongoDB integration, run the following command in your terminal:\n\n```bash\nnpx create-next-app --example with-mongodb sample_mflix\n```\n\nThe command uses `npx create-next-app` and the `--example with-mongodb` parameter to create an application from the MongoDB integration example. `sample_mflix` is the name of the application. Use a different name if you prefer.\n\nAfter the command completes, navigate to your project directory by running the following command:\n\n```bash\ncd sample_mflix\n```\n\nInstall the npm dependencies by running the following command:\n\n```bash\nnpm install\n```\n\nTo start your Next.js application, run the following command:\n\n```bash\nnpm run dev\n```\n\nAfter the application builds, navigate to `localhost:3000` in your browser. The page displays an error message because you have not yet provided your MongoDB connection string.\n\n### Connect MongoDB to Next.js\n\nThe Next.js application directory contains an `env.local.example` file. Rename this file to `env.local` and open it. The file contains one property: `MONGODB_URI`.\n\nSet your MongoDB connection string as the value for the `MONGODB_URI` property. Your `env.local` file looks similar to the following example:\n\n```none\nMONGODB_URI=\n```\n\nTo verify your configuration, restart your Next.js application by running the following command in your terminal:\n\n```bash\nnpm run dev\n```\n\nWhen the application builds, navigate to `localhost:3000` in your browser. You see the **with-mongodb** Next.js application welcome page.\n\nYour connection is successful if you see the message \"*You are connected to MongoDB*\". If you see the message \"*You are NOT connected to MongoDB*\", verify your connection string and ensure that your database user and network connection are configured correctly."} -{"chunk_id": "698c1f7b8ef09cee81a660fc-1", "page_id": "698c1f7b8ef09cee81a660fc", "source_name": "node", "product_name": "Node.js Driver", "url": "https://mongodb.com/docs/drivers/node/current/integrations/next-vercel", "title": "Tutorial: Deploy a Next.js Application on Vercel", "text": "### Query MongoDB from Next.js\n\nNext.js supports multiple ways to retrieve data. You can create API endpoints, run server-side rendered functions for a page, or generate static pages by getting data at build time. This tutorial shows examples of all three methods.\n\n#### Example 1: Create a Next.js API Endpoint for MongoDB\n\nTo create a new API endpoint route, create an `api` directory in your `pages` directory. Each file you create in the `api` directory becomes an individual API endpoint.\n\nCreate a new file in the `api` directory called `movies.tsx`. This endpoint returns a list of movies from your MongoDB database. Add the following code to the `movies.tsx` file:\n\n```typescript\nimport clientPromise from \"../../lib/mongodb\";\nimport { NextApiRequest, NextApiResponse } from 'next';\n\nexport default async (req: NextApiRequest, res: NextApiResponse) => {\n try {\n const client = await clientPromise;\n const db = client.db(\"sample_mflix\");\n const movies = await db\n .collection(\"movies\")\n .find({})\n .sort({ metacritic: -1 })\n .limit(10)\n .toArray();\n res.json(movies);\n } catch (e) {\n console.error(e);\n }\n}\n```\n\nThe preceding code creates an API endpoint that returns the top 10 movies from the `sample_mflix` database sorted by their `metacritic` rating in descending order. The `res.json` method serves the array of movies in JSON format to the browser. When you navigate to `localhost:3000/api/movies`, the browser displays a list of movies returned from your database.\n\nAdd more API routes by creating additional files in the `api` directory.\n\n#### Example 2: Next.js Pages with MongoDB\n\nYou can get data directly into your Next.js pages by using the `getServerSideProps()` method. This method is available when you use Next.js pages.\n\nThe `getServerSideProps()` method forces a Next.js page to use server-side rendering to load. Every time the page loads, the `getServerSideProps()` method runs on the backend, gets data, and sends it into the React component through props. The code inside `getServerSideProps()` is never sent to the client.\n\nCreate a new file in the `pages` directory called `movies.tsx`. The following code shows how to use `getServerSideProps()` to query MongoDB:\n\n```typescript\nimport clientPromise from \"../lib/mongodb\";\nimport { GetServerSideProps } from 'next';\n\ninterface Movie {\n _id: string;\n title: string;\n metacritic: number;\n plot: string;\n}\n\ninterface MoviesProps {\n movies: Movie[];\n}\n\nconst Movies: React.FC = ({ movies }) => {\n return (\n
\n

Top 20 Movies of All Time

\n

\n (According to Metacritic)\n

\n
    \n {movies.map((movie) => (\n
  • \n

    {movie.title}

    \n

    {movie.metacritic}

    \n

    {movie.plot}

    \n
  • \n ))}\n
\n
\n );\n};\n\nexport default Movies;\n\nexport const getServerSideProps: GetServerSideProps = async () => {\n try {\n const client = await clientPromise;\n const db = client.db(\"sample_mflix\");\n const movies = await db\n .collection(\"movies\")\n .find({})\n .sort({ metacritic: -1 })\n .limit(20)\n .toArray();\n return {\n props: { movies: JSON.parse(JSON.stringify(movies)) },\n };\n } catch (e) {\n console.error(e);\n return { props: { movies: [] } };\n }\n};\n```\n\nThe `Movies` page component receives the props from the `getServerSideProps()` method and uses that data to render the page. The page shows the top movie title, metacritic rating, and plot.\n\nThe `getServerSideProps()` method runs every time the page is called. If your data does not change often, use static page generation instead.\n\n#### Example 3: Next.js Static Generation with MongoDB\n\nYou can use static page generation to pre-render pages at build time. This method is useful when your data does not change frequently.\n\nCreate a new file in the `pages` directory called `top.tsx`. The following code shows how to use `getStaticProps()` to render the top one-thousand highest rated movies from your MongoDB database:\n\n```typescript\nimport { ObjectId } from \"mongodb\";\nimport clientPromise from \"../lib/mongodb\";\nimport { GetStaticProps } from \"next\";\n\ninterface Movie {\n _id: ObjectId;\n title: string;\n metacritic: number;\n plot: string;\n}\n\ninterface TopProps {\n movies: Movie[];\n}\n\nexport default function Top({ movies }: TopProps) {\n return (\n
\n

Top 1000 Movies of All Time

\n

\n (According to Metacritic)\n

\n
    \n {movies.map((movie) => (\n
  • \n

    {movie.title}

    \n

    {movie.metacritic}

    \n

    {movie.plot}

    \n
  • \n ))}\n
\n
\n );\n}\n\nexport const getStaticProps: GetStaticProps = async () => {\n try {\n const client = await clientPromise;\n\n const db = client.db(\"sample_mflix\");\n\n const movies = await db\n .collection(\"movies\")\n .find({})\n .sort({ metacritic: -1 })\n .limit(1000)\n .toArray();\n\n return {\n props: { movies: JSON.parse(JSON.stringify(movies)) },\n };\n } catch (e) {\n console.error(e);\n return {\n props: { movies: [] },\n };\n }\n};\n```\n\nWhen you navigate to `localhost:3000/top`, the browser displays a list of movies.\n\nIn development mode, your application calls the `getStaticProps()` method every time similar to the `getServerSideProps()` method. In production mode, the `/top` page pre-renders and loads almost immediately.\n\nTo run your Next.js application in production mode, build it first. Then, run the `start` command to serve the built application. Run the following commands in your terminal:\n\n```bash\nnpm run build\nnpm run start\n```\n\nWhen you run the `npm run start` command, Next.js serves your application in production mode. The `getStaticProps()` method does not run every time you access the `/top` route because Next.js serves the page statically. To see the pre-rendered static page, view the `.next/server/pages/top.html` file.\n\n### Deploy your application on Vercel\n\nDeploy your Next.js application with MongoDB on Vercel. Before you deploy, you must commit the application code from the preceding steps to a GitHub repository. To learn how to create a Github account and commit to a repository, see the GitHub documentation.\n\nAfter you commit your code to a repository, navigate to Vercel and log in. On your Vercel dashboard, click the **Import Project** button, and then click **Import Git Repository**.\n\nEnter your GitHub repository URL and click **Continue**. On the next screen, add the variables from your `env.local` file.\n\nClick the **Deploy** button. Vercel automatically builds and deploys your Next.js application. When it completes, you will receive a URL where you can access your application.\n\nVercel uses dynamic IP addresses, so you must add an exception to access your data from any IP address in your MongoDB Atlas dashboard. To do this, navigate to the Network Access tab, click the `Add IP Address` button, and then click the **Allow Access From Anywhere** button.\n\n## Additional Resources\n\nFor more information about the concepts in this tutorial, see the following resources:\n\n- Next.js Documentation\n\n- Vercel Documentation\n\n- Next.js Dynamic API Routes"} -{"chunk_id": "68b144e0d523194d21063519-0", "page_id": "68b144e0d523194d21063519", "source_name": "node", "product_name": "Node.js Driver", "url": "https://mongodb.com/docs/drivers/node/current/crud/compound-operations", "title": "Compound Operations", "text": "# Compound Operations\n\n## Overview\n\nMost database requests either read data from a database or write data into a database. However, there are instances where you may require a single operation that reads and writes data.\n\n**Compound operations** combine read and write operations in a single atomic statement, so there's no chance of data changing in between a read and a subsequent write.\n\nIf you execute each operation separately, another request may alter the data between the read and write operations. These data changes may not prevent your operation from succeeding, but they can make error handling more difficult. When your application handles potential errors at any stage of the process, it can become brittle and difficult to test.\n\n## Built-in Methods\n\nThe Node.js driver provides the following methods to perform compound operations:\n\n- findOneAndDelete()\n\n- findOneAndUpdate()\n\n- findOneAndReplace()\n\nThese methods accept an optional `options` object with configurable sort and projection options.\n\nYou can also set the `includeResultMetadata` option to specify the return type of each of these methods. To learn more about this option, see the includeResultMetadata Option section of this guide.\n\nThe `findOneAndUpdate()` and `findOneAndDelete()` methods take the `returnDocument` setting, which specifies if the method returns the pre-update or post-update version of the modified document.\n\n### includeResultMetadata Option\n\nThe `includeResultMetadata` option determines the return type of the compound methods.\n\nThis setting defaults to `false`, which means that each method returns the matched document. If no document is matched, each method returns `null`. If you set `includeResultMetadata` to `true`, the method returns a `ModifyResult` type that contains the found document and metadata.\n\nSuppose a collection contains only the following document:\n\n```json\n{ _id: 1, x: \"on\" }\n```\n\nThe following table shows how the value of the `includeResultMetadata` option changes the return type of the `findOneAndDelete()` method:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nOption Value\n\n\nSyntax and Output\n\n
\nDefault: `false`\n\n\n*Document matched*\n\n```js\nawait coll.findOneAndDelete({ x: \"on\" });\n```\n\n```js\n{ _id: 1, x: 'on' }\n```\n\n*No document matched*\n\n```js\nawait coll.findOneAndDelete({ x: \"off\" });\n```\n\n```js\nnull\n```\n\n
\n`true`\n\n\n```js\nawait coll.findOneAndDelete({ x: \"on\" }, { includeResultMetadata: true });\n```\n\n```js\n{ lastErrorObject: { n: 1 }, value: { _id: 1, x: 'on' }, ok: 1, ... }\n```\n\n
"} -{"chunk_id": "68b144e0d523194d2106354e-0", "page_id": "68b144e0d523194d2106354e", "source_name": "node", "product_name": "Node.js Driver", "url": "https://mongodb.com/docs/drivers/node/current/data-formats/time-series", "title": "Time Series", "text": "# Time Series\n\n## Overview\n\nIn this guide, you can learn about time series collections in the MongoDB Node.js driver.\n\n## Create a Time Series Collection\n\nWe recommend that you create a time series collection using the MongoDB Shell. Learn more about how to install and run the MongoDB Shell in the MongoDB Shell documentation. For detailed instructions on creating a time series collection using the MongoDB Shell, see our MongoDB Manual entry on time series collections.\n\n## Query a Time Series Collection\n\nSince you query a time series collection in the same way you query other collection types in MongoDB, the Node.js driver has no features specifically for querying time series data.\n\nFor more information on querying data in the MongoDB Node.js driver, see the following resources:\n\n- Guide On Read Operations\n\n- Guide On Aggregation\n\nMongoDB version 5.0 introduces window functions into the MongoDB aggregation pipeline. You can use window functions to perform operations on a contiguous span of time series data. For more information, see the reference documentation for the $setWindowFields aggregation stage."} -{"chunk_id": "68a95c4b5e79d242619e2c27-0", "page_id": "68a95c4b5e79d242619e2c27", "source_name": "ops-manager", "product_name": "MongoDB Ops Manager", "url": "https://mongodb.com/docs/ops-manager/current/reference/api/log-collections/log-collections-get-one", "title": "Get One Log Collection Job", "text": "# Get One Log Collection Job\n\nGroups and projects are synonymous terms. Your `{PROJECT-ID}` is the same as your project ID. For existing groups, your group/project ID remains the same. This page uses the more familiar term group when referring to descriptions. The endpoint remains as stated in the document.\n\nWhen you create a log collection job, Ops Manager starts a background job to download the logs from the specified Ops Manager deployment. Use this endpoint to retrieve a single log collection job by its unique identifier.\n\nBase URL: `https://{OPSMANAGER-HOST}:{PORT}/api/public/v1.0`\n\n## Resource\n\n```http\nGET /groups/{GROUP-ID}/logCollectionJobs/{JOB-ID}\n```\n\n### Request Path Parameters\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nNecessity\n\n\nDescription\n\n
\nGROUP-ID\n\n\nstring\n\n\nRequired\n\n\nUnique 24-hexadecimal digit string that identifies the log collection request job.\n\n
\nJOB-ID\n\n\nstring\n\n\nRequired\n\n\nUnique 24-hexadecimal digit string that identifies the log collection job to retry. Use the Get All Log Collection Jobs for One Project endpoint to obtain the IDs associated with your project.\n\n
\n\n### Request Query Parameters\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nDescription\n\n\nDefault\n\n
\npageNum\n\n\ninteger\n\n\nPage number (1-index based).\n\n\n`1`\n\n
\nitemsPerPage\n\n\ninteger\n\n\nNumber of items to return per page, up to a maximum of 500.\n\n\n`100`\n\n
\npretty\n\n\nboolean\n\n\nIndicates whether the response body should be in a prettyprint format.\n\n\n`false`\n\n
\nenvelope\n\n\nboolean\n\n\nIndicates whether or not to wrap the response in an envelope.\n\nSome API (Application Programming Interface) clients cannot access the HTTP (Hypertext Transfer Protocol) response headers or status code. To remediate this, set `\"envelope\" : true` in the query.\n\nFor endpoints that return one result, response body includes:\n\n- `status`: HTTP (Hypertext Transfer Protocol) response code\n\n- `content`: Expected response body\n\nFor endpoints that return a list of results, the `results` object is an envelope. Ops Manager adds the `status` field to the response body.\n\n\nNone\n\n
\n\n\n\n\n\n\n\n
\nverbose\n\n\nBoolean\n\n\nIf true, returns all child jobs in the response. A log collection job contains child jobs for each log type and MongoDB process included in the request.\n\n\n`false`\n\n
\n\n### Request Body Parameters\n\nThis endpoint doesn't use HTTP request body parameters."} -{"chunk_id": "68a95c4b5e79d242619e2c27-1", "page_id": "68a95c4b5e79d242619e2c27", "source_name": "ops-manager", "product_name": "MongoDB Ops Manager", "url": "https://mongodb.com/docs/ops-manager/current/reference/api/log-collections/log-collections-get-one", "title": "Get One Log Collection Job", "text": "## Response\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nDescription\n\n
\nchildJobs\n\n\narray\n\n\nList of child jobs associated with this request. Included in the response if you set tthe **verbose** query parameter to `true`.\n\n
\nchildJobs[n].errorMessage\n\n\nstring\n\n\nError message showing why this child job failed, if applicable.\n\n
\nchildJobs[n].finishDate\n\n\nstring\n\n\nTimestamp in ISO 8601 date and time format in UTC (Coordinated Universal Time) when this child job finished.\n\n
\nchildJobs[n].hostName\n\n\nstring\n\n\nName of the host from whom the child job collects the logs.\n\n
\nchildJobs[n].logCollectionType\n\n\nstring\n\n\nType of log this child job collects. Returns one of the following values:\n\n- `AUTOMATION_AGENT`\n\n- `BACKUP_AGENT`\n\n- `MONITORING_AGENT`\n\n- `MONGODB`\n\n- `FTDC`\n\n
\nchildJobs[n].path\n\n\nstring\n\n\nPath to the process in the deployment for which this child job collects logs. MongoDB Atlas uses these paths to build the directory hierarchy in the compressed archive file.\n\n- `AUTOMATION_AGENT`: `/automation_agent`\n\n- `BACKUP_AGENT`: `/automation_agent`\n\n- `MONITORING_AGENT`: `/automation_agent`\n\n- `MONGODB`: `//`\n\n- `FTDC`: `//`\n\n
\nchildJobs[n].startDate\n\n\nstring\n\n\nTimestamp in ISO 8601 date and time format in UTC (Coordinated Universal Time) when this child job started.\n\n
\nchildJobs[n].status\n\n\nstring\n\n\nStatus of this child job. This resource returns one of the following values:\n\n- `SUCCESS`\n\n- `FAILURE`\n\n- `IN_PROGRESS`\n\n- `MARKED_FOR_EXPIRY`\n\n- `EXPIRED`\n\n
\nchildJobs[n].uncompressedDiskSpaceBytes\n\n\nnumber\n\n\nTotal uncompressed disk space in bytes that this child job uses.\n\n
\ncreationDate\n\n\nstring\n\n\nTimestamp, in the number of seconds that have elapsed since the UNIX epoch when you created the log collection request job.\n\n
\nexpirationDate\n\n\nstring\n\n\nTimestamp, in the number of seconds that have elapsed since the UNIX epoch when the log collection request job expires.\n\n
\ngroupId\n\n\nstring\n\n\nUnique 24-hexadecimal digit string that identifies the project associated with log collection request.\n\n
\nid\n\n\nstring\n\n\nUnique 24-hexadecimal digit string that identifies the log collection request job.\n\n
\nlogTypes\n\n\narray\n\n\nList of log types included in this request. This resource returns one or more of the following values:\n\n- `AUTOMATION_AGENT`\n\n- `BACKUP_AGENT`\n\n- `MONITORING_AGENT`\n\n- `MONGODB`\n\n- `FTDC`\n\n
\nredacted\n\n\nboolean\n\n\nFlag that indicates whether the request replaces emails, hostnames, IP addresses, and namespaces in the response with random string values.\n\n
\nresourceName\n\n\nstring\n\n\nName of the resource for which you requested logs.\n\n
\nresourceType\n\n\nstring\n\n\nType of resource for which you requested logs. This resource returns one of the following values:\n\n- `CLUSTER`\n\n- `PROCESS`\n\n- `REPLICA_SET`\n\n
\nrootResourceName\n\n\nstring\n\n\nName of the complete deployment if you made the log request to a part of a deployment. Part of the deployment could be a replica set in a cluster or one shard of a sharded cluster.\n\n
\nrootResourceType\n\n\nstring\n\n\nType of the part of the complete deployment if you made the log request to a part of a deployment. Part of the deployment could be a replica set in a cluster or one shard of a sharded cluster. This resource returns one of the following values:\n\n- `CLUSTER`\n\n- `PROCESS`\n\n- `REPLICA_SET`\n\n
\nstatus\n\n\nstring\n\n\nStatus of the log collection request job. This resource returns one of the following values:\n\n- `SUCCESS`\n\n- `FAILURE`\n\n- `IN_PROGRESS`\n\n- `MARKED_FOR_EXPIRY`\n\n- `EXPIRED`\n\n
\nsizeRequestedPerFileBytes\n\n\nnumber\n\n\nSize for each log file in bytes.\n\n
\nuncompressedSizeTotalBytes\n\n\nnumber\n\n\nTotal uncompressed size of the log data in bytes that this request returns.\n\n
\nuserId\n\n\nstring\n\n\nUnique 24-hexadecimal digit string that identifies the user executing the request.\n\n
\ndownloadUrl\n\n\nstring\n\n\nInternet address from which you download the logs from this request.\n\n
\n\n## Example Request\n\n```sh\ncurl --user \"{PUBLIC-KEY}:{PRIVATE-KEY}\" --digest \\\n --header \"Accept: application/json\" \\\n --include \\\n --request GET \"https://:/api/public/v1.0/groups/{GROUP-ID}/logCollectionJobs/{JOB-ID}?verbose=true&pretty=true\"\n```\n\n## Example Response\n\n### Response Header\n\n```http\nHTTP/1.1 401 Unauthorized\nContent-Type: application/json;charset=ISO-8859-1\nDate: {dateInUnixFormat}\nWWW-Authenticate: Digest realm=\"MMS Public API\", domain=\"\", nonce=\"{nonce}\", algorithm=MD5, op=\"auth\", stale=false\nContent-Length: {requestLengthInBytes}\nConnection: keep-alive\n```\n\n```http\nHTTP/1.1 200 OK\nVary: Accept-Encoding\nContent-Type: application/json\nStrict-Transport-Security: max-age=300\nDate: {dateInUnixFormat}\nConnection: keep-alive\nContent-Length: {requestLengthInBytes}\nX-MongoDB-Service-Version: gitHash={gitHash}; versionString={ApplicationVersion}\n```"} -{"chunk_id": "68a95c4b5e79d242619e2c27-2", "page_id": "68a95c4b5e79d242619e2c27", "source_name": "ops-manager", "product_name": "MongoDB Ops Manager", "url": "https://mongodb.com/docs/ops-manager/current/reference/api/log-collections/log-collections-get-one", "title": "Get One Log Collection Job", "text": "### Response Body\n\n```json\n{\n \"childJobs\": [\n {\n \"automationAgentId\": \"5c81086e014b76a3d85e1123\",\n \"errorMessage\": null,\n \"finishDate\": \"2019-03-07T12:02:57Z\",\n \"hostName\": \"server1.example.com\",\n \"logCollectionType\": \"AUTOMATION_AGENT\",\n \"path\": \"server1.example.com/automation_agent\",\n \"startDate\": \"2019-03-07T12:02:54Z\",\n \"status\": \"SUCCESS\",\n \"uncompressedDiskSpaceBytes\": 12827\n },\n {\n \"automationAgentId\": \"5c81086e014b76a3d85e1117\",\n \"errorMessage\": null,\n \"finishDate\": \"2019-03-07T12:02:57Z\",\n \"hostName\": \"server1.example.com:27027\",\n \"logCollectionType\": \"MONGODB\",\n \"path\": \"server1.example.com/27027/mongodb\",\n \"startDate\": \"2019-03-07T12:02:54Z\",\n \"status\": \"SUCCESS\",\n \"uncompressedDiskSpaceBytes\": 9292\n },\n ...\n ],\n \"creationDate\": \"2019-03-07T12:02:54Z\",\n \"downloadUrl\": \"https://:/api/public/v1.0/groups/{GROUP-ID}/logCollectionJobs/5c81086e014b76a3d85e1113/download\",\n \"expirationDate\": \"2019-05-06T12:02:54Z\",\n \"groupId\": \"5c8100bcf2a30b12ff88258f\",\n \"id\": \"5c81086e014b76a3d85e1113\",\n \"logTypes\": [\n \"AUTOMATION_AGENT\",\n \"MONGODB\",\n \"FTDC\"\n ],\n \"redacted\": false,\n \"resourceName\": \"myReplicaSet\",\n \"resourceType\": \"replicaset\",\n \"rootResourceName\": \"myReplicaSet\",\n \"rootResourceType\": \"replicaset\",\n \"sizeRequestedPerFileBytes\": 1000,\n \"status\": \"IN_PROGRESS\",\n \"uncompressedSizeTotalBytes\": 44518,\n \"userId\": \"5c80f75fcf09a246878f67a4\"\n}\n```"} -{"chunk_id": "68a95c4b5e79d242619e2d82-0", "page_id": "68a95c4b5e79d242619e2d82", "source_name": "ops-manager", "product_name": "MongoDB Ops Manager", "url": "https://mongodb.com/docs/ops-manager/current/tutorial/add-existing-mongodb-processes", "title": "Add Existing MongoDB Processes to Ops Manager", "text": "# Add Existing MongoDB Processes to Ops Manager\n\nOps Manager provides a wizard for adding your existing MongoDB deployments to monitoring and management. The wizard prompts you to:\n\n- Install the MongoDB Agent if you don't have it installed\n\n- Identify the sharded cluster, the replica set, or the standalone to add. You can choose to add the deployment to Monitoring or to both Monitoring and Automation.\n\n If you are adding a deployment that you intend to live migrate to Atlas, you need to add the deployment (and its credentials) only for Monitoring.\n\n## Considerations\n\n### Unique Names\n\nDeployments must have unique names within the projects.\n\nReplica set, sharded cluster, and shard names within the same project must be unique. Failure to have unique names for the deployments will result in broken backup snapshots.\n\n### MongoDB Configuration Options\n\nAutomation doesn't support all MongoDB options, which can result in failed import attempts. To learn more, see MongoDB Settings and Automation Support.\n\n### TLS (Transport Layer Security)\n\nIf you enable TLS (Transport Layer Security), the FQDN (fully qualified domain name) for the host serving a MongoDB process must match the SAN (Subject Alternative Name) for the TLS (Transport Layer Security) certificate on that host.\n\nTo prevent man-in-the-middle attacks, keep the scope of TLS (Transport Layer Security) certificates as narrow as possible. Although you can use one TLS (Transport Layer Security) certificate with many SANs (Subject Alternative Names), or a wildcard TLS (Transport Layer Security) certificate on each host, you should not. To learn more, see RFC 2818, section 3.1.\n\n### Preferred Hostnames\n\nSet up a preferred hostname if you:\n\n- Require a specific hostname, FQDN (fully qualified domain name), IPv4 (Internet Protocol version 4) address or IPv6 (Internet Protocol version 6) address to access the MongoDB process, or\n\n- Must specify the hostname to use for hosts with multiple aliases.\n\nTo learn more, see the Preferred Hostnames setting in Project Settings.\n\n#### Restore a Previously Removed Host\n\nIf you have not completely removed a host from Ops Manager and want to restore that host, you can reimport the deleted MongoDB process.\n\nIf you have completely removed a host from Ops Manager, restore that host before you reimport it. To search for a deleted host, you must have the `Global Owner` role.\n\nTo locate and restore a deleted host:\n\n1. Navigate to the Deployment view.\n\n2. From the More menu, click Deleted Hosts.\n\n3. Select the to restore the host.\n\nAfter you restore the host, you can import existing process procedure.\n\nIf your host does not appear in the Deleted Hosts list, you can reimport the process immediately.\n\n### Managing Windows MongoDB Services\n\nIf you are adding an existing MongoDB process that runs as a Windows Service to Automation, Automation:\n\n- Stops and disables the existing service\n\n- Creates and starts a new service\n\n### Authentication Credentials on Source and Destination Clusters\n\nIf the Ops Manager project has MongoDB authentication settings enabled for its deployments, the MongoDB deployment you import must support the project's authentication mechanism.\n\nWe recommend that you import to a **new** destination project that has no running processes and doesn't have authentication enabled.\n\nIf the source cluster uses authentication, and the destination Ops Manager project doesn't have any existing managed processes, Ops Manager enables authentication in the destination project, imports the existing keyfile from the source cluster, and uses it to authenticate the user that conducts the import process.\n\nIf the source cluster and the destination Ops Manager project both use authentication, and the project has processes, Ops Manager attempts to use existing authentication settings in the destination project during the import process. For the import process to succeed, authentication credentials on the source cluster and the Ops Manager destination project must be the same.\n\nTo ensure that import is successful, before you start the import process, add the Ops Manager destination project's credentials on the source cluster. To learn more, see Rotate Keys for Replica Set or Rotate Keys for Sharded Clusters.\n\n### Authentication Use Cases\n\nIf your MongoDB deployment requires authentication, when you add the deployment to Ops Manager for monitoring, you must provide the necessary credentials.\n\n- If the deployment doesn't use Automation, but *did* use Backup, Monitoring, or both, you can find those credentials where the credentials were before updating to the MongoDB Agent.\n\n- If the deployment doesn't use Automation, but *will* use Backup, Monitoring, or both:\n\n 1. Create the credentials for the MongoDB Deployment. To learn more, see Required Access for MongoDB Agent for Monitoring and Required Access for MongoDB Agent for Backup.\n\n 2. Add the credentials that you granted to those functions to Ops Manager after you add the MongoDB processes. To learn more, see Add Credentials for Monitoring and Add Credentials for Backup.\n\n- If the deployment *uses* Automation, Ops Manager uses the credentials from the MongoDB Agent. You can delete the credentials from the legacy Backup, and Monitoring Agents. The MongoDB Agent uses those credentials for its Automation, Backup, and Monitoring functions.\n\n- If the deployment *will* use Automation but didn't use it before you import it, add the `mms-automation` user to the database processes you imported and add the user's credentials to Ops Manager.\n\nTo learn more, see Add Credentials for Automation."} -{"chunk_id": "68a95c4b5e79d242619e2d82-1", "page_id": "68a95c4b5e79d242619e2d82", "source_name": "ops-manager", "product_name": "MongoDB Ops Manager", "url": "https://mongodb.com/docs/ops-manager/current/tutorial/add-existing-mongodb-processes", "title": "Add Existing MongoDB Processes to Ops Manager", "text": "### Automation and Updated Security Settings Upon Import\n\nAdding a MongoDB deployment to automation may affect the security settings of the Ops Manager project and the MongoDB deployment.\n\n- **Automation enables the Project Security Setting**. If the MongoDB deployment requires authentication but the Ops Manager project doesn't have authentication settings enabled, when you add the MongoDB deployment to automation, Ops Manager updates the project's security settings to the security settings of the newly imported deployment.\n\n The import process only updates the Ops Manager project's security setting if the project's security setting is currently disabled. The import process doesn't disable the project's security setting or change its enabled authentication mechanism.\n\n- **Automation Imports MongoDB Users and Roles**. The following statements apply to situations where a MongoDB deployment requires authentication or the Ops Manager project has authentication settings enabled.\n\n If the MongoDB deployment contains users or user-defined roles, you can choose to import these users and roles for Ops Manager to manage. The imported users and roles are Synced to all managed deployments in the Ops Manager project.\n\n - If you set the project's Enforce Consistent Set value to `Yes`, Ops Manager deletes from the MongoDB deployments those users and roles that are *not* imported.\n\n - If you set the project's Enforce Consistent Set value to `No`, Ops Manager stops managing non-imported users and roles in the project. These users and roles remain in the MongoDB deployment. To manage these users and roles, you must connect directly to the MongoDB deployment.\n\n If you don't want the Ops Manager project to manage specific users and roles, use the Authentication & Users and Authentication & Roles pages to remove these users and roles during import before you confirm and deploy the changes. To learn more, see Manage or Unmanage MongoDB Users.\n\n If the imported MongoDB deployment already has `mms-backup-agent` and `mms-monitoring-agent` users in its `admin` database, the import process overrides these users' roles with the roles for `mms-backup-agent` and `mms-monitoring-agent` users as set in the Ops Manager project.\n\n- **Automation Applies to All Deployments in the Project**. The project's updated security settings, including all users and roles managed by the Ops Manager project, apply to *all* deployments in the project, including the imported MongoDB deployment.\n\n Ops Manager restarts all deployments in the project with the new setting, including the imported MongoDB deployment. After import, all deployments in the project use the Ops Manager automation keyfile upon restart.\n\n The deployment that you import must use the same keyfile as the existing processes in the destination project or the import process may not proceed. To learn more, see Authentication Credentials on Source and Destination Clusters.\n\n If the existing deployments in the project require a different security profile from the imported process, create a new project into which you can import the source MongoDB deployment.\n\n#### Examples of Imported Users\n\nThe following examples apply to situations where the MongoDB deployment requires authentication or the Ops Manager project has authentication settings enabled.\n\nIf you import the MongoDB users and custom roles, once the Ops Manager project begins to manage the MongoDB deployment, the following happens, regardless of the Enforce Consistent Set value:\n\n- The Ops Manager project enables authentication, manages imported users and roles, and syncs the new users and roles to all its managed deployments.\n\n- The MongoDB deployment's access control is enabled and requires authentication. The MongoDB deployment has all users and roles that the Ops Manager project manages. These users and roles have `Synced` set to `Yes`.\n\nIf you don't import the MongoDB users and custom roles, once the Ops Manager project begins to manage the MongoDB deployment, the following happens:\n\nIf Enforce Consistent Set is set to `Yes`:\n\n- The Ops Manager project enables authentication and doesn't change its managed users and roles.\n\n- The MongoDB deployment's access control is enabled and requires authentication.\n\n- Ops Manager deletes the non-imported MongoDB users and roles from the deployment.\n\n- The MongoDB deployment has all users and roles that the Ops Manager project manages. These users and roles have `Synced` set to `Yes`.\n\nIf Enforce Consistent Set is set to `No`:\n\n- The Ops Manager project enables authentication and doesn't change its security settings, including users and roles.\n\n- The MongoDB deployment's access control is enabled and requires authentication.\n\n- The non-imported MongoDB users and roles remain in the MongoDB deployment.\n\n- The MongoDB deployment has all users and roles managed by the Ops Manager project. These users and roles have `Synced` set to `Yes`."} -{"chunk_id": "68a95c4b5e79d242619e2d82-2", "page_id": "68a95c4b5e79d242619e2d82", "source_name": "ops-manager", "product_name": "MongoDB Ops Manager", "url": "https://mongodb.com/docs/ops-manager/current/tutorial/add-existing-mongodb-processes", "title": "Add Existing MongoDB Processes to Ops Manager", "text": "## Prerequisites\n\n- If `mongod` is enabled as a service on the deployment, a race condition might result where `systemd` starts `mongod` on reboot, rather than the Automation. To prevent this issue, ensure the `mongod` service is disabled before you add your deployment to Automation:\n\n 1. Verify whether the `mongod` service is enabled:\n\n ```sh\n sudo systemctl is-enabled mongod.service\n ```\n\n 2. If the service is enabled, disable it:\n\n ```sh\n sudo systemctl disable mongod.service\n ```\n\n- If the Ops Manager project doesn't have authentication settings enabled but the MongoDB process requires authentication, add the MongoDB Agent user for the Ops Manager project with the appropriate roles. The import process displays the required roles for the user. The added user becomes the project's MongoDB Agent user.\n\n- If the Ops Manager project has authentication settings enabled, add the Ops Manager project's MongoDB Agent user to the MongoDB process.\n\n - To find the MongoDB Agent user, click Deployments, then Security, then Users.\n\n - To find the password for the Ops Manager project's MongoDB Agent user, use one of the following methods:\n\n \n\n \n\n Follow the steps in the Add MongoDB Processes procedure to launch the wizard in the UI. When you reach the modal that says Do you want to add automation to this deployment?:\n\n 1. Select Add Automation and Configure Authentication.\n\n 2. Click Show Password.\n\n \n\n \n\n Use the Automation Configuration Resource endpoint:\n\n ```sh\n curl --user \"{PUBLIC-KEY}:{PRIVATE-KEY}\" --digest \\\n --header \"Accept: application/json\" \\\n --include \\\n --request GET \"/api/public/v1.0/groups//automationConfig\"\n ```\n\n \n\n \n\n Open the `mmsConfigBackup` file in your preferred text editor and find the `autoPwd` value.\n\n \n\n \n\n - In `mongosh`, use the `db.createUser()` method to add the Ops Manager project's MongoDB Agent user to the MongoDB process. For example, if the Ops Manager project uses Username/Password authentication, run the following command to add the `mms-automation` user to the `admin` database in the MongoDB deployment to import:\n\n ```javascript\n db.getSiblingDB(\"admin\").createUser(\n {\n user: \"mms-automation\",\n pwd: \"\",\n roles: [\n 'clusterAdmin',\n 'dbAdminAnyDatabase',\n 'readWriteAnyDatabase',\n 'userAdminAnyDatabase',\n 'restore',\n 'backup',\n 'directShardOperations' // Required for sharded clusters\n ]\n }\n )\n ```\n\n You must specify the `directShardOperations` role for sharded cluster automation. This role allows the automation agent to perform maintenance operations that require direct access to shards, such as adding shards to existing clusters. For non-sharded deployments (standalone or replica sets), you can omit this role.\n\n- When you add a cluster under Ops Manager, Ops Manager automatically enables log rotation, which could collide with your existing `logRotate` configuration for `mongod` or `mongos` logs. To prevent this collision, do the following:\n\n - Disable your `logRotate` configuration for `mongod` or `mongos` processes.\n\n - Remove the `systemLog.logRotate` and `systemLog.logAppend`\n options from the `mongod` or `mongos` process configuration to use the default of Ops Manager.\n\n- The import process requires that the authentication credentials and keyfiles are the same on the source and destination clusters. To learn more, see Authentication Credentials on Source and Destination Clusters.\n\n- To successfully import an existing replica set to Ops Manager, the instance must be healthy.\n\nIf you are adding a sharded cluster, you must create this user through the `mongos` *and* on every shard. That is, create the user both as a cluster wide user through `mongos` as well as a shard local user on each shard.\n\n## Procedures\n\n### Add MongoDB Processes\n\nTo add existing MongoDB processes to Ops Manager:\n\n#### Navigate to the Deployment page for your project.\n\n- If it is not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.\n\n- If it is not already displayed, select your desired project from the Projects menu in the navigation bar.\n\n- If it is not already displayed, click Deployment in the sidebar.\n\n#### Click Add and select Existing MongoDB Deployment.\n\n#### Follow the prompts to add the deployment."} -{"chunk_id": "68a95c4b5e79d242619e2d82-3", "page_id": "68a95c4b5e79d242619e2d82", "source_name": "ops-manager", "product_name": "MongoDB Ops Manager", "url": "https://mongodb.com/docs/ops-manager/current/tutorial/add-existing-mongodb-processes", "title": "Add Existing MongoDB Processes to Ops Manager", "text": "### Add Authentication Credentials to your Deployment\n\nAfter you add existing MongoDB process to Ops Manager, you might have to add authentication credentials for the new deployments if authentication is enabled for the project into which you imported the deployment. See Authentication Use Cases to learn in which situations you must add Automation, Monitoring, or Backup credentials for your new deployment.\n\nIf you are adding a deployment that you intend to live migrate to Atlas, you need to add the deployment (and its credentials) only for Monitoring.\n\nSelect the authentication mechanism that you want to use:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n#### Add Credentials for Automation\n\nTo add credentials for a deployment that will use Automation but didn't use it before you imported it to Ops Manager:\n\n##### Add the MongoDB Agent user to your databases.\n\nThe MongoDB Agent user performs automation tasks for your MongoDB databases. Make sure this MongoDB user has the proper privileges.\n\n##### Navigate to the Security Settings dialog for your deployment.\n\n- If it is not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.\n\n- If it is not already displayed, select your desired project from the Projects menu in the navigation bar.\n\n- If it is not already displayed, click Deployment in the sidebar.\n\n1. Click the Security tab.\n\n2. Click the Settings tab.\n\n3. Perform one of the following actions:\n\n - If this is your first time configuring TLS (Transport Layer Security), authentication, or authorization settings for this project, click Get Started.\n\n - If you have already configured TLS (Transport Layer Security) authentication, or authorization settings for this project, click Edit.\n\n##### Click Edit Credentials.\n\n##### Continue through the modal until you see the Configure Ops Manager Agents page.\n\n##### Add the appropriate credentials:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nSetting\n\n\nValue\n\n
\nMongoDB Agent Username\n\n\nEnter the MongoDB Agent username.\n\n
\nMongoDB Agent Password\n\n\nEnter the password for MongoDB Agent Username.\n\n
\n\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nSetting\n\n\nValue\n\n
\nMongoDB Agent LDAP Username\n\n\nEnter the LDAP (Lightweight Directory Access Protocol) username.\n\n
\nMongoDB Agent LDAP Password\n\n\nEnter the password for MongoDB Agent's LDAP (Lightweight Directory Access Protocol) Username.\n\n
\nMongoDB Agent LDAP Group DN\n\n\nEnter the Distinguished Name for the MongoDB Agent's LDAP (Lightweight Directory Access Protocol) Group.\n\nProvide the MongoDB Agent's LDAP (Lightweight Directory Access Protocol) Group DN (Distinguished Name) only if you use LDAP (Lightweight Directory Access Protocol) Authorization. Each MongoDB Agent should have and use its own LDAP (Lightweight Directory Access Protocol) Group DN (Distinguished Name).\n\n
\n\n
\n\n\n\nThe required values depend upon whether you are connecting to a Linux-served KDC (Key Distribution Center) or Windows Active Directory Server.\n\n**Linux KDC:**\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nSetting\n\n\nValue\n\n
\nMonitoring Kerberos Principal\n\n\nKerberos Principal.\n\n
\nMonitoring Keytab Path\n\n\nAbsolute file path to the MongoDB Agent's Keytab.\n\n
\nMonitoring LDAP Group DN\n\n\nEnter the Distinguished Name for the MongoDB Agent's LDAP (Lightweight Directory Access Protocol) Group.\n\nThe LDAP (Lightweight Directory Access Protocol) Group DN is then created as a role in MongoDB to grant the MongoDB Agent the appropriate privileges.\n\nYou only need to provide the LDAP Group DN if you use LDAP Authorization.\n\n
**Windows Active Directory:**\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nSetting\n\n\nValue\n\n
\nMongoDB Agent Username\n\n\nActive Directory user name.\n\n
\nMongoDB Agent Password\n\n\nActive Directory password.\n\n
\nDomain\n\n\nNetBIOS name of a domain in Active Directory Domain Services. Must be in all capital letters.\n\n
\n\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nSetting\n\n\nValue\n\n
\nMongoDB Agent Username\n\n\nEnter the LDAP (Lightweight Directory Access Protocol)v3 distinguished name derived from the MongoDB Agent's PEM (Privacy-Enhanced Mail) Key file.\n\n
\nTLS/SSL CA File Path\n\n\nThe path on disk that contains the trusted certificate authority (CA) certificates in PEM (Privacy-Enhanced Mail) format. These certificates verify the server certificate returned from any MongoDB instances running with TLS (Transport Layer Security)/SSL (Secure Sockets Layer). You must enter at least one TLS (Transport Layer Security)/SSL (Secure Sockets Layer) CA file path.\n\n
\nMongoDB Agent PEM Key file\n\n\nIf your MongoDB deployment requires client certificates, on the line for the appropriate operating system, provide the path and `.pem` filename for the client certificate used by the MongoDB Agent's PEM (Privacy-Enhanced Mail) Key file on the server. You must enter a value for at least one MongoDB Agent PEM Key File.\n\n
\nMongoDB Agent PEM Key Password\n\n\nProvide the password to the PEM (Privacy-Enhanced Mail) Key file if it was encrypted.\n\n
\nMongoDB Agent LDAP Group DN\n\n\nEnter the Distinguished Name for the MongoDB Agent's LDAP (Lightweight Directory Access Protocol) Group.\n\nYou only need to provide MongoDB Agent's LDAP (Lightweight Directory Access Protocol) Group DN if you use LDAP (Lightweight Directory Access Protocol) Authorization.\n\n
\n\n
\n\n
\n\n#### Add Credentials for Monitoring\n\nTo add credentials for a deployment that will not use Automation but will use Monitoring:\n\n##### Navigate to the Monitoring Settings dialog for your deployment.\n\n- If it is not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.\n\n- If it is not already displayed, select your desired project from the Projects menu in the navigation bar.\n\n- If it is not already displayed, click Deployment in the sidebar.\n\n1. Click , then click Monitoring Settings next to the deployment for which you want to view monitoring settings.\n\n##### Click Credentials.\n\n##### Add the appropriate credentials:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nSetting\n\n\nValue\n\n
\nMonitoring Username\n\n\nEnter the Monitoring username.\n\n
\nMonitoring Password\n\n\nEnter the password for Monitoring Username.\n\n
\n\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nSetting\n\n\nValue\n\n
\nMonitoring LDAP Username"} -{"chunk_id": "68a95c4b5e79d242619e2d82-4", "page_id": "68a95c4b5e79d242619e2d82", "source_name": "ops-manager", "product_name": "MongoDB Ops Manager", "url": "https://mongodb.com/docs/ops-manager/current/tutorial/add-existing-mongodb-processes", "title": "Add Existing MongoDB Processes to Ops Manager", "text": "\nEnter the LDAP (Lightweight Directory Access Protocol) username.\n\n
\nMonitoring LDAP Password\n\n\nEnter the password for Monitoring's LDAP (Lightweight Directory Access Protocol) Username.\n\n
\nMonitoring LDAP Group DN\n\n\nEnter the Distinguished Name for the Monitoring's LDAP (Lightweight Directory Access Protocol) Group.\n\nProvide the Monitoring's LDAP (Lightweight Directory Access Protocol) Group DN (Distinguished Name) only if you use LDAP (Lightweight Directory Access Protocol) Authorization. Each Monitoring should have and use its own LDAP (Lightweight Directory Access Protocol) Group DN (Distinguished Name).\n\n
\n\n
\n\n\n\nThe required values depend upon whether you are connecting to a Linux-served KDC (Key Distribution Center) or Windows Active Directory Server.\n\n**Linux KDC:**\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nSetting\n\n\nValue\n\n
\nMonitoring Kerberos Principal\n\n\nKerberos Principal.\n\n
\nMonitoring Keytab Path\n\n\nAbsolute file path to the Monitoring's Keytab.\n\n
\nMonitoring LDAP Group DN\n\n\nEnter the Distinguished Name for the Monitoring's LDAP (Lightweight Directory Access Protocol) Group.\n\nThe LDAP (Lightweight Directory Access Protocol) Group DN is then created as a role in MongoDB to grant the Monitoring the appropriate privileges.\n\nYou only need to provide the LDAP Group DN if you use LDAP Authorization.\n\n
**Windows Active Directory:**\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nSetting\n\n\nValue\n\n
\nMonitoring Username\n\n\nActive Directory user name.\n\n
\nMonitoring Password\n\n\nActive Directory password.\n\n
\nDomain\n\n\nNetBIOS name of a domain in Active Directory Domain Services. Must be in all capital letters.\n\n
\n\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nSetting\n\n\nValue\n\n
\nMonitoring Username\n\n\nEnter the LDAP (Lightweight Directory Access Protocol)v3 distinguished name derived from the Monitoring's PEM (Privacy-Enhanced Mail) Key file.\n\n
\nMonitoring PEM Key file\n\n\nProvide the path and filename for the Monitoring's PEM (Privacy-Enhanced Mail) Key file on the server on the line for the appropriate operating system.\n\n
\nMonitoring PEM Key Password\n\n\nProvide the password to the PEM (Privacy-Enhanced Mail) Key file if it was encrypted.\n\n
\nMonitoring LDAP Group DN\n\n\nEnter the Distinguished Name for the Monitoring's LDAP (Lightweight Directory Access Protocol) Group.\n\nYou only need to provide the Monitoring's LDAP (Lightweight Directory Access Protocol) Group DN if you use LDAP (Lightweight Directory Access Protocol) Authorization.\n\n
\n\n
\n\n
\n\n#### Add Credentials for Backup\n\nTo add credentials for a deployment that will not use Automation but will use Backup:\n\n##### Navigate to the Continuous Backup page for your project.\n\n- If it is not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.\n\n- If it is not already displayed, select your desired project from the Project menu in the navigation bar.\n\n- Click Continuous Backup in the sidebar.\n\n##### For your deployment, Click , then click Edit Credentials.\n\n##### Add the appropriate credentials:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nSetting\n\n\nValue\n\n
\nBackup Username\n\n\nEnter the Backup username.\n\n
\nBackup Password\n\n\nEnter the password for Backup Username.\n\n
\n\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nSetting\n\n\nValue\n\n
\nBackup LDAP Username\n\n\nEnter the LDAP (Lightweight Directory Access Protocol) username.\n\n
\nBackup LDAP Password\n\n\nEnter the password for Backup's LDAP (Lightweight Directory Access Protocol) Username.\n\n
\nBackup LDAP Group DN\n\n\nEnter the Distinguished Name for the Backup's LDAP (Lightweight Directory Access Protocol) Group.\n\nProvide the Backup's LDAP (Lightweight Directory Access Protocol) Group DN (Distinguished Name) only if you use LDAP (Lightweight Directory Access Protocol) Authorization. Each Backup should have and use its own LDAP (Lightweight Directory Access Protocol) Group DN (Distinguished Name).\n\n
\n\n
\n\n\n\nThe required values depend upon whether you are connecting to a Linux-served KDC (Key Distribution Center) or Windows Active Directory Server.\n\n**Linux KDC:**\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nSetting\n\n\nValue\n\n
\nMonitoring Kerberos Principal\n\n\nKerberos Principal.\n\n
\nMonitoring Keytab Path\n\n\nAbsolute file path to the Backup's Keytab.\n\n
\nMonitoring LDAP Group DN\n\n\nEnter the Distinguished Name for the Backup's LDAP (Lightweight Directory Access Protocol) Group.\n\nThe LDAP (Lightweight Directory Access Protocol) Group DN is then created as a role in MongoDB to grant the Backup the appropriate privileges.\n\nYou only need to provide the LDAP Group DN if you use LDAP Authorization.\n\n
**Windows Active Directory:**\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nSetting\n\n\nValue\n\n
\nBackup Username\n\n\nActive Directory user name.\n\n
\nBackup Password\n\n\nActive Directory password.\n\n
\nDomain\n\n\nNetBIOS name of a domain in Active Directory Domain Services. Must be in all capital letters.\n\n
\n\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nSetting\n\n\nValue\n\n
\nBackup Username\n\n\nEnter the LDAP (Lightweight Directory Access Protocol)v3 distinguished name derived from the Backup's PEM (Privacy-Enhanced Mail) Key file.\n\n
\nBackup PEM Key file\n\n\nProvide the path and filename for the Backup's PEM (Privacy-Enhanced Mail) Key file on the server on the line for the appropriate operating system.\n\n
\nBackup PEM Key Password\n\n\nProvide the password to the PEM (Privacy-Enhanced Mail) Key file if it was encrypted.\n\n
\nBackup LDAP Group DN\n\n\nEnter the Distinguished Name for the Backup's LDAP (Lightweight Directory Access Protocol) Group.\n\nYou only need to provide Backup's LDAP (Lightweight Directory Access Protocol) Group DN if you use LDAP (Lightweight Directory Access Protocol) Authorization.\n\n
\n\n
\n\n
"} -{"chunk_id": "68a95c4b5e79d242619e2c4e-0", "page_id": "68a95c4b5e79d242619e2c4e", "source_name": "ops-manager", "product_name": "MongoDB Ops Manager", "url": "https://mongodb.com/docs/ops-manager/current/reference/api/nav/administration-backup", "title": "Backup Administration", "text": "# Backup Administration\n\nGroups and projects are synonymous terms. Your `{PROJECT-ID}` is the same as your project ID. For existing groups, your group/project ID remains the same. This page uses the more familiar term group when referring to descriptions. The endpoint remains as stated in the document.\n\nThe Ops Manager API exposes the following resources for backup administration:\n\n- Blockstore Configurations\n\n- File System Store Configurations\n\n- S3-Compatible Blockstore Configurations\n\n- S3-Compatible Blockstore (v2.0)\n\n- Oplog Store Configurations\n\n- S3 Oplog Configurations\n\n- Sync Store Configurations\n\n- Backup Daemon Configurations\n\n- Project Backup Job Configurations\n\n- Backup Encryption Keys\n\n- Key Vault"} -{"chunk_id": "68a95c4b5e79d242619e2a5c-0", "page_id": "68a95c4b5e79d242619e2a5c", "source_name": "ops-manager", "product_name": "MongoDB Ops Manager", "url": "https://mongodb.com/docs/ops-manager/current/reference/api/access-list", "title": "Access List", "text": "# Access List\n\nThe `whitelist` resource is deprecated for Ops Manager 5.0 and later. Use the `accessList` resource instead to control access to API operations.\n\nThe `accessList` resource lets you retrieve and update a user's access list, which controls the user's access to API operations. Users can issue API operations only from addresses on their own access list. To use the `accessList` resource you must know the unique identifier of the user who owns the access list. To retrieve a user's ID, see Get All Users in One Project.\n\nThe `accessList` resource's `POST` and `DELETE` operations are in the access list themselves. They must originate from an address already on the user's access list.\n\nYou can retrieve access list information only for the user issuing the request. The **USER-ID** in the URL *must* match the ID of the user associated with the public API key used to send the request.\n\nBase URL: `https://{OPSMANAGER-HOST}:{PORT}/api/public/v1.0`\n\n## Endpoints\n\nThe following endpoints are available for `hosts`.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nMethod\n\n\nEndpoint\n\n\nDescription\n\n
\nGET\n\n\n/users/{USER-ID}/accessList\n\n\nRetrieves the access list for the current user.\n\n
\nGET\n\n\n/users/{USER-ID}/accessList/{IP-ADDRESS}\n\n\nRetrieves the access list for the specified IP address.\n\n
\nPOST\n\n\n/users/{USER-ID}/accessList/{IP-ADDRESS}\n\n\nAdds entries to the access list for the current user.\n\n
\nDELETE\n\n\n/users/{USER-ID}/accessList/{IP-ADDRESS}\n\n\nDeletes an entry from the access list for the current user.\n\n
"} -{"chunk_id": "68a95c4b5e79d242619e29cd-0", "page_id": "68a95c4b5e79d242619e29cd", "source_name": "ops-manager", "product_name": "MongoDB Ops Manager", "url": "https://mongodb.com/docs/ops-manager/current/admin/backup/grooms-page", "title": "Grooms", "text": "# Grooms\n\nThis page lists active and recent groom jobs.\n\nGroom jobs remove unused blocks in blockstores and S3 blockstores to reclaim storage space.\n\nIf no existing snapshots reference a given block, Ops Manager considers the block *unused* or *dead*. Ops Manager grooms blockstores after the snapshot drops below the threshold of living bytes.\n\n## How Groom Jobs Work\n\nGroom job differ based on the snapshot store.\n\nDuring grooming operations, you may notice that the file sizes of blockstores and S3-compatible storage snapshot stores fluctuate, sometimes dramatically. This is normal during these operations.\n\n### Intra-Blockstore Groom Job\n\nAn intra-blockstore groom job performs the following tasks:\n\n1. Writes all new blocks for ongoing snapshots to a new *target* location on the blockstore.\n\n2. Copies all existing living blocks from the *source* location to the new *target* location in the same blockstore.\n\n This means two copies of the living blocks exist on the blockstore at the same time. This impacts storage usage.\n\n3. Updates references to maintain data relationships.\n\n4. Drops the *source* database.\n\n### Inter-Blockstore Groom Job\n\nAn inter-blockstore groom job performs the following tasks:\n\n1. Writes all new blocks for ongoing snapshots to a different *target* blockstore.\n\n2. Copies all existing living blocks from the *source* blockstore to the new *target* blockstore.\n\n3. Updates references to maintain data relationships.\n\n4. Drops the database from the *source* blockstore.\n\n### File System Groom Job\n\nA File System Groom Job deletes the database files from the file system.\n\n### S3 Groom Job\n\nAn S3-compatible storage blockstore groom job performs the following tasks:\n\n1. Writes all new blocks for ongoing snapshots to temporary database.\n\n2. Sends a delete request for dead blocks in source database.\n\n3. Resumes writing new blocks for ongoing snapshots to source database.\n\n4. Copies over new blocks from the temporary database back to the source database.\n\n## What Triggers a Groom Job\n\nWhen calculating the threshold for triggering a groom job, Ops Manager considers these factors:\n\n- Living bytes: bytes referenced by at least one existing snapshot.\n\n- Dead bytes: bytes no longer referenced by any snapshot.\n\n- Total bytes: the sum of living and dead bytes in a blockstore.\n\nOps Manager triggers groom jobs for a blockstore when both of these conditions are met:\n\n- the percentage of living to total bytes drops below a given threshold, and\n\n- the number of dead bytes exceeds a minimum value.\n\nThe thresholds vary by blockstore type:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nBlockstore Type\n\n\nPercentage of Living to Total Bytes\n\n\nMinimum Number of Dead Bytes\n\n
\nS3\n\n\n75%\n\n\n0\n\n
\nMongoDB\n\n\n45%\n\n\n2 GB\n\n
Ops Manager also runs groom jobs at the following minimum intervals:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nBlockstore Location\n\n\nMinimum Groom Interval\n\n
\nS3\n\n\nOne time every two weeks\n\n
\nMongoDB\n\n\nOne time per year\n\n
When grooming, Ops Manager removes all the dead bytes.\n\nYou can start a groom from the Grooms Priority admin page.\n\nOps Manager limits a project's Tracking and Groom Jobs to the Backup Daemons set in the project's Backup Configuration."} -{"chunk_id": "68a95c4b5e79d242619e2d7f-0", "page_id": "68a95c4b5e79d242619e2d7f", "source_name": "ops-manager", "product_name": "MongoDB Ops Manager", "url": "https://mongodb.com/docs/ops-manager/current/tutorial/add-message-to-interface", "title": "Add a Message to the Interface", "text": "# Add a Message to the Interface\n\n## Overview\n\nYou can display a message on any page of the Ops Manager interface to notify users of information or events, such as impending maintenance windows.\n\n## Procedures\n\n### Add a Message\n\n1. Click the Admin link in the upper right corner of the Ops Manager interface.\n\n2. Click the General tab and then click Messages.\n\n3. Click the Add Message button.\n\n4. Enter the message and the page or page prefix. The page prefix allows you to specify a path of a single page or the URL prefix of a group of pages. The prefix must begin with a `/` character.\n\n For example, entering the page prefix `/settings/profile` will display a message on the default Settings page and Account page but not on any other page in the application.\n\n5. Click the Active checkbox to make the message live. Optionally, you can leave the box unchecked to disable the message.\n\n6. Click Add.\n\nOnce added, active messages take 60 seconds before they display.\n\n### Disable a Message\n\n1. Click the Admin link in the upper right corner of the Ops Manager interface.\n\n2. Click the General tab and then click Messages.\n\n3. Click the orange square button to the right of the alert.\n\nTo re-enable a disabled message, click the grey button.\n\n### Delete a Message\n\n1. Click the Admin link in the upper right corner of the Ops Manager interface.\n\n2. Click the General tab and then click Messages.\n\n3. Click the garbage can icon to the right of the alert."} -{"chunk_id": "68a95c4b5e79d242619e2ec6-0", "page_id": "68a95c4b5e79d242619e2ec6", "source_name": "ops-manager", "product_name": "MongoDB Ops Manager", "url": "https://mongodb.com/docs/ops-manager/current/tutorial/view-agent-status", "title": "View Agent Status", "text": "# View Agent Status\n\nClick Deployment, then the Agents tab, then All Agents. Ops Manager displays the following information about your agents:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nField\n\n\nDescription\n\n
\nAgent Hostname\n\n\nThe hostname of the agent and the agent type, indicated by the icon on the left-hand side. The icon to agent type mapping is as follows:\n\n- Automation\n\n- Backup\n\n- Monitoring\n\n
\nLast Conf Call\n\n\nThe number of seconds since the last time the agent polled Ops Manager.\n\n
\nVersion\n\n\nThe version of the agent software running on this agent instance.\n\n
\nStatus\n\n\nIndicates whether the agent is active.\n\n
\nAction\n\n\nClick View Logs to view the agent's log.\n\nTo access this feature, you must either:\n\n- Belong to the project\n\n- Have the Global Monitoring Admin role or the Global Owner role\n\n
"} -{"chunk_id": "68a95c4b5e79d242619e2e4a-0", "page_id": "68a95c4b5e79d242619e2e4a", "source_name": "ops-manager", "product_name": "MongoDB Ops Manager", "url": "https://mongodb.com/docs/ops-manager/current/tutorial/nav/mongodb-agent", "title": "MongoDB Agent for Ops Manager Hosts", "text": "# MongoDB Agent for Ops Manager Hosts\n\nThe MongoDB Agent is a single binary that connects your MongoDB hosts to Ops Manager. You install the MongoDB Agent on the hosts that run the MongoDB processes you want Ops Manager to manage. Each agent polls Ops Manager to determine the current goal, performs the work needed to reach that goal, and continually reports its status back to Ops Manager.\n\n## Agent Functions\n\nThe MongoDB Agent performs any -- or all -- of the following three functions, depending on what you need:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nFunction\n\n\nDescription\n\n
\nAutomation\n\n\nDeploys and maintains MongoDB nodes and clusters to match the goal state that your project's automation configuration defines.\n\n
\nMonitoring\n\n\nCollects statistics from the nodes in your MongoDB deployment and transmits them to Ops Manager so that Ops Manager can report deployment status in real time.\n\n
\nBackup\n\n\nTakes snapshots of the MongoDB processes you specify so that you can restore your deployment to an earlier state.\n\n
To activate the Monitoring or Backup function, use the Ops Manager UI. To activate the Automation function, create a new cluster or import an existing one. To learn how to activate and deactivate each function, see Manage Automation Function.\n\nAgents send deployment configuration information and MongoDB logs only. They don't send any data records from your MongoDB deployment.\n\n## Legacy Agents\n\nBefore the introduction of the MongoDB Agent, each function -- Automation, Backup, and Monitoring -- ran as a separate agent binary in your project. These legacy Agents reached end of life in Ops Manager 4.4. To learn about the update process, see My clusters are already managed using all 3 legacy Agents, what will happen?."} -{"chunk_id": "68a95c4b5e79d242619e2b2e-0", "page_id": "68a95c4b5e79d242619e2b2e", "source_name": "ops-manager", "product_name": "MongoDB Ops Manager", "url": "https://mongodb.com/docs/ops-manager/current/reference/api/admin/backup/s3-blockstore-config", "title": "S3-Compatible Blockstore Configurations", "text": "# S3-Compatible Blockstore Configurations\n\nGroups and projects are synonymous terms. Your `{PROJECT-ID}` is the same as your project ID. For existing groups, your group/project ID remains the same. This page uses the more familiar term group when referring to descriptions. The endpoint remains as stated in the document.\n\nBase URL: `https://{OPSMANAGER-HOST}:{PORT}/api/public/v1.0/admin/backup`\n\nTo learn more about the v2.0 resource, which adds HashiCorp Vault support through the `keyVault` object, see S3-Compatible Blockstore Configurations (v2.0).\n\n## Endpoints\n\nThe following lists the endpoints available for S3 blockstore configurations.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nMethod\n\n\nEndpoint\n\n\nDescription\n\n
\nGET\n\n\n/snapshot/s3Configs/{S3-BLOCKSTORE-ID}\n\n\nGet One S3-Compatible Blockstore Configuration by ID\n\n
\nGET\n\n\n/snapshot/s3Configs\n\n\nGet All S3-Compatible Blockstore Configurations\n\n
\nPOST\n\n\n/snapshot/s3Configs\n\n\nCreate One S3-Compatible Blockstore Configuration\n\n
\nPUT\n\n\n/snapshot/s3Configs/{S3-BLOCKSTORE-ID}\n\n\nUpdate One S3-Compatible Blockstore Configuration\n\n
\nDELETE\n\n\n/snapshot/s3Configs/{S3-BLOCKSTORE-ID}\n\n\nDelete One S3-Compatible Blockstore Configuration\n\n
"} -{"chunk_id": "68a95c4b5e79d242619e2a5e-0", "page_id": "68a95c4b5e79d242619e2a5e", "source_name": "ops-manager", "product_name": "MongoDB Ops Manager", "url": "https://mongodb.com/docs/ops-manager/current/reference/api/access-list-add-entries", "title": "Add Entries to an Access List", "text": "# Add Entries to an Access List\n\nBase URL: `https://{OPSMANAGER-HOST}:{PORT}/api/public/v1.0`\n\n## Resource\n\n```none\nPOST /users/{USER-ID}/accessList\n```\n\n### Request Path Parameters\n\n\n\n\n\n\n\n\n\n\n\n\n
\nParameter\n\n\nType\n\n\nDescription\n\n
\nUSER-ID\n\n\nstring\n\n\n*(Required.)* Unique identifier of the current user. To retrieve the ID of the current user, see Get All Users in One Project.\n\n
\n\n### Request Query Parameters\n\nThe following query parameters are optional:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nNecessity\n\n\nDescription\n\n\nDefault\n\n
\npageNum\n\n\nnumber\n\n\nOptional\n\n\nOne-based integer that returns a subsection of results.\n\n\n`1`\n\n
\nitemsPerPage\n\n\nnumber\n\n\nOptional\n\n\nNumber of items to return per page, up to a maximum of 500.\n\n\n`100`\n\n
\npretty\n\n\nboolean\n\n\nOptional\n\n\nFlag that indicates whether the response body should be in a prettyprint format.\n\n\n`false`\n\n
\nenvelope\n\n\nboolean\n\n\nOptional\n\n\nFlag that indicates whether or not to wrap the response in an envelope.\n\nSome API (Application Programming Interface) clients cannot access the HTTP (Hypertext Transfer Protocol) response headers or status code. To remediate this, set `envelope : true` in the query.\n\nFor endpoints that return a list of results, the `content` object is an envelope. Ops Manager adds the `status` field to the response body.\n\n\n`false`\n\n
\n\n### Request Body Parameters\n\nThe request body must be an array of access list entities, even if there is only one. The only field that you need to specify for each request object is the **IP-ADDRESS**.\n\nIf an IP address is already in the access list, it will be ignored.\n\nIf you specify a single IP address with the `/32` subnet mask, Ops Manager does not store the `/32`, as the `/32` does not change the address.\n\nAn address of `12.34.56.78` is the same as `12.34.56.78/32`.\n\n\n\n\n\n\n\n\n\n\n\n\n
\nParameter\n\n\nType\n\n\nDescription\n\n
\nipAddress\n\n\nstring\n\n\n*(Required.)* The IP address or CIDR (Classless Inter-Domain Routing) block that you want to add to the specified user's access list.\n\n
\n\n## Response\n\n### Response Document\n\nThe response JSON (Javascript Object Notation) document includes an array of result objects, an array of link objects and a count of the total number of result objects retrieved.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nDescription\n\n
\n`results`\n\n\narray\n\n\nArray includes one object for each item detailed in the `results` Embedded Document section.\n\n
\n`links`\n\n\narray\n\n\nArray includes one or more links to sub-resources and/or related resources. The relations between URL (Uniform Resource Locator)s are explained in the Web Linking Specification.\n\n
\n`totalCount`\n\n\nnumber\n\n\nInteger count of the total number of items in the result set. It may be greater than the number of objects in the results array if the entire result set is paginated.\n\n
\n\n### `results` Embedded Document\n\nEach **result** is one access list.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nDescription\n\n
\n`cidrBlock`\n\n\nstring\n\n\nA CIDR-notated range of IP addresses.\n\n
\n`created`\n\n\ndate\n\n\nThe date this IP address was added to the access list.\n\n
\n`ipAddress`\n\n\nstring\n\n\nAn IP address in the access list.\n\n
\n`lastUsed`\n\n\ndate\n\n\nThe date of the most recent request that originated from this IP address. Note that this field is *only* updated when a resource that is protected by the access list is accessed.\n\n
\n`lastUsedAddress`\n\n\nstring\n\n\nThe address from which the last call to the API was issued.\n\n
\n`count`\n\n\nnumber\n\n\nThe total number of requests that originated from this IP address. Note that this field is *only* updated when a resource that is protected by the access list is accessed.\n\n
\n`links`\n\n\narray\n\n\nLinks to related sub-resources. All links arrays in responses contain at least one link called `self`. The relations between URLs are explained in the Web Linking Specification.\n\n
\n\n## Example Request\n\n```sh\ncurl --user '{PUBLIC-KEY}:{PRIVATE-KEY}' --digest \\\n--header 'Accept: application/json' \\\n--header 'Content-Type: application/json' \\\n--include \\\n--request POST \"https://{OPSMANAGER-HOST}:{PORT}/api/public/v1.0/users/{USER-ID}/accessList\" --data '\n [\n {\n \"ipAddress\" : \"192.0.1.15\",\n \"comment\" : \"IP address for Application Server A\"\n },\n {\n \"cidrBlock\" : \"192.0.2.0/24\",\n \"comment\" : \"CIDR block for Application Server B - D\"\n }\n ]'\n```\n\n## Example Response\n\n### Response Header\n\n```http\nHTTP/1.1 401 Unauthorized\nContent-Type: application/json;charset=ISO-8859-1\nDate: {dateInUnixFormat}\nWWW-Authenticate: Digest realm=\"MMS Public API\", domain=\"\", nonce=\"{nonce}\", algorithm=MD5, op=\"auth\", stale=false\nContent-Length: {requestLengthInBytes}\nConnection: keep-alive\n```\n\n```http\nHTTP/1.1 201 Created\nVary: Accept-Encoding\nContent-Type: application/json\nStrict-Transport-Security: max-age=300\nDate: {dateInUnixFormat}\nConnection: keep-alive\nContent-Length: {requestLengthInBytes}\nX-MongoDB-Service-Version: gitHash={gitHash}; versionString={ApplicationVersion}\n```\n\n### Response Body\n\n```json\n{\n \"totalCount\" : 3,\n \"results\" : [ {\n \"cidrBlock\" : \"12.34.56.78/32\",\n \"ipAddress\" : \"12.34.56.78\",\n \"created\" : \"2014-04-23T16:17:44Z\",\n \"lastUsed\" : \"2016-08-17T19:34:05Z\",\n \"lastUsedAddress\" : \"12.34.56.78\",\n \"count\" : 0,\n \"links\" : []\n }, {\n \"cidrBlock\" : \"76.54.32.10/32\",\n \"ipAddress\" : \"76.54.32.10\",\n \"created\" : \"2016-08-17T19:34:05Z\",\n \"count\" : 0,\n \"links\" : []\n }, {\n \"cidrBlock\" : \"2.3.4.5/32\",\n \"ipAddress\" : \"2.3.4.5\",\n \"created\" : \"2016-08-17T19:34:05Z\",\n \"count\" : 0,\n \"links\" : []\n } ],\n \"links\" : []\n}\n```"} -{"chunk_id": "68a95c285e79d242619dedb1-0", "page_id": "68a95c285e79d242619dedb1", "source_name": "php-library", "product_name": "PHP Library", "url": "https://mongodb.com/docs/php-library/current/reference/method/MongoDBCollection-getWriteConcern", "title": "MongoDB\\Collection::getWriteConcern()", "text": "# MongoDB\\Collection::getWriteConcern()\n\n## Definition\n\n`MongoDB\\Collection::getWriteConcern()`\nReturns the write concern for this collection.\n\n```php\nfunction getWriteConcern(): MongoDB\\Driver\\WriteConcern\n```\n\n## Return Values\n\nA MongoDB\\Driver\\WriteConcern object.\n\n## Example\n\n```php\ngetCollection('test', 'users', [\n 'writeConcern' => new MongoDB\\Driver\\WriteConcern(1, 0, true),\n]);\n\nvar_dump($collection->getWriteConcern());\n```\n\nThe output would then resemble:\n\n```none\nobject(MongoDB\\Driver\\WriteConcern)#5 (2) {\n [\"w\"]=>\n int(1)\n [\"j\"]=>\n bool(true)\n}\n```\n\n## See Also\n\n- Write Concern in the MongoDB manual\n\n- MongoDB\\Driver\\WriteConcern::isDefault()\n\n- `MongoDB\\Client::getWriteConcern()`\n\n- `MongoDB\\Database::getWriteConcern()`\n\n- `MongoDB\\GridFS\\Bucket::getWriteConcern()`"} -{"chunk_id": "68a95c285e79d242619ded01-0", "page_id": "68a95c285e79d242619ded01", "source_name": "php-library", "product_name": "PHP Library", "url": "https://mongodb.com/docs/php-library/current/reference/class/MongoDBInsertManyResult", "title": "MongoDB\\InsertManyResult Class", "text": "# MongoDB\\InsertManyResult Class\n\n## Definition\n\n`MongoDB\\InsertManyResult`\nThis class contains information about an executed bulk insert operation. It encapsulates a MongoDB\\Driver\\WriteResult object and is returned from `MongoDB\\Collection::insertMany()`.\n\n## Methods\n\n- `MongoDB\\InsertManyResult::getInsertedCount()`\n\n- `MongoDB\\InsertManyResult::getInsertedIds()`\n\n- `MongoDB\\InsertManyResult::isAcknowledged()`"} -{"chunk_id": "68a95c285e79d242619dee47-0", "page_id": "68a95c285e79d242619dee47", "source_name": "php-library", "product_name": "PHP Library", "url": "https://mongodb.com/docs/php-library/current/reference/method/MongoDBCollection-findOneAndUpdate", "title": "MongoDB\\Collection::findOneAndUpdate()", "text": "# MongoDB\\Collection::findOneAndUpdate()\n\n## Definition\n\n`MongoDB\\Collection::findOneAndUpdate()`\nFinds a single document matching the query and updates it.\n\n```php\nfunction findOneAndUpdate(\n array|object $filter,\n array|object $update,\n array $options = []\n): object|null\n```\n\n## Parameters\n\nThe filter criteria that specifies the documents to update.\n\nSpecifies the field and value combinations to update and any relevant update operators. `$update` uses MongoDB's update operators. You can also pass an aggregation pipeline as this parameter.\n\nAn array specifying the desired options.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nType\n\n\nDescription\n\n
\nbypassDocumentValidation\n\n\nboolean\n\n\nIf `true`, allows the write operation to circumvent document level validation. Defaults to `false`.\n\n
\narrayFilters\n\n\narray\n\n\nAn array of filter documents that determines which array elements to modify for an update operation on an array field.\n\n
\ncollation\n\n\narray|object\n\n\nCollation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks. When specifying collation, the `locale` field is mandatory; all other collation fields are optional. For descriptions of the fields, see Collation Document.\n\nIf the collation is unspecified but the collection has a default collation, the operation uses the collation specified for the collection. If no collation is specified for the collection or for the operation, MongoDB uses the simple binary comparison used in prior versions for string comparisons.\n\n
\ncomment\n\n\nmixed\n\n\nEnables users to specify an arbitrary comment to help trace the operation through the database profiler, currentOp output, and logs.\n\nThis option is available since MongoDB 4.4 and will result in an exception at execution time if specified for an older server version.\n\n
\nhint\n\n\nstring|array|object\n\n\nThe index to use. Specify either the index name as a string or the index key pattern as a document. If specified, then the query system will only consider plans using the hinted index.\n\nThis option is available since MongoDB 4.4 and will result in an exception at execution time if specified for an older server version.\n\n
\nmaxTimeMS\n\n\ninteger\n\n\nThe cumulative time limit in milliseconds for processing operations on the cursor. MongoDB aborts the operation at the earliest following interrupt point.\n\n
\nlet\n\n\narray|object\n\n\nMap of parameter names and values. Values must be constant or closed expressions that do not reference document fields. Parameters can then be accessed as variables in an aggregate expression context (e.g. `$$var`).\n\nThis is not supported for server versions prior to 5.0 and will result in an exception at execution time if used.\n\n
\nprojection\n\n\narray|object\n\n\nThe projection specification to determine which fields to include in the returned documents. See Project Fields to Return from Query and Projection Operators in the MongoDB manual.\n\n
\nreturnDocument\n\n\ninteger\n\n\nSpecifies whether to return the document before the update is applied, or after. `returnDocument` supports the following values:\n\n- `MongoDB\\Operation\\FindOneAndUpdate::RETURN_DOCUMENT_BEFORE` (*default*)\n\n- `MongoDB\\Operation\\FindOneAndUpdate::RETURN_DOCUMENT_AFTER`\n\n
\nsession\n\n\nMongoDB\\Driver\\Session\n\n\nClient session to associate with the operation.\n\n
\nsort\n\n\narray|object\n\n\nThe sort specification for the ordering of the results.\n\n
\ntypeMap\n\n\narray\n\n\nThe type map to apply to cursors, which determines how BSON documents are converted to PHP values. Defaults to the collection's type map.\n\nThis will be used for the returned result document.\n\n
\nupsert\n\n\nboolean\n\n\nIf set to `true`, creates a new document when no document matches the query criteria. The default value is `false`, which does not insert a new document when no match is found.\n\n
\nwriteConcern\n\n\nMongoDB\\Driver\\WriteConcern\n\n\nWrite concern to use for the operation. Defaults to the collection's write concern.\n\nIt is not possible to specify a write concern for individual operations as part of a transaction. Instead, set the `writeConcern` option when starting the transaction.\n\n
\n\n## Return Values\n\nAn array or object for either the original or the updated document, depending on the specified value of the `returnDocument` option. By default, the original document is returned. If no document matched the query, `null` is returned. The return type will depend on the `typeMap` option.\n\n## Errors/Exceptions\n\n`MongoDB\\Exception\\UnexpectedValueException` if the command response from the server was malformed.\n\n`MongoDB\\Exception\\UnsupportedException` if options are used and not supported by the selected server (e.g. `collation`, `readConcern`, `writeConcern`).\n\n`MongoDB\\Exception\\InvalidArgumentException` for errors related to the parsing of parameters or options.\n\nMongoDB\\Driver\\Exception\\RuntimeException for other errors at the extension level (e.g. connection errors).\n\n## Behavior\n\nWhen evaluating query criteria, MongoDB compares types and values according to its own comparison rules for BSON types, which differs from PHP's comparison and type juggling rules. When matching a special BSON type the query criteria should use the respective BSON class in the extension (e.g. use MongoDB\\BSON\\ObjectId to match an ObjectId)."} -{"chunk_id": "68a95c285e79d242619dee47-1", "page_id": "68a95c285e79d242619dee47", "source_name": "php-library", "product_name": "PHP Library", "url": "https://mongodb.com/docs/php-library/current/reference/method/MongoDBCollection-findOneAndUpdate", "title": "MongoDB\\Collection::findOneAndUpdate()", "text": "## Examples\n\nThe following operation updates the restaurant with `restaurant_id` of `\"40361708\"` in the `restaurants` collection in the `test` database by setting its building number to `\"761\"`:\n\n```php\ntest->restaurants;\n\n$updatedRestaurant = $collection->findOneAndUpdate(\n [ 'restaurant_id' => '40361708' ],\n [ '$set' => [ 'address.building' => '761' ]],\n [\n 'projection' => [ 'address' => 1 ],\n 'returnDocument' => MongoDB\\Operation\\FindOneAndUpdate::RETURN_DOCUMENT_AFTER,\n ]\n);\n\nvar_dump($updatedRestaurant);\n```\n\nThe output would then resemble:\n\n```none\nobject(MongoDB\\Model\\BSONDocument)#20 (1) {\n [\"storage\":\"ArrayObject\":private]=>\n array(2) {\n [\"_id\"]=>\n object(MongoDB\\BSON\\ObjectId)#12 (1) {\n [\"oid\"]=>\n string(24) \"594d5ef280a846852a4b3dee\"\n }\n [\"address\"]=>\n object(MongoDB\\Model\\BSONDocument)#19 (1) {\n [\"storage\":\"ArrayObject\":private]=>\n array(4) {\n [\"building\"]=>\n string(3) \"761\"\n [\"coord\"]=>\n object(MongoDB\\Model\\BSONArray)#18 (1) {\n [\"storage\":\"ArrayObject\":private]=>\n array(2) {\n [0]=>\n float(-73.9925306)\n [1]=>\n float(40.7309346)\n }\n }\n [\"street\"]=>\n string(8) \"Broadway\"\n [\"zipcode\"]=>\n string(5) \"10003\"\n }\n }\n }\n}\n```\n\n## See Also\n\n- `MongoDB\\Collection::findOneAndDelete()`\n\n- `MongoDB\\Collection::findOneAndReplace()`\n\n- findAndModify command reference in the MongoDB manual"} -{"chunk_id": "68a95c285e79d242619ded1b-0", "page_id": "68a95c285e79d242619ded1b", "source_name": "php-library", "product_name": "PHP Library", "url": "https://mongodb.com/docs/php-library/current/reference/method/MongoDBBulkWriteResult-getInsertedIds", "title": "MongoDB\\BulkWriteResult::getInsertedIds()", "text": "# MongoDB\\BulkWriteResult::getInsertedIds()\n\n## Definition\n\n`MongoDB\\BulkWriteResult::getInsertedIds()`\nReturn a map of IDs (i.e. `_id` field values) for documents that were inserted by all insert operations in the bulk write.\n\n```php\nfunction getInsertedIds(): array\n```\n\nSince IDs are created by the driver, this method may be called irrespective of whether the write was acknowledged.\n\n## Return Values\n\nA map of IDs (i.e. `_id` field values) for documents that were inserted by all insert operations in the bulk write.\n\nThe index of each ID in the map corresponds to each document's position in the bulk operation. If a document had an ID prior to inserting (i.e. the driver did not generate an ID), the index will contain its `_id` field value. Any driver-generated ID will be a MongoDB\\BSON\\ObjectId instance."} -{"chunk_id": "68a95c285e79d242619dece0-0", "page_id": "68a95c285e79d242619dece0", "source_name": "php-library", "product_name": "PHP Library", "url": "https://mongodb.com/docs/php-library/current/get-started", "title": "Get Started with the MongoDB PHP Library", "text": "# Get Started with the MongoDB PHP Library\n\n## Overview\n\nThe MongoDB PHP Library is a high-level abstraction for the MongoDB PHP extension, which you can use to connect to MongoDB and interact with data stored in your deployment. This guide shows you how to create an application that uses the MongoDB PHP Library to connect to a MongoDB cluster hosted on MongoDB Atlas and query data in your cluster.\n\nMongoDB Atlas is a fully managed cloud database service that hosts your MongoDB deployments. You can create your own free (no credit card required) MongoDB Atlas deployment by following the steps in this guide.\n\nFollow this guide to connect a sample PHP application to a MongoDB Atlas deployment. If you prefer to connect to MongoDB using a different driver or programming language, see our list of official drivers.\n\n## Download and Install\n\n### Install dependencies.\n\nBefore you begin developing, ensure that you have the following dependencies installed on your local machine:\n\n- PHP version 7.4 or later\n\n- Composer version 2.0 or later\n\n- pie\n\n### Install the MongoDB PHP extension.\n\nRun the following command to install the `mongodb` PHP extension:\n\n```bash\npie install mongodb/mongodb-extension\n```\n\nTo install a specific version of the PHP extension, include the version number as shown in the following command:\n\n```bash\npie install mongodb/mongodb-extension:^2.5.0\n```\n\nTo install a PHP extension version before v1.21, you must use the pecl command.\n\n### Create a project directory.\n\nFrom your root directory, run the following command in your shell to create a directory called `php-quickstart` for this project:\n\n```bash\nmkdir php-quickstart\n```\n\nSelect the tab corresponding to your operating system and run the following commands to create a `quickstart.php` application file in the `php-quickstart` directory:\n\n\n\n\n\n```bash\ncd php-quickstart\ntouch quickstart.php\n```\n\n\n\n\n\n```bash\ncd php-quickstart\ntype nul > quickstart.php\n```\n\n\n\n\n\n### Install the MongoDB PHP Library.\n\nTo install the MongoDB PHP Library, run the following command in your `php-quickstart` directory:\n\n```bash\ncomposer require mongodb/mongodb\n```\n\nAfter installing the library, include Composer's `autoload.php` file by adding the following code to the top of your `quickstart.php` file:\n\n```php\n` placeholder with your database user's password. The connection string is already populated with your database user's username.\n\nSave this file to a safe location for use in the next step.\n\nAfter completing these steps, you have a connection string that corresponds to your Atlas cluster.\n\n## Run a Sample Query\n\nAfter retrieving the connection string for your MongoDB Atlas deployment, you can connect to the deployment from your PHP application and query the Atlas sample datasets.\n\n### Edit your PHP application file.\n\nCopy and paste the following code into the `quickstart.php` file, which queries the `movies` collection in the `sample_mflix` database:\n\n```php\nsample_mflix->movies;\n\n$filter = ['title' => 'The Shawshank Redemption'];\n$result = $collection->findOne($filter);\n\nif ($result) {\n echo json_encode($result, JSON_PRETTY_PRINT);\n} else {\n echo 'Document not found';\n}\n\n```\n\n### Assign the connection string.\n\nAssign the `MONGODB_URI` environment variable to the connection string that you copied from the Create a Connection String step of this guide. You can assign this variable by running a shell command or creating a `.env` file in your application, as show in the following tabs:\n\n\n\n\n\n```sh\nexport MONGODB_URI=\n```\n\n\n\n\n\n```none\nMONGODB_URI=\n```\n\n\n\n\n\n### Run your PHP application.\n\nIn your project directory, run the following shell command to start the application:\n\n```bash\nphp quickstart.php\n```\n\nThe command line output contains details about the retrieved movie document:\n\n```none\n{\n \"_id\": {\n \"$oid\": \"...\"\n },\n ...\n \"rated\": \"R\",\n \"metacritic\": 80,\n \"title\": \"The Shawshank Redemption\",\n ...\n}\n```\n\nIf you encounter an error or see no output, ensure that you assigned the proper connection string to the `MONGODB_URI` environment variable and that you loaded the sample data.\n\nAfter you complete these steps, you have a PHP application that connects to your MongoDB deployment, runs a query on the sample data, and returns a matching document.\n\n## Next Steps\n\nCongratulations on completing the quick start tutorial!\n\nIf you run into issues on this step, submit feedback by using the Rate this page tab on the right or bottom right side of this page.\n\nYou can find support for general questions by using the MongoDB Stack Overflow tag or the MongoDB Reddit community.\n\nIn this tutorial, you created a PHP application that connects to a MongoDB deployment hosted on MongoDB Atlas and retrieves a document that matches a query.\n\nLearn more about the MongoDB PHP Library from the following resources:\n\n- Learn how to configure your MongoDB connection in the Connect to MongoDB section.\n\n- Learn how to perform read and write operations in the CRUD Operations section."} -{"chunk_id": "68a95c285e79d242619dece0-1", "page_id": "68a95c285e79d242619dece0", "source_name": "php-library", "product_name": "PHP Library", "url": "https://mongodb.com/docs/php-library/current/get-started", "title": "Get Started with the MongoDB PHP Library", "text": "## Troubleshooting\n\nThis section addresses issues that you might encounter when installing the PHP library and its dependencies.\n\n### PHP Headers Not Found\n\nYou might see a header file error that resembles the following code when installing the PHP library:\n\n```none\n/private/tmp/pear/install/mongodb/php_phongo.c:24:10: fatal error: 'php.h' file not found\n\n#include \n ^~~~~~~\n```\n\nThis error indicates that PHP's build system cannot find the necessary headers. All PHP extensions require headers to compile. Those headers must correspond to the PHP runtime for which the extension will be used. The `phpize` command, which is invoked by `pecl` and `pie`, usually ensures that the extension builds with the correct headers.\n\nIf you install a PHP runtime, the corresponding headers are not always automatically available. On many Linux distributions, headers are often published under a separate `php-dev` or `php-devel` package. On macOS, the default PHP runtime does not include headers. Users typically must install PHP and its headers by using Homebrew.\n\n### Multiple PHP Runtimes Installed\n\nIf your system has multiple versions of PHP installed, each version will have its own `pecl`, `pie`, and `phpize` commands. Additionally, each PHP runtime may have separate `php.ini` files for each server application programming interface (SAPI), such as FPM and CLI. If you installed the extension but it is not available at runtime, ensure that you use the correct `pecl` or `pie` command and modify the appropriate `php.ini` file.\n\nTo see which `php.ini` file a PHP runtime uses, view the output of phpinfo() for that particular SAPI. Additionally, you can use php_ini_loaded_file() and php_ini_scanned_files() to determine which INI files have been loaded by PHP.\n\nTo debug issues when the extension is not loaded, you can use the `detect-extension` script provided in the tools directory. You can run this script from the CLI or include it in a script available to your web server. The tool finds potential issues and installation instructions for your system. If you installed the library by using Composer, you can call the script from the vendor directory as shown in the following code:\n\n```none\nphp vendor/mongodb/mongodb/tools/detect-extension.php\n```\n\nIf you want to check configuration for a web server SAPI, include the file in a script available to the web server and open it in your browser. Ensure that you wrap the script in `
` tags to properly format its output as shown in the following code:\n\n```php\n
\n```\n\n### Loading an Incompatible DLL on Windows\n\nWindows binaries are available for several combinations of a PHP version, thread safety setting (TS or NTS), and architecture type (x86 or x64). Failure to select the correct binary causes an error when attempting to load the extension DLL at runtime, as shown in the following sample output:\n\n```none\nPHP Warning: PHP Startup: Unable to load dynamic library 'mongodb'\n```\n\nEnsure that you have downloaded a DLL that corresponds to the following PHP runtime properties:\n\n- PHP version (`PHP_VERSION`)\n\n- Thread safety (`PHP_ZTS`)\n\n- Architecture (`PHP_INT_SIZE`)\n\nIn addition to the preceding constants, these properties can also be inferred from phpinfo(). If your system has multiple PHP runtimes installed, view the `phpinfo()` output for the correct environment.\n\nYou can also use the `detect-extension` script described in the previous section to determine the correct DLL for your PHP environment."} -{"chunk_id": "68a95c285e79d242619deeaa-0", "page_id": "68a95c285e79d242619deeaa", "source_name": "php-library", "product_name": "PHP Library", "url": "https://mongodb.com/docs/php-library/current/security/authentication", "title": "Authentication Mechanisms", "text": "# Authentication Mechanisms\n\n## Overview\n\nThis guide describes the mechanisms you can use in the PHP library to authenticate users.\n\nYou must percent-encode a username and password before you include them in a MongoDB URI. You can use the `rawurlencode()` method to encode these values according to the URI syntax specified in RFC 3986. Don't percent-encode the username or password when passing them in an options array parameter to the `MongoDB\\Client` constructor.\n\nTo learn more, see the following resources:\n\n- RFC 3986\n\n- rawurlencode in the PHP manual\n\n## MongoDB Edition Compatibility\n\nThe following table lists the authentication mechanisms supported by MongoDB and the MongoDB Server editions that each mechanism is compatible with. Click the name of a mechanism to learn more about how to use it with your application.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nAuthentication Mechanism\n\n\nAtlas\n\n\nEnterprise Advanced\n\n\nCommunity\n\n
\nSCRAM Authentication\n\n\nYes\n\n\nYes\n\n\nYes\n\n
\nX.509 Authentication\n\n\nYes\n\n\nYes\n\n\nYes\n\n
\nAWS IAM Authentication\n\n\nYes\n\n\nNo\n\n\nNo\n\n
"} -{"chunk_id": "68a95c285e79d242619ded50-0", "page_id": "68a95c285e79d242619ded50", "source_name": "php-library", "product_name": "PHP Library", "url": "https://mongodb.com/docs/php-library/current/reference/method/MongoDBClient-getTypeMap", "title": "MongoDB\\Client::getTypeMap()", "text": "# MongoDB\\Client::getTypeMap()\n\n## Definition\n\n`MongoDB\\Client::getTypeMap()`\nReturns the type map for this client.\n\n```php\nfunction getTypeMap(): array\n```\n\n## Return Values\n\nA type map array.\n\n## Example\n\n```php\n [\n 'root' => 'array',\n 'document' => 'array',\n 'array' => 'array',\n ],\n]);\n\nvar_dump($client->getTypeMap());\n```\n\nThe output would then resemble:\n\n```none\narray(3) {\n [\"root\"]=>\n string(5) \"array\"\n [\"document\"]=>\n string(5) \"array\"\n [\"array\"]=>\n string(5) \"array\"\n}\n```\n\n## See Also\n\n- BSON\n\n- `MongoDB\\Collection::getTypeMap()`\n\n- `MongoDB\\Database::getTypeMap()`\n\n- `MongoDB\\GridFS\\Bucket::getTypeMap()`"} -{"chunk_id": "68a95c285e79d242619deea5-0", "page_id": "68a95c285e79d242619deea5", "source_name": "php-library", "product_name": "PHP Library", "url": "https://mongodb.com/docs/php-library/current/reference/method/MongoDBModelIndexInfo-isSparse", "title": "MongoDB\\Model\\IndexInfo::isSparse()", "text": "# MongoDB\\Model\\IndexInfo::isSparse()\n\n## Definition\n\n`MongoDB\\Model\\IndexInfo::isSparse()`\nReturn whether the index is a sparse index. This correlates with the `sparse` option for `MongoDB\\Collection::createIndex()`.\n\n```php\nfunction isSparse(): boolean\n```\n\n## Return Values\n\nA boolean indicating whether the index is a sparse index.\n\n## Examples\n\n```php\n true,\n]);\n\nvar_dump($info->isSparse());\n```\n\nThe output would then resemble:\n\n```none\nbool(true)\n```\n\n## See Also\n\n- `MongoDB\\Collection::createIndex()`\n\n- listIndexes command reference in the MongoDB manual\n\n- Sparse Indexes in the MongoDB manual"} -{"chunk_id": "68a95c285e79d242619decf9-0", "page_id": "68a95c285e79d242619decf9", "source_name": "php-library", "product_name": "PHP Library", "url": "https://mongodb.com/docs/php-library/current/crud/query/distinct", "title": "Retrieve Distinct Field Values", "text": "# Retrieve Distinct Field Values\n\n## Overview\n\nIn this guide, you can learn how to use the MongoDB PHP Library to retrieve the distinct values of a specified field across a collection.\n\nWithin a collection, different documents might contain different values for a single field. For example, one document in a `restaurants` collection has a `borough` value of `'Manhattan'`, and another has a `borough` value of `'Queens'`. By using the MongoDB PHP Library, you can retrieve all the unique values that a field contains across multiple documents in a collection.\n\n### Sample Data\n\nThe examples in this guide use the `restaurants` collection in the `sample_restaurants` database from the Atlas sample datasets. To access this collection from your PHP application, instantiate a `MongoDB\\Client` that connects to an Atlas cluster and assign the following value to your `$collection` variable:\n\n```php\n$collection = $client->sample_restaurants->restaurants;\n```\n\nTo learn how to create a free MongoDB deployment and load the sample datasets, see the MongoDB Get Started guide.\n\n## `MongoDB\\Collection::distinct()` Method\n\nTo retrieve the distinct values for a specified field, call the `MongoDB\\Collection::distinct()` method and pass in the name of the field you want to find distinct values for.\n\n### Retrieve Distinct Values Across a Collection\n\nThe following example retrieves the distinct values of the `borough` field in the `restaurants` collection:\n\n```php\n$results = $collection->distinct('borough', []);\nforeach ($results as $value) {\n echo json_encode($value), PHP_EOL;\n}\n```\n\n```\n\"Bronx\"\n\"Manhattan\"\n\"Missing\"\n\"Queens\"\n\"Staten Island\"\n```\n\nThe operation returns an array that stores each distinct `borough` field value. Although several documents have the same value in the `borough` field, each value appears in the results only once.\n\n### Retrieve Distinct Values Across Specified Documents\n\nYou can provide a **query filter** to the `distinct()` method to find the distinct field values across a subset of documents in a collection. A query filter is an expression that specifies search criteria used to match documents in an operation. For more information about creating a query filter, see the Specify a Query guide.\n\nThe following example retrieves the distinct values of the `borough` field for all documents that have a `cuisine` field value of `'Italian'`:\n\n```php\n$results = $collection->distinct('borough', ['cuisine' => 'Italian']);\nforeach ($results as $value) {\n echo json_encode($value), PHP_EOL;\n}\n```\n\n```\n\"Bronx\"\n\"Manhattan\"\n\"Queens\"\n\"Staten Island\"\n```\n\n### Modify Distinct Behavior\n\nYou can modify the behavior of the `distinct()` method by passing an array that specifies option values. The following table describes some options you can set to customize the operation:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nOption\n\n\nDescription\n\n
\n`collation`\n\n\nThe collation to use for the operation. To learn more, see the Collation section of this page.**Type**: `array|object`\n\n
\n`maxTimeMS`\n\n\nThe maximum amount of time in milliseconds that the operation can run.**Type**: `integer`\n\n
\n`comment`\n\n\nThe comment to attach to the operation.**Type**: any valid BSON type\n\n
\n`readPreference`\n\n\nThe read preference to use for the operation. To learn more, see Read Preference in the Server manual.**Type**: `MongoDB\\Driver\\ReadPreference`\n\n
\n`hint`\n\n\nThe index to use for the operation.**Type**: `string|object`\n\n
The following example retrieves the distinct values of the `name` field for all documents that have a `borough` field value of `'Bronx'` and a `cuisine` field value of `'Pizza'`. It also specifies the `comment` field in an options array to add a comment to the operation:\n\n```php\n$query = ['borough' => 'Bronx', 'cuisine' => 'Pizza'];\n$options = ['comment' => 'Bronx pizza restaurants'];\n$results = $collection->distinct('name', $query, $options);\n\nforeach ($results as $value) {\n echo json_encode($value), PHP_EOL;\n}\n```\n\n```\n\"$1.25 Pizza\"\n\"18 East Gunhill Pizza\"\n\"2 Bros\"\n\"Aenos Pizza\"\n\"Alitalia Pizza Restaurant\"\n\"Amici Pizza And Pasta\"\n\"Angie'S Cafe Pizza\"\n...\n```\n\n#### Collation\n\nTo specify a collation for your operation, pass an `$options` array parameter that sets the `collation` option to the operation method. Assign the `collation` option to an array that configures the collation rules.\n\nThe following table describes the fields you can set to configure the collation:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nField\n\n\nDescription\n\n
\n`locale`\n\n\n*(Required)* Specifies the International Components for Unicode (ICU) locale. For a list of supported locales, see Collation Locales and Default Parameters in the MongoDB Server manual.**Data Type**: `string`\n\n
\n`caseLevel`\n\n\n*(Optional)* Specifies whether to include case comparison.When set to `true`, the comparison behavior depends on the value of the `strength` field:- If `strength` is `1`, the PHP library compares basecharacters and case.- If `strength` is `2`, the PHP library compares basecharacters, diacritics, other secondary differences, and case.- If `strength` is any other value, this field is ignored.When set to `false`, the PHP library doesn't include case comparison at strength level `1` or `2`.**Data Type**: `bool`**Default**: `false`\n\n
\n`caseFirst`\n\n\n*(Optional)* Specifies the sort order of case differences during tertiary level comparisons.**Data Type**: `string`**Default**: `\"off\"`\n\n
\n`strength`\n\n\n*(Optional)* Specifies the level of comparison to perform, as defined in the ICU documentation.**Data Type**: `int`**Default**: `3`\n\n
\n`numericOrdering`\n\n\n*(Optional)* Specifies whether the driver compares numeric strings as numbers.If set to `true`, the PHP library compares numeric strings as numbers. For example, when comparing the strings \"10\" and \"2\", the library uses the strings' numeric values and treats \"10\" as greater than \"2\".If set to `false`, the PHP library compares numeric strings as strings. For example, when comparing the strings \"10\" and \"2\", the library compares one character at a time and treats \"10\" as less than \"2\".For more information, see Collation Restrictions in the MongoDB Server manual.**Data Type**: `bool`**Default**: `false`\n\n
\n`alternate`\n\n\n*(Optional)* Specifies whether the library considers whitespace and punctuation as base characters for comparison purposes.**Data Type**: `string`**Default**: `\"non-ignorable\"`\n\n
\n`maxVariable`\n\n\n*(Optional)* Specifies which characters the library considers ignorable when the `alternate` field is set to `\"shifted\"`.**Data Type**: `string`**Default**: `\"punct\"`\n\n
\n`backwards`\n\n\n*(Optional)* Specifies whether strings containing diacritics sort from the back of the string to the front.**Data Type**: `bool`**Default**: `false`\n\n
To learn more about collation and the possible values for each field, see the Collation entry in the MongoDB Server manual.\n\n## API Documentation\n\nTo learn more about the `distinct()` method, see `MongoDB\\Collection::distinct()` in the API documentation."} -{"chunk_id": "68a95c285e79d242619ded0e-0", "page_id": "68a95c285e79d242619ded0e", "source_name": "php-library", "product_name": "PHP Library", "url": "https://mongodb.com/docs/php-library/current/reference/function/remove_logger", "title": "MongoDB\\remove_logger()", "text": "# MongoDB\\remove_logger()\n\n## Definition\n\n`MongoDB\\remove_logger()`\nUnregisters a PSR logger to no longer receive log messages from the extension.\n\n```php\nfunction remove_logger(Psr\\Log\\LoggerInterface $logger): void\n```\n\n## Parameters\n\nA logger to unregister.\n\nIf the logger is not registered, the method will have no effect.\n\n## Errors/Exceptions\n\n`MongoDB\\Exception\\InvalidArgumentException` for errors related to the parsing of parameters or options.\n\n## See Also\n\n- `MongoDB\\add_logger()`\n\n- PSR-3: Logger Interface\n\n- libmongoc: Logging"} -{"chunk_id": "68a95c3b5e79d242619e153e-0", "page_id": "68a95c3b5e79d242619e153e", "source_name": "pymongo", "product_name": "PyMongo", "url": "https://mongodb.com/docs/languages/python/pymongo-driver/current/issues-and-help", "title": "Issues & Help", "text": "# Issues & Help\n\nIn this guide, you can learn how to report issues, suggest new features, and contribute to PyMongo.\n\nYou can find support for general questions by using the MongoDB Stack Overflow tag or the MongoDB Reddit community.\n\n## Bugs / Feature Requests\n\nTo report a bug or to request a new feature in PyMongo, please open an issue in JIRA, our issue-management tool, using the following steps:\n\n1. Create a JIRA account.\n\n2. Navigate to the PYTHON Driver project.\n\n3. Click Create Issue. Please provide as much information as possible about the issue and the steps to reproduce it.\n\nBug reports in JIRA for the PyMongo project can be viewed by everyone.\n\nIf you identify a security vulnerability in the driver or in any other MongoDB project, please report it according to the instructions found in Create a Vulnerability Report.\n\n## Pull Requests\n\nWe are happy to accept contributions to help improve the driver. To contribute to the official driver, follow the development and testing guidelines. We will guide user contributions to ensure they meet the standards of the codebase."} -{"chunk_id": "68a95c3b5e79d242619e1530-0", "page_id": "68a95c3b5e79d242619e1530", "source_name": "pymongo", "product_name": "PyMongo", "url": "https://mongodb.com/docs/languages/python/pymongo-driver/current/data-formats/time-series", "title": "Time Series Data", "text": "# Time Series Data\n\n## Overview\n\nIn this guide, you can learn how to use PyMongo to store and interact with **time series data**.\n\nTime series data is composed of the following components:\n\n- Measured quantity\n\n- Timestamp for the measurement\n\n- Metadata that describes the measurement\n\nThe following table describes sample situations for which you could store time series data:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nSituation\n\n\nMeasured Quantity\n\n\nMetadata\n\n
\nRecording monthly sales by industry\n\n\nRevenue in USD\n\n\nCompany, country\n\n
\nTracking weather changes\n\n\nPrecipitation level\n\n\nLocation, sensor type\n\n
\nRecording fluctuations in housing prices\n\n\nMonthly rent price\n\n\nLocation, currency\n\n
\n\n## Create a Time Series Collection\n\nTo create and interact with time series collections, you must be connected to a deployment running MongoDB Server 5.0 or later.\n\nTo create a time series collection, pass the following arguments to the `create_collection()` method:\n\n- Name of the new collection to create\n\n- `timeseries` argument\n\nThe `timeseries` argument is of type `dict`. It contains the following fields:\n\n- `timeField`: Specifies the field that stores a timestamp in each time series document.\n\n- `metaField`: Specifies the field that stores metadata in each time series document.\n\n- `granularity`: Specifies the approximate time between consecutive timestamps. The possible values are `'seconds'`, `'minutes'`, and `'hours'`.\n\n- `bucketMaxSpanSeconds`: Sets the maximum time between timestamps in the same bucket.\n\n- `bucketRoundingSeconds`: Sets the number of seconds to round down by when MongoDB sets the minimum timestamp for a new bucket. Must be equal to `bucketMaxSpanSeconds`.\n\nSee Command Fields to learn more about these fields.\n\n### Example\n\nThe following example creates a time series collection named `october2024` with the `timeField` option set to `\"timestamp\"`. Select the Synchronous or Asynchronous tab to see the corresponding code:\n\n\n\n\n\n```python\ndatabase = client.get_database(\"weather\")\n\ntime_series_options = {\n \"timeField\": \"timestamp\"\n}\n\ndatabase.create_collection(\"october2024\", timeseries=time_series_options)\n```\n\n\n\n\n\n```python\ndatabase = client.get_database(\"weather\")\n\ntime_series_options = {\n \"timeField\": \"timestamp\"\n}\n\nawait database.create_collection(\"october2024\", timeseries=time_series_options)\n```\n\n\n\n\n\nTo check if you successfully created the collection, you can get a list of all collections in your database and filter by collection name. Select the Synchronous or Asynchronous tab to see the corresponding code:\n\n\n\n\n\n```python\nprint(list(database.list_collections(filter={'name': 'october2024'})))\n```\n\n```json\n{\n \"name\": \"october2024\",\n \"type\": \"timeseries\",\n \"options\": {\n \"timeseries\": {\n \"timeField\": \"timestamp\",\n \"granularity\": \"seconds\",\n \"bucketMaxSpanSeconds\": 3600\n }\n },\n \"info\": {\n \"readOnly\": False\n }\n}\n```\n\n\n\n\n\n```python\ncollections = await database.list_collections(filter={'name': 'october2024'})\nprint(await collections.to_list())\n```\n\n```json\n{\n \"name\": \"october2024\",\n \"type\": \"timeseries\",\n \"options\": {\n \"timeseries\": {\n \"timeField\": \"timestamp\",\n \"granularity\": \"seconds\",\n \"bucketMaxSpanSeconds\": 3600\n }\n },\n \"info\": {\n \"readOnly\": False\n }\n}\n```\n\n\n\n\n\n## Store Time Series Data\n\nYou can insert data into a time series collection by using the `insert_one()` or `insert_many()` methods and specifying the measurement, timestamp, and metadata in each inserted document.\n\nTo learn more about inserting documents, see Insert Documents.\n\n### Example\n\nThis example inserts New York City temperature data into the `october2024` time series collection created in Create a Time Series Collection. Each document contains the following fields:\n\n- `temperature`, which stores temperature measurements in degrees Fahrenheit\n\n- `location`, which stores location metadata\n\n- `timestamp`, which stores the measurement timestamp\n\nSelect the Synchronous or Asynchronous tab to see the corresponding code:\n\n\n\n\n\n```python\nfrom datetime import datetime\n\ncollection = database[\"october2024\"]\n\ndocument_list = [\n { \"temperature\": 77, \"location\": \"New York City\", \"timestamp\": datetime(2024, 10, 22, 6, 0, 0) },\n { \"temperature\": 74, \"location\": \"New York City\", \"timestamp\": datetime(2024, 10, 23, 6, 0, 0) }\n]\n\ncollection.insert_many(document_list)\n```\n\n\n\n\n\n```python\nfrom datetime import datetime\n\ncollection = database[\"october2024\"]\n\ndocument_list = [\n { \"temperature\": 77, \"location\": \"New York City\", \"timestamp\": datetime(2024, 10, 22, 6, 0, 0) },\n { \"temperature\": 74, \"location\": \"New York City\", \"timestamp\": datetime(2024, 10, 23, 6, 0, 0) }\n]\n\nawait collection.insert_many(document_list)\n```\n\n\n\n\n\nTo learn more about using `datetime` objects in PyMongo, see Dates and Times.\n\n## Query Time Series Data\n\nYou can use the same syntax and conventions to query data stored in a time series collection as you use when performing read or aggregation operations on other collections. To learn more about these operations, see Query and Transform Your Data with Aggregation.\n\n## Additional Information\n\nTo learn more about the concepts in this guide, see the following MongoDB Server manual entries:\n\n- Time Series\n\n- Create and Query a Time Series Collection\n\n- Set Granularity for Time Series Data\n\n### API Documentation\n\nTo learn more about the methods mentioned in this guide, see the following API documentation:\n\n- create_collection()\n\n- list_collections()\n\n- insert_one()\n\n- insert_many()"} -{"chunk_id": "68a95c3b5e79d242619e154d-0", "page_id": "68a95c3b5e79d242619e154d", "source_name": "pymongo", "product_name": "PyMongo", "url": "https://mongodb.com/docs/languages/python/pymongo-driver/current/crud/query/count", "title": "Count Documents", "text": "# Count Documents\n\n## Overview\n\nIn this guide, you can learn how to retrieve an accurate and estimated count of the number of documents in a collection.\n\n## Retrieve an Accurate Count\n\nUse the `count_documents()` method to count the number of documents that are in a collection. To count the number of documents that match a specific search critera, pass a dictionary that includes a query filter to the `count_documents()` method.\n\nTo learn more about specifying a query, see Specify a Query.\n\n### Count All Documents\n\nTo return a count of all documents in the collection, pass an empty dictionary to the `count_documents()` method, as shown in the following example. Select the Synchronous or Asynchronous tab to see the corresponding code:\n\n\n\n\n\n```python\ncollection.count_documents({})\n```\n\n\n\n\n\n```python\nawait collection.count_documents({})\n```\n\n\n\n\n\n### Count Specific Documents\n\nTo return a count of documents that match specific search criteria, specify your query in the `count_documents()` method, as shown in the following example. Select the Synchronous or Asynchronous tab to see the corresponding code:\n\n\n\n\n\n```python\ncollection.count_documents({ \"author\": \"Mike\" })\n```\n\n\n\n\n\n```python\nawait collection.count_documents({ \"author\": \"Mike\" })\n```\n\n\n\n\n\n### Customize Count Behavior\n\nThe `count_documents()` method accepts optional parameters, which represent options you can use to configure the count operation. If you don't specify any options, the driver does not customize the count operation.\n\nThe following table describes the options you can set to customize `count_documents()`:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nProperty\n\n\nDescription\n\n
\n`comment`\n\n\nA comment to attach to the operation.\n\n
\n`session`\n\n\nAn instance of `ClientSession`.\n\n
\n`skip`\n\n\nThe number of documents to skip before returning results.\n\n
\n`limit`\n\n\nThe maximum number of documents to count. Must be a positive integer.\n\n
\n`maxTimeMS`\n\n\nThe maximum amount of time to allow the operation to run, in milliseconds.\n\n
\n`collation`\n\n\nAn instance of `Collation`.\n\n
\n`hint`\n\n\nGets or sets the index to scan for documents.\n\n
\n\n## Retrieve an Estimated Count\n\nYou can get an estimate of the number of documents in a collection by calling the `estimated_document_count()` method. The method estimates the amount of documents based on collection metadata, which might be faster than performing an accurate count.\n\nThe following example estimates the number of documents in a collection. Select the Synchronous or Asynchronous tab to see the corresponding code:\n\n\n\n\n\n```python\ncollection.estimated_document_count()\n```\n\n\n\n\n\n```python\nawait collection.estimated_document_count()\n```\n\n\n\n\n\n### Customize Estimated Count Behavior\n\nThe `estimated_document_count()` method accepts optional parameters, which represent options you can use to configure the count operation. If you don't specify any options, the driver does not customize the count operation.\n\nThe following table describes the options you can set to customize `estimated_document_count()`:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nProperty\n\n\nDescription\n\n
\n`comment`\n\n\nA comment to attach to the operation.\n\n
\n`maxTimeMS`\n\n\nThe maximum amount of time to allow the operation to run, in milliseconds.\n\n
\n\n## Troubleshooting\n\n### DeprecationWarning: Count Is Deprecated\n\nPyMongo no longer supports the `count()` method. Instead, use the `count_documents()` method from the `Collection` class.\n\nThe `count_documents()` method belongs to the `Collection` class. If you try to call `Cursor.count_documents()`, PyMongo raises the following error:\n\n```\nTraceback (most recent call last):\n File \"\", line 1, in \nAttributeError: 'Cursor' object has no attribute 'count'\n```\n\n## API Documentation\n\nTo learn more about any of the methods or types discussed in this guide, see the following API documentation:\n\n- count_documents()\n\n- estimated_document_count()\n\n- Collation\n\n- ClientSession"} -{"chunk_id": "68a95c3b5e79d242619e1565-0", "page_id": "68a95c3b5e79d242619e1565", "source_name": "pymongo", "product_name": "PyMongo", "url": "https://mongodb.com/docs/languages/python/pymongo-driver/current/run-command", "title": "Run a Database Command", "text": "# Run a Database Command\n\n## Overview\n\nIn this guide, you can learn how to use PyMongo to run a database command. You can use database commands to perform a variety of administrative and diagnostic tasks, such as fetching server statistics, initializing a replica set, or running an aggregation pipeline.\n\nThe library provides wrapper methods for many database commands. We recommend using these methods instead of executing database commands when possible.\n\nTo perform administrative tasks, use the MongoDB Shell instead of PyMongo. The shell provides helper methods that might not be available in the driver.\n\nIf there are no available helpers in the library or the shell, you can use the `db.runCommand()` shell method or the driver's `command()` method, which is described in this guide.\n\n## Execute a Command\n\nYou can use the `command()` method to run a database command. You must specify the command and any relevant arguments. If the command is simple, these can be passed as strings. Otherwise, they can be passed as a `dict` object. The method will return the result of the command that was run.\n\nThe following code shows how you can use the `command()` method on a `Database` to run the `hello` command, which returns information about the server. Select the Synchronous or Asynchronous tab to see the corresponding code:\n\n\n\n\n\n```python\ndatabase = client.get_database(\"my_db\")\n\nhello = database.command(\"hello\")\n\nprint(hello)\n```\n\n```json\n{\n 'topologyVersion': {\n 'processId': ObjectId('...'),\n 'counter': 6\n },\n 'hosts': [...],\n 'setName': '...',\n 'setVersion': 114,\n 'isWritablePrimary': True,\n 'secondary': False,\n 'primary': '...',\n 'tags': {...},\n 'me': '...',\n 'electionId': ...,\n 'lastWrite': {...},\n 'maxBsonObjectSize': 16777216,\n 'maxMessageSizeBytes': 48000000,\n 'maxWriteBatchSize': 100000,\n 'localTime': ...,\n 'logicalSessionTimeoutMinutes': 30,\n 'connectionId': ...,\n 'minWireVersion': 0,\n 'maxWireVersion': 21,\n 'readOnly': False,\n 'ok': 1.0,\n '$clusterTime': {...},\n 'operationTime': ...\n}\n```\n\n\n\n\n\n```python\ndatabase = client.get_database(\"my_db\")\n\nhello = await database.command(\"hello\")\n\nprint(hello)\n```\n\n```\n{\n 'topologyVersion': {\n 'processId': ObjectId('...'),\n 'counter': 6\n },\n 'hosts': [...],\n 'setName': '...',\n 'setVersion': 114,\n 'isWritablePrimary': True,\n 'secondary': False,\n 'primary': '...',\n 'tags': {...},\n 'me': '...',\n 'electionId': ...,\n 'lastWrite': {...},\n 'maxBsonObjectSize': 16777216,\n 'maxMessageSizeBytes': 48000000,\n 'maxWriteBatchSize': 100000,\n 'localTime': ...,\n 'logicalSessionTimeoutMinutes': 30,\n 'connectionId': ...,\n 'minWireVersion': 0,\n 'maxWireVersion': 21,\n 'readOnly': False,\n 'ok': 1.0,\n '$clusterTime': {...},\n 'operationTime': ...\n}\n```\n\n\n\n\n\nFor a full list of database commands and corresponding parameters, see the Additional Information section.\n\n## Command Cursor\n\nThe `command()` method returns the result of the command that was run. You can also use the `cursor_command()` method, which issues a MongoDB command and parses the response as a CommandCursor. The `CommandCursor` can be used to iterate over command results.\n\nThe following example uses the `cursor_command()` method on the `sample_mflix` database. It runs the `find` command on the `movies` collection to filter by documents in which the `runtime` field has a value of `11`. Select the Synchronous or Asynchronous tab to see the corresponding code:\n\n\n\n\n\n```python\ndatabase = client.get_database(\"sample_mflix\")\n\nresult = database.cursor_command(\"find\", \"movies\", filter={\"runtime\": 11})\n\nprint(result.to_list())\n```\n\n```json\n{\n '_id': ObjectId(...),\n 'runtime': 11,\n 'title': 'The Great Train Robbery',\n ...\n},\n{\n {'_id': ObjectId(...),\n 'runtime': 11,\n 'title': 'Glas',\n ...\n},\n...\n```\n\n\n\n\n\n```python\ndatabase = client.get_database(\"sample_mflix\")\n\nresult = await database.cursor_command(\"find\", \"movies\", filter={\"runtime\": 11})\n\nprint(result.to_list())\n```\n\n```json\n{\n '_id': ObjectId(...),\n 'runtime': 11,\n 'title': 'The Great Train Robbery',\n ...\n},\n{\n {'_id': ObjectId(...),\n 'runtime': 11,\n 'title': 'Glas',\n ...\n},\n...\n```\n\n\n\n\n\nTo learn about the response format of the command, see Database Commands.\n\nThe `command()` and `cursor_command()` methods do not obey the read preference you might have set on your `Database` instance elsewhere in your code. If a ClientSession is provided by using the `session` parameter, and this session is in a transaction, the command's read preference will be set to the transaction's read preference. Otherwise, the command's read preference defaults to `PRIMARY`.\n\nYou can set a read preference for command execution by using the `read_preference` parameter. For example:\n\n```python\nfrom pymongo.read_preferences import Secondary\n\ndatabase = client.get_database(\"my_db\")\n\nhello = database.command(\"hello\", read_preference=Secondary())\n\nprint(hello)\n```\n\nLearn more about the `read_preferences` module in the API documentation.\n\nTo learn more about read preference options, see Read Preference in the MongoDB Server manual.\n\n## Command Example\n\nThe following example uses the `command()` method to run the `dbStats` command to retrieve storage statistics for the `sample_mflix` database. Select the Synchronous or Asynchronous tab to see the corresponding code:\n\n\n\n\n\n```python\ndatabase = client.get_database(\"sample_mflix\")\n\nresult = database.command(\"dbStats\")\n\nprint(result)\n```\n\n```\n{'db': 'sample_mflix', 'collections': 9, 'views': 1, 'objects': 67662,\n'avgObjSize': 1796.788182436227, 'dataSize': 121574282, 'storageSize': 97779712,\n'totalFreeStorageSize': 0, 'numExtents': 0, 'indexes': 13, 'indexSize': 19423232,\n'indexFreeStorageSize': 0, 'fileSize': 0, 'nsSizeMB': 0, 'ok': 1}\n```\n\n\n\n\n\n```python\ndatabase = client.get_database(\"sample_mflix\")\n\nresult = await database.command(\"dbStats\")\n\nprint(result)\n```\n\n```\n{'db': 'sample_mflix', 'collections': 9, 'views': 1, 'objects': 67662,\n'avgObjSize': 1796.788182436227, 'dataSize': 121574282, 'storageSize': 97779712,\n'totalFreeStorageSize': 0, 'numExtents': 0, 'indexes': 13, 'indexSize': 19423232,\n'indexFreeStorageSize': 0, 'fileSize': 0, 'nsSizeMB': 0, 'ok': 1}\n```\n\n\n\n\n\nThe output of this command includes information about the collections in the database, and describes the amount and size of data stored across collections."} -{"chunk_id": "68a95c3b5e79d242619e1565-1", "page_id": "68a95c3b5e79d242619e1565", "source_name": "pymongo", "product_name": "PyMongo", "url": "https://mongodb.com/docs/languages/python/pymongo-driver/current/run-command", "title": "Run a Database Command", "text": "## Type Hints\n\nThe `Database.command()` method can decode the returned BSON documents to instances of a specific class. To specify this class, construct a `CodecOptions` object and pass the class name. The class can be one of the following types:\n\n- `bson.raw_bson.RawBSONDocument`. To learn more about the `RawBSONDocument` class, see Work with Raw BSON Data.\n\n- A subclass of the `collections.abc.Mapping` type, such as `OrderedDict`. Depending on the strictness of your type-checking rules, you might also need to specify types for the key and value.\n\n- A subclass of the `TypedDict` type. To pass a `TypedDict` subclass for this parameter, you must also include the class in a type hint for your `CodecOptions` object.\n\nThe TypedDict class is in the `typing` module, which is available only in Python 3.8 and later. To use the `TypedDict` class in earlier versions of Python, install the typing_extensions package.\n\nThe following example decodes the BSON returned by the `ping` command to instances of the `RawBSONDocument` class. Select the Synchronous or Asynchronous tab to see the corresponding code:\n\n\n\n\n\n```python\nfrom pymongo import MongoClient\nfrom bson.raw_bson import RawBSONDocument\nfrom bson import CodecOptions\n\nclient: MongoClient = MongoClient()\noptions = CodecOptions(RawBSONDocument)\nresult = client.admin.command(\"ping\", codec_options=options)\n```\n\n\n\n\n\n```python\nfrom pymongo import AsyncMongoClient\nfrom bson.raw_bson import RawBSONDocument\nfrom bson import CodecOptions\n\nclient: AsyncMongoClient = AsyncMongoClient()\noptions = CodecOptions(RawBSONDocument)\nresult = await client.admin.command(\"ping\", codec_options=options)\n```\n\n\n\n\n\nTo decode BSON to a subclass of the `TypedDict` class, specify the class name in the `CodecOptions` type hint, as shown in the following example. Select the Synchronous or Asynchronous tab to see the corresponding code:\n\n\n\n\n\n```python\nfrom pymongo import MongoClient\nfrom bson.raw_bson import RawBSONDocument\nfrom bson import CodecOptions\nfrom typing import TypedDict\n\nclass Movie(TypedDict):\n name: str\n year: int\n\nclient: MongoClient = MongoClient()\noptions: CodecOptions[Movie] = CodecOptions(Movie)\nresult = client.admin.command(\"ping\", codec_options=options)\n```\n\n\n\n\n\n```python\nfrom pymongo import AsyncMongoClient\nfrom bson.raw_bson import RawBSONDocument\nfrom bson import CodecOptions\nfrom typing import TypedDict\n\nclass Movie(TypedDict):\n name: str\n year: int\n\nclient: AsyncMongoClient = AsyncMongoClient()\noptions: CodecOptions[Movie] = CodecOptions(Movie)\nresult = await client.admin.command(\"ping\", codec_options=options)\n```\n\n\n\n\n\n## Troubleshooting\n\n### Client Type Annotations\n\nIf you don't add a type annotation for your `MongoClient` object, your type checker might show an error similar to the following:\n\n```python\nfrom pymongo import MongoClient\nclient = MongoClient() # error: Need type annotation for \"client\"\n```\n\nThe solution is to annotate the `MongoClient` object as `client: MongoClient` or `client: MongoClient[Dict[str, Any]]`.\n\n### Incompatible Type\n\nIf you specify `MongoClient` as a type hint but don't include data types for the document, keys, and values, your type checker might show an error similar to the following:\n\n```python\nerror: Dict entry 0 has incompatible type \"str\": \"int\";\nexpected \"Mapping[str, Any]\": \"int\"\n```\n\nThe solution is to add the following type hint to your `MongoClient` object:\n\n```python\nclient: MongoClient[Dict[str, Any]]\n```\n\n## Additional Information\n\nFor more information about the concepts in this guide, see the following documentation in the MongoDB Server manual:\n\n- db.runCommand()\n\n- Database Commands\n\n- hello Command\n\n- find Command\n\n- dbStats Command\n\n### API Documentation\n\nFor more information about the `command()` and `cursor_command()` methods, see the following PyMongo API documentation:\n\n- command()\n\n- cursor_command()"} -{"chunk_id": "68a95c3b5e79d242619e155b-0", "page_id": "68a95c3b5e79d242619e155b", "source_name": "pymongo", "product_name": "PyMongo", "url": "https://mongodb.com/docs/languages/python/pymongo-driver/current/reference/previous-versions", "title": "Previous Versions", "text": "# Previous Versions\n\nThe following links direct you to documentation for previous versions of PyMongo.\n\n- Version 4.6\n\n- Version 4.5\n\n- Version 4.4\n\n- Version 4.3\n\n- Version 4.2\n\n- Version 4.1\n\n- Version 4.0\n\n- Version 3.13"} -{"chunk_id": "68a95c3b5e79d242619e1555-0", "page_id": "68a95c3b5e79d242619e1555", "source_name": "pymongo", "product_name": "PyMongo", "url": "https://mongodb.com/docs/languages/python/pymongo-driver/current/data-formats/dates-and-times", "title": "Dates and Times", "text": "# Dates and Times\n\n## Overview\n\nIn this guide, you can learn how to handle Python `datetime` objects in PyMongo.\n\n### Terminology\n\nPython uses a dedicated data type, `datetime.datetime`, to represent dates and times. MongoDB stores `datetime` values in *coordinated universal time (UTC)*, a global time standard local to London, England.\n\n#### Naive Datetimes\n\nA `datetime` value is *naive* when it doesn't include supplemental information about its UTC offset or time zone. The following is an example of a naive `datetime` object:\n\n```python\ndatetime(2002, 10, 27, 14, 0, 0)\n```\n\n#### Aware Datetimes\n\nA `datetime` value is *aware* when it includes a `tzinfo` attribute. This attribute indicates the value's offset from UTC time, its time zone, and whether daylight saving time was in effect. The following is an example of an aware `datetime` object:\n\n```python\ndatetime(2002, 10, 27, 6, 0,\n tzinfo=)\n```\n\nPyMongo treats naive `datetime` values as UTC values. PyMongo does not convert naive values into UTC; it simply interprets them as UTC for storage and retrieval.\n\nTo prevent ambiguity and potential errors, use aware `datetime` values with explicit time zone information. Using aware datetimes will help you avoid timezone mismatches.\n\n#### Localization\n\n*Localization* is the process of adding hours to, or subtracting hours from, a `datetime` value to translate its value to another time zone. To localize a `datetime` value, perform the following steps:\n\n1. Use pip to install the `pytz` library in your Python environment: `pip install pytz`\n\n2. Create a `pytz.timezone` object. Pass the target time zone to the constructor as a string.\n\n3. Call the `localize()` method on your `timezone` object, passing in the `datetime` value to localize.\n\nThe following code example localizes a `datetime` value to the `\"US/Pacific\"` time zone, an offset of eight hours:\n\n```python\nfrom datetime import datetime\nfrom pytz import timezone\n\nutc_datetime = datetime(2002, 10, 27, 6, 0, 0)\npacific = timezone(\"US/Pacific\")\nlocal_datetime = pacific.localize(utc_datetime)\n\nprint(f\"UTC datetime: {utc_datetime}\")\nprint(f\"Local datetime: {local_datetime}\")\n```\n\n```shell\nUTC datetime: 2002-10-27 06:00:00\nLocal datetime: 2002-10-27 06:00:00-08:00\n```\n\nFor a canonical list of time zone strings, see the Time Zone Database or its corresponding article on Wikipedia.\n\nWith PyMongo, you can't save `datetime.date` instances, because there is no BSON type for dates without times. Convert all `date` objects to `datetime` objects before saving them to MongoDB.\n\n## Reading datetimes\n\nWhen you use PyMongo to retrieve a `datetime` value, the driver can format it as a naive UTC, aware UTC, or localized value. The following sections describe how to retrieve each kind of value.\n\nFor these sections, assume that a MongoDB collection named `sample_collection` contains the following document. The value of the `\"date\"` field is a UTC `datetime` value.\n\n```shell\n{\"date\": datetime(2002, 10, 27, 14, 0, 0)}\n```\n\n### Naive UTC datetime\n\nBy default, PyMongo retrieves UTC `datetime` values with no supplemental information. The following code example retrieves the sample document and prints the `datetime` value. The printed value is identical to the one in the sample document. Select the Synchronous or Asynchronous tab to see the corresponding code:\n\n\n\n\n\n```python\nfrom datetime import datetime\n\ncollection = database[\"sample_collection\"]\nfind_result = collection.find_one()[\"date\"]\nprint(f\"datetime: {find_result}\")\nprint(f\"datetime.tzinfo: {find_result.tzinfo}\")\n```\n\n```shell\ndatetime: 2002-10-27 14:00:00\ndatetime.tzinfo: None\n```\n\n\n\n\n\n```python\nfrom datetime import datetime\n\ncollection = database[\"sample_collection\"]\nfind_result = (await collection.find_one())[\"date\"]\nprint(f\"datetime: {find_result}\")\nprint(f\"datetime.tzinfo: {find_result.tzinfo}\")\n```\n\n```shell\ndatetime: 2002-10-27 14:00:00\ndatetime.tzinfo: None\n```\n\n\n\n\n\n### Aware UTC datetime\n\nTo instruct PyMongo to retrieve an aware `datetime` value, create a `CodecOptions` object and pass `tz_aware = True` to the constructor. Then, pass the `CodecOptions` object to the `get_collection()` method.\n\nThe following code example retrieves the `datetime` value from the sample document as an aware `datetime`. Select the Synchronous or Asynchronous tab to see the corresponding code:\n\n\n\n\n\n```python\nfrom pymongo import MongoClient\nfrom datetime import datetime\nfrom bson.codec_options import CodecOptions\n\noptions = CodecOptions(tz_aware = True)\ncollection = database.get_collection(\"sample_collection\", options)\nfind_result = collection.find_one()[\"date\"]\n\nprint(f\"datetime: {find_result}\")\nprint(f\"datetime.tzinfo: {find_result.tzinfo}\")\n```\n\n```shell\ndatetime: 2002-10-27 14:00:00+00:00\ndatetime.tzinfo: \n```\n\n\n\n\n\n```python\nfrom pymongo import MongoClient\nfrom datetime import datetime\nfrom bson.codec_options import CodecOptions\n\noptions = CodecOptions(tz_aware = True)\ncollection = database.get_collection(\"sample_collection\", options)\nfind_result = (await collection.find_one())[\"date\"]\n\nprint(f\"datetime: {find_result}\")\nprint(f\"datetime.tzinfo: {find_result.tzinfo}\")\n```\n\n```shell\ndatetime: 2002-10-27 14:00:00+00:00\ndatetime.tzinfo: \n```\n\n\n\n\n\n### Localized datetime\n\nIf you plan to show `datetime` values to the user, you can instruct PyMongo to automatically convert all times read from MongoDB to a specific time zone. To do so, create a `timezone` object for the target time zone, as described in the Terminology section. Then, create a `CodecOptions` object and pass the following arguments to the constructor:\n\n- `tz_aware`: Set to `True`.\n\n- `tzinfo`: The `timezone` object.\n\nThe following code example retrieves the sample document, but uses the `tz_aware` and `tzinfo` arguments to automatically localize the `datetime` value to the `\"US/Pacific\"` time zone. Select the Synchronous or Asynchronous tab to see the corresponding code:\n\n\n\n\n\n```python\nfrom pymongo import MongoClient\nfrom datetime import datetime\nfrom bson.codec_options import CodecOptions\nimport pytz\nfrom pytz import timezone\n\npacific = timezone(\"US/Pacific\")\noptions = CodecOptions(tz_aware = True, tzinfo = pacific)\ncollection = database.get_collection(\"sample_collection\", options)\n\nfind_result = collection.find_one()[\"date\"]\nprint(f\"datetime: {find_result}\")\nprint(f\"datetime.tzinfo: {find_result.tzinfo}\")\n```\n\n```shell\ndatetime: 2002-10-27 06:00:00-08:00\ndatetime.tzinfo: US/Pacific\n```\n\n\n\n\n\n```python\nfrom pymongo import MongoClient\nfrom datetime import datetime\nfrom bson.codec_options import CodecOptions\nimport pytz\nfrom pytz import timezone\n\npacific = timezone(\"US/Pacific\")\noptions = CodecOptions(tz_aware = True, tzinfo = pacific)\ncollection = database.get_collection(\"sample_collection\", options)\n\nfind_result = (await collection.find_one())[\"date\"]\nprint(f\"datetime: {find_result}\")\nprint(f\"datetime.tzinfo: {find_result.tzinfo}\")\n```\n\n```shell\ndatetime: 2002-10-27 06:00:00-08:00\ndatetime.tzinfo: US/Pacific\n```\n\n\n\n\n\nThe preceding example specifies codec options at the collection level. You can also specify codec options at the client or database level."} -{"chunk_id": "68a95c3b5e79d242619e1555-1", "page_id": "68a95c3b5e79d242619e1555", "source_name": "pymongo", "product_name": "PyMongo", "url": "https://mongodb.com/docs/languages/python/pymongo-driver/current/data-formats/dates-and-times", "title": "Dates and Times", "text": "## Storing datetimes\n\nFor consistency, store only UTC `datetime` values to MongoDB. When you use PyMongo to create or update a field containing a `datetime` value, the driver first checks whether the `datetime` value is naive or aware:\n\n- If the `datetime` is naive, PyMongo assumes the `datetime` is in UTC and stores it to MongoDB unchanged.\n\n- If the `datetime` is aware, PyMongo automatically converts the time to UTC before storing it to MongoDB.\n\nThe following code example inserts a document containing a `datetime` value localized to the `\"US/Pacific\"` time zone. PyMongo uses the attached time zone to convert the local time to UTC. When the document is retrieved from MongoDB, the `datetime` value is in UTC. Select the Synchronous or Asynchronous tab to see the corresponding code:\n\n\n\n\n\n```python\nfrom pymongo import MongoClient\nfrom datetime import datetime\nfrom pytz import timezone\n\nutc_datetime = datetime(2002, 10, 27, 6, 0, 0)\npacific = timezone(\"US/Pacific\")\nlocal_datetime = pacific.localize(utc_datetime)\n\nprint(f\"datetime before storage: {local_datetime}\")\ncollection.insert_one({\"date\": local_datetime})\nfind_result = collection.find_one()[\"date\"]\nprint(f\"datetime after storage: {find_result}\")\n```\n\n```shell\ndatetime before storage: 2002-10-27 06:00:00-08:00\ndatetime after storage: 2002-10-27 14:00:00\n```\n\n\n\n\n\n```python\nfrom pymongo import MongoClient\nfrom datetime import datetime\nfrom pytz import timezone\n\nutc_datetime = datetime(2002, 10, 27, 6, 0, 0)\npacific = timezone(\"US/Pacific\")\nlocal_datetime = pacific.localize(utc_datetime)\n\nprint(f\"datetime before storage: {local_datetime}\")\nawait collection.insert_one({\"date\": local_datetime})\nfind_result = (await collection.find_one())[\"date\"]\nprint(f\"datetime after storage: {find_result}\")\n```\n\n```shell\ndatetime before storage: 2002-10-27 06:00:00-08:00\ndatetime after storage: 2002-10-27 14:00:00\n```\n\n\n\n\n\nAvoid calling the `datetime.now()` method with no arguments. This returns the current local time.\n\nInstead, always call the `datetime.now(tz=datetime.timezone.utc)` method, which returns the current time in UTC.\n\n## Handling Out-of-Range datetimes\n\nPython's `datetime` class can represent only `datetime` values between `datetime.min` and `datetime.max` (years 1-9999). You can represent a much greater range of dates and times by using BSON, which allows any 64-bit millisecond value from the Unix epoch.\n\nTo represent a BSON time with PyMongo, create a `datetime_ms.DatetimeMS` object, a wrapper for Python's built-in `int` type. You can manually create a `DatetimeMS` object by passing in one of the following values:\n\n- An `int` representing the number of milliseconds since the Unix epoch\n\n- A `datetime` object\n\nThe following code example constructs a `DatetimeMS` object by passing in an `int` value that represents the year -146136543, a date outside of the `datetime` range:\n\n```python\nfrom bson.datetime_ms import DatetimeMS\n\nout_of_range = DatetimeMS(-(2**62))\n```\n\nYou can also instruct PyMongo to automatically decode UTC `datetime` values as `DatetimeMS` objects. To do so, set the `datetime_conversion` parameter of `CodecOptions` to a value from the `datetime_ms.DatetimeConversion` enum. The following sections describe these values.\n\n`DatetimeMS` objects support rich comparison methods against other instances of `DatetimeMS`. You can also convert them to `datetime` objects by using the `DatetimeMS.to_datetime()` method.\n\n### DatetimeConversion.DATETIME\n\n`DatetimeConversion.DATETIME` is the default value. This value causes PyMongo to raise an error when it tries to decode an out-of-range date, as shown in the following example:\n\n```python\nfrom datetime import datetime\nfrom bson import encode, decode\nfrom bson.datetime_ms import DatetimeMS\n\nout_of_range = DatetimeMS(-(2**62))\nval = encode({\"date\": out_of_range})\ndecoded = decode(val)\nprint(decoded)\n```\n\n```shell\n...\nbson.errors.InvalidBSON: year -146136543 is out of range (Consider Using\nCodecOptions(datetime_conversion=DATETIME_AUTO) or\nMongoClient(datetime_conversion='DATETIME_AUTO')).\n...\n```\n\n### DatetimeConversion.DATETIME_MS\n\nThis value instructs PyMongo to return only `DatetimeMS` objects, even if the date is within the range of `datetime`:\n\n```python\nfrom datetime import datetime\nfrom bson import encode, decode\nfrom bson.datetime_ms import DatetimeMS\nfrom bson.codec_options import CodecOptions, DatetimeConversion\n\nval = encode({\"date\": datetime(1970, 1, 2)})\ncodec_ms = CodecOptions(datetime_conversion=DatetimeConversion.DATETIME_MS)\ndecoded = decode(val, codec_options=codec_ms)\nprint(decoded)\n```\n\n```javascript\n{\"date\": DatetimeMS(86400000)}\n```\n\n### DatetimeConversion.DATETIME_AUTO\n\nThis value instructs PyMongo to return `datetime` objects if the value is within `datetime` range, and return a `DatetimeMS` object otherwise. The following code example encodes and decodes one datetime in the `datetime` range and one outside the range:\n\n```python\nfrom datetime import datetime\nfrom bson import encode, decode\nfrom bson.datetime_ms import DatetimeMS\nfrom bson.codec_options import CodecOptions, DatetimeConversion\n\nin_range = encode({\"date\": datetime(1970, 1, 1)})\nout_of_range = encode({\"date\": DatetimeMS(-(2**62))})\ncodec_auto = CodecOptions(datetime_conversion=DatetimeConversion.DATETIME_AUTO)\n\nin_decoded = decode(in_range, codec_options=codec_auto)\nout_decoded = decode(out_of_range, codec_options=codec_auto)\nprint(f\"in-range date: {in_decoded}\")\nprint(f\"out-of-range date: {out_decoded}\")\n```\n\n```shell\nin-range date: {\"date\": datetime.datetime(1970, 1, 1, 0, 0)}\nout-of-range date: {'x': DatetimeMS(-4611686018427387904)}\n```\n\n### DatetimeConversion.DATETIME_CLAMP\n\nThis value \"clamps\" the resulting `datetime` objects, forcing them to be within the `datetime` range (trimmed to 999,000 microseconds).\n\nThe following code example encodes and decodes one datetime earlier than the `datetime` range and one datetime later than the `datetime` range. The resulting values are at the beginning and end of the allowed range.\n\n```python\nfrom datetime import datetime\nfrom bson import encode, decode\nfrom bson.datetime_ms import DatetimeMS\nfrom bson.codec_options import CodecOptions, DatetimeConversion\n\nbefore = encode({\"date\": DatetimeMS(-(2**62))})\nafter = encode({\"date\": DatetimeMS(2**62)})\ncodec_clamp = CodecOptions(datetime_conversion=DatetimeConversion.DATETIME_CLAMP)\n\nbefore_decoded = decode(before, codec_options=codec_clamp)\nafter_decoded = decode(after, codec_options=codec_clamp)\nprint(f\"datetime before the range: {before_decoded}\")\nprint(f\"datetime after the range: {after_decoded}\")\n```\n\n```shell\ndatetime before the range: {\"date\": datetime.datetime(1, 1, 1, 0, 0)}\ndatetime after the range: {\"date\": datetime.datetime(9999, 12, 31, 23, 59, 59, 999000)}\n```\n\n## Troubleshooting"} -{"chunk_id": "68a95c3b5e79d242619e1555-2", "page_id": "68a95c3b5e79d242619e1555", "source_name": "pymongo", "product_name": "PyMongo", "url": "https://mongodb.com/docs/languages/python/pymongo-driver/current/data-formats/dates-and-times", "title": "Dates and Times", "text": "### OverflowError When Decoding Dates Stored by Another Language's Driver\n\nPyMongo decodes BSON `datetime` values to instances of Python's `datetime.datetime` class. Instances of `datetime.datetime` are limited to years between `datetime.MINYEAR` (1) and `datetime.MAXYEAR` (9999). Some MongoDB drivers can store BSON datetimes with year values far outside those supported by `datetime.datetime`.\n\nThere are a few ways to work around this issue. Starting with PyMongo 4.3, `bson.decode` can decode BSON `datetime` values in one of four ways. You can specify the conversion method by using `datetime_conversion` parameter of `~bson.codec_options.CodecOptions`.\n\nThe default conversion option is `~bson.codec_options.DatetimeConversion.DATETIME`, which will attempt to decode the value as a `datetime.datetime`, allowing `~builtin.OverflowError` to occur for out-of-range dates. `~bson.codec_options.DatetimeConversion.DATETIME_AUTO` alters this behavior to instead return `~bson.datetime_ms.DatetimeMS` when representations are out-of-range, while returning `~datetime.datetime` objects as before. Select the Synchronous or Asynchronous tab to see the corresponding code:\n\n\n\n\n\n```python\nfrom datetime import datetime\nfrom bson.datetime_ms import DatetimeMS\nfrom bson.codec_options import DatetimeConversion\nfrom pymongo import MongoClient\n\nclient = MongoClient(datetime_conversion=DatetimeConversion.DATETIME_AUTO)\nclient.db.collection.insert_one({\"x\": datetime(1970, 1, 1)})\n\nclient.db.collection.insert_one({\"x\": DatetimeMS(2**62)})\n\nfor x in client.db.collection.find():\n print(x)\n```\n\n```\n{'_id': ObjectId('...'), 'x': datetime.datetime(1970, 1, 1, 0, 0)}\n{'_id': ObjectId('...'), 'x': DatetimeMS(4611686018427387904)}\n```\n\n\n\n\n\n```python\nfrom datetime import datetime\nfrom bson.datetime_ms import DatetimeMS\nfrom bson.codec_options import DatetimeConversion\nfrom pymongo import MongoClient\n\nclient = AsyncMongoClient(datetime_conversion=DatetimeConversion.DATETIME_AUTO)\nawait client.db.collection.insert_one({\"x\": datetime(1970, 1, 1)})\n\nawait client.db.collection.insert_one({\"x\": DatetimeMS(2**62)})\n\nasync for x in client.db.collection.find():\n print(x)\n```\n\n```\n{'_id': ObjectId('...'), 'x': datetime.datetime(1970, 1, 1, 0, 0)}\n{'_id': ObjectId('...'), 'x': DatetimeMS(4611686018427387904)}\n```\n\n\n\n\n\nFor other options, see the API documentation for the DatetimeConversion class.\n\nAnother option that does not involve setting `datetime_conversion` is to filter out document values outside of the range supported by `~datetime.datetime`. Select the Synchronous or Asynchronous tab to see the corresponding code:\n\n\n\n\n\n```python\nfrom datetime import datetime\ncoll = client.test.dates\ncur = coll.find({'dt': {'$gte': datetime.min, '$lte': datetime.max}})\n```\n\n\n\n\n\n```python\nfrom datetime import datetime\ncoll = client.test.dates\ncur = coll.find({'dt': {'$gte': datetime.min, '$lte': datetime.max}})\n```\n\n\n\n\n\nIf you don't need the value of `datetime`, you can filter out just that field. Select the Synchronous or Asynchronous tab to see the corresponding code:\n\n\n\n\n\n```python\ncur = coll.find({}, projection={'dt': False})\n```\n\n\n\n\n\n```python\ncur = coll.find({}, projection={'dt': False})\n```\n\n\n\n\n\n## API Documentation\n\nFor more information about working with dates and times in PyMongo, see the following API documentation:\n\n- `datetime` at docs.python.org\n\n- `pytz` at pypi.org\n\n- CodecOptions\n\n- DatetimeMS"} -{"chunk_id": "69a137545ebfad7ec1c0880a-0", "page_id": "69a137545ebfad7ec1c0880a", "source_name": "pymongo", "product_name": "PyMongo", "url": "https://mongodb.com/docs/languages/python/pymongo-driver/current/integrations/flask-migrate-to-mongo", "title": "Tutorial: Migrate Flask From SQL to MongoDB", "text": "# Tutorial: Migrate Flask From SQL to MongoDB\n\n## Overview\n\nThis tutorial shows you how to migrate a Flask application from SQL to MongoDB. Specifically, the tutorial converts an example blog application that uses SQLAlchemy to one that uses Flask-PyMongo.\n\nThe example application includes the following features:\n\n- Creating, editing, and viewing blog posts\n\n- Searching for blog posts\n\n### Understanding MongoDB\n\nMongoDB is a NoSQL database that stores data in documents. The following list describes key MongoDB concepts:\n\n- **Collections**: Groups of documents, similar to tables in SQL databases. Collections don't enforce a schema.\n\n- **Documents**: JSON-like objects that store data. Documents can contain arrays and nested subdocuments.\n\n- **BSON**: Binary JSON format that MongoDB uses internally. BSON extends JSON with additional data types such as Date and Binary.\n\nThe following table compares MongoDB and SQL databases:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nFeature\n\n\nSQL\n\n\nMongoDB\n\n
\nSchema\n\n\nEnforces a fixed schema with predefined tables and columns\n\n\nFlexible schemas that allow for dynamic data models\n\n
\nData Structure\n\n\nStores data in tables with rows and columns\n\n\nStores data in collections of documents\n\n
\nRelationships\n\n\nUses foreign keys and joins to establish relationships between tables\n\n\nEmbeds documents within other documents or references them, without the need for joins\n\n
\nQuery Language\n\n\nUses Structured Query Language (SQL)\n\n\nUses a rich, JSON-based query language\n\n
\n\n## Tutorial\n\nThis tutorial shows you how to complete the following steps:\n\n- Verify the prerequisites\n\n- Install Flask-PyMongo\n\n- Update the Flask application models\n\n- Update the Flask application configuration\n\n- Update the Flask application routes\n\n- Export data from SQLite\n\n- Import data into MongoDB\n\n- Update the Flask templates\n\n- Run the migrated application\n\n### Verify the prerequisites\n\nThis tutorial requires the following prerequisites:\n\n- MongoDB installed on your local machine. See the Install MongoDB guide in the MongoDB Server manual for instructions.\n\n- An existing Flask application that uses SQLAlchemy. You can use the example Flask application from the flask-mongo repository on GitHub for this tutorial.\n\n- Python 3.7 or later.\n\nThe `flask-mongo` example application contains two sub-folders, `flask-mongo` and `flask-sql`. The `flask-sql` folder contains a Flask application that uses SQLAlchemy, which you can use for the migration in this tutorial.\n\nBefore you begin the migration, complete the following actions:\n\n- Review your SQL database schema, including tables, relationships, and data types.\n\n- Identify complex queries and relationships that might require special handling in MongoDB.\n\n- Design your MongoDB schema considering the document-oriented nature of the database. To learn more about schema design in MongoDB, see the Designing Your Schema guide in the MongoDB Server manual.\n\n- Create a complete backup of your current SQL database.\n\n### Install Flask-PyMongo\n\nFlask-PyMongo is a Flask extension that integrates MongoDB with Flask applications.\n\nInstall Flask-PyMongo by running the following command:\n\n```bash\npip install Flask-PyMongo Flask\n```\n\n### Update the Flask application models\n\nReplace the contents of your `models.py` file with the following code:\n\n```python\nfrom datetime import datetime\nfrom bson.objectid import ObjectId\n\nclass Post:\n def __init__(self, title, content, date_posted=None,\n _id=None):\n self.title = title\n self.content = content\n self.date_posted = date_posted if date_posted \\\n else datetime.utcnow()\n self._id = _id if _id else ObjectId()\n\n def to_dict(self):\n return {\n \"title\": self.title,\n \"content\": self.content,\n \"date_posted\": self.date_posted,\n \"_id\": self._id\n }\n\n @staticmethod\n def from_dict(data):\n return Post(\n title=data.get('title'),\n content=data.get('content'),\n date_posted=data.get('date_posted'),\n _id=data.get('_id')\n )\n\n def __repr__(self):\n return f\"Post('{self.title}', \\\n '{self.date_posted}')\"\n\n```\n\nThis code defines a `Post` class that models a blog post for MongoDB. The class includes the following methods:\n\n- `__init__`: Sets the title, content, date posted, and unique identifier for each post\n\n- `to_dict`: Converts an instance into a dictionary for MongoDB storage\n\n- `from_dict`: Creates a `Post` instance from a dictionary\n\n- `__repr__`: Returns a string representation of the post\n\n### Update the Flask application configuration\n\nReplace the contents of your `__init__.py` file with the following code:\n\n```python\nfrom flask import Flask\nfrom flask_pymongo import PyMongo\nfrom config import Config\n\napp = Flask(__name__)\napp.config.from_object(Config)\nmongo = PyMongo(app)\n\nfrom app import routes\n\n```\n\nThis code initializes the Flask application to use MongoDB through the Flask-PyMongo extension.\n\nUpdate your `config.py` file to include MongoDB settings by adding the following code:\n\n```python\nimport os\n\nclass Config:\n SECRET_KEY = os.urandom(24)\n MONGO_URI = 'mongodb://localhost:27017/blogdb'\n\n```\n\nDelete the `manage.py` file. You use this file for database migrations in SQL, which doesn't apply to MongoDB.\n\nIf you need migrations for MongoDB, the Beanie ODM provides migration support."} -{"chunk_id": "69a137545ebfad7ec1c0880a-1", "page_id": "69a137545ebfad7ec1c0880a", "source_name": "pymongo", "product_name": "PyMongo", "url": "https://mongodb.com/docs/languages/python/pymongo-driver/current/integrations/flask-migrate-to-mongo", "title": "Tutorial: Migrate Flask From SQL to MongoDB", "text": "### Update the Flask application routes\n\nReplace the contents of your `routes.py` file with the following code:\n\n```python\nfrom flask import render_template, url_for, flash, \\\n redirect, request\nfrom app import app, mongo\nfrom bson.objectid import ObjectId\nfrom app.models import Post\nfrom app.forms import PostForm\n\n@app.route(\"/\")\n@app.route(\"/home\")\ndef home():\n posts_data = mongo.db.posts.find()\n posts = [Post.from_dict(post) for post in posts_data]\n return render_template(\"index.html\", posts=posts)\n\n@app.route(\"/post/new\", methods=[\"GET\", \"POST\"])\ndef new_post():\n form = PostForm()\n if form.validate_on_submit():\n post = Post(title=form.title.data,\n content=form.content.data)\n mongo.db.posts.insert_one(post.to_dict())\n flash(\"Your post has been created!\", \"success\")\n return redirect(url_for(\"home\"))\n return render_template(\"post.html\", title=\"New Post\",\n form=form)\n\n@app.route(\"/post/\")\ndef post(post_id):\n post_data = mongo.db.posts.find_one_or_404(\n {\"_id\": ObjectId(post_id)})\n post = Post.from_dict(post_data)\n return render_template(\"detail.html\", post=post)\n\n@app.route(\"/post//edit\", methods=[\"GET\", \"POST\"])\ndef edit_post(post_id):\n post_data = mongo.db.posts.find_one_or_404(\n {\"_id\": ObjectId(post_id)})\n post = Post.from_dict(post_data)\n form = PostForm()\n if form.validate_on_submit():\n updated_post = {\n \"$set\": {\"title\": form.title.data,\n \"content\": form.content.data}\n }\n mongo.db.posts.update_one(\n {\"_id\": ObjectId(post_id)}, updated_post)\n flash(\"Your post has been updated!\", \"success\")\n return redirect(url_for(\"post\", post_id=post_id))\n elif request.method == \"GET\":\n form.title.data = post.title\n form.content.data = post.content\n return render_template(\"edit_post.html\",\n title=\"Edit Post\", form=form)\n\n@app.route(\"/post//delete\", methods=[\"POST\"])\ndef delete_post(post_id):\n mongo.db.posts.delete_one({\"_id\": ObjectId(post_id)})\n flash(\"Your post has been deleted!\", \"success\")\n return redirect(url_for(\"home\"))\n\n@app.route(\"/search\", methods=[\"GET\", \"POST\"])\ndef search():\n query = request.args.get(\"query\")\n posts_data = mongo.db.posts.find(\n {\n \"$or\": [\n {\"title\": {\"$regex\": query,\n \"$options\": \"i\"}},\n {\"content\": {\"$regex\": query,\n \"$options\": \"i\"}},\n ]\n }\n )\n posts = [Post.from_dict(post) for post in posts_data]\n return render_template(\"index.html\", posts=posts)\n\n```\n\nThis code updates the routes to use MongoDB instead of SQLAlchemy. The routes complete the following actions:\n\n- Convert `Post` instances to dictionaries by using the `to_dict` method for storage in MongoDB\n\n- Retrieve posts by using `mongo.db.posts.find()`\n\n- Insert posts by using `mongo.db.posts.insert_one()`\n\n- Update posts by using `mongo.db.posts.update_one()`\n\n- Delete posts by using `mongo.db.posts.delete_one()`\n\n- Search posts by using MongoDB's regex capabilities\n\n### Export data from SQLite\n\nCreate a Python script named `export_list_tables.py` to list all tables in your SQLite database by adding the following code to a new file:\n\n```python\nimport sqlite3\n\n# Connect to the SQLite database\ndb_path = 'relative/path/to/site.db'\nconn = sqlite3.connect(db_path)\ncursor = conn.cursor()\n\n# Query to get all table names\ncursor.execute(\"SELECT name FROM sqlite_master WHERE \\\n type='table';\")\ntables = cursor.fetchall()\n\n# Close the connection\nconn.close()\n\nprint(tables)\n\n```\n\nRun this script to display your table names. The output shows the `post` table.\n\nCreate another Python script named `export_to_json.py` to export the data to JSON by adding the following code to a new file:\n\n```python\nimport sqlite3\nimport json\n\n# Connect to the SQLite database\ndb_path = 'relative/path/to/site.db'\nconn = sqlite3.connect(db_path)\ncursor = conn.cursor()\n\n# Export data from the 'post' table\ncursor.execute(\"SELECT * FROM post\")\nrows = cursor.fetchall()\n\n# Get the column names\ncolumn_names = [description[0] for description in \\\n cursor.description]\n\n# Convert to list of dictionaries\ndata = [dict(zip(column_names, row)) for row in rows]\n\n# Save to a JSON file\nwith open('post.json', 'w') as f:\n json.dump(data, f, indent=4)\n\n# Close the connection\nconn.close()\n\n```\n\nRun this script to create the `post.json` file in the current directory. This file contains your exported data in JSON format.\n\n### Import data into MongoDB\n\nCreate a Python script named `import_to_mongo.py` to import the JSON file into MongoDB by adding the following code to a new file:\n\n```python\nfrom pymongo import MongoClient\nimport json\nfrom datetime import datetime\n\ndef import_json_to_mongo(db_name, collection_name,\n json_path):\n client = MongoClient(\"mongodb://localhost:27017/\")\n db = client[db_name]\n\n def convert_date(data):\n # Update 'date_posted' field to datetime object\n for item in data:\n if 'date_posted' in item:\n item['date_posted'] = datetime.strptime(\n item['date_posted'],\n '%Y-%m-%d %H:%M:%S.%f')\n return data\n\n with open(json_path, 'r') as f:\n data = json.load(f)\n data = convert_date(data)\n db[collection_name].insert_many(data)\n\n client.close()\n\nif __name__ == \"__main__\":\n db_name = 'blogdb'\n collection_name = 'posts'\n json_path = 'flask-mongo/post.json'\n import_json_to_mongo(db_name, collection_name,\n json_path)\n\n```\n\nRun this script to import your data into MongoDB. The script converts the `date_posted` field to a datetime object and inserts all posts into the MongoDB collection.\n\nThe connection string `mongodb://localhost:27017/blogdb` connects to your MongoDB instance on localhost at port 27017. MongoDB creates the database automatically when you first write data.\n\n### Update the Flask templates\n\nUpdate your template files to use the MongoDB document ID by changing all instances of `post_id=post.id` to `post_id=post._id`.\n\n### Run the migrated application\n\nRun the Flask application by running the following command:\n\n```bash\npython run.py\n```\n\nYou can access your application by navigating to `http://127.0.0.1:5000/home` in your web browser.\n\n## Additional Resources\n\nTo learn more about Flask-Pymongo, see the Flask-PyMongo documentation."} -{"chunk_id": "68a95c3b5e79d242619e155c-0", "page_id": "68a95c3b5e79d242619e155c", "source_name": "pymongo", "product_name": "PyMongo", "url": "https://mongodb.com/docs/languages/python/pymongo-driver/current/crud/query", "title": "Query", "text": "# Query\n\n## Overview\n\nOn this page, you can see copyable code examples that show common methods you can use to find documents with PyMongo.\n\nTo learn more about any of the methods shown on this page, see the link provided in each section.\n\nTo use an example from this page, copy the code example into the sample application or your own application. Be sure to replace all placeholders in the code examples, such as ``, with the relevant values for your MongoDB deployment.\n\n### Sample Application\n\nYou can use the following sample application to test the code examples on this page. To use the sample application, perform the following steps:\n\n1. Ensure you have PyMongo installed.\n\n2. Copy the following code and paste it into a new `.py` file.\n\n3. Copy a code example from this page and paste it on the specified lines in the file.\n\nSelect the Synchronous or Asynchronous tab to see the corresponding code:\n\n\n\n\n\n```python\nimport pymongo\nfrom pymongo import MongoClient\n\ntry:\n uri = \"\"\n client = MongoClient(uri)\n\n database = client[\"\"]\n collection = database[\"\"]\n\n # start example code here\n\n # end example code here\n\n client.close()\n\nexcept Exception as e:\n raise Exception(\n \"The following error occurred: \", e)\n\n```\n\n\n\n\n\n```python\nimport asyncio\nimport pymongo\nfrom pymongo import AsyncMongoClient\n\nasync def main():\n try:\n uri = \"\"\n client = AsyncMongoClient(uri)\n\n database = client[\"\"]\n collection = database[\"\"]\n\n # start example code here\n\n # end example code here\n\n await client.close()\n\n except Exception as e:\n raise Exception(\n \"The following error occurred: \", e)\n\nasyncio.run(main())\n```\n\n\n\n\n\n## Find One\n\n\n\n\n\n```\nresults = collection.find_one({ \"\" : \"\" })\n\nprint(results)\n```\n\n\n\n\n\n```\nresults = await collection.find_one({ \"\" : \"\" })\n\nprint(results)\n```\n\n\n\n\n\nTo learn more about the `find_one()` method, see Find One Document in the Retrieve Data guide.\n\n## Find Multiple\n\n\n\n\n\n```\nresults = collection.find({ \"\" : \"\" })\n\nfor document in results:\n print(document)\n```\n\n\n\n\n\n```\nresults = collection.find({ \"\" : \"\" })\n\nasync for document in results:\n print(document)\n```\n\n\n\n\n\nTo learn more about the `find()` method, see Find Multiple Documents in the Retrieve Data guide.\n\n## Count Documents in a Collection\n\n\n\n\n\n```\ncount = collection.count_documents({})\n\nprint(count)\n```\n\n\n\n\n\n```\ncount = await collection.count_documents({})\n\nprint(count)\n```\n\n\n\n\n\nTo learn more about the `count_documents()` method, see the Retrieve an Accurate Count guide.\n\n## Count Documents Returned from a Query\n\n\n\n\n\n```\ncount = collection.count_documents({ \"\": \"\" })\n\nprint(count)\n```\n\n\n\n\n\n```\ncount = await collection.count_documents({ \"\": \"\" })\n\nprint(count)\n```\n\n\n\n\n\nTo learn more about the `count_documents()` method, see the Retrieve an Accurate Count guide.\n\n## Estimated Document Count\n\n\n\n\n\n```\ncount = collection.estimated_document_count()\n\nprint(count)\n```\n\n\n\n\n\n```\ncount = await collection.estimated_document_count()\n\nprint(count)\n```\n\n\n\n\n\nTo learn more about the `estimated_document_count()` method, see the Retrieve an Estimated Count guide.\n\n## Retrieve Distinct Values\n\n\n\n\n\n```\nresults = collection.distinct(\"\")\n\nfor document in results:\n print(document)\n```\n\n\n\n\n\n```\nresults = await collection.distinct(\"\")\n\nfor document in results:\n print(document)\n```\n\n\n\n\n\nTo learn more about the `distinct()` method, see the Retrieve Distinct Field Values guide.\n\n## Monitor Data Changes\n\n\n\n\n\n```\nwith collection.watch() as stream:\n for change in stream:\n print(change)\n```\n\n\n\n\n\n```\nasync with await collection.watch() as stream:\n async for change in stream:\n print(change)\n```\n\n\n\n\n\nTo learn more about the `watch()` method, see the Monitor Data with Change Streams guide."} -{"chunk_id": "68a95c3b5e79d242619e153a-0", "page_id": "68a95c3b5e79d242619e153a", "source_name": "pymongo", "product_name": "PyMongo", "url": "https://mongodb.com/docs/languages/python/pymongo-driver/current/get-started", "title": "Get Started with PyMongo", "text": "# Get Started with PyMongo\n\n## Overview\n\nPyMongo is a Python package that you can use to connect to and communicate with MongoDB. This guide shows you how to create an application that uses PyMongo to connect to a MongoDB cluster hosted on MongoDB Atlas.\n\nMongoDB Atlas is a fully managed cloud database service that hosts your MongoDB deployments. You can create your own free (no credit card required) MongoDB Atlas deployment by following the steps in this guide.\n\nFollow this guide to connect a sample Python application to a MongoDB Atlas deployment. If you prefer to connect to MongoDB using a different driver or programming language, see our list of official drivers.\n\n## Download and Install\n\nThe following steps show you how to install PyMongo by using pip. To install PyMongo from source, see Install from Source in the API documentation.\n\n### Install dependencies.\n\nEnsure you have the following dependencies installed in your development environment:\n\n- Python3 version 3.8 or later\n\n- pip\n\n- dnspython\n\n### Create a project directory.\n\nIn your shell, run the following command to create a directory called `pymongo-quickstart` for this project:\n\n```bash\nmkdir pymongo-quickstart\n```\n\nSelect the tab corresponding to your operating system and run the following commands to create a `quickstart.py` application file in the `pymongo-quickstart` directory:\n\n\n\n\n\n```bash\ncd pymongo-quickstart\ntouch quickstart.py\n```\n\n\n\n\n\n```bash\ncd pymongo-quickstart\ntype nul > quickstart.py\n```\n\n\n\n\n\n### Install PyMongo.\n\nSelect the tab corresponding to your operating system and run the following commands to create and activate a virtual environment in which to install the driver:\n\n\n\n\n\n```bash\npython3 -m venv venv\nsource venv/bin/activate\n```\n\n\n\n\n\n```bash\npython3 -m venv venv\n. venv\\Scripts\\activate\n```\n\n\n\n\n\nWith the virtual environment activated, run the following command to install the current version of PyMongo:\n\n```bash\npython3 -m pip install pymongo\n```\n\nAfter you complete these steps, you have a new project directory and the driver dependencies installed.\n\n## Create a MongoDB Deployment\n\nYou can create a free-tier MongoDB deployment on MongoDB Atlas to store and manage your data. MongoDB Atlas hosts and manages your MongoDB database in the cloud.\n\n### Create a free MongoDB deployment on Atlas.\n\nComplete the Get Started with Atlas guide to set up a new Atlas account and load sample data into a new free tier MongoDB deployment.\n\n### Save your credentials.\n\nAfter you create your database user, save that user's username and password to a safe location for use in an upcoming step.\n\nAfter you complete these steps, you have a new free cluster on Atlas, database user credentials, and sample data loaded in your database.\n\n## Create a Connection String\n\nYou can connect to your MongoDB deployment by providing a **connection URI**, also called a *connection string*, which instructs the driver on how to connect to a MongoDB deployment and how to behave while connected.\n\nThe connection string includes the hostname or IP address and port of your deployment, the authentication mechanism, user credentials when applicable, and connection options.\n\nTo connect to an instance or deployment not hosted on Atlas, see Choose a Connection Target.\n\n### Find your MongoDB Atlas connection string.\n\nTo retrieve your connection string for the deployment that you created in the previous step, log into your Atlas account and navigate to the Clusters page under the Database section. Click the Connect button for your new deployment.\n\nIf you do not already have a database user configured, MongoDB will prompt you to create and configure a new user.\n\nClick the Drivers button under Connect to your application section and select \"Python\" from the Driver selection menu and the version that best matches the version you installed from the Version selection menu.\n\nEnsure the View full code sample option is deselected to view only the connection string.\n\n### Copy your connection string.\n\nClick the button on the right of the connection string to copy it to your clipboard as shown in the following screenshot:\n\n### Update the password placeholder.\n\nPaste this connection string into a file in your preferred text editor and replace the `` placeholder with your database user's password. The connection string is already populated with your database user's username.\n\nSave this file to a safe location for use in the next step.\n\nAfter completing these steps, you have a connection string that contains your database username and password.\n\n## Connect to MongoDB\n\n### Create your PyMongo application.\n\nCopy and paste the following code into the `quickstart.py` file in your application. Select the Synchronous or Asynchronous tab to see the corresponding code:\n\n\n\n\n\n```python\nfrom pymongo import MongoClient\nimport json\n\nuri = \"\"\nclient = MongoClient(uri)\n\ntry:\n database = client.get_database(\"sample_mflix\")\n movies = database.get_collection(\"movies\")\n\n # Queries for a movie that has the title 'Back to the Future'\n query = { \"title\": \"Back to the Future\" }\n movie = movies.find_one(query)\n\n print(json.dumps(movie, indent=4, default=str))\n\n client.close()\n\nexcept Exception as e:\n raise Exception(\"Unable to find the document due to the following error: \", e)\n\n```\n\n\n\n\n\n```python\nimport asyncio\nfrom pymongo import AsyncMongoClient\n\nasync def main():\n uri = \"\"\n client = AsyncMongoClient(uri)\n\n try:\n database = client.get_database(\"sample_mflix\")\n movies = database.get_collection(\"movies\")\n\n # Query for a movie that has the title 'Back to the Future'\n query = { \"title\": \"Back to the Future\" }\n movie = await movies.find_one(query)\n\n print(movie)\n\n await client.close()\n\n except Exception as e:\n raise Exception(\"Unable to find the document due to the following error: \", e)\n\n# Run the async function\nasyncio.run(main())\n\n```\n\n\n\n\n\n### Assign the connection string.\n\nReplace the `` placeholder with the connection string that you copied from the Create a Connection String step of this guide.\n\n### Run your application.\n\nIn your shell, run the following command to start this application:\n\n```sh\npython3 quickstart.py\n```\n\nThe output includes details of the retrieved movie document:\n\n```none\n{\n _id: ...,\n plot: 'A young man is accidentally sent 30 years into the past...',\n genres: [ 'Adventure', 'Comedy', 'Sci-Fi' ],\n ...\n title: 'Back to the Future',\n ...\n}\n```\n\nIf you encounter an error or see no output, check whether you specified the proper connection string, and that you loaded the sample data.\n\nAfter you complete these steps, you have a working application that uses the driver to connect to your MongoDB deployment, runs a query on the sample data, and prints out the result.\n\n## Next Steps\n\nCongratulations on completing the tutorial!\n\nIn this tutorial, you created a Python application that connects to a MongoDB deployment hosted on MongoDB Atlas and retrieves a document that matches a query.\n\nLearn more about PyMongo from the following resources:\n\n- Learn how to insert documents in the Insert Documents section.\n\n- Learn how to find documents in the Query section.\n\n- Learn how to update documents in the Update Documents section.\n\n- Learn how to delete documents in the Delete Documents section.\n\nIf you run into issues on this step, submit feedback by using the Rate this page tab on the right or bottom right side of this page.\n\nYou can find support for general questions by using the MongoDB Stack Overflow tag or the MongoDB Reddit community."} -{"chunk_id": "68a95c3b5e79d242619e1551-0", "page_id": "68a95c3b5e79d242619e1551", "source_name": "pymongo", "product_name": "PyMongo", "url": "https://mongodb.com/docs/languages/python/pymongo-driver/current/monitoring-and-logging/monitoring", "title": "Monitoring", "text": "# Monitoring\n\n## Overview\n\nIn this guide, you can learn how to configure **monitoring** in PyMongo by using PyMongo's callback-based interface. Monitoring is the process of gathering information about your application's behavior as it runs. This information can help you make informed decisions when designing and debugging your application. You can also use information from monitoring events to track your application's performance and resource usage.\n\nThe driver provides information about your application by emitting events. You can listen for driver events to monitor your application.\n\nThis page explains how to monitor your application in code. To learn how to record this information to an external log, see the Logging guide.\n\n## Event Types\n\nThe type of event that the driver emits depends on the operation being performed. The following table describes the types of events that the driver emits:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nEvent Type\n\n\nDescription\n\n
\nCommand events\n\n\nEvents related to MongoDB database commands, such as `find`, `insert`, `delete`, and `count`. To learn how to use PyMongo to run a database command, see Run a Database Command. For more information about MongoDB database commands, see Database Commands in the MongoDB Server manual.\n\nAs a security measure, the driver redacts the contents of some command events. This protects the sensitive information contained in these command events.\n\n
\nServer Discovery and Monitoring (SDAM) events\n\n\nEvents related to changes in the state of the MongoDB deployment.\n\n
\nConnection Pool events\n\n\nEvents related to the connection pool held by the driver.\n\n
For a complete list of events the driver emits, see the pymongo.monitoring API documentation.\n\n## Listening for Events\n\nTo monitor an event, you must pass an event listener to your application's `MongoClient`. The following steps describe how to monitor your application by using an event listener:\n\n1. Create a class that inherits from one of the event listener base classes provided by PyMongo. The base class you choose depends on the type of event you want to monitor. For example, to monitor command events, create a class that inherits from `CommandListener`.\n\n2. Implement the methods of the base class that correpond to the events you want to monitor.\n\n3. Pass an instance of your listener class to the `MongoClient` constructor.\n\nThe following code implements a `CommandListener` to listen for command events, a `ServerListener` to listen for SDAM events, and a `ConnectionPoolListener` to listen for connection pool events:\n\n```python\nclass MyCommandListener(CommandListener):\n def succeeded(self, event: CommandSucceededEvent):\n print(f\"Command {event.command_name} succeeded\")\n\n # Include other event method implementations here\n\nclass MyServerListener(ServerListener):\n def heartbeat_started(self, event: ServerHeartbeatStartedEvent):\n print(f\"Heartbeat started on server with id: {event.connection_id}\")\n\n # Include other event method implementations here\n\nclass MyPoolListener(ConnectionPoolListener):\n def connection_created(self, event: ConnectionCreatedEvent):\n print(f\"Connection {event.connection_id} created\")\n\n # Include other event method implementations here\n```\n\nThe following code passes instances of the preceding listeners to the `MongoClient` constructor. Select the Synchronous or Asynchronous tab to see the corresponding code:\n\n\n\n\n\n```python\nlisteners = [MyCommandListener(), MyServerListener(), MyPoolListener()]\nclient = MongoClient(\"\", event_listeners=listeners)\n```\n\n\n\n\n\n```python\nlisteners = [MyCommandListener(), MyServerListener(), MyPoolListener()]\nclient = AsyncMongoClient(\"\", event_listeners=listeners)\n```\n\n\n\n\n\n## API Documentation\n\nTo learn more about the methods and classes used to monitor events in the driver, see the following API documentation:\n\n- monitoring\n\n- MongoClient"} -{"chunk_id": "69afb7ec9a04e6cf66167020-0", "page_id": "69afb7ec9a04e6cf66167020", "source_name": "pymongo-arrow", "product_name": "PyMongo Arrow Driver", "url": "https://mongodb.com/docs/languages/python/pymongo-arrow-driver/current", "title": "MongoDB PyMongoArrow", "text": "# MongoDB PyMongoArrow\n\n## Introduction\n\n**PyMongoArrow** is a PyMongo extension containing tools for loading MongoDB query result-sets as Apache Arrow tables, NumPy arrays, and Pandas or Polars DataFrames. PyMongoArrow is the recommended way to materialize MongoDB query result-sets as contiguous-in-memory typed arrays suited for in-memory analytical processing applications.\n\n## Get Started\n\nLearn how to install or upgrade PyMongoArrow, and how to begin working with data in the Get Started guide.\n\n## Data Types\n\nLearn about the types of data supported with PyMongoArrow in the Data Types section.\n\n## Schema Examples\n\nFor examples of using PyMongoArrow schemas, see the Schema Examples section.\n\n## Reference\n\nFind more information about PyMongoArrow versions, release notes, and documentation for previous versions in the Reference section.\n\n## Compatibility\n\nFind information about PyMongoArrow compatibility with Python, PyArrow, and PyMongo, see the Compatibility page.\n\n## API Documentation\n\nFor detailed information about types and methods in PyMongoArrow, see the PyMongoArrow API documentation.\n\n## Issues and Help\n\nFind information about reporting bugs, requesting features, and contributing to PyMongoArrow on the Issues and Help page."} -{"chunk_id": "69afb7ec9a04e6cf66167032-0", "page_id": "69afb7ec9a04e6cf66167032", "source_name": "pymongo-arrow", "product_name": "PyMongo Arrow Driver", "url": "https://mongodb.com/docs/languages/python/pymongo-arrow-driver/current/reference/previous-versions", "title": "Documentation for Versions 0.4 to 1.2", "text": "# Documentation for Versions 0.4 to 1.2\n\nThe following links direct you to documentation for previous versions of PyMongoArrow:\n\n- Version 1.2\n\n- Version 1.1\n\n- Version 1.0\n\n- Version 0.7\n\n- Version 0.6\n\n- Version 0.5\n\n- Version 0.4"} -{"chunk_id": "69afb7ec9a04e6cf66167026-0", "page_id": "69afb7ec9a04e6cf66167026", "source_name": "pymongo-arrow", "product_name": "PyMongo Arrow Driver", "url": "https://mongodb.com/docs/languages/python/pymongo-arrow-driver/current/reference/comparison", "title": "Compare PyMongoArrow to PyMongo", "text": "# Compare PyMongoArrow to PyMongo\n\nIn this guide, you can learn about the differences between PyMongoArrow and the PyMongo driver. This guide assumes familiarity with basic PyMongo and MongoDB concepts.\n\n## Reading Data\n\nThe most basic way to read data using PyMongo is:\n\n```python\ncoll = db.benchmark\nf = list(coll.find({}, projection={\"_id\": 0}))\ntable = pyarrow.Table.from_pylist(f)\n```\n\nThis works, but you have to exclude the `_id` field, otherwise you get the following error:\n\n```python\npyarrow.lib.ArrowInvalid: Could not convert ObjectId('642f2f4720d92a85355671b3') with type ObjectId: did not recognize Python value type when inferring an Arrow data type\n```\n\nThe following code example shows a workaround for the preceding error when using PyMongo:\n\n```python\n>>> f = list(coll.find({}))\n>>> for doc in f:\n... doc[\"_id\"] = str(doc[\"_id\"])\n...\n>>> table = pyarrow.Table.from_pylist(f)\n>>> print(table)\npyarrow.Table\n_id: string\nx: int64\ny: double\n```\n\nEven though this avoids the error, a drawback is that Arrow can't identify that `_id` is an ObjectId, as noted by the schema showing `_id` as a string.\n\nPyMongoArrow supports BSON types through Arrow or Pandas Extension Types. This allows you to avoid the preceding workaround.\n\n```python\n>>> from pymongoarrow.types import ObjectIdType\n>>> schema = Schema({\"_id\": ObjectIdType(), \"x\": pyarrow.int64(), \"y\": pyarrow.float64()})\n>>> table = find_arrow_all(coll, {}, schema=schema)\n>>> print(table)\npyarrow.Table\n_id: extension>\nx: int64\ny: double\n```\n\nWith this method, Arrow correctly identifies the type. This has limited use for non-numeric extension types, but avoids unnecessary casting for certain operations, such as sorting datetimes.\n\n```python\nf = list(coll.find({}, projection={\"_id\": 0, \"x\": 0}))\nnaive_table = pyarrow.Table.from_pylist(f)\n\nschema = Schema({\"time\": pyarrow.timestamp(\"ms\")})\ntable = find_arrow_all(coll, {}, schema=schema)\n\nassert (\n table.sort_by([(\"time\", \"ascending\")])[\"time\"]\n == naive_table[\"time\"].cast(pyarrow.timestamp(\"ms\")).sort()\n)\n```\n\nAdditionally, PyMongoArrow supports Pandas extension types. With PyMongo, a `Decimal128` value behaves as follows:\n\n```python\ncoll = client.test.test\ncoll.insert_many([{\"value\": Decimal128(str(i))} for i in range(200)])\ncursor = coll.find({})\ndf = pd.DataFrame(list(cursor))\nprint(df.dtypes)\n# _id object\n# value object\n```\n\nThe equivalent in PyMongoArrow is:\n\n```python\nfrom pymongoarrow.api import find_pandas_all\ncoll = client.test.test\ncoll.insert_many([{\"value\": Decimal128(str(i))} for i in range(200)])\ndf = find_pandas_all(coll, {})\nprint(df.dtypes)\n# _id bson_PandasObjectId\n# value bson_PandasDecimal128\n```\n\nIn both cases, the underlying values are the BSON class type:\n\n```python\nprint(df[\"value\"][0])\nDecimal128(\"0\")\n```\n\n## Writing Data\n\nWriting data from an Arrow table using PyMongo looks like the following:\n\n```python\ndata = arrow_table.to_pylist()\ndb.collname.insert_many(data)\n```\n\nThe equivalent in PyMongoArrow is:\n\n```python\nfrom pymongoarrow.api import write\n\nwrite(db.collname, arrow_table)\n```\n\nAs of PyMongoArrow 1.0, the main advantage to using the `write` function is that it iterates over the arrow table, data frame, or numpy array, and doesn't convert the entire object to a list.\n\n## Benchmarks\n\nThe following measurements were taken with PyMongoArrow version 1.0 and PyMongo version 4.4. For insertions, the library performs about the same as when using conventional PyMongo, and uses the same amount of memory.\n\n```none\nProfileInsertSmall.peakmem_insert_conventional 107M\nProfileInsertSmall.peakmem_insert_arrow 108M\nProfileInsertSmall.time_insert_conventional 202\u00b10.8ms\nProfileInsertSmall.time_insert_arrow 181\u00b10.4ms\n\nProfileInsertLarge.peakmem_insert_arrow 127M\nProfileInsertLarge.peakmem_insert_conventional 125M\nProfileInsertLarge.time_insert_arrow 425\u00b11ms\nProfileInsertLarge.time_insert_conventional 440\u00b11ms\n```\n\nFor reads, the library is slower for small documents and nested documents, but faster for large documents. It uses less memory in all cases.\n\n```none\nProfileReadSmall.peakmem_conventional_arrow 85.8M\nProfileReadSmall.peakmem_to_arrow 83.1M\nProfileReadSmall.time_conventional_arrow 38.1\u00b10.3ms\nProfileReadSmall.time_to_arrow 60.8\u00b10.3ms\n\nProfileReadLarge.peakmem_conventional_arrow 138M\nProfileReadLarge.peakmem_to_arrow 106M\nProfileReadLarge.time_conventional_ndarray 243\u00b120ms\nProfileReadLarge.time_to_arrow 186\u00b10.8ms\n\nProfileReadDocument.peakmem_conventional_arrow 209M\nProfileReadDocument.peakmem_to_arrow 152M\nProfileReadDocument.time_conventional_arrow 865\u00b17ms\nProfileReadDocument.time_to_arrow 937\u00b11ms\n```"} -{"chunk_id": "69afb7ec9a04e6cf6616701e-0", "page_id": "69afb7ec9a04e6cf6616701e", "source_name": "pymongo-arrow", "product_name": "PyMongo Arrow Driver", "url": "https://mongodb.com/docs/languages/python/pymongo-arrow-driver/current/get-started", "title": "Get Started with PyMongoArrow", "text": "# Get Started with PyMongoArrow\n\nThis tutorial is intended as an introduction to working with **PyMongoArrow**. The tutorial assumes the reader is familiar with basic PyMongo and MongoDB concepts.\n\n## Install PyMongoArrow\n\nFor information about compatibility with PyMongo, PyArrow, and your operating system, see the Compatibility page.\n\nYou can install **PyMongoArrow** in three ways:\n\n- Pip\n\n- Conda\n\n- From source\n\n### Install with Pip\n\nWe recommend using pip to install PyMongoArrow on all platforms. PyMongoArrow is available on PyPI.\n\n```sh\n$ python -m pip install pymongoarrow\n```\n\nTo get a specific version of pymongo:\n\n```sh\n$ python -m pip install pymongoarrow==1.14.0\n```\n\nTo upgrade using pip:\n\n```sh\n$ python -m pip install --upgrade pymongoarrow\n```\n\nIf the install fails because of an error, such as `ValueError: Could not find \"libbson-1.0\" library`, it means that `pip` failed to find a suitable wheel for your platform. We recommend first ensuring you have `pip` >= 20.3 installed. To upgrade `pip`, run the following shell command:\n\n```python\n$ python -m pip install --upgrade pip\n```\n\nYou can then try to re-install `pymongoarrow`.\n\nWe currently distribute wheels for macOS, Windows, and Linux on x86_64 architectures.\n\nTo test your installation, run the following code in the Python shell. If PyMongoArrow is correctly installed, you won't see any errors or exceptions.\n\n```python\n>>> import pymongoarrow as pma\n```\n\n### Install with Conda\n\nPyMongoArrow is available for `conda` users by running the following shell command:\n\n```python\n$ conda install --channel conda-forge pymongoarrow\n```\n\nTo test your installation, run the following code in the Python shell. If PyMongoArrow is correctly installed, you won't see any errors or exceptions.\n\n```python\n>>> import pymongoarrow as pma\n```\n\n### Install from Source\n\nIf you can't use the above options to install `pymongoarrow` on your system, you can install from source. To learn how, see the Contributing Guide.\n\n#### Dependencies\n\nInstalling from source on Linux requires the following dependencies:\n\n- GCC version 12 or later\n\n- CMake\n\n- pkg-config\n\nTo use PyMongoArrow with a PyMongo feature that requires an optional dependency, you must set the dependency as an option when you install PyMongo.\n\nTo learn more about PyMongo's optional dependencies, see Dependencies in the PyMongo documentation.\n\nFor example, to use PyMongoArrow with Client-Side Field Level Encryption, you must install PyMongo with the `encryption` option in addition to installing PyMongoArrow:\n\n```sh\n$ python -m pip install 'pymongo[encryption]' pymongoarrow\n```\n\nApplications using PyMongoArrow APIs that return query result-sets as `pandas.DataFrame` instances, such as `~pymongoarrow.api.find_pandas_all()`, must also have `pandas` installed:\n\n```sh\n$ python -m pip install pandas\n```\n\nTo test your installation, run the following code in the Python shell. If PyMongoArrow is correctly installed, you won't see any errors or exceptions.\n\n```python\n>>> import pymongoarrow as pma\n```\n\n## Install MongoDB\n\nThis tutorial assumes that a MongoDB instance is running on the default host and port. After you have downloaded and installed MongoDB, you can start it as shown in the following code example:\n\n```bash\n$ mongod\n```\n\n## Insert Sample Data\n\nRun the following code to insert sample data into your cluster:\n\n```python\nfrom datetime import datetime\nfrom pymongo import MongoClient\nclient = MongoClient()\nclient.db.data.insert_many([\n {'_id': 1, 'amount': 21, 'last_updated': datetime(2020, 12, 10, 1, 3, 1), 'account': {'name': 'Customer1', 'account_number': 1}, 'txns': ['A']},\n {'_id': 2, 'amount': 16, 'last_updated': datetime(2020, 7, 23, 6, 7, 11), 'account': {'name': 'Customer2', 'account_number': 2}, 'txns': ['A', 'B']},\n {'_id': 3, 'amount': 3, 'last_updated': datetime(2021, 3, 10, 18, 43, 9), 'account': {'name': 'Customer3', 'account_number': 3}, 'txns': ['A', 'B', 'C']},\n {'_id': 4, 'amount': 0, 'last_updated': datetime(2021, 2, 25, 3, 50, 31), 'account': {'name': 'Customer4', 'account_number': 4}, 'txns': ['A', 'B', 'C', 'D']}])\n```\n\n## Define the Schema\n\nPyMongoArrow relies on a data schema to marshall query result sets into tabular form. If you don't provide this schema, PyMongoArrow infers one from the data. You can define the schema by creating a `Schema` object and mapping the field names to type-specifiers, as shown in the following example:\n\n```python\nfrom pymongoarrow.api import Schema\nschema = Schema({'_id': int, 'amount': float, 'last_updated': datetime})\n```\n\nMongoDB uses embedded documents to represent nested data. PyMongoArrow offers first-class support for these documents:\n\n```python\nschema = Schema({'_id': int, 'amount': float, 'account': { 'name': str, 'account_number': int}})\n```\n\nPyMongoArrow also supports lists and nested lists:\n\n```python\nfrom pyarrow import list_, string\nschema = Schema({'txns': list_(string())})\npolars_df = client.db.data.find_polars_all({'amount': {'$gt': 0}}, schema=schema)\n```\n\nPyMongoArrow includes multiple permissible type-identifiers for each supported BSON type. For a full list of these data types and their associated type-identifiers, see Data Types.\n\n## Find Operations\n\nThe following code example shows how to load all records that have a non-zero value for the `amount` field as a `pandas.DataFrame` object:\n\n```python\ndf = client.db.data.find_pandas_all({'amount': {'$gt': 0}}, schema=schema)\n```\n\nYou can also load the same result set as a `pyarrow.Table` instance:\n\n```python\narrow_table = client.db.data.find_arrow_all({'amount': {'$gt': 0}}, schema=schema)\n```\n\nOr as a `polars.DataFrame` instance:\n\n```python\ndf = client.db.data.find_polars_all({'amount': {'$gt': 0}}, schema=schema)\n```\n\nOr as a NumPy `arrays` object:\n\n```python\nndarrays = client.db.data.find_numpy_all({'amount': {'$gt': 0}}, schema=schema)\n```\n\nWhen using NumPy, the return value is a dictionary where the keys are field names and the values are the corresponding `numpy.ndarray` instances.\n\nIn all of the preceding examples, you can omit the schema as shown in the following example:\n\n```python\narrow_table = client.db.data.find_arrow_all({'amount': {'$gt': 0}})\n```\n\nIf you omit the schema, PyMongoArrow tries to automatically apply a schema based on the data contained in the first batch.\n\n## Aggregate Operations\n\nRunning an aggregate operation is similar to running a find operation, but it takes a sequence of operations to perform.\n\nThe following is a simple example of the `aggregate_pandas_all()` method that outputs a new dataframe in which all `_id` values are grouped together and their `amount` values summed:\n\n```python\ndf = client.db.data.aggregate_pandas_all([{'$group': {'_id': None, 'total_amount': { '$sum': '$amount' }}}])\n```\n\nYou can also run aggregate operations on embedded documents. The following example unwinds values in the nested `txn` field, counts the number of each value, then returns the results as a list of NumPy `ndarray` objects, sorted in descending order:\n\n```python\npipeline = [{'$unwind': '$txns'}, {'$group': {'_id': '$txns', 'count': {'$sum': 1}}}, {'$sort': {\"count\": -1}}]\nndarrays = client.db.data.aggregate_numpy_all(pipeline)\n```\n\nFor more information about aggregation pipelines, see the MongoDB Server documentation.\n\n## Writing to MongoDB\n\nYou can use the `write()` method to write objects of the following types to MongoDB:\n\n- Arrow `Table`\n\n- Pandas `DataFrame`\n\n- NumPy `ndarray`\n\n- Polars `DataFrame`\n\n```python\nfrom pymongoarrow.api import write\nfrom pymongo import MongoClient\ncoll = MongoClient().db.my_collection\nwrite(coll, df)\nwrite(coll, arrow_table)\nwrite(coll, ndarrays)\n```\n\nNumPy arrays are specified as `dict[str, ndarray]`."} -{"chunk_id": "69afb7ec9a04e6cf6616701e-1", "page_id": "69afb7ec9a04e6cf6616701e", "source_name": "pymongo-arrow", "product_name": "PyMongo Arrow Driver", "url": "https://mongodb.com/docs/languages/python/pymongo-arrow-driver/current/get-started", "title": "Get Started with PyMongoArrow", "text": "### Ignore Empty Values\n\nThe `write()` method optionally accepts a boolean `exclude_none` parameter. If you set this parameter to `True`, the driver doesn't write empty values to the database. If you set this parameter to `False` or leave it blank, the driver writes `None` for each empty field.\n\nThe code in the following example writes an Arrow `Table` to MongoDB twice. One of the values in the `'b'` field is set to `None`.\n\nThe first call to the `write()` method omits the `exclude_none` parameter, so it defaults to `False`. All values in the `Table`, including `None`, are written to the database. The second call to the `write()` method sets `exclude_none` to `True`, so the empty value in the `'b'` field is ignored.\n\n```python\ndata_a = [1, 2, 3]\ndata_b = [1, None, 3]\n\ndata = Table.from_pydict(\n {\n \"a\": data_a,\n \"b\": data_b,\n },\n)\n\ncoll.drop()\nwrite(coll, data)\ncol_data = list(coll.find({}))\n\ncoll.drop()\nwrite(coll, data, exclude_none=True)\ncol_data_exclude_none = list(coll.find({}))\n\nprint(col_data)\n\nprint(col_data_exclude_none)\n```\n\n```json\n{'_id': ObjectId('...'), 'a': 1, 'b': 1}\n{'_id': ObjectId('...'), 'a': 2, 'b': None}\n{'_id': ObjectId('...'), 'a': 3, 'b': 3}\n\n{'_id': ObjectId('...'), 'a': 1, 'b': 1}\n{'_id': ObjectId('...'), 'a': 2}\n{'_id': ObjectId('...'), 'a': 3, 'b': 3}\n```\n\n## Writing to Other Formats\n\nOnce result sets have been loaded, you can then write them to any format that the package supports.\n\nFor example, to write the table referenced by the variable `arrow_table` to a Parquet file named `example.parquet`, run the following code:\n\n```python\nimport pyarrow.parquet as pq\npq.write_table(arrow_table, 'example.parquet')\n```\n\nPandas also supports writing `DataFrame` instances to a variety of formats, including CSV and HDF. To write the data frame referenced by the variable `df` to a CSV file named `out.csv`, run the following code:\n\n```python\ndf.to_csv('out.csv', index=False)\n```\n\nThe Polars API is a mix of the two preceding examples:\n\n```python\nimport polars as pl\ndf = pl.DataFrame({\"foo\": [1, 2, 3, 4, 5]})\ndf.write_parquet('example.parquet')\n```\n\nNested data is supported for parquet read and write operations, but is not well supported by Arrow or Pandas for CSV read and write operations.\n\n## Extending PyMongo\n\nThe `pymongoarrow.monkey` module provides an interface to patch PyMongo in place, and add PyMongoArrow functionality directly to `Collection` instances:\n\n```python\nfrom pymongoarrow.monkey import patch_all\npatch_all()\n```\n\nAfter you run the `monkey.patch_all()` method, new instances of the `Collection` class will contain the PyMongoArrow APIs-- for example, the `pymongoarrow.api.find_pandas_all()` method.\n\nYou can also use any of the PyMongoArrow APIs by importing them from the `pymongoarrow.api` module. If you do, you must pass the instance of the `Collection` on which the operation is to be run as the first argument when calling the API method.\n\n## Troubleshooting\n\n### Why Do I Get an `undefined symbol` Error When Installing PyMongoArrow from Source?\n\nPyMongoArrow raises this error when GCC version 12 or later is not installed in your Linux environment. If you experience this error, ensure that you have GCC version 12 or later installed.\n\n### Why Do I Get `ModuleNotFoundError: No module named 'polars'` When Using PyMongoArrow?\n\nPyMongoArrow raises this error when an application attempts to use a PyMongoArrow API that returns query result-sets as a `polars.DataFrame` instance without having `polars` installed in the Python environment. Since `polars` is not a direct dependency of PyMongoArrow, it's not automatically installed when you install `pymongoarrow`. You must install `polars` separately with the following shell command:\n\n```sh\n$ python -m pip install polars\n```"} -{"chunk_id": "69afb7ec9a04e6cf66167042-0", "page_id": "69afb7ec9a04e6cf66167042", "source_name": "pymongo-arrow", "product_name": "PyMongo Arrow Driver", "url": "https://mongodb.com/docs/languages/python/pymongo-arrow-driver/current/schemas", "title": "Schema Examples", "text": "# Schema Examples\n\nThis guide shows examples of how to use PyMongoArrow schemas in common situations.\n\n## Nested Data with Schema\n\nWhen performing aggregate or find operations, you can provide a schema for nested data by using the `struct` object. There can be conflicting names in sub-documents compared to their parent documents.\n\n```python\n>>> from pymongo import MongoClient\n... from pymongoarrow.api import Schema, find_arrow_all\n... from pyarrow import struct, field, int32\n... coll = MongoClient().db.coll\n... coll.insert_many(\n... [\n... {\"start\": \"string\", \"prop\": {\"name\": \"foo\", \"start\": 0}},\n... {\"start\": \"string\", \"prop\": {\"name\": \"bar\", \"start\": 10}},\n... ]\n... )\n... arrow_table = find_arrow_all(\n... coll, {}, schema=Schema({\"start\": str, \"prop\": struct([field(\"start\", int32())])})\n... )\n... print(arrow_table)\npyarrow.Table\nstart: string\nprop: struct\n child 0, start: int32\n----\nstart: [[\"string\",\"string\"]]\nprop: [\n -- is_valid: all not null\n -- child 0 type: int32\n[0,10]]\n```\n\nYou can do the same thing when using Pandas and NumPy:\n\n```python\n>>> df = find_pandas_all(\n... coll, {}, schema=Schema({\"start\": str, \"prop\": struct([field(\"start\", int32())])})\n... )\n... print(df)\n start prop\n0 string {'start': 0}\n1 string {'start': 10}\n```\n\n## Nested Data with Projections\n\nYou can also use projections to flatten the data before passing it to PyMongoArrow. The following example illustrates how to do this by using a very simple nested document structure:\n\n```python\n>>> df = find_pandas_all(\n... coll,\n... {\n... \"prop.start\": {\n... \"$gte\": 0,\n... \"$lte\": 10,\n... }\n... },\n... projection={\"propName\": \"$prop.name\", \"propStart\": \"$prop.start\"},\n... schema=Schema({\"_id\": ObjectIdType(), \"propStart\": int, \"propName\": str}),\n... )\n... print(df)\n _id propStart propName\n0 b'c\\xec2\\x98R(\\xc9\\x1e@#\\xcc\\xbb' 0 foo\n1 b'c\\xec2\\x98R(\\xc9\\x1e@#\\xcc\\xbc' 10 bar\n```\n\nWhen performing an aggregate operation, you can flatten the fields by using the `$project` stage, as shown in the following example:\n\n```pycon\n>>> df = aggregate_pandas_all(\n... coll,\n... pipeline=[\n... {\"$match\": {\"prop.start\": {\"$gte\": 0, \"$lte\": 10}}},\n... {\n... \"$project\": {\n... \"propStart\": \"$prop.start\",\n... \"propName\": \"$prop.name\",\n... }\n... },\n... ],\n... )\n```"} -{"chunk_id": "69afb7ec9a04e6cf66167023-0", "page_id": "69afb7ec9a04e6cf66167023", "source_name": "pymongo-arrow", "product_name": "PyMongo Arrow Driver", "url": "https://mongodb.com/docs/languages/python/pymongo-arrow-driver/current/issues-and-help", "title": "Issues & Help", "text": "# Issues & Help\n\nIn this guide, you can learn how to report issues, suggest new features, and contribute to PyMongoArrow.\n\nYou can find support for general questions by using the MongoDB Stack Overflow tag or the MongoDB Reddit community.\n\n## Bugs and Feature Requests\n\nTo report a bug or to request a new feature in PyMongoArrow, please open an issue in JIRA, our issue management tool, using the following steps:\n\n1. Create a JIRA account.\n\n2. Navigate to the ARROW project.\n\n3. Click Create Issue. Please provide as much information as possible about the issue and the steps to reproduce it.\n\nBug reports in JIRA for the ARROW project can be viewed by everyone.\n\nIf you identify a security vulnerability in the library or in any other MongoDB project, please report it according to the instructions found in Create a Vulnerability Report.\n\n## Pull Requests\n\nWe are happy to accept contributions to help improve the library. To contribute, open a pull request against the PyMongoArrow GitHub repository. We will guide user contributions to ensure that they meet the standards of the codebase."} -{"chunk_id": "69afb7ed9a04e6cf66167066-0", "page_id": "69afb7ed9a04e6cf66167066", "source_name": "pymongo-arrow", "product_name": "PyMongo Arrow Driver", "url": "https://mongodb.com/docs/languages/python/pymongo-arrow-driver/current/data-types", "title": "Data Types", "text": "# Data Types\n\nPyMongoArrow supports a majority of the BSON types. Because Arrow and Polars provide first-class support for Lists and Structs, this includes embedded arrays and documents.\n\nSupport for additional types will be added in subsequent releases.\n\nFor more information about BSON types, see the BSON specification.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nBSON Type\n\n\nType Identifiers\n\n
\nString\n\n\n- `py.str`\n\n- Instance of `pyarrow.string`\n\n
\nEmbedded document\n\n\n- `py.dict`\n\n- Instance of `pyarrow.struct`\n\n
\nEmbedded array\n\n\n- Instance of `pyarrow.list_`\n\n
\nObjectId\n\n\n- `py.bytes`\n\n- `bson.ObjectId`\n\n- Instance of `pymongoarrow.types.ObjectIdType`\n\n- Instance of `pymongoarrow.pandas_types.PandasObjectId`\n\n
\nDecimal128\n\n\n- `bson.Decimal128`\n\n- Instance of `pymongoarrow.types.Decimal128Type`\n\n- Instance of `pymongoarrow.pandas_types.PandasDecimal128`\n\n- Instance of `pyarrow.Decimal128`\n\n
\nBoolean\n\n\n- `~py.bool`\n\n- Instance of `~pyarrow.bool_`\n\n
\n64-bit binary floating point\n\n\n- `py.float`\n\n- Instance of `pyarrow.float64`\n\n
\n32-bit integer\n\n\n- Instance of `pyarrow.int32`\n\n
\n64-bit integer\n\n\n- `~py.int`\n\n- `bson.int64.Int64`\n\n- Instance of `pyarrow.int64`\n\n
\nUTC datetime\n\n\n- `py.datetime.datetime`\n\n- Instance of `~pyarrow.timestamp` with `ms` resolution\n\n
\nBinary data\n\n\n- `bson.Binary`\n\n- Instance of `pymongoarrow.types.BinaryType`\n\n- Instance of `pymongoarrow.pandas_types.PandasBinary`\n\n
\nJavaScript code\n\n\n- `bson.Code`\n\n- Instance of `pymongoarrow.types.CodeType`\n\n- Instance of `pymongoarrow.pandas_types.PandasCode`\n\n
\nnull\n\n\n- Instance of `pyarrow.null`\n\n
PyMongoArrow supports `Decimal128` on only little-endian systems. On big-endian systems, it uses `null` instead.\n\nUse type identifiers to specify that a field is of a certain type during `pymongoarrow.api.Schema` declaration. For example, if your data has fields `f1` and `f2` bearing types 32-bit integer and UTC datetime, and an `_id` that is an `ObjectId`, you can define your schema as follows:\n\n```python\nschema = Schema({\n '_id': ObjectId,\n 'f1': pyarrow.int32(),\n 'f2': pyarrow.timestamp('ms')\n})\n```\n\nUnsupported data types in a schema cause a `ValueError` identifying the field and its data type.\n\n## Embedded Array Considerations\n\nThe schema used for an embedded array must use the `pyarrow.list_()` type, to specify the type of the array elements. For example,\n\n```python\nfrom pyarrow import list_, float64\nschema = Schema({'_id': ObjectId,\n 'location': {'coordinates': list_(float64())}\n})\n```\n\n## Extension Types\n\nPyMongoArrow implements the `ObjectId`, `Decimal128`, `Binary data`, and `JavaScript code` types as extension types for PyArrow and Pandas. For arrow tables, values of these types have the appropriate `pymongoarrow` extension type, such as `pymongoarrow.types.ObjectIdType`. You can obtain the appropriate `bson` Python object by using the `.as_py()` method, or by calling `.to_pylist()` on the table.\n\n```python\n>>> from pymongo import MongoClient\n>>> from bson import ObjectId\n>>> from pymongoarrow.api import find_arrow_all\n>>> client = MongoClient()\n>>> coll = client.test.test\n>>> coll.insert_many([{\"_id\": ObjectId(), \"foo\": 100}, {\"_id\": ObjectId(), \"foo\": 200}])\n\n>>> table = find_arrow_all(coll, {})\n>>> table\npyarrow.Table\n_id: extension>\nfoo: int32\n----\n_id: [[64408B0D5AC9E208AF220142,64408B0D5AC9E208AF220143]]\nfoo: [[100,200]]\n>>> table[\"_id\"][0]\n\n>>> table[\"_id\"][0].as_py()\nObjectId('64408b0d5ac9e208af220142')\n>>> table.to_pylist()\n[{'_id': ObjectId('64408b0d5ac9e208af220142'), 'foo': 100},\n {'_id': ObjectId('64408b0d5ac9e208af220143'), 'foo': 200}]\n```\n\nWhen converting to pandas, the extension type columns have an appropriate `pymongoarrow` extension type, such as `pymongoarrow.pandas_types.PandasDecimal128`. The value of the element in the dataframe is the appropriate `bson` type.\n\n```python\n>>> from pymongo import MongoClient\n>>> from bson import Decimal128\n>>> from pymongoarrow.api import find_pandas_all\n>>> client = MongoClient()\n>>> coll = client.test.test\n>>> coll.insert_many([{\"foo\": Decimal128(\"0.1\")}, {\"foo\": Decimal128(\"0.1\")}])\n\n>>> df = find_pandas_all(coll, {})\n>>> df\n _id foo\n0 64408bf65ac9e208af220144 0.1\n1 64408bf65ac9e208af220145 0.1\n>>> df[\"foo\"].dtype\n\n>>> df[\"foo\"][0]\nDecimal128('0.1')\n>>> df[\"_id\"][0]\nObjectId('64408bf65ac9e208af220144')\n```\n\nPolars does not support Extension Types.\n\n## Null Values and Conversion to Pandas DataFrames\n\nIn Arrow and Polars, all Arrays are nullable. Pandas has experimental nullable data types, such as `Int64`. You can instruct Arrow to create a pandas DataFrame using nullable dtypes with the following Apache documentation code.\n\n```pycon\n>>> dtype_mapping = {\n... pa.int8(): pd.Int8Dtype(),\n... pa.int16(): pd.Int16Dtype(),\n... pa.int32(): pd.Int32Dtype(),\n... pa.int64(): pd.Int64Dtype(),\n... pa.uint8(): pd.UInt8Dtype(),\n... pa.uint16(): pd.UInt16Dtype(),\n... pa.uint32(): pd.UInt32Dtype(),\n... pa.uint64(): pd.UInt64Dtype(),\n... pa.bool_(): pd.BooleanDtype(),\n... pa.float32(): pd.Float32Dtype(),\n... pa.float64(): pd.Float64Dtype(),\n... pa.string(): pd.StringDtype(),\n... }\n... df = arrow_table.to_pandas(\n... types_mapper=dtype_mapping.get, split_blocks=True, self_destruct=True\n... )\n... del arrow_table\n```\n\nDefining a conversion for `pa.string()` also converts Arrow strings to NumPy strings, and not objects.\n\n## Nested Extension Types\n\nPending ARROW-179, extension types, such as `ObjectId`, that appear in nested documents are not converted to the corresponding PyMongoArrow extension type, but instead have the raw Arrow type, `FixedSizeBinaryType(fixed_size_binary[12])`.\n\nThese values can be consumed as-is, or converted individually to the desired extension type, such as `_id = out['nested'][0]['_id'].cast(ObjectIdType())`."} -{"chunk_id": "69afb7ed9a04e6cf66167066-1", "page_id": "69afb7ed9a04e6cf66167066", "source_name": "pymongo-arrow", "product_name": "PyMongo Arrow Driver", "url": "https://mongodb.com/docs/languages/python/pymongo-arrow-driver/current/data-types", "title": "Data Types", "text": "## Strict Type Adherence\n\nWhen you provide a schema for data in PyMongoArrow v1.9 and later, the driver enforces strict type adherence. If a field value had a type mismatch with the schema's type for that field, the driver raises a `TypeError`. `NaN` is a valid type for all fields.\n\nTo suppress `TypeErrors` and silently convert type mismatches to `NaN`, pass the `allow_invalid=True` argument to your `pymongoarrow` API call. The following example passes `allow_invalid=True` to the `pymongoarrow` API call to convert mismatches in sample data to `NaN`:\n\n```python\n>>> from pymongoarrow.monkey import patch_all\n>>> from pymongoarrow.api import Schema, find_arrow_all\n>>> from pyarrow import int32, string\n>>> from pymongo import MongoClient\n>>> patch_all()\n>>> client = MongoClient()\n>>> coll = client.test.test\n>>> sample_data = [\n... {\"name\": \"Alice\", \"age\": 35, \"city\": \"Chicago\"},\n... {\"name\": {\"first\": \"Bob\", \"last\": \"Smith\"}, \"age\": 28, \"city\": \"Boston\"},\n... {\"name\": \"Charlie\", \"age\": \"thirty-two\", \"city\": \"Seattle\"}\n... ]\n>>> coll.insert_many(sample_data)\n>>> schema = Schema({\n... \"name\": string(),\n... \"age\": int32(),\n... \"city\": string()\n... })\n>>> result = find_arrow_all(collection, {}, schema=schema, allow_invalid=True)\n```"} -{"chunk_id": "69afb7ec9a04e6cf66167036-0", "page_id": "69afb7ec9a04e6cf66167036", "source_name": "pymongo-arrow", "product_name": "PyMongo Arrow Driver", "url": "https://mongodb.com/docs/languages/python/pymongo-arrow-driver/current/reference/release-notes", "title": "Release Notes", "text": "# Release Notes\n\n## Changes in Version 1.14.0\n\nPyMongoArrow v1.14.0 drops support for PyArrow 23.0.\n\n- Adds support for PyArrow 24.0\n\n- Fixes an issue where running `find_all` in parallel on an empty result set raised an error\n\nTo learn more about this release, see the 1.14.0 Release Notes on GitHub.\n\n## Changes in Version 1.13.0\n\n- Adds `ExtensionType`, which allows you to create custom types subclasses for``ObjectId``, `Code`, or `Decimal128`.\n\n- Fixes an `OverflowError` bug for `Int32` fields that occurred due to schema inferences when a schema was not provided.\n\n- Adds support for parallel batch processing by using an optional `parallelism` argument for the `find_arrow_all()`, `aggregate_arrow_all()`, `find_numpy_all()`, and `aggregate_numpy_all()` methods.\n\n## Changes in Version 1.12.0\n\n- Adds support for PyArrow 23.0.\n\n- Adds support for Pandas 3.0.\n\n## Changes in Version 1.11.0\n\n- Adds support for PyArrow 22.0.\n\n- Adds support for Python 3.14 and 3.14 free-threaded on Linux and MacOS.\n\n- Drops support for Python 3.9 and Python 3.13 free-threaded.\n\n- Extends, rather than replaces, the `TypeRegistry` in `write()` functions to preserve custom codecs.\n\n## Changes in Version 1.10.0\n\n- Adds support for PyArrow 21.0\n\n- Adds support for conversion of unsupported Arrow data types in `write` functions with `auto_convert` parameters\n\n- Makes `pandas` an optional dependency\n\n- Adds support for free-threaded Python 3.13 on Windows\n\n- Adds support for building against `libbson 2.0`\n\n## Changes in Version 1.9.0\n\n- Adds support for strict type adherence for data if a schema is provided. If a field value contains a type mismatch with the schema's type for that field, a TypeError will be raised. Note that `NaN` is a valid type for all fields. To suppress these errors and instead silently convert such mismatches to `NaN`, pass the `allow_invalid=True` argument to your `pymongoarrow` API call. For an example of passing the `allow_invalid=True` argument to your `pymongoarrow` API call, see the Strict Type Adherence section in the Data Types guide.\n\n## Changes in Version 1.8.0\n\n- Adds support for PyArrow 20.0\n\n- Adds support for free-threaded Python on Linux and macOS\n\n## Changes in Version 1.7.0\n\n- Adds support for PyArrow 19.0\n\n- Adds support for the `pyarrow.Decimal128` data type\n\n## Changes in Version 1.6.0\n\nThis version of PyMongoArrow removes support for Python v3.8.\n\n- Adds support for PyArrow 18.0 and Python 3.13\n\n- Fixes an issue that caused data loss on documents with nested data containing null or extension types\n\n- Adds support for PyArrow's `null` type\n\n- Checks the status of all PyArrow C API calls to prevent segmentation faults\n\n## Changes in Version 1.5.0\n\n- Adds support for PyArrow 17.0\n\n- Adds support for nested `ObjectId` values in Polars conversions\n\n## Changes in Version 1.4.0\n\n- Added support for PyArrow 16.0.\n\n- Added a top-level Contributing guide.\n\n- Added an optional `bool` flag to the `write()` function to skip writing null fields.\n\n- Migrated documentation to the MongoDB Docs site.\n\n## Changes in Version 1.3.0\n\n- Support for Polars\n\n- Support for PyArrow.DataTypes: large_list, large_string, date32, date64\n\n## Changes in Version 1.2.0\n\n- Support for PyArrow 14.0.\n\n- Support for Python 3.12.\n\n## Changes in Version 1.1.0\n\n- Support for PyArrow 13.0.\n\n- Revert bug fix for nested extension objects in auto schema, since it caused a performance regression.\n\n## Changes in Version 1.0.2\n\n- Bug fix for projection on nested fields.\n\n- Bug fix for nested extension objects in auto schema.\n\n## Changes in Version 1.0.1\n\n- Support BSON binary type.\n\n- Support BSON Decimal128 type.\n\n- Support Pandas 2.0 and Pandas extension types.\n\n- Support PyArrow 12.0.\n\n## Changes in Version 0.7.0\n\n- Added support for BSON Embedded Document type.\n\n- Added support for BSON Array type.\n\n- Support PyArrow 11.0.\n\n## Changes in Version 0.6.3\n\n- Added wheels for Linux AArch64 and Python 3.11.\n\n- Fixed handling of time zones in schema auto-discovery.\n\n## Changes in Version 0.6.2\n\n- Fixed `ImportError` on Windows by building `libbson` in \"Release\" mode.\n\n- Support PyArrow 10.0.\n\n## Changes in Version 0.5.1\n\n- Fixed auto-discovery of schemas for aggregation and `numpy` methods.\n\n- Added documentation for auto-discovery of schemas.\n\n## Changes in Version 0.5.0\n\n- Support auto-discovery of schemas in `find/aggregate_*_all` methods. If the schema is not given, it will be inferred using the first document in the result set.\n\n- Support PyArrow 9.0.\n\n- Improve error message for lib ImportError.\n\n## Changes in Version 0.4.0\n\n- Support for `Decimal128` type.\n\n- Support for macOS arm64 architecture on Python 3.9+.\n\n- Support for writing tabular datasets (materialized as PyArrow Tables, Pandas DataFrames, or NumPy arrays) to MongoDB by using the `write()` function. For more information, see the Get Started with PyMongoArrow guide for more info.\n\n## Changes in Version 0.3.0\n\n- Support for `PyArrow` 7.0.\n\n- Support for the `ObjectId` type.\n\n- Improve error message when schema contains an unsupported type.\n\n- Add support for BSON string type.\n\n- Add support for BSON boolean type.\n\n- Upgraded to bundle libbson 1.21.1. If installing from source, the minimum supported `libbson` version is now 1.21.0.\n\n- Dropped Python 3.6 support (it was dropped in `PyArrow` 7.0).\n\n## Changes in Version 0.2.0\n\n- Support for PyMongo 4.0.\n\n- Support for Python 3.10.\n\n- Support for Windows.\n\n- The `find_arrow_all()` method now accepts a user-provided `projection`.\n\n- The `find_arrow_all()` method now accepts a `session` object.\n\n- Note: PyMongoArrow now requires `pyarrow` v6.0.x.\n\n## Changes in Version 0.1.1\n\n- Fixed a bug that caused Linux wheels to be created without the appropriate `manylinux` platform tags.\n\n## Changes in Version 0.1.0\n\n- Support for efficiently converting find and aggregate query result sets into Arrow/Pandas/Numpy data structures.\n\n- Support for patching PyMongo's APIs by using the `monkey.patch_all()` method.\n\n- Support for loading the following BSON types:\n\n - 64-bit binary floating point\n\n - 32-bit integer\n\n - 64-bit integer\n\n - Timestamp"} -{"chunk_id": "68a95c2b5e79d242619df72c-0", "page_id": "68a95c2b5e79d242619df72c", "source_name": "ruby-driver", "product_name": "Ruby Driver", "url": "https://mongodb.com/docs/ruby-driver/current/vector-search", "title": "Run a MongoDB Vector Search Query", "text": "# Run a MongoDB Vector Search Query\n\n## Overview\n\nIn this guide, you can learn how to perform searches on your documents by using the MongoDB Vector Search feature. The Ruby driver allows you to perform MongoDB Vector Search queries by using the aggregation framework. To learn more about performing aggregations, see the Transform Your Data with Aggregation guide.\n\nYou can use the MongoDB Vector Search feature only when you connect to MongoDB Atlas clusters. This feature is not available for self-managed deployments.\n\nTo learn more about MongoDB Vector Search, see the MongoDB Vector Search Overview in the Atlas documentation.\n\nTo perform advanced full-text search on your documents, you can use the MongoDB Search feature. To learn about this feature, see the MongoDB Search Overview.\n\n### MongoDB Vector Search Index\n\nBefore you can perform MongoDB Vector Search queries, you must create a MongoDB Vector Search index on your collection. To learn more about creating this index, see the MongoDB Search and MongoDB Vector Search Indexes guide.\n\n## Vector Search Aggregation Stage\n\nTo create a `$vectorSearch` stage in your aggregation pipeline, perform the following actions:\n\n1. Create a vector to store the pipeline stages.\n\n2. Specify the `$vectorSearch` operator and provide details about the vector search query.\n\nThen, include the stage in an aggregation pipeline and pass the pipeline to the `aggregate` method.\n\nYou must define the following fields in your `$vectorSearch` stage:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nParameter\n\n\nType\n\n\nDescription\n\n
\n`index`\n\n\nstring\n\n\nName of the vector search index\n\n
\n`path`\n\n\nstring\n\n\nField that contains vector embeddings\n\n
\n`queryVector`\n\n\n`BSON::Binary` vector subtype, `BSON::Vector`, or array of numbers\n\n\nVector representation of your query\n\n
\n`limit`\n\n\nnumber\n\n\nNumber of results to return\n\n
\n\n## MongoDB Search Query Examples\n\nIn this section, you can learn how to perform MongoDB Vector Search queries. The examples in this section use sample data from the `sample_mflix.embedded_movies` collection. To learn how to load this sample data, see the Load Data into Atlas tutorial in the Atlas documentation.\n\n### Basic Vector Search Query\n\nThe following code performs a MongoDB Vector Search query on the `plot_embedding` vector field by using a query vector that is a vector embedding of the phrase \"time travel\":\n\n```ruby\nquery_vector = BSON::Binary.from_vector([ -0.0016261312, -0.028070757, ... ], :float32)\n\npipeline = [\n {\n '$vectorSearch' => {\n 'queryVector' => query_vector,\n 'index' => 'vs_idx',\n 'path' => 'plot_embedding',\n 'numCandidates' => 150,\n 'limit' => 5\n }\n },\n {\n '$project' => {\n '_id' => 0,\n 'plot' => 1,\n 'title' => 1,\n }\n }\n]\n\nresults = collection.aggregate(pipeline)\n\nresults.each do |doc|\n puts doc\nend\n```\n\n```none\n{\"plot\"=>\"A reporter, learning of time travelers visiting 20th century disasters, tries to change the history they know by averting upcoming disasters.\", \"title\"=>\"Thrill Seekers\"}\n{\"plot\"=>\"At the age of 21, Tim discovers he can travel in time and change what happens and has happened in his own life. His decision to make his world a better place by getting a girlfriend turns out not to be as easy as you might think.\", \"title\"=>\"About Time\"}\n{\"plot\"=>\"Hoping to alter the events of the past, a 19th century inventor instead travels 800,000 years into the future, where he finds humankind divided into two warring races.\", \"title\"=>\"The Time Machine\"}\n{\"plot\"=>\"An officer for a security agency that regulates time travel, must fend for his life against a shady politician who has a tie to his past.\", \"title\"=>\"Timecop\"}\n{\"plot\"=>\"After using his mother's newly built time machine, Dolf gets stuck involuntary in the year 1212. He ends up in a children's crusade where he confronts his new friends with modern techniques...\", \"title\"=>\"Crusade in Jeans\"}\n```\n\nThe preceding example creates an instance of the `BSON::Binary` type's vector subtype, introduced in `bson` gem v5.1, to serve as the query vector. You can also use an array of numbers as a query vector, but we recommend that you use the `BSON::Binary` vector type to improve storage efficiency. To learn more about this type, see the BSON::Vector section of the BSON guide.\n\n### Vector Search Score\n\nThe following code performs the same query as in the preceding example, but outputs only the `title` field and `vectorSearchScore` meta field, which describes how well the document matches the query vector:\n\n```ruby\nscore_pipeline = [\n {\n '$vectorSearch' => {\n 'queryVector' => query_vector,\n 'index' => 'vs_idx',\n 'path' => 'plot_embedding',\n 'numCandidates' => 150,\n 'limit' => 5\n }\n },\n {\n '$project' => {\n '_id' => 0,\n 'title' => 1,\n 'score' => { '$meta' => 'vectorSearchScore' }\n }\n }\n]\n\nresults = collection.aggregate(score_pipeline)\n\nresults.each do |document|\n puts document\nend\n```\n\n```none\n{\"title\"=>\"Thrill Seekers\", \"score\"=>0.9253387451171875}\n{\"title\"=>\"About Time\", \"score\"=>0.9246978759765625}\n{\"title\"=>\"The Time Machine\", \"score\"=>0.9229583740234375}\n{\"title\"=>\"Timecop\", \"score\"=>0.9228057861328125}\n{\"title\"=>\"Crusade in Jeans\", \"score\"=>0.9222259521484375}\n```\n\n## Vector Search Options\n\nYou can use a `$vectorSearch` stage to perform many types of MongoDB Vector Search queries. Depending on your desired query, you can specify the following options in the stage definition:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nOptional Parameter\n\n\nType\n\n\nDescription\n\n\nDefault Value\n\n
\n`exact`\n\n\nboolean\n\n\nSpecifies whether to run an Exact Nearest Neighbor (`true`) or Approximate Nearest Neighbor (`false`) search\n\n\n`false`\n\n
\n`filter`\n\n\ndocument\n\n\nSpecifies a pre-filter for documents to search on\n\n\nNo filtering\n\n
\n`numCandidates`\n\n\nnumber\n\n\nSpecifies the number of nearest neighbors to use during the search\n\n\nNo limit\n\n
To learn more about these options, see the Fields section of the `$vectorSearch` operator reference in the Atlas documentation.\n\n## Additional Information\n\nTo learn more about the concepts mentioned in this guide, see the following Server manual entries:\n\n- Run Vector Search Queries\n\n- Aggregation Pipeline\n\n- Aggregation Stages\n\nTo learn more about the behavior of the `aggregate` method, see the Transform Your Data with Aggregation guide.\n\n### API Documentation\n\nTo learn more about the methods and types mentioned in this guide, see the following API documentation:\n\n- aggregate"} -{"chunk_id": "68a95c2b5e79d242619df6a4-0", "page_id": "68a95c2b5e79d242619df6a4", "source_name": "ruby-driver", "product_name": "Ruby Driver", "url": "https://mongodb.com/docs/ruby-driver/current/connect/csot", "title": "Limit Server Execution Time", "text": "# Limit Server Execution Time\n\n## Overview\n\nIn this guide, you can learn how to use the `timeout_ms` option to set a timeout for server operations.\n\nWhen you use the Ruby driver to perform a server operation, you can limit the duration allowed for the server to finish the operation. To do so, specify a **client-side operation timeout (CSOT)**. The timeout applies to all steps needed to complete the operation, including server selection, connection checkout, and server-side execution. If the timeout expires before the operation completes, the Ruby driver raises a timeout exception.\n\n## timeout_ms Option\n\nTo specify a timeout when connecting to a MongoDB deployment, set the `timeout_ms` connection option to the timeout length in milliseconds. You can specify a timeout value in the following ways:\n\n- Pass the `timeout_ms` client option to the `Mongo::Client` constructor.\n\n- Pass the `timeoutMS` connection string option as a parameter to your connection string.\n\nSelect from the following tabs to view examples for how to use the `timeout_ms` client option or the `timeoutMS` connection string option to specify a timeout of 30 seconds:\n\n\n\n\n\n```ruby\nuri = \"\"\noptions = { timeout_ms: 30000 }\n\nclient = Mongo::Client.new(uri, options)\n```\n\n\n\n\n\n```ruby\nuri = \"mongodb://:?timeoutMS=30000\"\nclient = Mongo::Client.new(uri)\n```\n\n\n\n\n\nIf you specify the `timeout_ms` option, the driver automatically applies the specified timeout for each server operation.\n\nThe `timeout_ms` connection option unifies most timeout related options. The following timeout options are deprecated:\n\n- `socket_timeout`\n\n- `wait_queue_timeout`\n\n- `wtimeout`\n\n- `max_time_ms`\n\n- `max_commit_time_ms`\n\nThe `timeout_ms` connection option takes precedence over these deprecated timeout options.\n\n### Timeout Inheritance\n\nWhen you specify a `timeout_ms` option, the driver applies the timeout according to the same inheritance behaviors as the other Ruby driver options. The following table describes how the timeout value is inherited at each level:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nLevel\n\n\nInheritance Description\n\n
\nOperation\n\n\nTakes the highest precedence and overrides `timeout_ms` options set at any other level.\n\n
\nTransaction\n\n\nTakes precedence over `timeout_ms` set at the session, collection, database, or client level.\n\n
\nSession\n\n\nApplies to all transactions and operations within that session, unless the option is overridden by options set at those levels.\n\n
\nDatabase\n\n\nApplies to all sessions and operations within that database, unless the option is overridden by options set at those levels.\n\n
\nCollection\n\n\nApplies to all sessions and operations on that collection, unless the option is overridden by options set at those levels.\n\n
\nClient\n\n\nApplies to all databases, collections, sessions, transactions, and operations within that client that do not otherwise specify `timeout_ms`.\n\n
To learn more about overriding the timeout option and setting other options, see the following Overrides section.\n\n## Overrides\n\nYou can specify a `timeout_ms` option at the operation level to override the client-level configuration for a specific operation. This allows you to customize timeouts based on the needs of individual queries.\n\nThe following example demonstrates how an operation-level `timeout_ms` configuration can override a client-level `timeout_ms` configuration:\n\n```ruby\nrequire 'mongo'\n\n# Replace the placeholder with your connection string\nuri = \"\"\n\n# Sets a client-level timeout configuration\noptions = { timeout_ms: 30000 }\n\nMongo::Client.new(uri, options) do |client|\n db = client.use('test-db')\n collection = db[:test-collection]\n\n # Performs a query with an operation-level timeout configuration,\n # overriding the client-level configuration\n docs = collection.find({}, timeout_ms: 10000).to_a\n\n docs.each { |doc| puts doc }\nend\n```\n\n### Transactions\n\nYou can set a timeout for transactions by using the `default_timeout_ms` client option.\n\nWhen you create a new `Mongo::Session` instance to implement a transaction, you can set the `default_timeout_ms` client option to specify the `timeout_ms` values for the following methods:\n\n- commit_transaction\n\n- abort_transaction\n\n- with_transaction\n\n- end_session\n\nIf you do not specify `default_timeout_ms`, the driver uses the `timeout_ms` value set on the parent `Mongo::Client`.\n\nYou cannot override the `timeout_ms` value of the `Mongo::Client` for a call to `start_session`.\n\nYou can only set a timeout value for the start_transaction method by using the `timeout_ms` option.\n\nYou cannot override `default_timeout_ms` by setting the `timeout_ms` option on an operation in a transaction session provided by the `with_transaction` callback, or the driver throws an error.\n\n### Client Encryption\n\nWhen you use Client-Side Field Level Encryption (CSFLE), the driver uses the `timeout_ms` option to limit the time allowed for encryption and decryption operations.\n\nIf you specify the `timeout_ms` option when you construct a `ClientEncryption` instance, it controls the lifetime of all operations performed on that instance. If you do not provide `timeout_ms`, the instance inherits the `timeout_ms` setting from the `Mongo::Client` used in the `ClientEncryption` constructor.\n\nIf you set `timeout_ms` on both the client and directly in `ClientEncryption`, the value provided to `ClientEncryption` takes precedence.\n\n## Cursors\n\nCursors offer configurable timeout settings when using the CSOT feature. You can adjust cursor handling by configuring either the cursor lifetime or cursor iteration mode if needed. To configure the mode, set the `timeoutMode` option to `cursorLifetime`, which is the default, or `iteration`.\n\n### Cursor Lifetime Mode\n\nThe cursor lifetime mode uses `timeout_ms` to limit the entire lifetime of a cursor. In this mode, the initialization of the cursor and all subsequent calls to the cursor methods must complete within the limit specified by the `timeout_ms` option. All documents must be returned within this limit. Otherwise, the cursor's lifetime expires and a timeout error occurs.\n\nWhen you close a cursor by calling the `to_a` or `close` method, the timeout resets to ensure server-side resources are cleaned up.\n\nThe following example shows how to set the `timeout_ms` option to ensure that the cursor is initialized and all documents are retrieved within 10 seconds:\n\n```ruby\ndocs = collection.find({}, timeout_ms:10000).to_a\n```\n\n### Cursor Iteration Mode\n\nThe cursor iteration mode uses the `timeout_ms` option to limit each call to the `try_next` method. The timeout refreshes after each call completes. This is the default mode for all tailable cursors, such as the tailable cursors returned by the `find` method on capped collections or change streams.\n\nThe following code example iterates over documents in a sample collection by using an iterable cursor, and then fetches and logs the `title` information for each movie document:\n\n```ruby\ncursor = collection.find()\n\ncursor.each do |movie|\n puts movie['title']\nend\n```\n\n## API Documentation\n\nTo learn more about using timeouts with the Ruby driver, see the following API documentation:\n\n- Mongo::Client\n\n- Mongo::Session"} -{"chunk_id": "68a95c2b5e79d242619df706-0", "page_id": "68a95c2b5e79d242619df706", "source_name": "ruby-driver", "product_name": "Ruby Driver", "url": "https://mongodb.com/docs/ruby-driver/current/reference/upgrade", "title": "Upgrade Driver Versions", "text": "# Upgrade Driver Versions\n\n## Overview\n\nIn this section, you can identify the changes you must make to your application to upgrade your driver to a new version.\n\nBefore you upgrade, perform the following actions:\n\n- Ensure the new driver version is compatible with the MongoDB Server versions your application connects to and the Ruby versions your application runs on. To view compatibility information, see the Compatibility page.\n\n- Address any breaking changes between the current version of the driver your application is using and your planned upgrade version in the Breaking Changes section.\n\nStarting with version 2.18.0, the driver uses feature flags to manage breaking changes. This feature allows you to opt into breaking changes before the next major version release.\n\n## Versioning\n\nEach Ruby driver release has a version number in the format `MAJOR.MINOR.PATCH`. The Ruby driver uses Semantic Versioning (SemVer), which typically means:\n\n- Breaking changes, enablement of new functionality, and removal of deprecated functionality will only be done in major version releases.\n\n- New functionality will be added using feature flags, which must be enabled via an opt-in configuration change. These feature flags may be added in either major or minor releases.\n\n- Functionality may be marked as deprecated in either major or minor releases, but will not be removed until the next major release, at the earliest.\n\n- Patch version releases will contain only non-breaking fixes and security updates.\n\n## Breaking Changes\n\nA breaking change is a modification in a convention or behavior in a specific version of the driver that might prevent your application from working properly if you don't address it before upgrading.\n\nThe breaking changes in this section are categorized by the driver version that introduced them. When upgrading driver versions, address all the breaking changes between the current and upgrade versions.\n\n### Version 2.26 Breaking Changes\n\nThis driver version introduces the following breaking change:\n\n- Discontinues support for MongoDB Server 4.2. You must upgrade your MongoDB Server deployment to version 4.4 or later.\n\n### Version 2.24 Breaking Changes\n\nThis driver version introduces the following breaking change:\n\n- Discontinues support for MongoDB Server versions 3.6 and 4.0\n\n### Version 2.20 Breaking Changes\n\nThis driver version introduces the following breaking change:\n\n- Discontinues support for Ruby 2.5 and 2.6. Deprecates support for Ruby 2.7 and JRuby 9.2."} -{"chunk_id": "68a95c2b5e79d242619df6d3-0", "page_id": "68a95c2b5e79d242619df6d3", "source_name": "ruby-driver", "product_name": "Ruby Driver", "url": "https://mongodb.com/docs/ruby-driver/current/indexes/atlas-search-index", "title": "MongoDB Search and MongoDB Vector Search Indexes", "text": "# MongoDB Search and MongoDB Vector Search Indexes\n\n## Overview\n\nIn this guide, you can learn how to programmatically manage your MongoDB Search and MongoDB Vector Search indexes by using the Ruby driver.\n\nThe MongoDB Search feature enables you to perform full-text searches on collections hosted on MongoDB. To learn more about MongoDB Search, see the MongoDB Search Overview.\n\nMongoDB Vector Search enables you to perform semantic searches on vector embeddings stored in MongoDB. To learn more about MongoDB Vector Search, see the MongoDB Vector Search Overview.\n\nYou can call the following methods to manage your MongoDB Search and MongoDB Vector Search indexes:\n\n- `search_indexes#create_one`\n\n- `search_indexes#create_many`\n\n- `search_indexes#update_one`\n\n- `search_indexes#drop_one`\n\nThe Ruby driver manages MongoDB Search and MongoDB Vector Search indexes asynchronously. The methods described in the following sections return the server response immediately, but the changes to your Search indexes take place in the background and might not complete until some time later.\n\nThe following sections provide code examples that demonstrate how to use each of the preceding commands.\n\n## Create a Search Index\n\nTo create a single MongoDB Search or MongoDB Vector Search index, use the `search_indexes#create_one` method. To create multiple indexes, use the `search_indexes#create_many` method. Both methods return immediately, while the indexes are asynchronously created in the background.\n\nThe following code example shows how to create a MongoDB Search index by providing an index definition and an optional name for the index:\n\n```ruby\n# Creates indexes on all dynamically indexable fields with a default index name\ncollection.search_indexes.create_one(\n { mappings: { dynamic: true } }\n)\n\n# Creates an index on the specified field with the specified index name\nindex_definition = {\n mappings: {\n dynamic: false,\n fields: {\n fullplot: { type: 'string' }\n }\n }\n}\ncollection.search_indexes.create_one(index_definition, name: 'mySearchIndex')\n```\n\nBy default, the driver creates a MongoDB Search index if you do not pass a `type` parameter. To create a MongoDB Vector Search index, you must set the `type` parameter to `'vectorSearch'` when calling `create_one`.\n\nYou can use `search_indexes#create_many` to create multiple MongoDB Search or MongoDB Vector Search indexes by providing an array of index specifications. Each index specification should include the following components:\n\n- `definition` parameter: Defines the index\n\n- `name` parameter: Specifies the index name\n\n- `type` parameter: Specifies the type of index (`'search'` or `'vectorSearch'`)\n\nThe following code example shows how to create both MongoDB Search and MongoDB Vector Search indexes in one call:\n\n```ruby\nindex_spec_1 = {\n name: 'searchIndex_plot',\n type: 'search',\n definition: {\n mappings: {\n dynamic: false,\n fields: {\n plot: { type: 'string' }\n }\n }\n }\n}\n\nindex_spec_2 = {\n name: 'vsIndex_plot_embedding',\n type: 'vectorSearch',\n definition: {\n fields: [\n {\n type: \"vector\",\n path: \"plot_embedding\",\n numDimensions: 1536,\n similarity: \"dotProduct\"\n }\n ]\n }\n}\n\ncollection.search_indexes.create_many([index_spec_1, index_spec_2])\n```\n\nFor longer index definitions, it is helpful to define the index definitions outside of the method call. To learn more about the syntax of index definitions, see the Review MongoDB Search Index Syntax or the How to Index Fields for MongoDB Vector Search guides in the Atlas manual.\n\n## Update a Search Index\n\nTo update a MongoDB Search or MongoDB Vector Search index, use the `search_indexes#update_one` method.\n\nTo update an index, you must provide a new index definition. You must specify the index you want to update by using either the `name` or `id` of the index. The following code shows how to update a MongoDB Search index:\n\n```ruby\nupdated_definition = {\n mappings: {\n dynamic: false,\n fields: { fullplot: { type: 'string' } }\n }\n}\n\n# Specifies the index to update by using the index name\ncollection.search_indexes.update_one(updated_definition, name: 'searchIndex_plot')\n\n# Specifies the index to update by using the index id\ncollection.search_indexes.update_one(updated_definition, id: )\n```\n\n## Delete a Search Index\n\nTo delete a MongoDB Search or MongoDB Vector Search index, use the `search_indexes#drop_one` method.\n\nTo delete an index, you must provide the `id` or `name` of the index. The following code shows how to delete a search index from a collection:\n\n```ruby\n# Specifies the index to delete by using the index name\ncollection.search_indexes.drop_one(name: 'searchIndex_plot')\n\n# Specifies the index to delete by using the index id\ncollection.search_indexes.drop_one(id: )\n```\n\n## List Search Indexes\n\nYou can use the `search_indexes` object to list the entire index specification of each MongoDB Search and MongoDB Vector Search index on a collection:\n\n```ruby\nputs collection.search_indexes.collect(&:to_json)\n```\n\nTo list individual fields in the index specification for each index, iterate over the `search_indexes` object:\n\n```ruby\ncollection.search_indexes.each do |index_spec|\n p index_spec['id']\n p index_spec['name']\n p index_spec['status']\n p index_spec['queryable']\n p index_spec['latestDefinition']\nend\n```\n\n## Additional Information\n\nTo learn more about MongoDB Search, see the MongoDB Search documentation.\n\nTo learn more about MongoDB Vector Search, see the Ruby driver's Run a MongoDB Vector Search Query guide or the MongoDB Vector Search documentation.\n\n### API Documentation\n\nTo learn more about any of the methods discussed in this guide, see the following API documentation:\n\n- search_indexes\n\n- SearchIndex"} -{"chunk_id": "69a67d113328a617852a786c-0", "page_id": "69a67d113328a617852a786c", "source_name": "ruby-driver", "product_name": "Ruby Driver", "url": "https://mongodb.com/docs/ruby-driver/current/connect/server-selection", "title": "Server Selection", "text": "# Server Selection\n\n## Overview\n\nThe MongoDB Ruby Driver follows a defined algorithm or the read preference defined in the client options when selecting a server to read or write from.\n\n## Server Selection Algorithm\n\nWhen the Ruby driver executes a read operation, it performs the following steps, in order, to select a MongoDB deployment:\n\n1. From the list of known servers, the Ruby driver selects all servers that match the active read preference.\n\n2. The Ruby driver removes any server from the list that doesn't meet the `localThresholdMS` connection setting criteria, and returns the updated list.\n\n3. The Ruby driver selects a server at random from the servers still on the list and executes the operation against this server.\n\nWhen the Ruby driver executes a write operation, it begins by selecting all writeable servers, not just those that match the active read preference. The remaining steps are identical.\n\nTo learn more about the server-selection algorithm, see the Server Selection Algorithm in the MongoDB Server manual.\n\n## Customize Server Selection\n\nFor replica sets, you can select a read preference to determine which member the Ruby driver reads from. For more information about how to configure a read preference, see the Read Preference section of the Configure CRUD Operations guide.\n\n## API Documentation\n\nFor more information about the Ruby driver's server-selection algorithm, see the following API documentation:\n\n- Mongo::Client\n\n- Server::Description"} -{"chunk_id": "69a67d113328a617852a7881-0", "page_id": "69a67d113328a617852a7881", "source_name": "ruby-driver", "product_name": "Ruby Driver", "url": "https://mongodb.com/docs/ruby-driver/current/crud/query", "title": "Query Documents", "text": "# Query Documents\n\n## Overview\n\nOn this page, you can see copyable code examples that show common Ruby driver methods you can use to read data from MongoDB.\n\nTo learn more about any of the methods shown on this page, see the link provided in each section.\n\nTo use an example from this page, copy the code example into the Sample Application below or your own application. Be sure to replace all placeholders in the code examples, such as ``, with the relevant values for your MongoDB deployment.\n\n### Sample Application\n\nYou can use the following sample application to test the code examples on this page. To use the sample application, perform the following steps:\n\n1. Ensure you have the Ruby driver installed in your Ruby project.\n\n2. Copy the following code and paste it into a new `.rb` file.\n\n3. Copy a code example from this page and paste it on the specified lines in the file.\n\n```ruby\nrequire 'bundler/inline'\n\ngemfile do\n source 'https://rubygems.org'\n gem 'mongo'\nend\n\nuri = ''\n\nMongo::Client.new(uri) do |client|\n database = client.use('')\n collection = database['']\n\n # Start example code here\n\n # End example code here\nend\n```\n\n## Find One\n\nThe following example retrieves a document that matches the criteria specified by the given filter:\n\n```ruby\ndocument = collection.find(name: '').first\nputs document\n```\n\nTo learn more about the `first` method, see the Retrieve Data guide.\n\n## Find Multiple\n\nThe following example retrieves all documents that match the criteria specified by the given filter:\n\n```ruby\nresults = collection.find(founded_year: '')\n```\n\nTo learn more about the `find` method, see the Retrieve Data guide.\n\n## Count Documents in a Collection\n\nThe following example returns the number of documents in the specified collection:\n\n```ruby\nresult = collection.count_documents\nputs \"Number of documents: #{result}\"\n```\n\nTo learn more about the `count_documents` method, see the Count Documents guide.\n\n## Count Documents Returned from a Query\n\nThe following example returns the number of documents in the specified collection that match the query criteria:\n\n```ruby\nresult = collection.count_documents('key': '')\nputs \"value: #{result}\"\n```\n\nTo learn more about the `countDocuments()` method, see the Count Documents guide.\n\n## Estimated Document Count\n\nThe following example returns an approximate number of documents in the specified collection based on collection metadata:\n\n```ruby\nresult = collection.estimated_document_count\nputs \"Estimated number of documents: #{result}\"\n```\n\nTo learn more about the `estimated_document_count()` method, see the Count Documents guide.\n\n## Retrieve Distinct Values\n\nThe following example returns all distinct values of the specified field name in a given collection:\n\n```ruby\nresults = collection.distinct('field')\n```\n\nTo learn more about the `distinct` method, see the Retrieve Distinct Field Values guide.\n\n## Monitor Data Changes\n\nThe following example creates a change stream for a given collection and prints out subsequent change events in that collection:\n\n```ruby\nstream = collection.watch\ncollection.insert_one(a: 1)\ndoc = stream.first\nprocess(doc)\n```\n\nTo learn more about the `watch()` method, see the Monitor Data Changes guide."} -{"chunk_id": "69a67d113328a617852a7887-0", "page_id": "69a67d113328a617852a7887", "source_name": "ruby-driver", "product_name": "Ruby Driver", "url": "https://mongodb.com/docs/ruby-driver/current/crud/query/count", "title": "Count Documents", "text": "# Count Documents\n\n## Overview\n\nIn this guide, you can learn how to use the Ruby driver to retrieve an accurate and estimated count of the number of documents in a collection. The following methods count documents in a collection:\n\n- `count_documents`: Returns the exact number of documents that match a query filter or that exist in a collection\n\n- `estimated_document_count`: Returns the estimated number of documents that exist in a collection\n\n### Sample Data\n\nThe examples in this guide use the `companies` collection in the `sample_training` database from the Atlas sample datasets. To access this collection from your Ruby application, create a `Mongo::Client` object that connects to an Atlas cluster and assign the following values to your `database` and `collection` variables:\n\n```ruby\ndatabase = client.use('sample_training')\ncollection = database['companies']\n```\n\nTo learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the MongoDB Get Started guide.\n\n## Retrieve an Accurate Count\n\nUse the `count_documents` method to count the number of documents in a collection. To count the number of documents that match specific search criteria, pass a query filter to the `count_documents` method.\n\nTo learn more about specifying a query, see the Specify a Query guide.\n\n### Count All Documents\n\nTo return a count of all documents in the collection, call the `count_documents` method without passing a query filter, as shown in the following example:\n\n```ruby\nresult = collection.count_documents\nputs \"Number of documents: #{result}\"\n```\n\n```\nNumber of documents: 9500\n```\n\n### Count Specific Documents\n\nTo return a count of documents that match specific search criteria, pass a query filter to the `count_documents` method.\n\nThe following example counts the number of documents in which the value of the `founded_year` field is `2010`:\n\n```ruby\nresult = collection.count_documents(founded_year: 2010)\nputs \"Number of companies founded in 2010: #{result}\"\n```\n\n```\nNumber of companies founded in 2010: 33\n```\n\n### Customize Count Behavior\n\nYou can modify the behavior of the `count_documents` method by passing a second parameter that specifies option values. The following table describes the options you can set to customize the count operation:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nOption\n\n\nDescription\n\n
\n`collation`\n\n\nThe collation to use for the operation.**Type**: `Hash`\n\n
\n`hint`\n\n\nThe index to use for the operation.**Type**: `Hash`\n\n
\n`comment`\n\n\nThe comment to attach to the operation.**Type**: `Object`\n\n
\n`limit`\n\n\nThe maximum number of documents to count. This value must be a positive integer.**Type**: `Integer`\n\n
\n`max_time_ms`\n\n\nThe maximum amount of time in milliseconds that the operation can run.**Type**: `Integer`\n\n
\n`skip`\n\n\nThe number of documents to skip before counting documents.**Type**: `Integer`\n\n
\n`read`\n\n\nThe read preference to use for the operation. To learn more, see Read Preference in the MongoDB Server manual.**Type**: `Hash`\n\n
The following example uses the `count_documents` method to count the number of documents in which the `number_of_employees` field has the value `50` and instructs the operation to count a maximum of `100` results:\n\n```ruby\nresult = collection.count_documents({ number_of_employees: 50 }, limit: 100)\nputs \"Number of companies with 50 employees: #{result}\"\n```\n\n```\nNumber of companies with 50 employees: 100\n```\n\nWhen you pass an options parameter to the `count_documents` method, you must enclose the query filter in brackets (`{}`).\n\n## Retrieve an Estimated Count\n\nYou can retrieve an estimate of the number of documents in a collection by calling the `estimated_document_count` method. The method estimates the amount of documents based on collection metadata, which might be faster than performing an accurate count.\n\nThe following example estimates the number of documents in a collection:\n\n```ruby\nresult = collection.estimated_document_count\nputs \"Estimated number of documents: #{result}\"\n```\n\n```\nEstimated number of documents: 9500\n```\n\n### Customize Estimated Count Behavior\n\nYou can modify the behavior of the `estimated_document_count` method by passing a parameter that specifies option values. The following table describes the options you can set to customize the operation:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nOption\n\n\nDescription\n\n
\n`comment`\n\n\nThe comment to attach to the operation.**Type**: `Object`\n\n
\n`max_time_ms`\n\n\nThe maximum amount of time in milliseconds that the operation can run.**Type**: `Integer`\n\n
\n`read`\n\n\nThe read concern to use for the operation. To learn more, see Read Concern in the MongoDB Server manual.**Type**: `Hash`\n\n
The following example uses the `estimated_document_count` method to return an estimate of the number of documents in the collection and sets a timeout of `1000` milliseconds on the operation:\n\n```ruby\nresult = collection.estimated_document_count(max_time_ms: 1000)\nputs \"Estimated number of documents: #{result}\"\n```\n\n```\nEstimated number of documents: 9500\n```\n\n## API Documentation\n\nTo learn more about any of the methods discussed in this guide, see the following API documentation:\n\n- count_documents\n\n- estimated_document_count"} -{"chunk_id": "68a95c2b5e79d242619df6db-0", "page_id": "68a95c2b5e79d242619df6db", "source_name": "ruby-driver", "product_name": "Ruby Driver", "url": "https://mongodb.com/docs/ruby-driver/current/indexes/multikey-index", "title": "Multikey Indexes", "text": "# Multikey Indexes\n\n## Overview\n\n**Multikey indexes** are indexes that improve the performance of queries on array-valued fields. You can create a multikey index on a collection by using the `create_one` method and the same syntax that you use to create a single field index.\n\nWhen creating a multikey index, you must specify the following details:\n\n- The fields on which to create the index\n\n- The sort order for each field (ascending or descending)\n\n### Sample Data\n\nThe examples in this guide use the `movies` collection in the `sample_mflix` database from the Atlas sample datasets. To access this collection from your Ruby application, create a `Mongo::Client` object that connects to an Atlas cluster and assign the following values to your `database` and `collection` variables:\n\n```ruby\ndatabase = client.use('sample_mflix')\ncollection = database[:movies]\n```\n\nTo learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the Get Started with Atlas guide.\n\n## Create a Multikey Index\n\nUse the `create_one` method to create a multikey index. The following example creates an index in ascending order on the `cast` field:\n\n```ruby\ncollection.indexes.create_one({ cast: 1 })\n```\n\n## Verify Index Creation\n\nYou can verify that the index was created by listing the indexes in the collection. You should see an index for `cast` in the list, as shown in the following output:\n\n```ruby\nputs collection.indexes.collect(&:to_json)\n```\n\n```\n{\"v\": 2, \"key\": {\"cast\": 1}, \"name\": \"cast_1\"}\n```\n\n## Example Query\n\nThe following is an example of a query that is covered by the index created on the `cast` field:\n\n```ruby\nfilter = { cast: { '$all' => ['Aamir Khan', 'Kajol'] } }\ndoc = collection.find(filter).first\n\nif doc\n puts doc.to_json\nelse\n puts \"No document found\"\nend\n```\n\n```\n{\"_id\":...,\"title\":\"Fanaa\",...,\"cast\": [\"Aamir Khan\", \"Kajol\", \"Rishi Kapoor\", \"Tabu\"],...}\n```\n\n## Additional Information\n\nTo view runnable examples that demonstrate how to manage indexes, see Optimize Queries by Using Indexes.\n\nTo learn more about multikey indexes, see Multikey Indexes in the MongoDB Server manual.\n\n### API Documentation\n\nTo learn more about any of the methods discussed in this guide, see the following API documentation:\n\n- indexes\n\n- create_one\n\n- find"} -{"chunk_id": "69a67d113328a617852a7877-0", "page_id": "69a67d113328a617852a7877", "source_name": "ruby-driver", "product_name": "Ruby Driver", "url": "https://mongodb.com/docs/ruby-driver/current/crud/configure-crud", "title": "Configure CRUD Operations", "text": "# Configure CRUD Operations\n\n## Overview\n\nIn this guide, you can learn how to use the **write concern**, **read concern**, and **read preference** configurations to modify the way that MongoDB runs create, read, update, and delete (CRUD) operations on replica sets.\n\nYou can set write concern, read concern, and read preference options at the following levels:\n\n- Client, which sets the *default for all operation executions* unless overridden\n\n- Session\n\n- Transaction\n\n- Database\n\n- Collection\n\nThe preceding list also indicates the increasing order of precedence of the option settings. For example, if you set a read concern level for a transaction, it will override a read concern level set for the client.\n\nThese options allow you to customize the causal consistency and availability of the data in your replica sets.\n\n## Write Concern\n\nThe write concern specifies the level of acknowledgement requested from MongoDB for write operations, such as an insert or update, before the operation successfully returns. Operations that do not specify an explicit write concern inherit the global default write concern settings.\n\nFor more information, see Write Concern in the MongoDB Server manual. For detailed API documentation, see the Write Concern API documentation.\n\nThe following table describes the `write_concern` parameters:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nParameter\n\n\nType\n\n\nDescription\n\n
\n`w` *(optional)*\n\n\ninteger or string\n\n\nRequests acknowledgment that the write operation has propagated to a specified number of `mongod` instances or to `mongod` instances that are labelled with specified tags.\n\n
\n`wtimeoutMS` *(optional)*\n\n\ninteger\n\n\nSpecifies a time limit to prevent write operations from blocking indefinitely.\n\n
\n`journal` *(optional)*\n\n\nboolean\n\n\nRequests acknowledgment that the write operation has been written to the on-disk journal.\n\n
### Example: Set the Write Concern for a Single Write Operation\n\nThe following code creates a new document and specifies the `w` and `wtimeout` write concern settings:\n\n```ruby\nclient = Mongo::Client.new(['IP_ADDRESS_001:27017'], database: 'myDB')\nmyDB = client.database\nmyCollection = myDB[:myCollection]\n\nmyCollection.insert_one(\n { name: 'anotherDocumentName' },\n write: {\n w: 2,\n wtimeout: 5000\n }\n)\n```\n\n### Example: Retrieve and Apply an Existing Write Concern\n\nThe following code uses the `new_write_concern` method to construct a `write_concern` from the options of an existing database reference, `myDB`. Then the new write concern is applied to an inserted document.\n\n```ruby\nmyDoc = { name: 'New Document' }\nnew_write_concern = Mongo::WriteConcern.get(myDB.write_concern)\nmyDB[:myCollection].with(write: new_write_concern).insert_one(myDoc)\n```\n\n`myDB` can be replaced with a reference to any entity that accepts a write concern option.\n\n## Read Concern\n\nThe read concern specifies the following behaviors:\n\n- Level of causal consistency across replica sets\n\n- Isolation guarantees maintained during a query\n\nYou can specify the read concern setting by using the `level` parameter. The default read concern level is `local`. This means that the client returns the data from the replica set member that the client is connected to, with no guarantee that the data has been written to all replica set members.\n\nLower read concern level requirements may reduce latency.\n\nFor more information about read concerns or read concern levels, see Read Concern in the MongoDB Server manual. For more detail on the `read_concern` type and definitions of the read concern levels, see Read Concern in the API documentation.\n\n### Example: Set the Read Concern Level of an Aggregation\n\nThe following code sets the read concern level of an aggregation to `\"available\"`:\n\n```ruby\npipeline = [\n { \"$match\" => { category: 'KITCHENWARE' } },\n { \"$unset\" => ['_id', 'category'] }\n]\nresult = myCollection.aggregate(pipeline,\nread: { read_concern: { level: :available } })\n```\n\nTo learn more about aggregation operations, see the Transform Your Data with Aggregation guide.\n\n### Example: Change the Read Concern of a Database\n\nThe following code changes the read concern level of a database to `\"local\"`:\n\n```ruby\nclient = Mongo::Client.new(['IP_ADDRESS_001:27017'],\n database: 'mydb',\n read_concern: { level: :local })\nmyDB = client.database\n```\n\n## Read Preference\n\nThe read preference determines which member of a replica set MongoDB reads when running a query.\n\nFor more detailed API documentation, see the Read Preference API documentation.\n\nThe following table shows options you can use to customize how the server evaluates members:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nParameter\n\n\nType\n\n\nDescription\n\n
\n`mode`\n\n\n`Symbol`\n\n\nSpecifies a requirement or preference for which replica set member the server reads from. The default mode, `:primary`, specifies that operations read from the primary member of the replica set.\n\n
\n`tags` *(optional)*\n\n\n`Array`\n\n\nAssigns tags to secondary replica set members to customize how the server evaluates them. Tags cannot be used with the `:primary` read preference mode setting.\n\n
\n`options` *(optional)*\n\n\n`Hash`\n\n\nSets various options, including hedge and maxStalenessSeconds that can be applied to your read preference.\n\n
### Example: Set Read Preference and Concerns for a Transaction\n\nThe following code sets the read preference, read concern, and write concern for the operations in a transaction:\n\n```ruby\ntransaction_options = {\n read: { mode: :primary },\n read_concern: { level: :local },\n write_concern: { w: :majority }\n}\nsession = client.start_session\nsession.start_transaction(transaction_options)\nsession.commit_transaction\n# ...\nrescue => e\n session.abort_transaction\n puts \"Transaction aborted due to an error: #{e.message}\"\nensure\n session.end_session\nend\n```\n\nTo learn more about transactions, see the Transactions guide.\n\n### Example: Set the Read Preference of a Cluster in the Connection String\n\nThis code example creates a `MongoClient` that uses the `secondary` read preference mode when performing queries on a cluster:\n\n```ruby\nuri = 'mongodb+srv://:@'\noptions = {\n read: {\n mode: :secondary,\n max_staleness: 120\n }\n}\nclient = Mongo::Client.new(uri, options)\nmyDB = client.database\n```\n\nThe preceding example also sets the `maxStalenessSeconds` option to `120`. For more information about connection string options, see the Connection String Options section in the MongoDB Server manual."} -{"chunk_id": "69a67d113328a617852a7877-1", "page_id": "69a67d113328a617852a7877", "source_name": "ruby-driver", "product_name": "Ruby Driver", "url": "https://mongodb.com/docs/ruby-driver/current/crud/configure-crud", "title": "Configure CRUD Operations", "text": "## Retryable Reads and Writes\n\nThe Ruby driver automatically retries certain read and write operations once if they fail due to a network or server error.\n\nYou can explicitly disable modern retryable reads or retryable writes by setting the `retry_reads` or `retry_writes` options to `false` when you create a new client. When set to `false`, this enables legacy retry behavior.\n\nThe following example disables modern retryable reads and writes for a client:\n\n```ruby\nuri = 'mongodb+srv://:@'\noptions = {\n retry_reads: false,\n retry_writes: false\n}\nclient = Mongo::Client.new(uri, options)\nmyDB = client.database\n```\n\nTo learn more about supported retryable read operations, see Retryable Reads in the MongoDB Server manual. To learn more about supported retryable write operations, see Retryable Writes in the MongoDB Server manual.\n\n## API Documentation\n\nTo learn more about the methods and types mentioned in this guide, see the following API documentation:\n\n- Write Concern\n\n- Read Concern\n\n- Read Preference"} -{"chunk_id": "69a67d113328a617852a78dd-0", "page_id": "69a67d113328a617852a78dd", "source_name": "ruby-driver", "product_name": "Ruby Driver", "url": "https://mongodb.com/docs/ruby-driver/current/logging-and-monitoring/open-telemetry", "title": "Trace with OpenTelemetry", "text": "# Trace with OpenTelemetry\n\n## Overview\n\nIn this guide, you will learn how to use OpenTelemetry tracing with the Ruby driver. OpenTelemetry is an open source observability framework that provides a standardized way to instrument, generate, collect, and export telemetry data.\n\nThe Ruby driver supports OpenTelemetry tracing to help you understand the performance and behavior of your MongoDB operations. When you enable tracing, the driver creates spans that represent operations such as queries, updates, and transactions. These spans include attributes that follow MongoDB semantic conventions.\n\n### Required Dependencies\n\nTo use OpenTelemetry tracing, you must install the OpenTelemetry Ruby SDK and an exporter. To install these in your application, add the following gems to your `Gemfile`:\n\n```ruby\ngem 'opentelemetry-sdk'\ngem 'opentelemetry-exporter-otlp' # or your preferred exporter\n```\n\nIf you enable tracing but the OpenTelemetry library is not loaded, the driver logs a warning and automatically disables tracing.\n\n## Enable OpenTelemetry Tracing\n\nYou can enable OpenTelemetry tracing by specifying the `tracing` option when you create a client, or by setting an environment variable.\n\nIf you don't set tracing in the client configuration or by using the environment variable, tracing is disabled by default.\n\n### Enable Tracing in Client Configuration\n\nTo enable tracing when you create a client, pass the `tracing` option with `enabled` set to `true`, as shown in the following example:\n\n```ruby\nclient = Mongo::Client.new(['localhost:27017'],\n database: 'my_database',\n tracing: {\n enabled: true\n }\n)\n\n```\n\n### Enable Tracing with an Environment Variable\n\nTo enable tracing by using an environment variable, set the `OTEL_RUBY_INSTRUMENTATION_MONGODB_ENABLED` environment variable before you create a client, as shown in the following example:\n\n```bash\nexport OTEL_RUBY_INSTRUMENTATION_MONGODB_ENABLED=true\n\n```\n\nYou can use any of the following values in the environment variable to enable tracing:\n\n- `true`\n\n- `1`\n\n- `yes`\n\nAfter you set the variable, create your client, as shown in the following example:\n\n```ruby\nclient = Mongo::Client.new(['localhost:27017'],\n database: 'my_database')\n\n```\n\n## Configuration Options\n\nThe `tracing` option accepts the following parameters:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nParameter\n\n\nType\n\n\nDescription\n\n
\n`:enabled`\n\n\nBoolean\n\n\nEnables or disables OpenTelemetry tracing.**Default**: `nil`\n\n
\n`:query_text_max_length`\n\n\nInteger\n\n\nSpecifies the maximum length of query text toinclude in span attributes. Set to `0` to excludequery text. The query text appears in the`db.query.text` attribute.**Default**: `nil`\n\n
\n`:tracer`\n\n\n`OpenTelemetry::Trace::Tracer`\n\n\nSpecifies a custom OpenTelemetry tracer instance.**Default**: Uses the default tracer from theglobal tracer provider\n\n
The following example shows how to configure all available tracing options:\n\n```ruby\nclient = Mongo::Client.new(['localhost:27017'],\n database: 'my_database',\n tracing: {\n enabled: true,\n query_text_max_length: 1024,\n tracer: my_custom_tracer\n }\n)\n\n```\n\n## Operation Tracing\n\nThe Ruby driver creates OpenTelemetry spans for both high-level operations and low-level commands. The following sections describe the spans created and the attributes included.\n\n### High-Level Operations\n\nHigh-level operations are the methods you call directly on collections and databases. The driver creates spans for the following operations:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nOperation Type\n\n\nOperations\n\n
\n**Collection operations**\n\n\n`find`, `insert_one`, `insert_many`, `update_one`, `update_many`, `delete_one`, `delete_many`, `find_one_and_update`, `find_one_and_delete`, `find_one_and_replace`, `replace_one`, `count_documents`, `estimated_document_count`, `distinct`, `aggregate`\n\n
\n**Index operations**\n\n\n`create_index`, `create_indexes`, `drop_index`, `drop_all_indexes`, `list_indexes`\n\n
\n**Database operations**\n\n\n`list_collections`, `create_collection`, `drop_collection`, `list_databases`\n\n
Span names for high-level operations use the format `{operation_name}.{collection_name}`. For example, `find.users`, `insertOne.orders`, or `aggregate.products`.\n\n### Low-Level Commands\n\nLow-level commands are the actual commands sent to the MongoDB server over the wire protocol. The following lists some examples of low-level commands for which the driver creates spans:\n\n- `find`\n\n- `insert`\n\n- `update`\n\n- `delete`\n\n- `aggregate`\n\n- `create`\n\n- `drop`\n\nSpan names for low-level commands use the format `{command_name}`. For example, `find`, `insert`, or `update`.\n\nCommand spans are nested under their corresponding operation spans.\n\n### Span Attributes\n\nThe driver follows MongoDB semantic conventions and includes span attributes that provide context about each operation.\n\nAll spans include the following attributes:\n\n- `db.system.name`: Always set to `mongodb`\n\n- `db.namespace`: The database name\n\n- `db.collection.name`: The collection name (when applicable)\n\n- `db.command.name`: The MongoDB command name (command spans only)\n\n- `db.query.summary`: A high-level summary of the query structure\n\n#### Network Attributes\n\nCommand spans include the following network attributes:\n\n- `server.address`: MongoDB server host\n\n- `server.port`: MongoDB server port\n\n- `network.transport`: Transport protocol such as `tcp`\n\n#### Connection Attributes\n\nCommand spans include the following connection attributes:\n\n- `db.mongodb.server_connection_id`: Server-assigned connection ID\n\n- `db.mongodb.driver_connection_id`: Driver-assigned connection ID\n\n#### Session and Transaction Attributes\n\nWhen you use sessions or transactions, spans include the following attributes:\n\n- `db.mongodb.lsid`: Logical session ID (when using sessions)\n\n- `db.mongodb.txn_number`: Transaction number (when in a transaction)\n\n- `db.mongodb.cursor_id`: Cursor ID (for operations that return cursors)\n\n#### Query Attributes\n\nWhen you configure `query_text_max_length` with a value greater than `0`, spans include the following attribute:\n\n- `db.query.text`: The full query text, truncated to the specified maximum length\n\n#### Error Attributes\n\nWhen operations fail, the driver records exception details with OpenTelemetry's exception recording mechanism and sets the span status to `ERROR`. For MongoDB operation failures, the `db.response.status_code` attribute contains the error code.\n\n## Transaction Tracing\n\nThe driver creates a special transaction span that encompasses all operations within an explicit transaction. The following example demonstrates transaction tracing:\n\n```ruby\nsession = client.start_session\nsession.with_transaction do\n collection.insert_one({ name: 'Alice' }, session: session)\n collection.update_one(\n { name: 'Bob' },\n { '$set' => { age: 30 } },\n session: session\n )\nend\n\n```\n\nThe preceding example produces a span hierarchy similar to the following structure:\n\n```none\ntransaction\n \u2514\u2500\u2500 insertOne.users\n \u2514\u2500\u2500 insert (command)\n \u2514\u2500\u2500 updateOne.users\n \u2514\u2500\u2500 update (command)\n```\n\nImplicit sessions do not create transaction spans."} -{"chunk_id": "69a67d113328a617852a78dd-1", "page_id": "69a67d113328a617852a78dd", "source_name": "ruby-driver", "product_name": "Ruby Driver", "url": "https://mongodb.com/docs/ruby-driver/current/logging-and-monitoring/open-telemetry", "title": "Trace with OpenTelemetry", "text": "## Error Handling\n\nWhen operations fail, the driver records exceptions in the span by using OpenTelemetry's exception recording mechanism. The span status is then set to `ERROR`.\n\nFor MongoDB operation failures, the `db.response.status_code` attribute contains the error code.\n\nErrors do not prevent the driver from raising the exception to your application.\n\n## Performance Considerations\n\nConsider the following performance implications when you use OpenTelemetry tracing:\n\n- When you enable tracing, the driver incurs minimal overhead for span creation and attribute collection.\n\n- Query text capture (`db.query.text`) has additional overhead and you should use it judiciously in production. Setting `query_text_max_length` to `0` disables query text capture for better performance.\n\n- When you disable tracing, there is no performance impact because the feature is completely bypassed.\n\n## Example\n\nThe following example shows how to set up OpenTelemetry tracing for a MongoDB application:\n\n```ruby\nrequire 'mongo'\nrequire 'opentelemetry/sdk'\n\n# Configure OpenTelemetry\nOpenTelemetry::SDK.configure do |c|\n c.service_name = 'my-app'\nend\n\n# Create MongoDB client with tracing enabled\nclient = Mongo::Client.new(['localhost:27017'],\n database: 'test',\n tracing: {\n enabled: true,\n query_text_max_length: 1024\n }\n)\n\n# Use the client normally - operations are traced\ncollection = client[:users]\ncollection.insert_one({ name: 'Alice', age: 30 })\ncollection.find({ age: { '$gte': 25 } }).to_a\n\n```\n\n## Additional Information\n\nTo learn more about OpenTelemetry tracing with Ruby, see the OpenTelemetry Ruby SDK."} -{"chunk_id": "68a95c2f5e79d242619dfbec-0", "page_id": "68a95c2f5e79d242619dfbec", "source_name": "rust", "product_name": "Rust Driver", "url": "https://mongodb.com/docs/drivers/rust/current/issues-and-help", "title": "Issues & Help", "text": "# Issues & Help\n\nWe are lucky to have a vibrant MongoDB Rust community that includes users with varying levels of experience using the Rust driver.\n\nYou can find support for general questions by using the MongoDB Stack Overflow tag or the MongoDB Reddit community.\n\nTo learn more, visit the support channels.\n\n## Bugs / Feature Requests\n\nIf you think you found a bug or want to request a new feature in the Rust driver, please open a case in MongoDB's issue management tool, JIRA, by performing the following steps:\n\n1. Visit the MongoDB JIRA issue tracker and click the signup link. Create an account, and then log in to JIRA.\n\n2. Navigate to the RUST JIRA project.\n\n3. Click Create to create a ticket. Please provide as much information as possible about the issue or request in the ticket.\n\nBug reports in the RUST JIRA project are publicly viewable.\n\nIf you\u2019ve identified a security vulnerability in any official MongoDB product, please report it according to the instructions found in the Create a Vulnerability Report page.\n\n## Pull Requests\n\nWe are happy to accept contributions to help improve the Rust driver. We guide user contributions to ensure they meet the standards of the codebase. Please ensure that any pull requests include documentation and tests, and confirm that they pass the integration and unit tests in the source code.\n\nTo get started, clone the Rust driver repository and create a feature branch with the following shell commands:\n\n```bash\n$ git clone https://github.com/mongodb/mongo-rust-driver.git\n$ cd mongo-rust-driver\n$ git checkout -b myNewFeature\n```\n\nAfter making any code changes, follow the testing guidelines to ensure your code passes any newly added and existing tests. Then, push your changes to your branch and open a pull request in the Rust driver repository on GitHub."} -{"chunk_id": "69d7454c549f5046064e2e33-0", "page_id": "69d7454c549f5046064e2e33", "source_name": "rust", "product_name": "Rust Driver", "url": "https://mongodb.com/docs/drivers/rust/current/crud/bulk", "title": "Bulk Operations", "text": "# Bulk Operations\n\n## Overview\n\nIn this guide, you can learn how to use the Rust driver to perform **bulk operations**.\n\nBulk operations perform multiple write operations against one or more **namespaces**. A namespace is a combination of the database name and the collection name, in the format `.`. Since you perform bulk operations on a `Client` instance, you can perform bulk operations against any namespace in the cluster accessed by your client.\n\nYou can perform bulk operations to reduce the number of calls to the server. Instead of sending a request for each operation, bulk operations perform multiple operations within one action.\n\nThis guide includes the following sections:\n\n- Sample Data presents the sample data that is used by the bulk operation examples\n\n- Bulk Operation Types describes how to use `WriteModel` types to perform bulk insert, replace, update, and delete operations\n\n- Return Type describes the return value of the `bulk_write()` method and how to access information about the bulk operation\n\n- Modify Behavior describes how to modify the default behavior of the `bulk_write()` method\n\n- Write to Mixed Namespaces describes how to perform a bulk operation on multiple namespaces in one method call\n\n- Additional Information provides links to resources and API documentation for types and methods mentioned in this guide\n\nTo perform bulk write operations, ensure that your application meets the following requirements:\n\n- You are connected to MongoDB Server version 8.0 or later.\n\n- You are using Rust driver version 3.0 or later.\n\n## Sample Data\n\nThe examples in this guide use the following sample documents, which are stored in the `mushrooms` collection in the `db` database:\n\n```rust\nlet docs = vec![\n doc! {\"name\" : \"portobello\", \"color\" : \"brown\", \"edible\" : true },\n doc! {\"name\" : \"chanterelle\", \"color\" : \"yellow\", \"edible\" : true },\n doc! {\"name\" : \"oyster\", \"color\" : \"white\", \"edible\" : true },\n doc! {\"name\" : \"fly agaric\", \"color\" : \"red\", \"edible\" : false },\n];\n```\n\nYou can also use custom struct types to represent your sample data. For an example that performs a bulk operation by using `Mushroom` structs to model the same data, see the Insert Structs Example on this page.\n\n## Bulk Operation Types\n\nTo perform a bulk write operation, pass an array of `WriteModel` enum instances to the `bulk_write()` method.\n\nIn this section, you can learn how to perform the following bulk write operations by defining their corresponding `WriteModel` types:\n\n- Bulk insert operations\n\n- Bulk replace operations\n\n- Bulk update operations\n\n- Bulk delete operations\n\nYou can also perform multiple types of write operations in a single `bulk_write()` method call. To view an example that passes an `UpdateOneModel` and an `InsertOneModel` to the same `bulk_write()` call, see the Modify Behavior example in this guide.\n\n### Insert\n\nTo perform a bulk insert operation, create an `InsertOneModel` instance for each document you want to insert. Then, pass a list of models to the `bulk_write()` method.\n\nThe following table describes `InsertOneModel` fields that you can set by calling their corresponding builder methods:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nField\n\n\nDescription\n\n
\n`namespace`\n\n\nThe namespace on which the insert is performed.Type: `Namespace`\n\n
\n`document`\n\n\nThe document to insert.Type: `Document`\n\n
\n#### Insert Documents Example\n\nThis example performs the following actions:\n\n- Specifies two `InsertOneModel` instances in an array. Each `InsertOneModel` represents a document to be inserted into the `db.mushrooms` namespace.\n\n- Passes the array of models to the `bulk_write()` method.\n\n- Prints the number of inserted documents.\n\n```rust\nlet mushrooms: Collection = client.database(\"db\").collection(\"mushrooms\");\n\nlet models = vec![\n InsertOneModel::builder()\n .namespace(mushrooms.namespace())\n .document(doc! {\n \"name\": \"lion's mane\",\n \"color\": \"white\",\n \"edible\": true\n })\n .build(),\n InsertOneModel::builder()\n .namespace(mushrooms.namespace())\n .document(doc! {\n \"name\": \"angel wing\",\n \"color\": \"white\",\n \"edible\": false\n })\n .build(),\n];\n\nlet result = client.bulk_write(models).await?;\nprintln!(\"Inserted documents: {}\", result.inserted_count);\n```\n\n```console\nInserted documents: 2\n```\n\n#### Insert Structs Example\n\nYou can also model your documents by using structs and bulk insert struct instances into the `db.mushrooms` namespace.\n\nThis example performs the same operation as the preceding Insert Documents Example but inserts instances of the following `Mushroom` struct type:\n\n```rust\n#[derive(Serialize)]\nstruct Mushroom {\n name: String,\n color: String,\n edible: bool,\n}\n```\n\nThe following code uses the `insert_one_model()` method to construct an `InsertOneModel` from each `Mushroom` instance, then inserts both models in a bulk operation:\n\n```rust\nlet mushrooms: Collection = client.database(\"db\").collection(\"mushrooms\");\n\nlet lions_mane = Mushroom {\n name: \"lion's mane\".to_string(),\n color: \"white\".to_string(),\n edible: true,\n};\n\nlet angel_wing = Mushroom {\n name: \"angel wing\".to_string(),\n color: \"white\".to_string(),\n edible: false,\n};\n\nlet lions_mane_model = mushrooms.insert_one_model(lions_mane)?;\nlet angel_wing_model = mushrooms.insert_one_model(angel_wing)?;\n\nlet result = client.bulk_write([lions_mane_model, angel_wing_model]).await?;\nprintln!(\"Inserted documents: {}\", result.inserted_count);\n```\n\n```console\nInserted documents: 2\n```\n\nTo learn more about custom struct types and serialization in the Rust driver, see the guide on Data Modeling and Serialization."} -{"chunk_id": "69d7454c549f5046064e2e33-1", "page_id": "69d7454c549f5046064e2e33", "source_name": "rust", "product_name": "Rust Driver", "url": "https://mongodb.com/docs/drivers/rust/current/crud/bulk", "title": "Bulk Operations", "text": "### Replace\n\nTo perform a bulk replace operation, create a `ReplaceOneModel` instance for each document you want to replace. Then, pass a list of models to the `bulk_write()` method.\n\nThe following table describes `ReplaceOneModel` fields that you can set by calling their corresponding builder methods:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nField\n\n\nDescription\n\n
\n`namespace`\n\n\nThe namespace on which the operation is performed.Type: `Namespace`\n\n
\n`filter`\n\n\nThe filter that matches the document you want to replace.Type: `Document`\n\n
\n`replacement`\n\n\nThe replacement document.Type: `Document`\n\n
\n`collation`\n\n\n(Optional) The collation to use when sorting results. To learn more about collations, see the Collations guide.Type: `Document`\n\n
\n`hint`\n\n\n(Optional) The index to use for the operation. To learn more about indexes, see the Indexes guide.Type: `Bson`\n\n
\n`upsert`\n\n\n(Optional) Whether a new document is created if no document matches the filter.By default, this field is set to `false`.Type: `bool`\n\n
#### Example\n\nThis example performs the following actions:\n\n- Specifies two `ReplaceOneModel` instances in an array. The `ReplaceOneModel` instances contain instructions to replace documents representing mushrooms in the `db.mushrooms` namespace.\n\n- Passes the array of models to the `bulk_write()` method.\n\n- Prints the number of modified documents.\n\n```rust\nlet mushrooms: Collection = client.database(\"db\").collection(\"mushrooms\");\n\nlet models = vec![\n ReplaceOneModel::builder()\n .namespace(mushrooms.namespace())\n .filter(doc! { \"name\": \"portobello\" })\n .replacement(doc! {\n \"name\": \"cremini\",\n \"color\": \"brown\",\n \"edible\": true\n })\n .build(),\n ReplaceOneModel::builder()\n .namespace(mushrooms.namespace())\n .filter(doc! { \"name\": \"oyster\" })\n .replacement(doc! {\n \"name\": \"golden oyster\",\n \"color\": \"yellow\",\n \"edible\": true\n })\n .upsert(true)\n .build(),\n];\n\nlet result = client.bulk_write(models).await?;\nprintln!(\"Modified documents: {}\", result.modified_count);\n```\n\n```console\nModified documents: 2\n```\n\n### Update\n\nTo perform a bulk update operation, create an `UpdateOneModel` or `UpdateManyModel` instance for each update you want to make. Then, pass a list of models to the `bulk_write()` method. An `UpdateOneModel` updates only one document that matches a filter, while an `UpdateManyModel` updates all documents that match a filter.\n\nThe following table describes `UpdateOneModel` and `UpdateManyModel` fields that you can set by calling their corresponding builder methods:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nField\n\n\nDescription\n\n
\n`namespace`\n\n\nThe namespace on which the operation is performed.Type: `Namespace`\n\n
\n`filter`\n\n\nThe filter that matches one or more documents you want to update. When specified in an `UpdateOneModel`, only the first matching document will be updated. When specified in an `UpdateManyModel`, all matching documents will be updated.Type: `Document`\n\n
\n`update`\n\n\nThe update to perform.Type: `UpdateModifications`\n\n
\n`array_filters`\n\n\n(Optional) A set of filters specifying which array elements an update applies to if you are updating an array-valued field.Type: `Array`\n\n
\n`collation`\n\n\n(Optional) The collation to use when sorting results. To learn more about collations, see the Collations guide.Type: `Document`\n\n
\n`hint`\n\n\n(Optional) The index to use for the operation. To learn more about indexes, see the Indexes guide.Type: `Bson`\n\n
\n`upsert`\n\n\n(Optional) Whether a new document is created if no document matches the filter. By default, this field is set to `false`.Type: `bool`\n\n
#### Example\n\nThis example performs the following actions:\n\n- Specifies an `UpdateOneModel` and an `UpdateManyModel` instance in an array. These models contain instructions to update documents representing mushrooms in the `db.mushrooms` namespace.\n\n- Passes the array of models to the `bulk_write()` method.\n\n- Prints the number of modified documents.\n\n```rust\nlet mushrooms: Collection = client.database(\"db\").collection(\"mushrooms\");\n\nlet models = vec![\n WriteModel::UpdateOne(\n UpdateOneModel::builder()\n .namespace(mushrooms.namespace())\n .filter(doc! { \"name\": \"fly agaric\" })\n .update(doc! { \"$set\": { \"name\": \"fly amanita\" } })\n .upsert(true)\n .build(),\n ),\n WriteModel::UpdateMany(\n UpdateManyModel::builder()\n .namespace(mushrooms.namespace())\n .filter(doc! { \"color\": \"yellow\" })\n .update(doc! { \"$set\": { \"color\": \"yellow/orange\" } })\n .build(),\n ),\n];\n\nlet result = client.bulk_write(models).await?;\nprintln!(\"Modified documents: {}\", result.modified_count);\n```\n\n```console\nModified documents: 2\n```"} -{"chunk_id": "69d7454c549f5046064e2e33-2", "page_id": "69d7454c549f5046064e2e33", "source_name": "rust", "product_name": "Rust Driver", "url": "https://mongodb.com/docs/drivers/rust/current/crud/bulk", "title": "Bulk Operations", "text": "### Delete\n\nTo perform a bulk delete operation, create a `DeleteOneModel` or `DeleteManyModel` instance for each delete operation. Then, pass a list of models to the `bulk_write()` method. A `DeleteOneModel` deletes only one document that matches a filter, while a `DeleteManyModel` deletes all documents that match a filter.\n\nThe following table describes `DeleteOneModel` and `DeleteManyModel` fields that you can set by calling their corresponding builder methods:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nField\n\n\nDescription\n\n
\n`namespace`\n\n\nThe namespace on which the operation is performed.Type: `Namespace`\n\n
\n`filter`\n\n\nThe filter that matches one or more documents you want to delete. When specified in a `DeleteOneModel`, only the first matching document will be deleted. When specified in a `DeleteManyModel`, all matching documents will be deleted.Type: `Document`\n\n
\n`collation`\n\n\n(Optional) The collation to use when sorting results. To learn more about collations, see the Collations guide.Type: `Document`\n\n
\n`hint`\n\n\n(Optional) The index to use for the operation. To learn more about indexes, see the Indexes guide.Type: `Bson`\n\n
#### Example\n\nThis example performs the following actions:\n\n- Specifies a `DeleteOneModel` and a `DeleteManyModel` instance in an array. These models contain instructions to delete documents representing mushrooms in the `db.mushrooms` namespace.\n\n- Passes the array of models to the `bulk_write()` method.\n\n- Prints the number of deleted documents.\n\n```rust\nlet mushrooms: Collection = client.database(\"db\").collection(\"mushrooms\");\n\nlet models = vec![\n WriteModel::DeleteOne(\n DeleteOneModel::builder()\n .namespace(mushrooms.namespace())\n .filter(doc! { \"color\": \"red\" })\n .build(),\n ),\n WriteModel::DeleteMany(\n DeleteManyModel::builder()\n .namespace(mushrooms.namespace())\n .filter(doc! { \"edible\": true })\n .build(),\n ),\n];\n\nlet result = client.bulk_write(models).await?;\nprintln!(\"Deleted documents: {}\", result.deleted_count);\n```\n\n```console\nDeleted documents: 4\n```\n\n## Return Type\n\nThe `bulk_write()` method returns a `SummaryBulkWriteResult` struct instance from which you can access information about your bulk operation.\n\nThe `SummaryBulkWriteResult` type has the following fields:\n\n- `inserted_count`: the number of inserted documents\n\n- `matched_count`: the number of matched documents\n\n- `modified_count`: the number of updated documents\n\n- `upserted_count`: the number of upserted documents\n\n- `deleted_count`: the number of deleted documents\n\nYou can also use the `verbose_results()` method to see detailed information about each operation. The `verbose_results()` method returns a `VerboseBulkWriteResult` struct instance, which has the following fields:\n\n- `delete_results`: the results of each successful delete operation\n\n- `insert_results`: the results of each successful insert operation\n\n- `update_results`: the results of each successful update operation\n\n- `summary`: a summary of the results of each operation type\n\nThe following example chains the `verbose_results()` method to the `bulk_write()` method and prints the results of the update and delete operations:\n\n```rust\nlet models = vec![\n WriteModel::DeleteOne(\n DeleteOneModel::builder()\n .namespace(mushrooms.namespace())\n .filter(doc! { \"name\": \"oyster\" })\n .build(),\n ),\n WriteModel::UpdateOne(\n UpdateOneModel::builder()\n .namespace(mushrooms.namespace())\n .filter(doc! { \"name\": \"chanterelle\" })\n .update(doc! { \"$set\": { \"season\": [\"July\", \"August\", \"September\"] } })\n .build(),\n ),\n];\n\nlet result = client.bulk_write(models).verbose_results().await?;\nprintln!(\n \"Update results: {:?}\\nDelete results: {:?}\\n\",\n result.update_results, result.delete_results\n);\n```\n\n```console\nUpdate results: {1: UpdateResult { matched_count: 1, modified_count: 1, upserted_id: None }}\nDelete results: {0: DeleteResult { deleted_count: 1 }}\n```\n\n## Modify Behavior\n\nYou can modify the behavior of the `bulk_write()` method by setting `BulkWriteOptions` field values. To set these struct fields, chain the fields' corresponding methods to the `bulk_write()` method.\n\nThe `BulkWriteOptions` struct contains the following fields:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nField\n\n\nDescription\n\n\nDefault Value\n\n
\n`ordered`\n\n\nWhether the operations run in the order in which they were specified.When set to `true`, one failed operation prevents subsequent operations from running.When set to `false`, the server continues to attempt write operations if one fails.Type: `bool`\n\n\n`true`\n\n
\n`bypass_document_validation`\n\n\nWhether document-level validation is bypassed.Type: `bool`\n\n\n`false`\n\n
\n`comment`\n\n\nAn arbitrary comment to help trace the operation through the database profiler, currentOp, and logs.Type: `Bson`\n\n\n`None`\n\n
\n`let_vars`\n\n\nA map of parameter names and values to apply to all operations within the bulk write. Values must be constant or closed expressions that do not reference document fields.Type: `Document`\n\n\n`None`\n\n
\n`write_concern`\n\n\nThe write concern to use for this bulk operation.Type: `WriteConcern`\n\n\nInherits the namespace's write concern\n\n
"} -{"chunk_id": "69d7454c549f5046064e2e33-3", "page_id": "69d7454c549f5046064e2e33", "source_name": "rust", "product_name": "Rust Driver", "url": "https://mongodb.com/docs/drivers/rust/current/crud/bulk", "title": "Bulk Operations", "text": "### Example\n\nThis example attempts to perform update and insert operations on the `mushrooms` collection. The following code sets the `ordered` field to `false` by chaining the `ordered()` method to the `bulk_write()` method:\n\n```rust\nlet mushrooms: Collection = client.database(\"db\").collection(\"mushrooms\");\n\nlet models = vec![\n WriteModel::UpdateOne(UpdateOneModel::builder()\n .namespace(mushrooms.namespace())\n .filter(doc! { \"name\": \"portobello\" })\n .update(doc! { \"$set\": { \"_id\": 123 } })\n .upsert(true)\n .build()),\n WriteModel::InsertOne(InsertOneModel::builder()\n .namespace(mushrooms.namespace())\n .document(doc! {\n \"name\": \"reishi\",\n \"color\": \"red/brown\",\n \"edible\": true\n })\n .build()),\n];\n\nlet result = client.bulk_write(models).ordered(false).await?;\nprintln!(\n \"Inserted documents: {}\\nDeleted documents: {}\",\n result.inserted_count, result.deleted_count\n);\n```\n\n```console\nError: Error { kind: BulkWrite(BulkWriteError { write_concern_errors: [], write_errors:\n{0: WriteError { code: 66, code_name: None, message: \"Plan executor error during update ::\ncaused by :: Performing an update on the path '_id' would modify the immutable field '_id'\",\ndetails: None }}, partial_result: Some(Summary(SummaryBulkWriteResult { inserted_count: 1,\nmatched_count: 0, modified_count: 0, upserted_count: 0, deleted_count: 0 })) }),\nlabels: ... }\n```\n\nThe `_id` field is immutable and cannot be changed in an update operation. Since the `UpdateOneModel` includes instructions to update this field, the bulk operation returns a `BulkWriteError` and performs only the insert operation. If you set the `ordered` field to `true`, the driver does not attempt any subsequent operations after the unsuccessful update operation, and the driver does not insert any documents.\n\n## Write to Mixed Namespaces\n\nThe preceding examples on this page perform bulk operations on the `db.mushrooms` namespace. However, you can perform bulk writes on multiple namespaces in a single method call.\n\nThe following example inserts one document into the `ingredients.sweet` namespace and one document into the `meals.dessert` namespace:\n\n```rust\nlet sweet: Collection = client\n .database(\"ingredients\")\n .collection(\"sweet\");\nlet dessert: Collection = client\n .database(\"meals\")\n .collection(\"dessert\");\n\nlet models = vec![\n InsertOneModel::builder()\n .namespace(sweet.namespace())\n .document(doc! { \"name\": \"brown sugar\", \"price\": 3.99 })\n .build(),\n InsertOneModel::builder()\n .namespace(dessert.namespace())\n .document(doc! { \"name\": \"banana bread\", \"cook_time\": 75 })\n .build(),\n];\n\nlet result = client.bulk_write(models).await?;\nprintln!(\"Inserted documents: {}\", result.inserted_count);\n```\n\n```console\nInserted documents: 2\n```\n\n## Additional Information\n\nTo learn more about bulk operations, see Bulk Write Operations in the Server manual.\n\n### API Documentation\n\nTo learn more about any of the methods or types discussed in this guide, see the following API documentation:\n\n- bulk_write()\n\n- BulkWrite\n\n- BulkWriteOptions\n\n- WriteModel\n\n- InsertOneModel\n\n- ReplaceOneModel\n\n- UpdateOneModel\n\n- UpdateManyModel\n\n- DeleteOneModel\n\n- DeleteManyModel\n\n- SummaryBulkWriteResult\n\n- VerboseBulkWriteResult"} -{"chunk_id": "69d7454c549f5046064e2f25-0", "page_id": "69d7454c549f5046064e2f25", "source_name": "rust", "product_name": "Rust Driver", "url": "https://mongodb.com/docs/drivers/rust/current/vector-search", "title": "MongoDB Vector Search", "text": "# MongoDB Vector Search\n\n## Overview\n\nIn this guide, you can learn how to perform searches on your documents by using the MongoDB Vector Search feature. The Rust driver allows you to perform MongoDB Vector Search queries by using the aggregation framework. To learn more about performing aggregations, see the Aggregation guide.\n\nYou can use the MongoDB Vector Search feature only when you connect to MongoDB Atlas clusters. This feature is not available for self-managed deployments.\n\nTo learn more about MongoDB Vector Search, see the MongoDB Vector Search Overview.\n\nTo perform advanced full-text search on your documents, you can use the MongoDB Search feature. To learn about this feature, see the MongoDB Search Overview.\n\n### MongoDB Vector Search Index\n\nBefore you can perform MongoDB Vector Search queries, you must create a MongoDB Vector Search index on your collection. To learn more about creating this index, see the MongoDB Search and Vector Search Indexes guide.\n\n## MongoDB Vector Search Aggregation Stage\n\nTo create a `$vectorSearch` stage in your aggregation pipeline, perform the following actions:\n\n1. Create a vector to store the pipeline stages.\n\n2. Specify the `$vectorSearch` operator and provide details about the vector search query.\n\nYou must define the following fields in your `$vectorSearch` stage:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nParameter\n\n\nType\n\n\nDescription\n\n
\n`index`\n\n\nstring\n\n\nName of the vector search index\n\n
\n`path`\n\n\nstring\n\n\nField that contains vector embeddings\n\n
\n`queryVector`\n\n\narray of numbers\n\n\nVector representation of your query\n\n
\n`limit`\n\n\nnumber\n\n\nNumber of results to return\n\n
\n\n## MongoDB Vector Search Query Examples\n\nIn this section, you can learn how to perform MongoDB Vector Search queries. The examples in this section use sample data from the `sample_mflix.embedded_movies` collection. To learn how to load this sample data, see the Load Data into Atlas tutorial in the Atlas documentation.\n\n### Basic MongoDB Vector Search Query\n\nThe following code performs a MongoDB Vector Search query on the `plot_embedding` vector field by using a query vector that represents the term *time travel*:\n\n```rust\nlet query_vector = Vector::Float32(vec![-0.0016261312, -0.028070757, ...]);\nlet pipeline = vec![\n doc! {\n \"$vectorSearch\": doc! {\n \"queryVector\": &query_vector,\n \"path\": \"plot_embedding\",\n \"numCandidates\": 150,\n \"index\": \"vector_index\",\n \"limit\": 5\n }\n },\n doc! {\n \"$project\": doc! {\n \"_id\": 0,\n \"title\": 1,\n \"plot\": 1,\n }\n },\n];\n\nlet mut results = my_coll.aggregate(pipeline).await?;\nwhile let Some(result) = results.try_next().await? {\n println!(\"{}\", result);\n}\n```\n\n```json\n{ \"plot\": \"A reporter, learning of time travelers visiting 20th century disasters, tries to change the history they know by averting upcoming disasters.\", \"title\": \"Thrill Seekers\" }\n{ \"plot\": \"At the age of 21, Tim discovers he can travel in time and change what happens and has happened in his own life. His decision to make his world a better place by getting a girlfriend turns out not to be as easy as you might think.\", \"title\": \"About Time\" }\n{ \"plot\": \"Hoping to alter the events of the past, a 19th century inventor instead travels 800,000 years into the future, where he finds humankind divided into two warring races.\", \"title\": \"The Time Machine\" }\n{ \"plot\": \"After using his mother's newly built time machine, Dolf gets stuck involuntary in the year 1212. He ends up in a children's crusade where he confronts his new friends with modern techniques...\", \"title\": \"Crusade in Jeans\" }\n{ \"plot\": \"An officer for a security agency that regulates time travel, must fend for his life against a shady politician who has a tie to his past.\", \"title\": \"Timecop\" }\n```\n\nThe preceding example creates an instance of `bson::binary::Vector`, introduced in `bson` v2.14, to serve as the query vector. You can also use a `vec` of numbers as a query vector, but we recommend that you use the `Vector` type to improve storage efficiency.\n\n### MongoDB Vector Search Score\n\nThe following code performs the same query as in the preceding example, but outputs only the `title` field and `vectorSearchScore` meta field, which describes how well the document matches the query vector:\n\n```rust\nlet pipeline = vec![\n doc! {\n \"$vectorSearch\": doc! {\n \"queryVector\": &query_vector,\n \"path\": \"plot_embedding\",\n \"numCandidates\": 150,\n \"index\": \"vector_index\",\n \"limit\": 5\n }\n },\n doc! {\n \"$project\": doc! {\n \"_id\": 0,\n \"title\": 1,\n \"score\": doc! { \"$meta\": \"vectorSearchScore\" },\n }\n },\n];\n\nlet mut results = my_coll.aggregate(pipeline).await?;\nwhile let Some(result) = results.try_next().await? {\n println!(\"{}\", result);\n}\n```\n\n```json\n{ \"title\": \"Thrill Seekers\", \"score\": 0.9332504272460938 }\n{ \"title\": \"About Time\", \"score\": 0.9312690496444702 }\n{ \"title\": \"The Time Machine\", \"score\": 0.9295310378074646 }\n{ \"title\": \"Crusade in Jeans\", \"score\": 0.9290415048599243 }\n{ \"title\": \"Timecop\", \"score\": 0.9283164739608765 }\n```\n\n## MongoDB Vector Search Options\n\nYou can use a `$vectorSearch` stage to perform many types of MongoDB Vector Search queries. Depending on your desired query, you can specify the following options in the stage definition:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nOptional Parameter\n\n\nType\n\n\nDescription\n\n\nDefault Value\n\n
\n`exact`\n\n\nboolean\n\n\nSpecifies whether to run an Exact Nearest Neighbor (`true`) or Approximate Nearest Neighbor (`false`) search\n\n\n`false`\n\n
\n`filter`\n\n\ndocument\n\n\nSpecifies a pre-filter for documents to search on\n\n\nNo filtering\n\n
\n`numCandidates`\n\n\nnumber\n\n\nSpecifies the number of nearest neighbors to use during the search\n\n\nNo limit\n\n
To learn more about these options, see the Fields section of the `$vectorSearch` operator reference in the Atlas documentation.\n\n## Additional Information\n\nTo learn more about the concepts mentioned in this guide, see the following Server manual entries:\n\n- Run Vector Search Queries\n\n- Aggregation Pipeline\n\n- Aggregation Stages\n\nTo learn more about the behavior of the `aggregate()` method, see the Aggregation Operations section of the Retrieve Data guide.\n\n### API Documentation\n\nTo learn more about the methods and types mentioned in this guide, see the following API documentation:\n\n- aggregate()\n\n- Vector"} -{"chunk_id": "69d7454c549f5046064e2eca-0", "page_id": "69d7454c549f5046064e2eca", "source_name": "rust", "product_name": "Rust Driver", "url": "https://mongodb.com/docs/drivers/rust/current/indexes", "title": "Indexes", "text": "# Indexes\n\n## Overview\n\nIn this guide, you can learn how to use the Rust driver to create and manage **indexes**. Indexes are special data structures that improve query performance in MongoDB.\n\nIf you perform a query on a collection without any indexes, MongoDB scans every document to find matches. These collection scans are slow and can negatively affect the performance of your application. When you create an index that covers your query, MongoDB limits the number of documents it inspects to find matches, which results in improved performance.\n\nYou can use indexes in update operations, delete operations, and some aggregation pipeline stages. To learn more about using indexes in aggregations, see Improve Performance with Indexes and Document Filters in the Server manual.\n\n### Query Coverage and Performance\n\nThe following table describes the elements that you can include in a MongoDB query:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nElement\n\n\nDescription\n\n
\nQuery\n\n\n*Required*Specifies the fields and values to match\n\n
\nOptions\n\n\n*Optional*Specify how the query executes\n\n
\nProjection\n\n\n*Optional*Specifies the fields that MongoDB returns in matched documents\n\n
\nSort\n\n\n*Optional*Specifies the order of documents returned\n\n
When your query elements reference fields that are all included in the same index, MongoDB can return results directly from the index. These queries are called **covered queries**.\n\nTo learn how to ensure that your index covers your query, see Covered Query in the Server manual.\n\nYour sort criteria must match or invert the order of the index.\n\nSuppose a collection has the following index on the `name` field in ascending order (A-Z) and the `age` field in descending order (9-0):\n\n```none\nname_1_age_-1\n```\n\nMongoDB uses this index when you sort documents in either of the following configurations:\n\n- `name` ascending, `age` descending\n\n- `name` descending, `age` ascending\n\nIf you specify the same sort order for both fields, MongoDB does not use the index and instead performs an in-memory sort.\n\n### Operational Considerations\n\nTo improve your query performance, create indexes on fields that appear often in your queries. However, it is a good practice to track index memory and disk usage for capacity planning, because each index consumes disk space and memory. Additionally, if a write operation updates an indexed field, MongoDB also must update the relevant index.\n\nMongoDB supports dynamic schemas, so your application can query against fields with unknown or variable names. You can create wildcard indexes to support these queries. To learn more about this index type, see Wildcard Indexes in the Server manual.\n\n## Index Types\n\nMongoDB supports multiple index types to support your queries. The following sections describe common index types and show how to create each index type in a collection.\n\nThe examples in this guide use collections from the Atlas sample data. To learn how to import this data, see the Load Sample Data tutorial in the Atlas documentation.\n\nYou can use the `create_index()` and `create_indexes()` methods to create indexes in a collection. The `create_index()` method takes an `IndexModel` struct parameter that you can construct by using the type's `builder()` method.\n\nTo view a full list of index types, see Index Types in the Server manual.\n\n### Single Field Indexes\n\nA single field index holds a reference to a document field.\n\nThis index improves the performance of single field queries and sorts. It also supports TTL indexes that automatically remove documents from a collection after a certain amount of time. To learn more about TTL indexes, see TTL indexes in the Server manual.\n\nWhen you create a new collection, MongoDB automatically creates a unique, single field index on the `_id` field.\n\n#### Example\n\nThe following code creates an ascending index on the `city` field in the `sample_training.zips` collection:\n\n```rust\nlet index = IndexModel::builder().keys(doc! { \"city\": 1 }).build();\n\nlet idx = my_coll.create_index(index).await?;\nprintln!(\"Created index:\\n{}\", idx.index_name);\n```\n\n```console\nCreated index:\ncity_1\n```\n\n### Compound Indexes\n\nA compound index holds a reference to multiple document fields.\n\nThis index improves the performance of queries and sorts on multiple fields. When you create a compound index, you must specify a direction for each of the indexed fields.\n\nYou can create a multikey index by using the same syntax for creating a single field index.\n\n#### Example\n\nThe following code creates a compound index on the `city` and `pop` fields in the `sample_training.zips` collection:\n\n```rust\nlet index = IndexModel::builder()\n .keys(doc! { \"city\": 1, \"pop\": -1 })\n .build();\n\nlet idx = my_coll.create_index(index).await?;\nprintln!(\"Created index:\\n{}\", idx.index_name);\n```\n\n```console\nCreated index:\ncity_1_pop_-1\n```\n\n### Multikey Indexes (Array Field Indexes)\n\nA multikey index holds a reference to an array-valued field. This index improves the performance of queries on array fields.\n\nYou can create a multikey index by using the same syntax for creating a single field index.\n\n#### Example\n\nThe following code creates a multikey index on the `tags` field in the `sample_training.posts` collection:\n\n```rust\nlet index = IndexModel::builder().keys(doc! { \"tags\": 1 }).build();\n\nlet idx = my_coll.create_index(index).await?;\nprintln!(\"Created index:\\n{}\", idx.index_name);\n```\n\n```console\nCreated index:\ntags_1\n```\n\n### Clustered Indexes\n\nClustered indexes improve the performance of insert, update, and delete operations on clustered collections. Clustered collections store documents ordered by the clustered index key value. To learn more about these collections, see Clustered Collections in the Server manual.\n\nYou can create a clustered index only when creating a collection. To create a clustered collection, perform the following steps:\n\n1. Create a `ClusteredIndex` instance.\n\n2. Call the `create_collection()` method.\n\n3. Chain the `clustered_index()` method to the `create_collection()` method, passing your `ClusteredIndex` instance as a parameter of `clustered_index()`.\n\nYou must set the following fields of the `ClusteredIndex` struct:\n\n- The `key` field, which specifies the key pattern. The value of this field must be `{ _id: 1 }`.\n\n- The `unique` field, which specifies the uniqueness of the index. The value of this field must be `true`.\n\nTo create a `ClusteredIndex` instance that automatically uses the required values, you can call the type's `default()` method.\n\n#### Example\n\nThe following code creates a clustered index with default configuration on the `_id` field when creating a new collection called `items` in the `sample_training` database:\n\n```rust\nlet db = client.database(\"sample_training\");\nlet cl_idx = ClusteredIndex::default();\n\ndb.create_collection(\"items\")\n .clustered_index(cl_idx)\n .await?;\n```"} -{"chunk_id": "69d7454c549f5046064e2eca-1", "page_id": "69d7454c549f5046064e2eca", "source_name": "rust", "product_name": "Rust Driver", "url": "https://mongodb.com/docs/drivers/rust/current/indexes", "title": "Indexes", "text": "### Text Indexes\n\nA text index supports text query queries on string content. This index references a field with a string value or a string array value. MongoDB supports text query for several languages. When you create a text index, you can specify the default language as an option.\n\nA collection can only contain one text index. To create a text index on multiple text fields, you can create a compound index. When you run a text query after creating a compound index, the search operation runs on all the text fields in the compound index.\n\nText indexes are different from MongoDB Search indexes, which enable full-text searches. To learn more about MongoDB Search indexes, see the MongoDB Search and Vector Search Indexes guide.\n\n#### Example\n\nThe following code creates a text index on the `body` field in the `sample_training.posts` collection. The code sets an option to specify `\"spanish\"` as the default language for the text index:\n\n```rust\nlet idx_opts = IndexOptions::builder()\n .default_language(\"spanish\".to_string())\n .build();\n\nlet index = IndexModel::builder()\n .keys(doc! { \"body\": \"text\" })\n .options(idx_opts)\n .build();\n\nlet idx = my_coll.create_index(index).await?;\nprintln!(\"Created index:\\n{}\", idx.index_name);\n```\n\n```console\nCreated index:\nbody_\"text\"\n```\n\n### Geospatial Indexes\n\nMongoDB supports queries containing geospatial coordinate data by using `2dsphere` indexes. You can create a `2dsphere` index on a field with GeoJSON object values.\n\nThis index type supports the following tasks:\n\n- Queries on geospatial data to find inclusion, intersection, and proximity\n\n- Calculation of distances on a Euclidean plane\n\nYou cannot create two geospatial indexes on the same field.\n\n#### Example\n\nThe following sample document in the `sample_mflix.theaters` collection contains the field `location.geo`. This field has a GeoJSON point value:\n\n```javascript\n{\n \"_id\": ...,\n \"theaterId\": ...,\n \"location\": {\n \"address\": ...,\n \"geo\": {\n \"type\": \"Point\",\n \"coordinates\": [\n -93.24565,\n 44.85466\n ]\n }\n }\n}\n```\n\nThe following code creates a geospatial `2dsphere` index on the `location.geo` field in the `sample_mflix.theaters` collection:\n\n```rust\nlet index = IndexModel::builder()\n .keys(doc! { \"location.geo\": \"2dsphere\" })\n .build();\n\nlet idx = my_coll.create_index(index).await?;\nprintln!(\"Created index:\\n{}\", idx.index_name);\n```\n\n```console\nCreated index:\nlocation.geo_\"2dsphere\"\n```\n\n### Unique Indexes\n\nA unique index ensures that the indexed fields do not store duplicate values. By default, MongoDB creates a unique, single field index on the `_id` field when you create a collection.\n\nTo create a unique index, specify the field or combination of fields that you want to maintain uniqueness for and set the `unique` option to `true`.\n\n#### Example\n\nThe following code shows how to set the `unique` field to `true` in an `IndexOptions` instance and pass these options when creating an `IndexModel`:\n\n```rust\nlet opts = IndexOptions::builder().unique(true).build();\nlet index = IndexModel::builder()\n .keys(doc! { \"_id\": -1 })\n .options(opts)\n .build();\n```\n\n## Remove an Index\n\nYou can remove, or drop, any indexes from a collection except the default unique index on the `_id` field. To remove an index, pass the name of the index to the `drop_index()` method.\n\nYou can remove all the indexes on a collection except for the `_id` index at once by using the `drop_indexes()` method.\n\nThe following example removes an index called `city_1` from the `sample_training.zips` collection:\n\n```rust\nmy_coll.drop_index(\"city_1\".to_string()).await?;\n```\n\n## Additional Information\n\nTo learn more about designing data models and creating appropriate indexes for your application, see Indexing Strategies and Create Indexes to Support Your Queries in the Server manual.\n\nTo learn more about performing read operations, see the guides in the Find Documents guide.\n\nTo learn more about the concepts mentioned in this guide, see the following Server documentation:\n\n- Single Field Indexes\n\n- TTL Indexes\n\n- Compound Indexes\n\n- Multikey Indexes\n\n- Text Indexes\n\n- Compound Text Indexes\n\n- Geospatial Queries\n\n- GeoJSON Objects\n\n- Unique Indexes\n\n- Clustered Collections\n\n### API Documentation\n\nTo learn more about the methods and types mentioned in this guide, see the following API documentation:\n\n- create_index()\n\n- create_indexes()\n\n- IndexModel\n\n- IndexOptions\n\n- ClusteredIndex\n\n- CreateCollectionOptions\n\n- drop_index()\n\n- drop_indexes()"} -{"chunk_id": "69d7454c549f5046064e2ef7-0", "page_id": "69d7454c549f5046064e2ef7", "source_name": "rust", "product_name": "Rust Driver", "url": "https://mongodb.com/docs/drivers/rust/current/security/authentication", "title": "Authentication Mechanisms", "text": "# Authentication Mechanisms\n\n## Overview\n\nIn this guide, you can learn how to authenticate to MongoDB by using the **authentication mechanisms** available in MongoDB Server. Authentication mechanisms are processes by which the driver and server confirm the identity of a client to ensure security before connecting.\n\nTo learn how to establish a connection to your MongoDB deployment, see Create a MongoDB Client.\n\n## MongoDB Edition Compatibility\n\nThe following table lists the authentication mechanisms supported by MongoDB and the MongoDB Server editions that each mechanism is compatible with. Click the name of a mechanism to learn more about how to use it with your application.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nAuthentication Mechanism\n\n\nAtlas\n\n\nEnterprise Advanced\n\n\nCommunity\n\n
\nSCRAM\n\n\nYes\n\n\nYes\n\n\nYes\n\n
\nX.509\n\n\nYes\n\n\nYes\n\n\nYes\n\n
\nAWS IAM\n\n\nYes\n\n\nNo\n\n\nNo\n\n
\nOIDC (Workload Identity Federation)\n\n\nYes\n\n\nYes\n\n\nNo\n\n
\nLDAP (PLAIN SASL)\n\n\nYes\n\n\nYes\n\n\nNo\n\n
\nKerberos (GSSAPI)\n\n\nNo\n\n\nYes\n\n\nNo\n\n
\n\n## Specifying Authentication Mechanisms\n\nTo select a specific authentication mechanism, you can specify the mechanism, your credentials, and other necessary information in the options of your connection string or in a `Credential` struct.\n\nThe examples in the authentication mechanism guides demonstrate how to configure authentication in a `Credential` struct.\n\nTo learn more about the connection string options for authentication, see the Authentication Options section of the Connection Strings Option guide in the MongoDB Server manual."} -{"chunk_id": "69d7454c549f5046064e2e45-0", "page_id": "69d7454c549f5046064e2e45", "source_name": "rust", "product_name": "Rust Driver", "url": "https://mongodb.com/docs/drivers/rust/current/crud/delete", "title": "Delete Documents", "text": "# Delete Documents\n\n## Overview\n\nIn this guide, you can learn how to remove documents from your MongoDB collections using **delete operations**.\n\nThis guide includes the following sections:\n\n- Sample Data for Examples presents the sample data that is used by the delete operation example\n\n- Delete Operations describes how to use the driver to execute delete operations\n\n- Delete Examples provides code examples for the delete operations\n\n- Additional Information provides links to resources and API documentation for types and methods mentioned in this guide\n\n## Sample Data for Examples\n\nThe example in this guide uses the following sample documents. Each document represents an item in a store's inventory and contains information about its categorization and unit price:\n\n```json\n{ \"item\": \"trowel\", \"category\": \"garden\", \"unit_price\": 9.89 },\n{ \"item\": \"placemat\", \"category\": \"kitchen\", \"unit_price\": 3.19 },\n{ \"item\": \"watering can\", \"category\": \"garden\", \"unit_price\": 11.99 }\n```\n\n## Delete Operations\n\nThe Rust driver provides the `delete_one()` and `delete_many()` methods to perform delete operations.\n\n### Parameters\n\nThe `delete_one()` and `delete_many()` methods take a query filter as a parameter. A query filter consists of the fields and values that form criteria for documents to match.\n\n### Options\n\nYou can modify the behavior of the delete operation methods by chaining option builder methods to `delete_one()` and `delete_many()`. These option methods set `DeleteOptions` struct fields.\n\nYou can set `DeleteOptions` fields by chaining option builder methods directly to the delete method call. If you're using an earlier version of the driver, you must construct an `DeleteOptions` instance by chaining option builder methods to the `builder()` method. Then, pass your options instance as a parameter to `delete_one()` or `delete_many()`.\n\nThe following table describes the options available in `DeleteOptions`:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nOption\n\n\nDescription\n\n
\n`collation`\n\n\nThe collation to use when sorting results. To learn more about collations, see the Collations guide.Type: `Collation`Default: `None`\n\n
\n`write_concern`\n\n\nThe write concern for the operation. If you don't set this option, the operation inherits the write concern set for the collection. To learn more about write concerns, see Write Concern in the Server manual.Type: `WriteConcern`\n\n
\n`hint`\n\n\nThe index to use for the operation. To learn more about indexes, see Indexes in the Server manual. This option is available only when connecting to MongoDB Server versions 4.4 and later.Type: `Hint`Default: `None`\n\n
\n`let_vars`\n\n\nA map of parameters and values. These parameters can be accessed as variables in aggregation expressions. This option is available only when connecting to MongoDB Server versions 5.0 and later.Type: `Document`\n\n
\n`comment`\n\n\nAn arbitrary `Bson` value tied to the operation to trace it through the database profiler, `currentOp`, and logs. This option is available only when connecting to MongoDB Server versions 4.4 and later.Type: `Bson`Default: `None`\n\n
The following code shows how to set the `comment` field by chaining the `comment()` method to the `delete_one()` method:\n\n```rust\nlet res = my_coll\n .delete_one(filter)\n .comment(bson!(\"hello!\"))\n .await?;\n```\n\n### Return Value\n\nThe `delete_one()` and `delete_many()` methods return a `DeleteResult` type. This type contains the `deleted_count` property, which describes the number of documents deleted. If no documents match the query filter you specified, the delete operation does not remove any documents, and the value of `deleted_count` is `0`.\n\n## Delete Examples\n\nThis section provides code examples for the following delete operations:\n\n- delete_one()\n\n- delete_many()\n\n### Delete One Example\n\nThe following example uses the `delete_one()` method to delete a document that has an `item` value of `\"placemat\"`:\n\n```rust\nlet filter = doc! { \"item\": \"placemat\" };\n\nlet res = my_coll.delete_one(filter).await?;\nprintln!(\"Deleted documents: {}\", res.deleted_count);\n```\n\n```console\nDeleted documents: 1\n```\n\n### Full File Example: Delete a Document\n\nThis example deletes a document that matches a query filter from the `restaurants` collection in the `sample_restaurants` database. The `delete_one()` method deletes the first document in which the value of the `name` field is `\"Haagen-Dazs\"` and the `borough` field is `\"Brooklyn\"`.\n\nYou can access the documents in the `restaurants` collection as instances of the `Document` type or a custom data type. To specify which data type represents the collection's data, replace the `` type parameter on the highlighted line with one of the following values:\n\n- ``: Accesses collection documents as BSON documents\n\n- ``: Accesses collection documents as instances of the `Restaurant` struct, defined at the top of the code\n\nSelect the Asynchronous or Synchronous tab to see the corresponding code for each runtime:\n\n\n\n\n\n```rust\nuse mongodb::{\n bson::{ Document, doc },\n Client,\n Collection\n};\nuse serde::{ Deserialize, Serialize };\n\n#[derive(Serialize, Deserialize, Debug)]\nstruct Restaurant {\n name: String,\n borough: String,\n}\n\n#[tokio::main]\nasync fn main() -> mongodb::error::Result<()> {\n let uri = \"\";\n let client = Client::with_uri_str(uri).await?;\n\n // Replace with the or type parameter\n let my_coll: Collection = client\n .database(\"sample_restaurants\")\n .collection(\"restaurants\");\n\n let filter =\n doc! { \"$and\": [\n doc! { \"name\": \"Haagen-Dazs\" },\n doc! { \"borough\": \"Brooklyn\" }\n ]\n };\n\n let result = my_coll.delete_one(filter).await?;\n\n println!(\"Deleted documents: {}\", result.deleted_count);\n\n Ok(())\n}\n\n```\n\n```console\nDeleted documents: 1\n```\n\n\n\n\n\n```rust\nuse mongodb::{\n bson::{ Document, doc },\n sync::{ Client, Collection }\n};\nuse serde::{ Deserialize, Serialize };\n\n#[derive(Serialize, Deserialize, Debug)]\nstruct Restaurant {\n name: String,\n borough: String,\n}\n\nfn main() -> mongodb::error::Result<()> {\n let uri = \"\";\n let client = Client::with_uri_str(uri)?;\n\n // Replace with the or type parameter\n let my_coll: Collection = client\n .database(\"sample_restaurants\")\n .collection(\"restaurants\");\n\n let filter =\n doc! { \"$and\": [\n doc! { \"name\": \"Haagen-Dazs\" },\n doc! { \"borough\": \"Brooklyn\" }\n ]\n };\n\n let result = my_coll.delete_one(filter).run()?;\n\n println!(\"Deleted documents: {}\", result.deleted_count);\n\n Ok(())\n}\n\n```\n\n```console\nDeleted documents: 1\n```\n\n\n\n\n\n### Delete Many Example\n\nThis example performs the following actions:\n\n- Calls the `delete_many()` method\n\n- Passes a query filter to `delete_many()` that matches documents where the value of `category` is `\"garden\"`\n\n- Chains the `hint()` method to `delete_many()` to use the `_id_` index as the hint for the delete operation\n\n```rust\nlet filter = doc! { \"category\": \"garden\" };\nlet hint = Hint::Name(\"_id_\".to_string());\n\nlet res = my_coll\n .delete_many(filter)\n .hint(hint)\n .await?;\nprintln!(\"Deleted documents: {}\", res.deleted_count);\n```\n\n```console\nDeleted documents: 2\n```\n\nIf you use the `delete_one()` method instead of `delete_many()` in the preceding code example, the driver deletes only the first of the two documents that match the query filter."} -{"chunk_id": "69d7454c549f5046064e2e45-1", "page_id": "69d7454c549f5046064e2e45", "source_name": "rust", "product_name": "Rust Driver", "url": "https://mongodb.com/docs/drivers/rust/current/crud/delete", "title": "Delete Documents", "text": "### Full File Example: Delete Multiple Documents\n\nThis example deletes all documents that match a query filter from the `restaurants` collection in the `sample_restaurants` database. The `delete_many()` method deletes documents in which the value of the `borough` field is `\"Manhattan\"` and the value of the `address.street` field is `\"Broadway\"`.\n\nYou can access the documents in the `restaurants` collection as instances of the `Document` type or a custom data type. To specify which data type represents the collection's data, replace the `` type parameter on the highlighted line with one of the following values:\n\n- ``: Accesses collection documents as BSON documents\n\n- ``: Accesses collection documents as instances of the `Restaurant` struct, defined at the top of the code\n\nSelect the Asynchronous or Synchronous tab to see the corresponding code for each runtime:\n\n\n\n\n\n```rust\nuse mongodb::{\n bson::{ Document, doc },\n Client,\n Collection\n};\nuse serde::{ Deserialize, Serialize };\n\n#[derive(Debug, Serialize, Deserialize)]\nstruct Address {\n street: String,\n city: String,\n}\n\n#[derive(Serialize, Deserialize, Debug)]\nstruct Restaurant {\n name: String,\n borough: String,\n address: Address,\n}\n\n#[tokio::main]\nasync fn main() -> mongodb::error::Result<()> {\n let uri = \"\";\n let client = Client::with_uri_str(uri).await?;\n\n // Replace with the or type parameter\n let my_coll: Collection = client\n .database(\"sample_restaurants\")\n .collection(\"restaurants\");\n\n let filter =\n doc! { \"$and\": [\n doc! { \"borough\": \"Manhattan\" },\n doc! { \"address.street\": \"Broadway\" }\n ]\n };\n\n let result = my_coll.delete_many(filter).await?;\n\n println!(\"Deleted documents: {}\", result.deleted_count);\n\n Ok(())\n}\n\n```\n\n```console\n// Your values might differ\nDeleted documents: 615\n```\n\n\n\n\n\n```rust\nuse mongodb::{\n bson::{ Document, doc },\n sync::{ Client, Collection }\n};\nuse serde::{ Deserialize, Serialize };\n\n#[derive(Debug, Serialize, Deserialize)]\nstruct Address {\n street: String,\n city: String,\n}\n\n#[derive(Serialize, Deserialize, Debug)]\nstruct Restaurant {\n name: String,\n borough: String,\n address: Address,\n}\n\nfn main() -> mongodb::error::Result<()> {\n let uri = \"\";\n let client = Client::with_uri_str(uri)?;\n\n // Replace with the or type parameter\n let my_coll: Collection = client\n .database(\"sample_restaurants\")\n .collection(\"restaurants\");\n\n let filter =\n doc! { \"$and\": [\n doc! { \"borough\": \"Manhattan\" },\n doc! { \"address.street\": \"Broadway\" }\n ]\n };\n\n let result = my_coll.delete_many(filter).run()?;\n\n println!(\"Deleted documents: {}\", result.deleted_count);\n\n Ok(())\n}\n\n```\n\n```console\n// Your values might differ\nDeleted documents: 615\n```\n\n\n\n\n\n## Additional Information\n\nTo learn more about the operations in this guide, see the following documentation:\n\n- Specify a Query guide\n\n- Collations guide\n\n### API Documentation\n\nTo learn more about the methods and types mentioned in this guide, see the following API documentation:\n\n- delete_one()\n\n- delete_many()\n\n- DeleteOptions\n\n- Hint\n\n- DeleteResult"} -{"chunk_id": "69d7454c549f5046064e2e9c-0", "page_id": "69d7454c549f5046064e2e9c", "source_name": "rust", "product_name": "Rust Driver", "url": "https://mongodb.com/docs/drivers/rust/current/crud/web-app-tutorial", "title": "CRUD Web App with Rocket", "text": "# CRUD Web App with Rocket\n\n## Overview\n\nIn this tutorial, you can learn how to create a Rust web application by using the Rocket web framework. The Rust driver allows you to leverage features such as memory management, lifetimes, and database pooling to improve your application's performance.\n\nAfter you complete this tutorial, you will have a web application with routes to perform CRUD operations.\n\nTo view the complete sample app for this tutorial, see the web-app-tutorial folder on GitHub.\n\n## Prerequisites\n\nEnsure you have Rust 1.88 or later, and Cargo, the Rust package manager, installed in your development environment.\n\nFor information about how to install Rust and Cargo, see the official Rust guide on downloading and installing Rust.\n\nYou must also set up a MongoDB Atlas cluster. To learn how to create a cluster, see the Create a MongoDB Deployment step of the Quick Start guide. Save your connection string in a safe location to use later in the tutorial.\n\n## Steps\n\n### Create a Rust project.\n\nRun the following commands to create and enter the `rust-crud-app` project directory:\n\n```bash\ncargo new rust-crud-app\ncd rust-crud-app\n```\n\n### Install the Rust driver.\n\nRun the following command to add the Rust driver:\n\n```shell\ncargo add mongodb\n```\n\nVerify that your `Cargo.toml` file contains the following entry for the Rust driver:\n\n```toml\n[dependencies]\nmongodb = \"3.9.1\"\n```\n\n### Select the asynchronous runtime.\n\nWhen using the Rust driver, you must select either the synchronous or asynchronous runtime. This tutorial uses the asynchronous runtime, which is more suitable for building APIs.\n\nThe driver runs with the async `tokio` runtime by default.\n\nTo learn more about the available runtimes, see the Asynchronous and Synchronous APIs guide.\n\n### Create a database and collection in the Atlas UI.\n\nAccess the Atlas UI, and then select the Collections tab in your cluster settings. Select the + Create Database button. In the modal, create a database called `bread`, and within it, a collection called `recipes`.\n\n### Insert sample data.\n\nSelect the INSERT DOCUMENT button and paste the contents of the bread_data.json file in the sample app.\n\nAfter you insert the data, you can see the sample documents in the `recipes` collection.\n\n### Install Rocket.\n\nOpen your IDE and enter your project directory. Run the following command from your project root to install the Rocket web framework:\n\n```bash\ncargo add -F json rocket\n```\n\nVerify that the dependencies list in your `Cargo.toml` file contains an entry for `rocket`.\n\nYou must also add a crate developed by Rocket that allows you to use a wrapper to manage a collection pool for the async connections made by your MongoDB client. This crate allows you to parameterize your MongoDB databases and collections and have each app function receive its own connection to use.\n\nRun the following command to add the `rocket_db_pools` crate:\n\n```shell\ncargo add -F mongodb rocket_db_pools\n```\n\nVerify that the dependencies list in your `Cargo.toml` file contains an entry for `rocket_db_pools` that contains a feature flag for `mongodb`.\n\n### Configure Rocket.\n\nTo configure Rocket to use the `bread` database, create a file called `Rocket.toml` in your project root. Rocket looks for this file to read configuration settings. You can also store your MongoDB connection string in this file.\n\nPaste the following configuration into the `Rocket.toml` file:\n\n```toml\n[default.databases.db]\nurl = \"\"\n\n```\n\nTo learn more about configuring Rocket, see Configuration in the Rocket documentation.\n\n### Learn about the app structure.\n\nBefore you begin writing the API, learn about the structure of a simple Rocket app and create the corresponding files in your application.\n\nThe following diagram demonstrates the file structure that your Rocket app must have and explains the function of each file:\n\n```text\n.\n\u251c\u2500\u2500 Cargo.lock # Dependency info\n\u251c\u2500\u2500 Cargo.toml # Project and dependency info\n\u251c\u2500\u2500 Rocket.toml # Rocket configuration\n\u2514\u2500\u2500 src # Directory for all app code\n \u251c\u2500\u2500 db.rs # Establishes database connection\n \u251c\u2500\u2500 main.rs # Starts the web app\n \u251c\u2500\u2500 models.rs # Organizes data\n \u2514\u2500\u2500 routes.rs # Stores API routes\n```\n\nCreate the `src` directory and the files it contains, according to the preceding diagram. At this point, the files can be empty.\n\n### Set up the database connection.\n\nPaste the following code into the `db.rs` file:\n\n```rust\nuse rocket_db_pools::{mongodb::Client, Database};\n\n#[derive(Database)]\n#[database(\"db\")]\npub struct MainDatabase(Client);\n\n```\n\nYou must also attach the database struct to your Rocket instance. Copy the following template code into your `main.rs` file:\n\n```rust\nmod db;\nmod models;\nmod routes;\n\nuse rocket::{launch, routes};\nuse rocket_db_pools::Database;\n\n#[launch]\nfn rocket() -> _ {\n rocket::build()\n .attach(db::MainDatabase::init())\n // Paste mount() call below\n}\n```\n\nYour IDE might raise an error that the function body is incomplete. You can ignore this error, because you will add the `mount()` call in a later step.\n\n### Create data models.\n\nDefining consistent and useful structs to represent your data is important for maintaining type safety and reducing runtime errors.\n\nIn your `models.rs` file, define a `Recipe` struct that represents a recipe to bake bread:\n\n```rust\nuse mongodb::bson::oid::ObjectId;\nuse rocket::serde::{Deserialize, Serialize};\n\n#[derive(Debug, Serialize, Deserialize)]\n#[serde(crate = \"rocket::serde\")]\npub struct Recipe {\n #[serde(rename = \"_id\", skip_serializing_if = \"Option::is_none\")]\n pub id: Option,\n pub title: String,\n pub ingredients: Vec,\n pub temperature: u32,\n pub bake_time: u32,\n}\n\n```\n\n### Set up API routes.\n\nRouting allows the program to direct the request to the proper endpoint to send or receive the data. The file `routes.rs` stores all the routes defined in the API.\n\nCopy the following template code into your `routes.rs` file:\n\n```rust\nuse crate::db::MainDatabase;\nuse crate::models::Recipe;\nuse mongodb::bson::doc;\nuse mongodb::bson::oid::ObjectId;\nuse rocket::{\n delete, futures::TryStreamExt, get, http::Status, post, put, response::status,\n serde::json::Json,\n};\nuse rocket_db_pools::Connection;\nuse serde_json::{json, Value};\n\n// Paste index route below\n\n// Paste get_recipes route below\n\n// Paste get_recipe route below\n\n// Paste update_recipe route below\n\n// Paste delete_recipe route below\n\n// Paste create_recipe route below\n```\n\nPaste the following `index` route under the `// Paste index route below` comment:\n\n```rust\n#[get(\"/\")]\npub fn index() -> Json {\n Json(json!({\"status\": \"It is time to make some bread!!!\"}))\n}\n```\n\nBefore you write the remaining routes, add the routes to the main launch function for Rocket.\n\nIn your `main.rs` file, paste the following code under the `// Paste mount() call below` comment:\n\n```rust\n .mount(\n \"/\",\n routes![\n routes::index,\n routes::get_recipes,\n routes::create_recipe,\n routes::get_recipe,\n routes::update_recipe,\n routes::delete_recipe,\n ],\n )\n```\n\n### Implement error handling and responses.\n\nIn your app, you must implement error handling and custom responses to deal with unexpected outcomes of your CRUD operations.\n\nInstall the `serde_json` crate by running the following command:\n\n```bash\ncargo add serde_json\n```\n\nThis crate includes the `Value` enum that represents a JSON value.\n\nYou can specify that your routes return HTTP status codes by using Rocket's `status::Custom` structs, which allow you to specify the HTTP status code and any custom data to return. The following step describes how to write routes that return the `status::Custom` type."} -{"chunk_id": "69d7454c549f5046064e2e9c-1", "page_id": "69d7454c549f5046064e2e9c", "source_name": "rust", "product_name": "Rust Driver", "url": "https://mongodb.com/docs/drivers/rust/current/crud/web-app-tutorial", "title": "CRUD Web App with Rocket", "text": "### Write CRUD operation routes.\n\n#### Create\n\nWhen you attempt to create data in MongoDB, there are two possible outcomes:\n\n- Document is successfully created, so your app returns `HTTP 201`.\n\n- Error occurred during insertion, so your app returns `HTTP 400`.\n\nPaste the following `create_recipe()` route under the `// Paste create_recipe route below` comment in your `routes.rs` file:\n\n```rust\n#[post(\"/recipes\", data = \"\", format = \"json\")]\npub async fn create_recipe(\n db: Connection,\n data: Json,\n) -> status::Custom> {\n if let Ok(res) = db\n .database(\"bread\")\n .collection::(\"recipes\")\n .insert_one(data.into_inner(), None)\n .await\n {\n if let Some(id) = res.inserted_id.as_object_id() {\n return status::Custom(\n Status::Created,\n Json(\n json!({\"status\": \"success\", \"message\": format!(\"Recipe ({}) created successfully\", id.to_string())}),\n ),\n );\n }\n }\n\n status::Custom(\n Status::BadRequest,\n Json(json!({\"status\": \"error\", \"message\":\"Recipe could not be created\"})),\n )\n}\n```\n\n#### Read\n\nWhen you attempt to read data from MongoDB, there are two possible outcomes:\n\n- Return the vector of matching documents.\n\n- Return an empty vector, because there are no matching documents or because an error occurred.\n\nBecause of these expected outcomes, paste the following `get_recipes()` route under the `// Paste get_recipes route below` comment in your `routes.rs` file:\n\n```rust\n#[get(\"/recipes\", format = \"json\")]\npub async fn get_recipes(db: Connection) -> Json> {\n let recipes = db\n .database(\"bread\")\n .collection(\"recipes\")\n .find(None, None)\n .await;\n\n if let Ok(r) = recipes {\n if let Ok(collected) = r.try_collect::>().await {\n return Json(collected);\n }\n }\n\n return Json(vec![]);\n}\n```\n\n#### Retrieve by ID\n\nPaste the following `get_recipe()` route under the `// Paste get_recipe route below` comment:\n\n```rust\n#[get(\"/recipes/\", format = \"json\")]\npub async fn get_recipe(\n db: Connection,\n id: &str,\n) -> status::Custom> {\n let b_id = ObjectId::parse_str(id);\n\n if b_id.is_err() {\n return status::Custom(\n Status::BadRequest,\n Json(json!({\"status\": \"error\", \"message\":\"Recipe ID is invalid\"})),\n );\n }\n\n if let Ok(Some(recipe)) = db\n .database(\"bread\")\n .collection::(\"recipes\")\n .find_one(doc! {\"_id\": b_id.unwrap()}, None)\n .await\n {\n return status::Custom(\n Status::Ok,\n Json(json!({\"status\": \"success\", \"data\": recipe})),\n );\n }\n\n return status::Custom(\n Status::NotFound,\n Json(json!({\"status\": \"success\", \"message\": \"Recipe not found\"})),\n );\n}\n```\n\nThis route retrieves a single document by its `_id` value.\n\n#### Update\n\nPaste the following `update_recipe()` route under the `// Paste update_recipe route below` comment:\n\n```rust\n#[put(\"/recipes/\", data = \"\", format = \"json\")]\npub async fn update_recipe(\n db: Connection,\n data: Json,\n id: &str,\n) -> status::Custom> {\n let b_id = ObjectId::parse_str(id);\n\n if b_id.is_err() {\n return status::Custom(\n Status::BadRequest,\n Json(json!({\"status\": \"error\", \"message\":\"Recipe ID is invalid\"})),\n );\n }\n\n if let Ok(_) = db\n .database(\"bread\")\n .collection::(\"recipes\")\n .update_one(\n doc! {\"_id\": b_id.as_ref().unwrap()},\n doc! {\"$set\": mongodb::bson::to_document(&data.into_inner()).unwrap()},\n None,\n )\n .await\n {\n return status::Custom(\n Status::Created,\n Json(\n json!({\"status\": \"success\", \"message\": format!(\"Recipe ({}) updated successfully\", b_id.unwrap())}),\n ),\n );\n };\n\n status::Custom(\n Status::BadRequest,\n Json(\n json!({\"status\": \"success\", \"message\": format!(\"Recipe ({}) could not be updated successfully\", b_id.unwrap())}),\n ),\n )\n}\n```\n\nThis route updates a single document by its `_id` value.\n\n#### Delete\n\nPaste the following `delete_recipe()` route after the `// Paste delete_recipe route below` comment:\n\n```rust\n#[delete(\"/recipes/\")]\npub async fn delete_recipe(\n db: Connection,\n id: &str,\n) -> status::Custom> {\n let b_id = ObjectId::parse_str(id);\n\n if b_id.is_err() {\n return status::Custom(\n Status::BadRequest,\n Json(json!({\"status\": \"error\", \"message\":\"Recipe ID is invalid\"})),\n );\n }\n\n if db\n .database(\"bread\")\n .collection::(\"recipes\")\n .delete_one(doc! {\"_id\": b_id.as_ref().unwrap()}, None)\n .await\n .is_err()\n {\n return status::Custom(\n Status::BadRequest,\n Json(\n json!({\"status\": \"error\", \"message\":format!(\"Recipe ({}) could not be deleted\", b_id.unwrap())}),\n ),\n );\n };\n\n status::Custom(\n Status::Accepted,\n Json(\n json!({\"status\": \"\", \"message\": format!(\"Recipe ({}) successfully deleted\", b_id.unwrap())}),\n ),\n )\n}\n```\n\nThis route deletes a single document by its `_id` value.\n\n### Test routes to perform CRUD operations.\n\nStart your application by running the following command in your terminal:\n\n```bash\ncargo run\n```\n\nIn another terminal window, run the following command to test the `create_recipe()` route:\n\n```bash\ncurl -v --header \"Content-Type: application/json\" --request POST --data '{\"title\":\"simple bread recipe\",\"ingredients\":[\"water, flour\"], \"temperature\": 250, \"bake_time\": 120}' http://127.0.0.1:8000/recipes\n```\n\n```none\n{\"status\":\"success\",\"message\":\"Recipe (684c4245f5a3ca09efa92593) created successfully\"}\n```\n\nRun the following command to test the `get_recipes()` route:\n\n```bash\ncurl -v --header \"Content-Type: application/json\" --header \"Accept: application/json\" http://127.0.0.1:8000/recipes/\n```\n\n```none\n[{\"_id\":...,\"title\":\"artisan\",\"ingredients\":[\"salt\",\"flour\",\"water\",\"yeast\"],\"temperature\":404,\"bake_time\":5},\n{\"_id\":...,\"title\":\"rye\",\"ingredients\":[\"salt\"],\"temperature\":481,\"bake_time\":28},...]\n```\n\nRun the following command to test the `delete_recipe()` route. Replace the `` placeholder with a known `_id` value from your collection, which might resemble `68484d020f561e78c03c7800`:\n\n```bash\ncurl -v --header \"Content-Type: application/json\" --header \"Accept: application/json\" --request DELETE http://127.0.0.1:8000/recipes/\n```\n\n```none\n{\"status\":\"\",\"message\":\"Recipe (68484d020f561e78c03c7800) successfully deleted\"}\n```\n\n## Conclusion\n\nIn this tutorial, you learned how to build a simple web application with Rocket to perform CRUD operations.\n\n### Resources\n\nTo learn more about CRUD operations, see the following guides:\n\n- Insert Documents\n\n- Find Documents\n\n- Specify a Query\n\n- Replace Documents\n\n- Delete Documents"} -{"chunk_id": "69d7454c549f5046064e2e96-0", "page_id": "69d7454c549f5046064e2e96", "source_name": "rust", "product_name": "Rust Driver", "url": "https://mongodb.com/docs/drivers/rust/current/crud/update/replace", "title": "Replace Documents", "text": "# Replace Documents\n\n## Overview\n\nIn this guide, you can learn how to use the Rust driver to replace documents in a MongoDB collection by using the `replace_one()` method.\n\nReplace operations remove all existing fields of a document except for the `_id` field and substitute the removed fields with new fields and values.\n\nTo learn how to update specific fields in documents, see the Update Documents guide.\n\nThis guide includes the following sections:\n\n- Replace a Document describes how to use the driver to execute replace operations\n\n- Modify Replace Behavior describes how to modify the default behavior of the `replace_one()` method\n\n- Additional Information provides links to resources and API documentation for types and methods mentioned in this guide\n\n### The _id Field\n\nEach document in a MongoDB collection has a unique and immutable `_id` field. If you attempt to change the `_id` field through a replace operation, the driver raises a `WriteError` and performs no updates.\n\n## Replace a Document\n\nYou can perform a replace operation with the `replace_one()` method. This method removes all existing fields of a document except for the `_id` field and substitutes the removed fields with new fields and values that you specify.\n\nYou can also chain option builder methods to the `replace_one()` method. To learn about modifying the behavior of this method, see the Modify Replace Behavior section of this guide.\n\nYou can retrieve and modify data in one action by using compound operations. To learn more, see the guide on Compound Operations.\n\n### Parameters\n\nThe `replace_one()` method takes the following parameters:\n\n- **Query filter** to match the document to replace\n\n- **Replacement documents** that contains the fields and values that will replace an existing document\n\nReplacement documents use the following format:\n\n```rust\ndoc! { \"\": , \"\": , ... }\n```\n\n### Return Value\n\nThe `replace_one()` method returns an `UpdateResult` type if the operation is successful. The `UpdateResult` type contains the following properties that describe the operation:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nProperty\n\n\nDescription\n\n
\n`matched_count`\n\n\nThe number of documents matched by the filter\n\n
\n`modified_count`\n\n\nThe number of documents modified by the operation\n\n
\n`upserted_id`\n\n\nThe `_id` of the upserted document, or empty if there is none\n\n
If multiple documents match the query filter you pass to `replace_one()`, the method selects and replaces the first matched document. If no documents match the query filter, the replace operation makes no changes.\n\n## Examples\n\nThis section provides examples that demonstrate how to use the `replace_one()` method to replace documents in a collection.\n\n### Replace Example\n\nThe following document describes an employee of a company:\n\n```json\n{\n \"_id\": ObjectId('4501'),\n \"name\": \"Matt DeGuy\",\n \"role\": \"Consultant\",\n \"team_members\": [ \"Jill Gillison\", \"Susan Lee\" ]\n}\n```\n\nThis example uses the `replace_one()` method to replace the preceding document with one that has the following fields:\n\n- A `name` value of `\"Susan Lee\"`\n\n- A `role` value of `\"Lead Consultant\"`\n\n- A `team_members` value of `[ \"Jill Gillison\" ]`\n\n```rust\nlet replace_doc = doc! {\n \"name\": \"Susan Lee\",\n \"role\": \"Lead Consultant\",\n \"team_members\": vec! [ \"Jill Gillison\" ]\n};\n\nlet res = my_coll\n .replace_one(doc! { \"name\": \"Matt DeGuy\" }, replace_doc)\n .await?;\nprintln!(\n \"Matched documents: {}\\nModified documents: {}\",\n res.matched_count, res.modified_count\n);\n```\n\n```console\nMatched documents: 1\nModified documents: 1\n```\n\nThe replaced document contains the contents of the replacement document and the immutable `_id` field:\n\n```json\n{\n \"_id\": ObjectId('4501'),\n \"name\": \"Susan Lee\",\n \"role\": \"Lead Consultant\",\n \"team_members\": [ \"Jill Gillison\" ]\n}\n```\n\n### Full File Example: Replace a Document\n\nThis example replaces a document in the `restaurants` collection of the `sample_restaurants` database. The `replace_one()` method replaces the first document in which the value of the `name` field is `\"Landmark Coffee Shop\"` with a new document.\n\nYou can access the documents in the `restaurants` collection as instances of the `Document` type or a custom data type. To specify which data type represents the collection's data, perform the following actions on the highlighted lines:\n\n- To access collection documents as BSON documents, replace the `` type parameter with `` and the `` placeholder with `replace_doc`.\n\n- To access collection documents as instances of the `Restaurant` struct, replace the `` type parameter with `` and the `` placeholder with `replace_struct`. The `Restaurant` struct is defined at the top of the code file.\n\nSelect the Asynchronous or Synchronous tab to see the corresponding code for each runtime:\n\n\n\n\n\n```rust\nuse std::env;\nuse mongodb::{ bson::doc, Client, Collection };\nuse serde::{ Deserialize, Serialize };\n\n#[derive(Serialize, Deserialize, Debug)]\nstruct Restaurant {\n borough: String,\n cuisine: String,\n name: String,\n}\n\n#[tokio::main]\nasync fn main() -> mongodb::error::Result<()> {\n let uri = \"\";\n\n let client = Client::with_uri_str(uri).await?;\n\n // Replace with the or type parameter\n let my_coll: Collection = client\n .database(\"sample_restaurants\")\n .collection(\"restaurants\");\n\n let filter = doc! { \"name\": \"Landmark Coffee Shop\" };\n let replace_doc = doc! {\n \"borough\": \"Brooklyn\",\n \"cuisine\": \"Caf\u00e9/Coffee/Tea\",\n \"name\": \"Harvest Moon Caf\u00e9\",\n };\n let replace_struct = Restaurant {\n borough: \"Brooklyn\".to_string(),\n cuisine: \"Caf\u00e9/Coffee/Tea\".to_string(),\n name: \"Harvest Moon Caf\u00e9\".to_string(),\n };\n\n // Replace with the replace_struct or replace_doc variable\n let res = my_coll.replace_one(filter, ).await?;\n println!(\"Replaced documents: {}\", res.modified_count);\n\n Ok(())\n}\n\n```\n\n```console\nReplaced documents: 1\n```\n\n\n\n\n\n```rust\nuse std::env;\nuse mongodb::{ bson::doc, sync::{ Client, Collection } };\nuse serde::{ Deserialize, Serialize };\n\n#[derive(Serialize, Deserialize, Debug)]\nstruct Restaurant {\n borough: String,\n cuisine: String,\n name: String,\n}\n\nfn main() -> mongodb::error::Result<()> {\n let uri = \"\";\n\n let client = Client::with_uri_str(uri)?;\n\n // Replace with the or type parameter\n let my_coll: Collection = client\n .database(\"sample_restaurants\")\n .collection(\"restaurants\");\n\n let filter = doc! { \"name\": \"Landmark Coffee Shop\" };\n let replace_doc = doc! {\n \"borough\": \"Brooklyn\",\n \"cuisine\": \"Caf\u00e9/Coffee/Tea\",\n \"name\": \"Harvest Moon Caf\u00e9\",\n };\n let replace_struct = Restaurant {\n borough: \"Brooklyn\".to_string(),\n cuisine: \"Caf\u00e9/Coffee/Tea\".to_string(),\n name: \"Harvest Moon Caf\u00e9\".to_string(),\n };\n\n // Replace with the replace_struct or replace_doc variable\n let res = my_coll.replace_one(filter, ).run()?;\n println!(\"Replaced documents: {}\", res.modified_count);\n\n Ok(())\n}\n\n```\n\n```console\nReplaced documents: 1\n```\n\n\n\n"} -{"chunk_id": "69d7454c549f5046064e2e96-1", "page_id": "69d7454c549f5046064e2e96", "source_name": "rust", "product_name": "Rust Driver", "url": "https://mongodb.com/docs/drivers/rust/current/crud/update/replace", "title": "Replace Documents", "text": "## Modify Replace Behavior\n\nYou can modify the behavior of the `replace_one()` method by calling options methods that set `ReplaceOptions` struct fields.\n\nYou can set `ReplaceOptions` fields by chaining option builder methods directly to the `replace_one()` method call. If you're using an earlier version of the driver, you must construct a `ReplaceOptions` instance by chaining option builder methods to the `builder()` method. Then, pass your options instance as a parameter to `replace_one()`.\n\nThe following table describes the options available in `ReplaceOptions`:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nOption\n\n\nDescription\n\n
\n`array_filters`\n\n\nThe set of filters specifying the array elements to which the update applies.Type: `Vec`\n\n
\n`bypass_document_validation`\n\n\nIf `true`, allows the driver to perform a write that violates document-level validation. To learn more about validation, see the guide on Schema Validation.Type: `bool`Default: `false`\n\n
\n`upsert`\n\n\nIf `true`, the operation inserts a document if no documents match the query filter.Type: `bool`\n\n
\n`collation`\n\n\nThe collation to use when sorting results. To learn more about collations, see the Collations guide.Type: `Collation`Default: `None`\n\n
\n`hint`\n\n\nThe index to use for the operation.Type: `Hint`Default: `None`\n\n
\n`write_concern`\n\n\nThe write concern for the operation. If you don't set this option, the operation inherits the write concern set for the collection. To learn more about write concerns, see Write Concern in the MongoDB Server manual.Type: `WriteConcern`\n\n
\n`let_vars`\n\n\nA map of parameters and values. These parameters can be accessed as variables in aggregation expressions. This option is available only when connecting to MongoDB Server versions 5.0 and later.Type: `Document`\n\n
\n`comment`\n\n\nAn arbitrary `Bson` value tied to the operation to trace it through the database profiler, `currentOp`, and logs. This option is available only when connecting to MongoDB Server versions 4.4 and later.Type: `Bson`Default: `None`\n\n
The following code shows how to set the `upsert` field by chaining the `upsert()` method to the `replace_one()` method:\n\n```rust\nlet res = my_coll\n .replace_one(filter_doc, replace_doc)\n .upsert(true)\n .await?;\n```\n\n## Additional Information\n\nFor more information about the concepts in this guide, see the following documentation:\n\n- Specify a Query guide\n\n- Compound Operations guide\n\n- Update Documents guide\n\n### API Documentation\n\nTo learn more about the methods and types mentioned in this guide, see the following API documentation:\n\n- replace_one()\n\n- UpdateResult\n\n- ReplaceOptions\n\n- WriteError"} -{"chunk_id": "69d7454c549f5046064e2f18-0", "page_id": "69d7454c549f5046064e2f18", "source_name": "rust", "product_name": "Rust Driver", "url": "https://mongodb.com/docs/drivers/rust/current/security/authentication/oidc", "title": "OIDC (Workload Identity Federation)", "text": "# OIDC (Workload Identity Federation)\n\n## Overview\n\nThe MONGODB-OIDC authentication mechanism requires MongoDB Server v7.0 or later running on a Linux platform.\n\nThe Rust driver supports OpenID Connect (**OIDC**) authentication for **workload identities**. A workload identity is an identity you assign to a software workload, such as an application, service, script, or container, to authenticate and access other services and resources.\n\nYou can use this mechanism only when authenticating to MongoDB Atlas or MongoDB Enterprise Advanced.\n\nTo learn more about the MONGODB-OIDC authentication mechanism, see OpenID Connect Authentication and MongoDB Server Parameters in the MongoDB Server manual.\n\nThe following sections describe how to use the MONGODB-OIDC authentication mechanism to authenticate to various platforms.\n\n## Azure IMDS\n\nIf your application runs on an Azure VM, or otherwise uses the Azure Instance Metadata Service (IMDS), you can authenticate to MongoDB by using the Rust driver's built-in Azure support.\n\nYou can configure OIDC for Azure IMDS by setting the `mechanism` field of your `Credential` struct to `AuthMechanism::MongoDbOidc`. You must also specify the following values to the `Credential` struct:\n\n- `username`: If you're using an Azure managed identity, set this to the client ID of the managed identity. If you're using a service principal to represent an enterprise application, set this to the application ID of the service principal.\n\n- `mechanism_properties`: Set the `ENVIRONMENT` property to `azure` and the `TOKEN_RESOURCE` to the value of the audience parameter configured on your MongoDB deployment.\n\n### Example\n\nThe following code example shows how to set these options when creating a `Client`:\n\n```rust\nlet credential = Credential::builder()\n .username(\"\".to_owned())\n .mechanism(AuthMechanism::MongoDbOidc)\n .mechanism_properties(\n doc! { \"ENVIRONMENT\": \"azure\", \"TOKEN_RESOURCE\": \"\" }\n )\n .build();\n\nclient_options.credential = Some(credential);\nlet client = Client::with_options(client_options)?;\nlet res = client\n .database(\"test\")\n .collection::(\"test\")\n .find_one(doc! {})\n .await?;\n```\n\n## GCP IMDS\n\nIf your application runs on a Google Compute Engine VM, or otherwise uses the GCP Instance Metadata Service, you can authenticate to MongoDB by using the Rust driver's built-in GCP support.\n\nYou can configure OIDC for GCP IMDS by setting the `mechanism` field of your `Credential` struct to `AuthMechanism::MongoDbOidc`. Then, specify the authentication mechanism by setting the following values in the `mechanism_properties` field:\n\n- `ENVIRONMENT`: Set this property to `gcp`.\n\n- `TOKEN_RESOURCE`: Set this property to the value of the audience parameter configured on your MongoDB deployment.\n\n### Example\n\nThe following code example shows how to set these options when creating a `Client`:\n\n```rust\nlet credential = Credential::builder()\n .mechanism(AuthMechanism::MongoDbOidc)\n .mechanism_properties(\n doc! { \"ENVIRONMENT\": \"gcp\", \"TOKEN_RESOURCE\": \"\" }\n )\n .build();\n\nclient_options.credential = Some(credential);\nlet client = Client::with_options(client_options)?;\nlet res = client\n .database(\"test\")\n .collection::(\"test\")\n .find_one(doc! {})\n .await?;\n```\n\n## Kubernetes\n\nIf your application runs on a Kubernetes cluster, you can authenticate to MongoDB by using the Rust driver's built-in Kubernetes support.\n\nYou can configure OIDC for Kubernetes by setting the `mechanism` field of your `Credential` struct to `AuthMechanism::MongoDbOidc`. Then, specify the authentication mechanism by setting the `ENVIRONMENT` property to `k8s` in the `mechanism_properties` field.\n\nThe following code example shows how to set these options when creating a `Client`:\n\n```rust\nlet credential = Credential::builder()\n.mechanism(AuthMechanism::MongoDbOidc)\n.mechanism_properties(\n doc! { \"ENVIRONMENT\": \"k8s\" }\n)\n.build();\n\nclient_options.credential = Some(credential);\nlet client = Client::with_options(client_options)?;\nlet res = client\n .database(\"test\")\n .collection::(\"test\")\n .find_one(doc! {})\n .await?;\n```\n\n## Custom Callback\n\nThe Rust driver doesn't offer built-in support for all platforms, including the AWS Elastic Kubernetes Service (EKS). To use OIDC to authenticate against unsupported platforms, you must define a custom callback function.\n\n### Machine Callback\n\nThe following code is an example implementation of a custom callback for an EKS cluster. First, set the `oidc_callback` field of your `Credential` struct to `oidc::Callback::machine`. Then, read the access token from a path set in the `AWS_WEB_IDENTITY_TOKEN_FILE` environment variable. Finally, set the value of the `access_token` field of the `IdpServerResponse` struct. Optionally, set the values of the `expires` and `refresh_token` fields.\n\n```rust\nlet credential = Credential::builder()\n.mechanism(AuthMechanism::MongoDbOidc)\n.oidc_callback(oidc::Callback::machine(move |_| {\n async move {\n let token_file_path = std::env::var(\"AWS_WEB_IDENTITY_TOKEN_FILE\").map_err(mongodb::error::Error::custom)?;\n let access_token = tokio::fs::read_to_string(token_file_path).await?;\n Ok(IdpServerResponse::builder().access_token(access_token).build())\n }\n .boxed()\n}))\n.build()\n.into();\n\nclient_options.credential = Some(credential);\nlet client = Client::with_options(client_options)?;\n\nlet res = client\n .database(\"test\")\n .collection::(\"test\")\n .find_one(doc! {})\n .await?;\n```\n\n### Human Callback\n\nWhen the workforce identity authentication process involves human interaction, you must configure the client by setting the `oidc_callback` field of your `Credential` struct to `oidc::Callback::human` instead of `oidc::Callback::machine`. The Rust driver uses the callback in the following process:\n\n1. The driver retrieves the Identity Provider Information (IDPInfo) for the provided username.\n\n2. The callback negotiates with the IDP to obtain an `access_token`, and any potential `refresh_token` and timeout values, if configured. The callback returns a `Result`.\n\nThe following example defines a custom callback to handle workforce identity. To customize this example for your use case, replace `` with your own custom flow. Refer to Authorization Code Flow with OIDC for more details.\n\n```rust\nlet callback = Callback::human(move |context| {\n async move {\n \"\";\n todo!(\"human flow\")\n }\n .boxed()\n});\nlet credential = Credential::builder()\n .mechanism(AuthMechanism::MongoDbOidc)\n .oidc_callback(callback)\n .build();\nclient_options.credential = Some(credential);\nlet client = Client::with_options(client_options)?;\n\nlet res = client\n .database(\"test\")\n .collection::(\"test\")\n .find_one(doc! {})\n .await?;\n```\n\n## Additional Information\n\nTo learn more about the concepts in this guide, see the following documentation:\n\n- Specify Connection Options guide\n\n- Connection Strings in the Server manual\n\n### API Documentation\n\nTo learn more about the methods and types mentioned in this guide, see the following API documentation:\n\n- Credential\n\n- ClientOptions\n\n- Client\n\n- Client::with_options()\n\n- CallbackContext\n\n- IdpServerResponse\n\n- IdpServerInfo"} -{"chunk_id": "69d7454c549f5046064e2f1a-0", "page_id": "69d7454c549f5046064e2f1a", "source_name": "rust", "product_name": "Rust Driver", "url": "https://mongodb.com/docs/drivers/rust/current/security/authentication/scram", "title": "SCRAM", "text": "# SCRAM\n\n## Overview\n\n**Salted Challenge Response Authentication Mechanism (SCRAM)** is a family of authentication mechanisms that use a username and password to authenticate to a server.\n\nThe Rust driver supports the following SCRAM-based authentication mechanisms:\n\n- SCRAM-SHA-256: An authentication mechanism that uses your database username and password, encrypted with the `SHA-256` algorithm. This is the default authentication mechanism.\n\n- SCRAM-SHA-1: An authentication mechanism that uses your database username and password, encrypted with the `SHA-1` algorithm.\n\nYou can use SCRAM to authenticate to MongoDB Atlas, MongoDB Enterprise Advanced, and MongoDB Community Edition.\n\nTo learn more about the SCRAM family of authentication mechanisms, see RFC 5802 and Salted Challenge Response Authentication Mechanism on Wikipedia.\n\nFor more information about the MongoDB implementation of SCRAM, see SCRAM in the MongoDB Server manual.\n\n### Code Placeholders\n\nThe code examples on this page use the following placeholders:\n\n- `db_username`: Your database username\n\n- `db_password`: Your database password\n\n- `db`: The authentication database associated with the user\n\n## SCRAM-SHA-256\n\nSince `SCRAM-SHA-256` is the default authentication mechanism, you can omit the `mechanism` field when you instantiate your `Credential` struct to use this mechanism.\n\nThe following example specifies the default authentication mechanism:\n\n```rust\nlet uri = \"\";\nlet mut client_options = ClientOptions::parse(uri).await?;\n\nlet default_cred = Credential::builder()\n .username(\"\".to_string())\n .password(\"\".to_string())\n .source(\"\".to_string())\n .build();\n\nclient_options.credential = Some(default_cred);\nlet client = Client::with_options(client_options)?;\n```\n\nTo explicitly specify the `SCRAM-SHA-256` authentication mechanism, set the `mechanism` field of your `Credential` struct to `AuthMechanism::ScramSha256`:\n\n```rust\nlet uri = \"\";\nlet mut client_options = ClientOptions::parse(uri).await?;\n\nlet scram_sha_256_cred = Credential::builder()\n .username(\"\".to_string())\n .password(\"\".to_string())\n .mechanism(AuthMechanism::ScramSha256)\n .source(\"\".to_string())\n .build();\n\nclient_options.credential = Some(scram_sha_256_cred);\nlet client = Client::with_options(client_options)?;\n```\n\n## SCRAM-SHA-1\n\nTo specify the `SCRAM-SHA-1` authentication mechanism, set the `mechanism` field of your `Credential` struct to `AuthMechanism::ScramSha1`:\n\n```rust\nlet uri = \"\";\nlet mut client_options = ClientOptions::parse(uri).await?;\n\nlet scram_sha_1_cred = Credential::builder()\n .username(\"\".to_string())\n .password(\"\".to_string())\n .mechanism(AuthMechanism::ScramSha1)\n .source(\"\".to_string())\n .build();\n\nclient_options.credential = Some(scram_sha_1_cred);\nlet client = Client::with_options(client_options)?;\n```\n\n## Additional Information\n\nTo learn more about authenticating to MongoDB, see Authentication in the Server manual.\n\nTo learn more about managing users of your MongoDB deployment, see Users in the Server manual.\n\n### API Documentation\n\nTo learn more about the methods and types mentioned in this guide, see the following API documentation:\n\n- Credential\n\n- ClientOptions\n\n- Client\n\n- Client::with_options()\n\n- ClientOptions::parse()"} -{"chunk_id": "6a8940c56b548fccc780d8ae-0", "page_id": "6a8940c56b548fccc780d8ae", "source_name": "scala", "product_name": "Scala Driver", "url": "https://mongodb.com/docs/languages/scala/scala-driver/current/connect/connection-options/connection-pools", "title": "Connection Pools", "text": "# Connection Pools\n\n## Overview\n\nIn this guide, you can learn about how the Scala driver uses connection pools to manage connections to a MongoDB deployment and how you can configure connection pool settings in your application.\n\nA connection pool is a cache of open database connections maintained by the Scala driver. Your application retrieves a connection from the pool, performs operations, and returns the connection for reuse.\n\nUsing a connection pool reduces latency and minimizes the number of times the driver creates new connections.\n\n## Create a Connection Pool\n\nEvery `MongoClient` instance has a built-in connection pool for each server in your MongoDB topology. Connection pools open sockets on demand to support concurrent MongoDB operations in your application.\n\nThe `maxPoolSize` option sets the maximum size of each connection pool, which defaults to `100`. If the number of in-use connections to a server reaches the value of `maxPoolSize`, the next request to that server waits until a connection becomes available.\n\nEach `MongoClient` instance opens two more sockets per server in your MongoDB topology for monitoring the server's state.\n\n## Configure a Connection Pool\n\nYou can configure a connection pool by using either a connection string or a `MongoClientSettings` object.\n\nSelect the Connection String or MongoClientSettings tab to see the corresponding syntax:\n\n\n\n\n\nThe following table describes the connection string options for configuring a connection pool:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nOption\n\n\nDescription\n\n
\n`maxConnecting`\n\n\nThe maximum number of connections the driver can establish concurrently.\n\n*Default:* `2`\n\n
\n`maxIdleTimeMS`\n\n\nThe maximum number of milliseconds a connection can remain idle in the pool before the driver closes it. A value of `0` indicates no limit.\n\n*Default:* `0`\n\n
\n`maxPoolSize`\n\n\nThe maximum number of connections the driver can have open at one time in a single connection pool.\n\n*Default:* `100`\n\n
\n`minPoolSize`\n\n\nThe minimum number of connections the driver maintains in a single connection pool. This value must be less than `maxPoolSize`.\n\n*Default:* `0`\n\n
\n`waitQueueTimeoutMS` *(deprecated)*\n\n\nThis option is deprecated. Use `timeoutMS` instead. To learn more, see Limit Server Execution Time.\n\nMaximum wait time in milliseconds that an operation can wait for a connection to become available. A value of `0` means there is no limit.\n\n*Default:* `120000`\n\n
\n`maxLifeTimeMS`\n\n\nThe maximum number of milliseconds a connection can remain open. A value of `0` indicates no limit.\n\n*Default:* `0`\n\n
For more information, see the ConnectionString API documentation.\n\n
\n\n\n\nChain the `applyToConnectionPoolSettings()` method to the `MongoClientSettings.Builder` class to configure a connection pool. The following table describes the `ConnectionPoolSettings.Builder` methods you can chain to configure the pool:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nMethod\n\n\nDescription\n\n
\n`addConnectionPoolListener()`\n\n\nAdds a listener for connection pool events.\n\n
\n`applyConnectionString()`\n\n\nApplies settings from a `ConnectionString` object.\n\n
\n`applySettings()`\n\n\nApplies settings from a `ConnectionPoolSettings` object.\n\n
\n`connectionPoolListenerList()`\n\n\nSets a list of connection pool listeners.\n\n
\n`maintenanceFrequency()`\n\n\nSets the frequency of the periodic job that manages idle and expired connections.\n\n
\n`maintenanceInitialDelay()`\n\n\nSets the period of time to wait before running the first maintenance job on a connection pool.\n\n
\n`maxConnectionIdleTime()`\n\n\nSets the maximum idle time for a pooled connection. A value of `0` indicates no limit.\n\n
\n`maxConnectionLifeTime()`\n\n\nSets the maximum lifetime of a pooled connection. A value of `0` indicates no limit.\n\n
\n`maxConnecting()`\n\n\nSets the maximum number of connections a pool can establish concurrently.\n\n*Default:* `2`\n\n
\n`maxSize()`\n\n\nSets the maximum number of connections allowed in the pool.\n\n*Default:* `100`\n\n
\n`maxWaitTime()`\n\n\nSets the maximum time to wait for an available connection.\n\n*Default:* `2` minutes\n\n
\n`minSize()`\n\n\nSets the minimum number of connections the driver maintains in the pool.\n\n*Default:* `0`\n\n
The `maxSize()` and `minSize()` settings apply to each server in your deployment individually, not to the pool as a whole.\n\nTo learn more, see the ConnectionPoolSettings.Builder API documentation.\n\n
\n\n
\n\n### Example\n\nThe following example shows how to create a connection pool that has a maximum size of `50` connections.\n\nSelect the Connection String or MongoClientSettings tab to see the corresponding syntax:\n\n\n\n\n\n```scala\nval mongoClient = MongoClient(\"mongodb://:/?maxPoolSize=50\")\n```\n\n\n\n\n\n```scala\nval settings = MongoClientSettings.builder()\n .applyConnectionString(ConnectionString(\"\"))\n .applyToConnectionPoolSettings(\n (builder: ConnectionPoolSettings.Builder) => builder.maxSize(50))\n .build()\nval mongoClientWithSettings = MongoClient(settings)\n```\n\n\n\n\n\n## Additional Information\n\nFor more information on using a connection pool, see the Connection Pool documentation in the Server manual.\n\n## API Documentation\n\nTo learn more about the types and methods discussed in this guide, see the following API documentation:\n\n- MongoClient\n\n- MongoClientSettings\n\n- MongoClientSettings.Builder\n\n- ConnectionPoolSettings\n\n- ConnectionPoolSettings.Builder"} -{"chunk_id": "6a8940c56b548fccc780d8b1-0", "page_id": "6a8940c56b548fccc780d8b1", "source_name": "scala", "product_name": "Scala Driver", "url": "https://mongodb.com/docs/languages/scala/scala-driver/current/connect/connection-options/network-compression", "title": "Compress Network Traffic", "text": "# Compress Network Traffic\n\n## Overview\n\nMongoDB drivers can compress the messages sent to and received from MongoDB Server. This reduces the amount of data transferred for each operation. Compression can improve performance over constrained networks and lower the data transfer costs associated with running MongoDB Atlas.\n\nCompression operates at the wire protocol level, so it applies to every operation that your application performs. If you specify more than one algorithm, the driver uses the first algorithm in your list that MongoDB Server also supports.\n\n### Compression Algorithms\n\nMongoDB drivers support the following compression algorithms:\n\n- Snappy\n\n- Zlib\n\n- Zstandard\n\n## Network Compression Benefits\n\nMongoDB Atlas charges for data transferred across cloud regions, cloud providers, and between your infrastructure and MongoDB Atlas. Network compression reduces the amount of data that your application sends and receives, which can lower these data transfer costs. To learn more about pricing, see Data Transfer Costs.\n\nNetwork compression also has productivity benefits. Compressed messages take less time to transfer across the network, which can improve your application's response times. Compression also reduces the bandwidth that your MongoDB traffic uses, which leaves more bandwidth available for other applications on the same network.\n\nWhen you choose a compression algorithm, consider the following guidelines:\n\n- Use **Zstandard** for a balance of compression efficiency and resource usage. Zstandard is a good default choice for most applications.\n\n- Use **Snappy** for latency-sensitive applications that require minimal computational overhead.\n\n- Use **Zlib** for broad compatibility across MongoDB drivers and environments.\n\nCompression trades network bandwidth for CPU usage. After you enable network compression, monitor your application's CPU utilization to confirm that the trade-off benefits your workload. To learn more about these trade-offs, see the CPU Utilization and Network Compression in MongoDB blog post.\n\n## Version Compatibility\n\nThe following table lists the minimum supported driver and MongoDB Server version for each compression algorithm:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nCompression Algorithm\n\n\nMinimum Driver Version\n\n\nMinimum Server Version\n\n
\nSnappy\n\n\n2.2\n\n\n4.2\n\n
\nZlib\n\n\n2.2\n\n\n4.2\n\n
\nZstandard\n\n\n2.7\n\n\n4.2\n\n
\n\n## Enable Network Compression\n\nTo enable network compression for your MongoDB connection, install the required dependencies and specify the compression algorithms that you want to use.\n\n### Install Dependencies\n\nThe following table lists each algorithm and the dependency it requires, if any:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nCompression Algorithm\n\n\nDependency\n\n
\nSnappy\n\n\nDownload `snappy-java`, a Java JNI wrapper for the Snappy library. To install, see snappy-java in Maven Central. The driver tests against `org.xerial.snappy:snappy-java:1.1.10.3`.\n\n
\nZlib\n\n\nNone. The Java Development Kit (JDK) natively supports Zlib compression.\n\n
\nZstandard\n\n\nDownload `zstd-jni`, a Java JNI wrapper for the Zstandard library. To install, see zstd-jni in Maven Central. The driver tests against `com.github.luben:zstd-jni:1.5.5-3`.\n\n
\n\n### Specify Compression Algorithms\n\nYou can enable compression for the connection to your MongoDB instance by specifying the algorithms in one of the following ways:\n\n- In the `compressors` parameter of your connection string\n\n- In the `compressorList` method chained to the `MongoClientSettings.builder()` method\n\nThe following example shows how to specify all compression algorithms. Select the Connection String or MongoClientSettings tab to see the corresponding syntax:\n\n\n\n\n\n```scala\nval mongoClient = MongoClient(\n \"mongodb://:/?compressors=snappy,zlib,zstd\"\n)\n```\n\n\n\n\n\n```scala\nval settings = MongoClientSettings.builder()\n .applyConnectionString(ConnectionString(\"\"))\n .compressorList(List(\n MongoCompressor.createSnappyCompressor(),\n MongoCompressor.createZlibCompressor(),\n MongoCompressor.createZstdCompressor()\n ).asJava)\n .build()\nval mongoClient = MongoClient(settings)\n```\n\n\n\n\n\n## API Documentation\n\nTo learn more about any of the methods or types discussed in this guide, see the following API documentation:\n\n- MongoClientSettings\n\n- MongoClientSettings.Builder.compressorList()\n\n- MongoCompressor\n\n- MongoCompressor.createSnappyCompressor()\n\n- MongoCompressor.createZlibCompressor()\n\n- MongoCompressor.createZstdCompressor()"} -{"chunk_id": "6a8940c56b548fccc780d8e0-0", "page_id": "6a8940c56b548fccc780d8e0", "source_name": "scala", "product_name": "Scala Driver", "url": "https://mongodb.com/docs/languages/scala/scala-driver/current/mongodb-search", "title": "Run MongoDB Search Queries", "text": "# Run MongoDB Search Queries\n\n## Overview\n\nIn this guide, you can learn how to use the Scala driver to run MongoDB Search queries on a collection. MongoDB Search enables you to perform full-text searches on your collections. MongoDB Search indexes specify the behavior of the search and the fields to index.\n\nTo learn how to create and manage MongoDB Search indexes by using the Scala driver, see the MongoDB Search and MongoDB Vector Search Indexes guide.\n\n### Sample Data\n\nThe examples in this guide use the `movies` collection in the `sample_mflix` database from the Atlas sample datasets. To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see Get Started with Atlas.\n\n## Run a MongoDB Search Query\n\nMongoDB Search is available on the following deployments:\n\n- MongoDB Atlas v4.2 or later\n\n- MongoDB Community Edition v8.2 or later\n\nYour collection must have a MongoDB Search index to run MongoDB Search queries. To learn how to create a MongoDB Search index, see the MongoDB Search and MongoDB Vector Search Indexes guide.\n\nTo perform a full-text search, call the `aggregate()` method with a `$search` pipeline stage. The Scala driver provides the `Aggregates.search()` helper method to create this stage. The `search()` method requires the following arguments:\n\n- `SearchOperator` instance that specifies the field and text to search for\n\n- `SearchOptions` instance that specifies options to customize the search, including the name of the MongoDB Search index to use\n\nThe following example searches the `title` field for the text `\"Alabama\"` and projects only the `_id` field, which is included by default, and the `title` field of matching documents:\n\n```scala\nval operator = SearchOperator.text(\n SearchPath.fieldPath(\"title\"), \"Alabama\")\nval options = searchOptions().index(\"\")\n\nval pipeline = Seq(\n Aggregates.search(operator, options),\n Aggregates.project(Projections.include(\"title\"))\n)\n\ntry {\n Await\n .result(collection.aggregate(pipeline).toFuture(), 20.seconds)\n .foreach((doc: Document) => println(doc.toJson()))\n} catch {\n case e: Throwable => println(s\"There was an error: $e\")\n}\n```\n\n```\n{\"_id\": {\"$oid\": \"...\"}, \"title\": \"Alabama Moon\"}\n{\"_id\": {\"$oid\": \"...\"}, \"title\": \"Crazy in Alabama\"}\n{\"_id\": {\"$oid\": \"...\"}, \"title\": \"Sweet Home Alabama\"}\n```\n\nTo view MongoDB Search tutorials in the Atlas documentation, see Run Atlas Search Queries.\n\n## MongoDB Search Metadata\n\nMongoDB Search metadata is available on the following deployments:\n\n- MongoDB Atlas v4.4.11 or later\n\n- MongoDB Community Edition v8.2 or later\n\nUse the `Aggregates.searchMeta()` helper method to retrieve only the metadata from a MongoDB Search query without returning the search results. The following example returns metadata for a query that searches the `year` field for values near `2010`:\n\n```scala\ntry {\n Await\n .result(\n collection.aggregate(Seq(\n Aggregates.searchMeta(\n SearchOperator.near(2010, 1, SearchPath.fieldPath(\"year\")))\n )).toFuture(),\n 20.seconds\n )\n .foreach((doc: Document) => println(doc.toJson()))\n} catch {\n case e: Throwable => println(s\"There was an error: $e\")\n}\n```\n\n```\n{\"count\": {\"lowerBound\": 35}}\n```"} -{"chunk_id": "6a8940c56b548fccc780d8e0-1", "page_id": "6a8940c56b548fccc780d8e0", "source_name": "scala", "product_name": "Scala Driver", "url": "https://mongodb.com/docs/languages/scala/scala-driver/current/mongodb-search", "title": "Run MongoDB Search Queries", "text": "## Use Search Operators\n\nthe MongoDB Search and MongoDB Vector Search Indexes guide\n\n```scala\nval searchStage = Aggregates.search(\n SearchOperator.compound()\n .must(\n Iterable(\n SearchOperator.in(fieldPath(\"genres\"), List(\"Comedy\")),\n SearchOperator.phrase(fieldPath(\"fullplot\"), \"new york\"),\n SearchOperator.numberRange(fieldPath(\"year\")).gtLt(1950, 2000),\n SearchOperator.wildcard(\"Love *\", fieldPath(\"title\")),\n ).asJava\n )\n)\n\nval projectStage = Aggregates.project(\n Projections.include(\"title\", \"year\", \"genres\"))\n\ntry {\n Await\n .result(\n collection.aggregate(Seq(searchStage, projectStage)).toFuture(),\n 20.seconds\n )\n .foreach((doc: Document) => println(doc.toJson()))\n} catch {\n case e: Throwable => println(s\"There was an error: $e\")\n}\n```\n\n```console\n{\"_id\": ..., \"genres\": [\"Comedy\", \"Romance\"],\n\"title\": \"Love at First Bite\", \"year\": 1979}\n{\"_id\": ..., \"genres\": [\"Comedy\", \"Drama\"],\n\"title\": \"Love Affair\", \"year\": 1994}\n```\n\nThe Scala driver provides helper methods for the following operators:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nOperator\n\n\nDescription\n\n
\nautocomplete\n\n\nPerforms a search for a word or phrase that contains a sequence of characters from an incomplete input string.\n\n
\ncompound\n\n\nCombines two or more operators into a single query.\n\n
\nequals\n\n\nChecks whether a field matches a value you specify. Maps to the `equals()` and `equalsNull()` methods.\n\n
\nexists\n\n\nTests if a path to a specified indexed field name exists in a document.\n\n
\nin\n\n\nPerforms a search for an array of BSON number, date, boolean, objectId, uuid, or string values at the given path and returns documents where the value of the field equals any value in the specified array.\n\n
\nmoreLikeThis\n\n\nReturns documents similar to input documents.\n\n
\nnear\n\n\nSupports querying and scoring numeric, date, and GeoJSON point values.\n\n
\nphrase\n\n\nPerforms a search for documents containing an ordered sequence of terms using the analyzer specified in the index configuration.\n\n
\nqueryString\n\n\nSupports querying a combination of indexed fields and values.\n\n
\nrange\n\n\nSupports querying and scoring numeric, date, and string values. Maps to the `numberRange()` and `dateRange()` methods.\n\n
\nregex\n\n\nInterprets the query field as a regular expression.\n\n
\ntext\n\n\nPerforms a full-text search using the analyzer that you specify in the index configuration.\n\n
\nwildcard\n\n\nEnables queries which use special characters in the search string that can match any character.\n\n
### Example Pipeline Search Stage\n\nBefore you can run this example, you must create a MongoDB Search index on the `movies` collection that has the following definition:\n\n```json\n{\n \"mappings\": {\n \"dynamic\": true,\n \"fields\": {\n \"title\": {\n \"analyzer\": \"lucene.keyword\",\n \"type\": \"string\"\n },\n \"genres\": {\n \"normalizer\": \"lowercase\",\n \"type\": \"token\"\n }\n }\n }\n}\n```\n\nTo learn more about creating MongoDB Search indexes, see the MongoDB Search and MongoDB Vector Search Indexes guide.\n\nThe following code creates a `$search` stage that has the following specifications:\n\n- Checks that the `genres` array includes `\"Comedy\"`\n\n- Searches the `fullplot` field for the phrase `\"new york\"`\n\n- Matches `year` values between `1950` and `2000`, inclusive\n\n- Searches for `title` values that begins with the term `\"Love\"`\n\n```scala\nval searchStage = Aggregates.search(\n SearchOperator.compound()\n .must(\n Iterable(\n SearchOperator.in(fieldPath(\"genres\"), List(\"Comedy\")),\n SearchOperator.phrase(fieldPath(\"fullplot\"), \"new york\"),\n SearchOperator.numberRange(fieldPath(\"year\")).gtLt(1950, 2000),\n SearchOperator.wildcard(\"Love *\", fieldPath(\"title\")),\n ).asJava\n )\n)\n\nval projectStage = Aggregates.project(\n Projections.include(\"title\", \"year\", \"genres\"))\n\ntry {\n Await\n .result(\n collection.aggregate(Seq(searchStage, projectStage)).toFuture(),\n 20.seconds\n )\n .foreach((doc: Document) => println(doc.toJson()))\n} catch {\n case e: Throwable => println(s\"There was an error: $e\")\n}\n```\n\n```console\n{\"_id\": ..., \"genres\": [\"Comedy\", \"Romance\"],\n\"title\": \"Love at First Bite\", \"year\": 1979}\n{\"_id\": ..., \"genres\": [\"Comedy\", \"Drama\"],\n\"title\": \"Love Affair\", \"year\": 1994}\n```\n\nTo learn more about the MongoDB Search helper methods, see the SearchOperator interface reference in the Driver Core API documentation.\n\n## Additional Information\n\nFor more information about MongoDB Search, see MongoDB Search Overview in the Atlas documentation.\n\n## API Documentation\n\nTo learn more about the methods and types discussed in this guide, see the following API documentation:\n\n- aggregate()\n\n- Aggregates\n\n- SearchOperator\n\n- SearchOptions"} -{"chunk_id": "6a8940c56b548fccc780d8d1-0", "page_id": "6a8940c56b548fccc780d8d1", "source_name": "scala", "product_name": "Scala Driver", "url": "https://mongodb.com/docs/languages/scala/scala-driver/current/crud/update", "title": "Update Documents", "text": "# Update Documents\n\n## Overview\n\nIn this guide, you can learn how to use the Scala driver to update documents in a MongoDB collection by using the `updateOne()` and `updateMany()` methods.\n\n### Sample Data\n\nThe examples in this guide use the `restaurants` collection in the `sample_restaurants` database from the Atlas sample datasets. To access this collection from your Scala application, create a `MongoClient` that connects to an Atlas cluster and assign the following values to your `database` and `collection` variables:\n\n```scala\nval database: MongoDatabase = mongoClient.getDatabase(\"sample_restaurants\")\nval collection: MongoCollection[Document] = database.getCollection(\"restaurants\")\n```\n\nTo learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the MongoDB Get Started guide.\n\n## Update Operations\n\nYou can update documents in MongoDB by using the following methods:\n\n- `updateOne()`, which updates *the first document* that matches the search criteria\n\n- `updateMany()`, which updates *all documents* that match the search criteria\n\nEach update method requires the following parameters:\n\n- **Query filter**, which matches the documents you want to update. To learn more about query filters, see the Specify a Query guide.\n\n- **Update document**, which specifies the update operator and the fields and values to be updated. The update operator specifies the type of update to perform. To view a list of update operators and learn about their usages, see the Field Update Operators guide page in the MongoDB Server manual.\n\n### Update One Document Example\n\nThe following example uses the `updateOne()` method to update the `name` field value of a document from `\"Happy Garden\"` to `\"Mountain House\"`. The update document uses the `set()` method to update the `name` field value:\n\n```scala\nval filter = equal(\"name\", \"Happy Garden\")\nval update = set(\"name\", \"Mountain House\")\nval observable: Observable[UpdateResult] = collection.updateOne(filter, update)\n\nobservable.subscribe(new Observer[UpdateResult] {\n override def onNext(result: UpdateResult): Unit =\n println(s\"Updated document count: ${result.getModifiedCount}\")\n override def onError(e: Throwable): Unit = println(s\"Failed: ${e.getMessage}\")\n override def onComplete(): Unit = println(\"Completed\")\n})\n```\n\n```console\nUpdated document count: 1\nCompleted\n```\n\n### Update Many Documents Example\n\nThe following example uses the `updateMany()` method to update all documents in which the `name` field value is `\"Starbucks\"`. The update document uses the `rename()` method to change the name of the `address` field to `location`:\n\n```scala\nval filter = equal(\"name\", \"Starbucks\")\nval update = rename(\"address\", \"location\")\nval observable: Observable[UpdateResult] = collection.updateMany(filter, update)\n\nobservable.subscribe(new Observer[UpdateResult] {\n override def onNext(result: UpdateResult): Unit =\n println(s\"Updated document count: ${result.getModifiedCount}\")\n override def onError(e: Throwable): Unit = println(s\"Failed: ${e.getMessage}\")\n override def onComplete(): Unit = println(\"Completed\")\n})\n```\n\n```console\nUpdated document count: 11\nCompleted\n```\n\n### Customize the Update Operation\n\nThe `updateOne()` and `updateMany()` methods optionally accept a parameter that sets options to configure the update operation. If you don't specify any options, the driver performs update operations with default settings.\n\nThe following table describes the setter methods that you can use to configure an `UpdateOptions` instance:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nMethod\n\n\nDescription\n\n
\n`upsert()`\n\n\nSpecifies whether the update operation performs an upsert operation if no documents match the query filter. For more information, see the upsert statement in the MongoDB Server manual.Defaults to `false`\n\n
\n`sort()`\n\n\nSets the sort criteria to apply to the operation. If multiple documents match the query filter that you pass to the `updateOne()` method, the operation updates the first result. You can set this option to apply an order to matched documents to have more control over which document is updated.\n\n
\n`bypassDocumentValidation()`\n\n\nSpecifies whether the update operation bypasses document validation. This lets you update documents that don't meet the schema validation requirements, if any exist. For more information about schema validation, see Schema Validation in the MongoDB Server manual.Defaults to `false`.\n\n
\n`collation()`\n\n\nSpecifies the kind of language collation to use when sorting results. For more information, see Collation in the MongoDB Server manual.\n\n
\n`arrayFilters()`\n\n\nProvides a list of filters that you specify to select which array elements the update applies to.\n\n
\n`hint()`\n\n\nSets the index to use when matching documents. For more information, see the hint statement in the MongoDB Server manual.\n\n
\n`let()`\n\n\nProvides a map of parameter names and values to set top-level variables for the operation. Values must be constant or closed expressions that don't reference document fields. For more information, see the let statement in the MongoDB Server manual.\n\n
\n`comment()`\n\n\nSets a comment to attach to the operation. For more information, see the update command fields guide in the MongoDB Server manual for more information.\n\n
#### Modify Update Example\n\nThis example creates and passes options to the `updateOne()` method. The example uses the `equal()` helper method to match documents in which the `name` field value is `\"Sunrise Pizzeria\"`. It then uses the `set()` method to set the `borough` field value in the first matching document to `\"Queens\"` and the `cuisine` field value to `\"Italian\"`. The code uses the `combine()` method to specify multiple updates in one update document.\n\nBecause the `upsert` option is set to `true` in the `UpdateOptions` instance, the driver inserts a new document that has the fields and values specified in the filter and update document if the query filter doesn't match any existing documents.\n\n```scala\nval filter = equal(\"name\", \"Sunrise Pizzeria\")\nval opts = UpdateOptions().upsert(true)\nval update = combine(\n set(\"borough\", \"Queens\"),\n set(\"cuisine\", \"Italian\")\n)\nval observable: Observable[UpdateResult] = collection.updateOne(filter, update, opts)\n\nobservable.subscribe(new Observer[UpdateResult] {\n override def onNext(result: UpdateResult): Unit =\n println(s\"Updated document count: ${result.getModifiedCount}\")\n override def onError(e: Throwable): Unit = println(s\"Failed: ${e.getMessage}\")\n override def onComplete(): Unit = println(\"Completed\")\n})\n```\n\n```console\nUpdated document count: 1\nCompleted\n```"} -{"chunk_id": "6a8940c56b548fccc780d8d1-1", "page_id": "6a8940c56b548fccc780d8d1", "source_name": "scala", "product_name": "Scala Driver", "url": "https://mongodb.com/docs/languages/scala/scala-driver/current/crud/update", "title": "Update Documents", "text": "### Return Value\n\nThe `updateOne()` and `updateMany()` methods each return an `UpdateResult` object. You can use the following methods to access information from an `UpdateResult` instance:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nMethod\n\n\nDescription\n\n
\n`getMatchedCount()`\n\n\nReturns the number of documents that matched the query filter, regardless of how many updates were performed.\n\n
\n`getModifiedCount()`\n\n\nReturns the number of documents modified by the update operation. If an updated document is identical to the original, it is not included in this count.\n\n
\n`wasAcknowledged()`\n\n\nReturns `true` if the server acknowledged the result.\n\n
\n`getUpsertedId()`\n\n\nReturns the `_id` value of the document that was upserted in the database, if the driver performed an upsert.\n\n
If the `wasAcknowledged()` method returns `false`, trying to access other information from the `UpdateResult` instance results in an `InvalidOperation` exception. The driver cannot determine these values if the server does not acknowledge the write operation.\n\n## Additional Information\n\nTo view runnable code examples that demonstrate how to update documents by using the Scala driver, see CRUD Operations.\n\n### API Documentation\n\nTo learn more about any of the methods or types discussed in this guide, see the following API documentation:\n\n- updateOne()\n\n- updateMany()\n\n- UpdateOptions\n\n- UpdateResult"} -{"chunk_id": "6a8940c56b548fccc780d8be-0", "page_id": "6a8940c56b548fccc780d8be", "source_name": "scala", "product_name": "Scala Driver", "url": "https://mongodb.com/docs/languages/scala/scala-driver/current/crud/query/count", "title": "Count Documents", "text": "# Count Documents\n\n## Overview\n\nIn this guide, you can learn how to use the Scala driver to retrieve an accurate and estimated count of the number of documents in a collection. The following methods count documents in a collection:\n\n- `countDocuments()`: Returns the exact number of documents that match a query filter or that exist in a collection\n\n- `estimatedDocumentCount()`: Returns the estimated number of documents in a collection\n\n### Sample Data\n\nThe examples in this guide use the `companies` collection in the `sample_training` database from the Atlas sample datasets. To access this collection from your Scala application, create a `MongoClient` that connects to an Atlas cluster and assign the following value to your `database` and `collection` variables:\n\n```scala\nval database: MongoDatabase = mongoClient.getDatabase(\"sample_training\")\nval collection: MongoCollection[Document] = database.getCollection(\"companies\")\n```\n\nTo learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the MongoDB Get Started guide.\n\n## Retrieve an Accurate Count\n\nUse the `countDocuments()` method to count the number of documents in a collection. To count the number of documents that match specific search criteria, pass a query filter to the `countDocuments()` method.\n\nTo learn more about specifying a query, see the Specify a Query guide.\n\n### Count All Documents\n\nTo return a count of all documents in the collection, call the `countDocuments()` method without passing any parameters, as shown in the following example:\n\n```scala\ncollection.countDocuments()\n .subscribe((count: Long) => println(s\"Number of documents: $count\"),\n (e: Throwable) => println(s\"There was an error: $e\"))\n```\n\n```\nNumber of documents: 9500\n```\n\n### Count Specific Documents\n\nTo return a count of documents that match specific search criteria, pass a query filter to the `countDocuments()` method.\n\nThe following example counts the number of documents in which the value of the `founded_year` field is `2010`:\n\n```scala\ncollection.countDocuments(equal(\"founded_year\", 2010))\n .subscribe((count: Long) => println(s\"Companies founded in 2010: $count\"),\n (e: Throwable) => println(s\"There was an error: $e\"))\n```\n\n```\nNumber of companies founded in 2010: 33\n```\n\n### Customize Count Behavior\n\nYou can modify the behavior of the `countDocuments()` method by passing a `CountOptions` instance as a parameter. The following table describes some member functions of the `CountOptions` class, which you can use to set options for the count operation:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nMethod\n\n\nDescription\n\n
\n`collation()`\n\n\nSets the collation to use for the operation.**Parameter Type**: `Collation`\n\n
\n`hint()`\n\n\nSets the index to use for the operation.**ParameterType**: `Bson`\n\n
\n`limit()`\n\n\nSets the maximum number of documents to count. This value must be a positive integer.**Parameter Type**: `int`\n\n
\n`skip()`\n\n\nSets the number of documents to skip before counting documents.**Parameter Type**: `int`\n\n
The following example uses the `countDocuments()` method to count the number of documents in which the `number_of_employees` field has the value `50` and instructs the operation to count a maximum of `100` results:\n\n```scala\nval countOptions = CountOptions().limit(100)\ncollection.countDocuments(equal(\"number_of_employees\", 50), countOptions)\n .subscribe((count: Long) => println(s\"Companies with 50 employees: $count\"),\n (e: Throwable) => println(s\"There was an error: $e\"))\n```\n\n```\nNumber of companies with 50 employees: 100\n```\n\n## Retrieve an Estimated Count\n\nYou can retrieve an estimate of the number of documents in a collection by calling the `estimatedDocumentCount()` method. The method estimates the amount of documents based on collection metadata, which might be faster than performing an accurate count.\n\nThe following example estimates the number of documents in a collection:\n\n```scala\ncollection.estimatedDocumentCount()\n .subscribe((count: Long) => println(s\"Estimated number of documents: $count\"),\n (e: Throwable) => println(s\"There was an error: $e\"))\n```\n\n```\nEstimated number of documents: 9500\n```\n\n### Customize Estimated Count Behavior\n\nYou can modify the behavior of the `estimatedDocumentCount()` method by passing an `EstimatedDocumentCountOptions` instance as a parameter. The `EstimatedDocumentCountOptions` class includes the `comment()` member function, which you can use to set a comment attached to your operation.\n\nThe following example uses the `estimatedDocumentCount()` method to return an estimate of the number of documents in the collection and sets a comment on the operation:\n\n```scala\nval estimatedOptions = EstimatedDocumentCountOptions().comment(\"Count operation\")\ncollection.estimatedDocumentCount(estimatedOptions)\n .subscribe((count: Long) => println(s\"Estimated number of documents: $count\"),\n (e: Throwable) => println(s\"There was an error: $e\"))\n```\n\n```\nEstimated number of documents: 9500\n```\n\n## API Documentation\n\nTo learn more about any of the methods or types discussed in this guide, see the following API documentation:\n\n- countDocuments()\n\n- CountOptions\n\n- estimatedDocumentCount()\n\n- EstimatedDocumentCountOptions"} -{"chunk_id": "6a8940c56b548fccc780d8ad-0", "page_id": "6a8940c56b548fccc780d8ad", "source_name": "scala", "product_name": "Scala Driver", "url": "https://mongodb.com/docs/languages/scala/scala-driver/current/connect/connection-options", "title": "Specify Connection Options", "text": "# Specify Connection Options\n\n## Overview\n\nThis page describes the MongoDB connection and authentication options available in the Scala driver and explains how to specify them for your MongoDB connection.\n\n### Set Options in the Connection URI\n\nIf you pass a connection URI to the `MongoClient()` constructor, you can include connection options in the string as `=` pairs. In the following example, the connection URI contains the `connectTimeoutMS` option with a value of `60000` and the `tls` option with a value of `true`:\n\n```scala\nval uri = \"mongodb://localhost:27017/?connectTimeoutMS=60000&tls=true\"\nval mongoClient = MongoClient(uri)\n```\n\n### Set Options in MongoClientSettings\n\nYou can set connection options in a `MongoClientSettings` instance by using methods from the `MongoClientSettings.Builder` class, then passing the settings object to the `MongoClient()` constructor.\n\nConfiguring the connection this way makes it easier to change settings at runtime and can help you catch errors at compile time.\n\nThe following example shows how to specify your connection target and set other options when creating a `MongoClientSettings` instance:\n\n```scala\nval settings = MongoClientSettings.builder()\n .applyToClusterSettings(builder =>\n builder.hosts(List(new ServerAddress(\"localhost\", 27017)).asJava))\n .applyToSocketSettings(builder =>\n builder.connectTimeout(60000, TimeUnit.MILLISECONDS))\n .applyToSslSettings(builder => builder.enabled(true))\n .build()\n\nval mongoClient = MongoClient(settings)\n```\n\nIf you prefer to provide a connection string instead of specifying the hostname and port, you can use the `applyConnectionString()` method, then set other options by using builder methods, as shown in the following code:\n\n```scala\nval uri = \"mongodb://localhost:27017/\"\nval settings = MongoClientSettings.builder()\n .applyConnectionString(ConnectionString(uri))\n .applyToSocketSettings(builder =>\n builder.connectTimeout(60000, TimeUnit.MILLISECONDS))\n .applyToSslSettings(builder => builder.enabled(true))\n .build()\n\nval mongoClient = MongoClient(settings)\n```\n\n## Network Compression\n\n\n\n\n\n### compressors\n\nThe preferred compression types, in order, for wire-protocol messages sent to or received from the server. You can enable \"snappy\", \"zlib\", and \"zstd\" as optional build time dependencies. The driver uses the first of these compression types that the server supports.\n\n*Data Type:* comma-delimited `string`\n\n*Default Value:* `null`\n\n*Example:*\n\n```scala\nval uri = \"mongodb://localhost:27017/?compressors=snappy,zstd,zlib\"\nval mongoClient = MongoClient(uri)\n```\n\n### zlibCompressionLevel\n\nThe compression level for zlib to use. This option accepts an integer value between `-1` and `9`:\n\n- **-1:** (Default). zlib uses its default compression level (usually `6`).\n\n- **0:** No compression.\n\n- **1:** Fastest speed but lowest compression.\n\n- **9:** Best compression but slowest speed.\n\n*Data Type:* `integer`\n\n*Default Value:* `-1`\n\n*Example:*\n\n```scala\nval uri = \"mongodb://localhost:27017/?compressors=zlib&zlibCompressionLevel=3\"\nval mongoClient = MongoClient(uri)\n```\n\n\n\n\n\n### compressors\n\nThe preferred compression types, in order, for wire-protocol messages sent to or received from the server. You can enable \"snappy\", \"zlib\", and \"zstd\" as optional build time dependencies. The driver uses the first of these compression types that the server supports.\n\n*Data Type:* `List[MongoCompressor]`\n\n*Default Value:* empty list\n\n*Example:*\n\n```scala\nval settings = MongoClientSettings.builder()\n .compressorList(List(\n MongoCompressor.createSnappyCompressor(),\n MongoCompressor.createZstdCompressor(),\n MongoCompressor.createZlibCompressor()\n ).asJava)\n .build()\nval mongoClient = MongoClient(settings)\n```\n\n### zlibCompressionLevel\n\nThe compression level for zlib to use. This option accepts an integer value between `-1` and `9`:\n\n- **-1:** (Default). zlib uses its default compression level (usually `6`).\n\n- **0:** No compression.\n\n- **1:** Fastest speed but lowest compression.\n\n- **9:** Best compression but slowest speed.\n\n*Data Type:* `integer`\n\n*Default Value:* `-1`\n\n*Example:*\n\n```scala\nval settings = MongoClientSettings.builder()\n .compressorList(List(\n MongoCompressor.createZlibCompressor()\n .withProperty(MongoCompressor.LEVEL, 3)\n ).asJava)\n .build()\nval mongoClient = MongoClient(settings)\n```\n\n\n\n\n\n## Timeouts\n\n\n\n\n\n### connectTimeoutMS\n\nThe length of time the driver tries to establish a single TCP socket connection to the server before timing out.\n\n*Data Type:* `integer`\n\n*Default Value:* `10000`\n\n*Example:*\n\n```scala\nval uri = \"mongodb://localhost:27017/?connectTimeoutMS=10000\"\nval mongoClient = MongoClient(uri)\n```\n\n### socketTimeoutMS *(deprecated)*\n\nThis option is deprecated. Configure this timeout by setting the client-level timeout instead.\n\nThe length of time the driver tries to send or receive on a socket before timing out. The default value is set by the operating system.\n\n*Data Type:* `integer`\n\n*Default Value:* no timeout\n\n*Example:*\n\n```scala\nval uri = \"mongodb://localhost:27017/?socketTimeoutMS=5000\"\nval mongoClient = MongoClient(uri)\n```\n\n\n\n\n\n### connectTimeoutMS\n\nThe length of time the driver tries to establish a single TCP socket connection to the server before timing out.\n\n*Data Type:* `integer`\n\n*Default Value:* `10000`\n\n*Example:*\n\n```scala\nval settings = MongoClientSettings.builder()\n .applyToSocketSettings(builder =>\n builder.connectTimeout(10, TimeUnit.SECONDS))\n .build()\nval mongoClient = MongoClient(settings)\n```\n\n### socketTimeoutMS *(deprecated)*\n\nThis option is deprecated. Configure this timeout by setting the client-level timeout instead.\n\nThe length of time the driver tries to send or receive on a socket before timing out. The default value is set by the operating system.\n\n*Data Type:* `integer`\n\n*Default Value:* no timeout\n\n*Example:*\n\n```scala\nval settings = MongoClientSettings.builder()\n .applyToSocketSettings(builder =>\n builder.readTimeout(5, TimeUnit.SECONDS))\n .build()\nval mongoClient = MongoClient(settings)\n```\n\n\n\n\n\n## Server Selection\n\n\n\n\n\n### serverSelectionTimeoutMS\n\nThe length of time the driver tries to select a server before timing out.\n\n*Data Type:* `integer`\n\n*Default Value:* `30000`\n\n*Example:*\n\n```scala\nval uri = \"mongodb://localhost:27017/?serverSelectionTimeoutMS=30000\"\nval mongoClient = MongoClient(uri)\n```\n\n\n\n\n\n### serverSelectionTimeoutMS\n\nThe length of time the driver tries to select a server before timing out.\n\n*Data Type:* `integer`\n\n*Default Value:* `30000`\n\n*Example:*\n\n```scala\nval settings = MongoClientSettings.builder()\n .applyToClusterSettings(builder =>\n builder.serverSelectionTimeout(30, TimeUnit.SECONDS))\n .build()\nval mongoClient = MongoClient(settings)\n```\n\n\n\n\n\n## Authentication\n\nTo learn more about authentication options, see the Authentication Mechanisms section.\n\n\n\n\n\n### authMechanism\n\nThe mechanism that the driver uses to authenticate to MongoDB Server. If you don't specify an authentication mechanism, the driver uses either `SCRAM-SHA-1` or `SCRAM-SHA-256`, depending on the server version.\n\n*Data Type:* `string`\n\n*Default Value:* `\"SCRAM-SHA-256\"` when connecting to MongoDB v4.0 or later\n\n*Example:*\n\n```scala\nval uri = \"mongodb://:@localhost:27017/?authMechanism=SCRAM-SHA-256\"\nval mongoClient = MongoClient(uri)\n```"} -{"chunk_id": "6a8940c56b548fccc780d8ad-1", "page_id": "6a8940c56b548fccc780d8ad", "source_name": "scala", "product_name": "Scala Driver", "url": "https://mongodb.com/docs/languages/scala/scala-driver/current/connect/connection-options", "title": "Specify Connection Options", "text": "### authMechanismProperties\n\nOptions specific to the authentication mechanism. Not required for all authentication mechanisms.\n\n*Data Type:* `string`\n\n*Example:*\n\n```scala\nval uri = \"mongodb://localhost:27017/?authMechanismProperties=AWS_SESSION_TOKEN:12435\"\nval mongoClient = MongoClient(uri)\n```\n\n### authSource\n\nThe database to authenticate against.\n\n*Data Type:* `string`\n\n*Default Value:* `\"admin\"`\n\n*Example:*\n\n```scala\nval uri = \"mongodb://:@localhost:27017/?authSource=admin\"\nval mongoClient = MongoClient(uri)\n```\n\n### username\n\nThe username for authentication. When this option is included in a connection URI, you must percent-encode it.\n\n*Data Type:* `string`\n\n*Example:*\n\n```scala\nval uri = \"mongodb://myUser:@localhost:27017/\"\nval mongoClient = MongoClient(uri)\n```\n\n### password\n\nThe password for authentication. When this option is included in a connection URI, you must percent-encode it.\n\n*Data Type:* `string`\n\n*Example:*\n\n```scala\nval uri = \"mongodb://:myPassword@localhost:27017/\"\nval mongoClient = MongoClient(uri)\n```\n\n\n\n\n\n### authMechanism\n\nThe mechanism that the driver uses to authenticate to MongoDB Server. If you don't specify an authentication mechanism, the driver uses either `SCRAM-SHA-1` or `SCRAM-SHA-256`, depending on the server version.\n\n*Data Type:* `string`\n\n*Default Value:* `\"SCRAM-SHA-256\"` when connecting to MongoDB v4.0 or later\n\n*Example:*\n\n```scala\nval settings = MongoClientSettings.builder()\n .credential(MongoCredential.createScramSha256Credential(\n \"\", \"\", \"\".toCharArray))\n .build()\nval mongoClient = MongoClient(settings)\n```\n\nTo configure username, password, authentication source, and mechanism-specific properties in `MongoClientSettings`, use the appropriate `MongoCredential` factory method. To learn more, see the Authentication Mechanisms guide.\n\n\n\n\n\n## Read and Write Operations\n\n\n\n\n\n### replicaSet\n\nThe name of the replica set to connect to.\n\n*Data Type:* `string`\n\n*Example:*\n\n```scala\nval uri = \"mongodb://localhost:27017/?replicaSet=myRS\"\nval mongoClient = MongoClient(uri)\n```\n\n### directConnection\n\nSpecifies whether to force dispatch **all** operations to the host. If you specify this option, the driver doesn't accept the SRV connection format. You must use the standard connection URI format instead. To learn more about the SRV connection and the standard connection formats, see the Connection Strings guide in the MongoDB Server manual.\n\nThis property must be set to `false` if you specify more than one host name.\n\n*Data Type:* `boolean`\n\n*Default Value:* `false`\n\n*Example:*\n\n```scala\nval uri = \"mongodb://localhost:27017/?directConnection=true\"\nval mongoClient = MongoClient(uri)\n```\n\n### readPreference\n\nThe client's default read-preference settings. See Read Preference in the MongoDB Server manual for more information.\n\n*Data Type:* `string`\n\n*Default Value:* `primary`\n\n*Example:*\n\n```scala\nval uri = \"mongodb://localhost:27017/?readPreference=primary\"\nval mongoClient = MongoClient(uri)\n```\n\n### readConcern\n\nThe client's read concern. For more information, see Read Concern in the MongoDB Server manual.\n\n*Data Type:* `string`\n\n*Example:*\n\n```scala\nval uri = \"mongodb://localhost:27017/?readConcern=majority\"\nval mongoClient = MongoClient(uri)\n```\n\n### writeConcern\n\nThe client's write concern. For more information, see Write Concern in the MongoDB Server manual.\n\n*Data Type:* `string`\n\n*Example:*\n\n```scala\nval uri = \"mongodb://localhost:27017/?writeConcern=majority\"\nval mongoClient = MongoClient(uri)\n```\n\n### localThresholdMS\n\nThe latency window for server eligibility. If a server's round trip takes longer than the fastest server's round-trip time plus this value, the server isn't eligible for selection.\n\n*Data Type:* `integer`\n\n*Default Value:* `15`\n\n*Example:*\n\n```scala\nval uri = \"mongodb://localhost:27017/?localThresholdMS=35\"\nval mongoClient = MongoClient(uri)\n```\n\n\n\n\n\n### replicaSet\n\nThe name of the replica set to connect to.\n\n*Data Type:* `string`\n\n*Example:*\n\n```scala\nval settings = MongoClientSettings.builder()\n .applyToClusterSettings(builder =>\n builder.requiredReplicaSetName(\"myRS\"))\n .build()\nval mongoClient = MongoClient(settings)\n```\n\n### directConnection\n\nSpecifies whether to force dispatch **all** operations to the host. If you specify this option, the driver doesn't accept the SRV connection format. You must use the standard connection URI format instead. To learn more about the SRV connection and the standard connection formats, see the Connection Strings guide in the MongoDB Server manual.\n\nThis property must be set to `false` if you specify more than one host name.\n\n*Data Type:* `boolean`\n\n*Default Value:* `false`\n\n*Example:*\n\n```scala\nval settings = MongoClientSettings.builder()\n .applyToClusterSettings(builder =>\n builder.mode(ClusterConnectionMode.SINGLE))\n .build()\nval mongoClient = MongoClient(settings)\n```\n\n### readPreference\n\nThe client's default read-preference settings. See Read Preference in the MongoDB Server manual for more information.\n\n*Data Type:* `string`\n\n*Default Value:* `primary`\n\n*Example:*\n\n```scala\nval settings = MongoClientSettings.builder()\n .readPreference(ReadPreference.primary())\n .build()\nval mongoClient = MongoClient(settings)\n```\n\n### readConcern\n\nThe client's read concern. For more information, see Read Concern in the MongoDB Server manual.\n\n*Data Type:* `string`\n\n*Example:*\n\n```scala\nval settings = MongoClientSettings.builder()\n .readConcern(ReadConcern.MAJORITY)\n .build()\nval mongoClient = MongoClient(settings)\n```\n\n### writeConcern\n\nThe client's write concern. For more information, see Write Concern in the MongoDB Server manual.\n\n*Data Type:* `string`\n\n*Example:*\n\n```scala\nval settings = MongoClientSettings.builder()\n .writeConcern(WriteConcern.MAJORITY)\n .build()\nval mongoClient = MongoClient(settings)\n```\n\n### localThresholdMS\n\nThe latency window for server eligibility. If a server's round trip takes longer than the fastest server's round-trip time plus this value, the server isn't eligible for selection.\n\n*Data Type:* `integer`\n\n*Default Value:* `15`\n\n*Example:*\n\n```scala\nval settings = MongoClientSettings.builder()\n .applyToClusterSettings(builder =>\n builder.localThreshold(35, TimeUnit.MILLISECONDS))\n .build()\nval mongoClient = MongoClient(settings)\n```\n\n\n\n\n\n## SRV Configuration\n\n\n\n\n\n### srvAllowedHostsSuffix\n\nThe domain suffix that the driver uses to validate the host names returned by the SRV record lookup, instead of the domain inferred from the SRV host name. If the value doesn't begin with a period (`.`), the driver adds one. You can use this option only with the `mongodb+srv` connection string format.\n\n*Data Type:* `string`\n\n*Default Value:* `null`. The driver validates host names against the domain inferred from the SRV host name.\n\n*Example:*\n\n```scala\nval uri = \"mongodb+srv://cluster.test.internal.example.com/?srvAllowedHostsSuffix=.internal.example.com\"\nval mongoClient = MongoClient(uri)\n```\n\n\n\n"} -{"chunk_id": "6a8940c56b548fccc780d8ad-2", "page_id": "6a8940c56b548fccc780d8ad", "source_name": "scala", "product_name": "Scala Driver", "url": "https://mongodb.com/docs/languages/scala/scala-driver/current/connect/connection-options", "title": "Specify Connection Options", "text": "### srvAllowedHostsSuffix\n\nThe domain suffix that the driver uses to validate the host names returned by the SRV record lookup, instead of the domain inferred from the SRV host name. If the value doesn't begin with a period (`.`), the driver adds one. The driver uses this setting only with the SRV connection protocol.\n\n*Data Type:* `string`\n\n*Default Value:* `null`. The driver validates host names against the domain inferred from the SRV host name.\n\n*Example:*\n\n```scala\nval settings = MongoClientSettings.builder()\n .applyConnectionString(ConnectionString(\"mongodb+srv://cluster.test.internal.example.com/\"))\n .applyToClusterSettings(builder =>\n builder.srvAllowedHostsSuffix(\".internal.example.com\"))\n .build()\nval mongoClient = MongoClient(settings)\n```\n\n\n\n\n\nChanging the default SRV host name validation can create security vulnerabilities, because it relaxes a built-in safeguard against DNS spoofing. Specify the narrowest suffix that covers the hosts in your deployment. For example, if your SRV host name is `cluster.test.internal.example.com`, set `srvAllowedHostsSuffix` to `.internal.example.com`. Do not set it to `.example.com`, which accepts any host in the `example.com` domain.\n\n## Additional Information\n\nTo view a full list of connection options, see Connection String Options in the MongoDB Server manual.\n\n### API Documentation\n\nTo learn more about the classes and methods mentioned in this guide, see the following API documentation:\n\n- MongoClient\n\n- MongoClientSettings\n\n- MongoClientSettings.Builder\n\n- ConnectionString\n\n- SocketSettings\n\n- ClusterSettings\n\n- MongoCredential"} -{"chunk_id": "68a95c355e79d242619e0ab2-0", "page_id": "68a95c355e79d242619e0ab2", "source_name": "scala", "product_name": "Scala Driver", "url": "https://mongodb.com/docs/languages/scala/scala-driver/current", "title": "MongoDB Scala Driver", "text": "# MongoDB Scala Driver\n\n## Introduction\n\nWelcome to the documentation site for the MongoDB Scala Driver, the official MongoDB driver for Scala applications.\n\n## Get Started\n\nLearn how to install the driver, establish a connection to MongoDB, and begin working with data in the Get Started with the Scala Driver tutorial.\n\n## Connect to MongoDB\n\nLearn how to create and configure a connection to a MongoDB deployment in the Connect section.\n\n## Databases and Collections\n\nLearn how to use the Scala driver to work with MongoDB databases and collections in the Databases and Collections section.\n\n## CRUD Operations\n\nLearn how to insert, query, update, and delete data, and how to access results from an `Observable`, in the CRUD Operations section.\n\n## Transform Your Data with Aggregation\n\nLearn how to use the Scala driver to perform aggregation operations in the Transform Your Data with Aggregation section.\n\n## Data Formats\n\nLearn how to work with BSON, Extended JSON, and other data formats in the Data Formats section.\n\n## Optimize Queries with Indexes\n\nLearn how to work with common types of indexes in the Optimize Queries by Using Indexes section.\n\n## Run a Database Command\n\nLearn how to run a database command in the Run a Database Command section.\n\n## MongoDB Search\n\nLearn how to run MongoDB Search queries in the Run MongoDB Search Queries section.\n\n## MongoDB Vector Search\n\nLearn how to run MongoDB Vector Search queries in the MongoDB Vector Search section.\n\n## Logging and Monitoring\n\nLearn how to monitor changes to your application and write them to logs in the Logging and Monitoring section.\n\n## Secure Your Data\n\nLearn how to authenticate your application and encrypt your data in the Authentication Mechanisms section.\n\n## Reference\n\nFind information about new features, driver version compatibility, and upgrade steps in the Reference section.\n\n## Compatibility\n\nTo learn about the versions of the MongoDB Server and Scala that are compatible with each version of the Scala driver, see the Compatibility page.\n\n## API Documentation\n\nFor detailed information about the classes and methods in the Scala driver, see the MongoDB Scala Driver API documentation.\n\n## Issues & Help\n\nLearn how to report bugs, contribute to the driver, and find more resources for asking questions and receiving help in the Issues & Help section.\n\n## Learn\n\nYou can find support for general questions by using the MongoDB Stack Overflow tag or the MongoDB Reddit community."} -{"chunk_id": "6a8940c56b548fccc780d8c6-0", "page_id": "6a8940c56b548fccc780d8c6", "source_name": "scala", "product_name": "Scala Driver", "url": "https://mongodb.com/docs/languages/scala/scala-driver/current/crud/query/project", "title": "Specify Fields To Return", "text": "# Specify Fields To Return\n\n## Overview\n\nIn this guide, you can learn how to use the Scala driver to specify which fields to return from a read operation by using a **projection**. A projection is a document that specifies which fields MongoDB returns from a query.\n\n### Sample Data\n\nThe examples in this guide use the `restaurants` collection in the `sample_restaurants` database from the Atlas sample datasets. To access this collection from your Scala application, create a `MongoClient` that connects to an Atlas cluster and assign the following values to your `database` and `collection` variables:\n\n```scala\nval database: MongoDatabase = client.getDatabase(\"sample_restaurants\")\nval collection: MongoCollection[Document] = database.getCollection(\"restaurants\")\n```\n\nTo learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the MongoDB Get Started guide.\n\n## Projection Types\n\nYou can use a projection to specify which fields to include in a return document, or to specify which fields to exclude. You cannot combine inclusion and exclusion statements in a single projection, unless you are excluding the `_id` field.\n\n### Specify Fields to Include\n\nTo specify the fields to include in the result, chain the `projection()` method to the `find()` method. The `Projections` class provides the `include()` helper method that you can use to set the fields to include.\n\nThe following example uses the `find()` method to find all restaurants in which the `name` field value is `\"Emerald Pub\"`. Then, the code calls the `projection()` and `include()` methods to instruct the find operation to return only the `name`, `cuisine`, and `borough` fields of matching documents:\n\n```scala\ncollection\n .find(equal(\"name\", \"Emerald Pub\"))\n .projection(include(\"name\", \"cuisine\", \"borough\"))\n .subscribe((doc: Document) => println(doc.toJson()),\n (e: Throwable) => println(s\"There was an error: $e\"))\n```\n\n```\n{\"_id\": {\"$oid\": \"...\"}, \"borough\": \"Manhattan\", \"cuisine\": \"American\", \"name\": \"Emerald Pub\"}\n{\"_id\": {\"$oid\": \"...\"}, \"borough\": \"Queens\", \"cuisine\": \"American\", \"name\": \"Emerald Pub\"}\n```\n\nWhen you use a projection to specify fields to include in the return document, the `_id` field is also included by default. All other fields are implicitly excluded. To remove the `_id` field from the return document, you must explicitly exclude it.\n\n### Exclude the `_id` Field\n\nWhen specifying fields to include, you can also exclude the `_id` field from the returned document. The `Projections` class provides the `excludeId()` helper method that you can use to omit this field.\n\nThe following example performs the same query as the preceding example but excludes the `_id` field from the projection:\n\n```scala\ncollection\n .find(equal(\"name\", \"Emerald Pub\"))\n .projection(fields(include(\"name\", \"cuisine\", \"borough\"), excludeId()))\n .subscribe((doc: Document) => println(doc.toJson()),\n (e: Throwable) => println(s\"There was an error: $e\"))\n```\n\n```\n{\"borough\": \"Manhattan\", \"cuisine\": \"American\", \"name\": \"Emerald Pub\"}\n{\"borough\": \"Queens\", \"cuisine\": \"American\", \"name\": \"Emerald Pub\"}\n```\n\n### Specify Fields to Exclude\n\nTo specify the fields to exclude from the result, chain the `projection()` method to the `find()` method. The `Projections` class provides the `exclude()` helper method that you can use to set the fields to exclude.\n\nThe following example uses the `find()` method to find all restaurants in which the `name` field value is `\"Emerald Pub\"`. Then, the code calls the `projection()` and `exclude()` methods to instruct the find operation to omit the `name` and `address` fields in the result:\n\n```scala\ncollection\n .find(equal(\"name\", \"Emerald Pub\"))\n .projection(exclude(\"name\", \"address\"))\n .subscribe((doc: Document) => println(doc.toJson()),\n (e: Throwable) => println(s\"There was an error: $e\"))\n```\n\n```\n{\"_id\": {\"$oid\": \"...\"}, \"borough\": \"Manhattan\", \"cuisine\": \"American\",\n\"grades\": [...], \"restaurant_id\": \"40367329\"}\n{\"_id\": {\"$oid\": \"...\"}, \"borough\": \"Queens\", \"cuisine\": \"American\",\n\"grades\": [...], \"restaurant_id\": \"40668598\"}\n```\n\nWhen you use a projection to specify which fields to exclude, any unspecified fields are implicitly included in the return document.\n\n## Additional Information\n\nTo learn more about projections, see the Project Fields guide in the MongoDB Server manual.\n\n### API Documentation\n\nTo learn more about any of the methods or types discussed in this guide, see the following API documentation:\n\n- find()\n\n- projection()\n\n- Projections\n\n- include()\n\n- excludeId()\n\n- exclude()"} -{"chunk_id": "68a95c355e79d242619e0a6f-0", "page_id": "68a95c355e79d242619e0a6f", "source_name": "scala", "product_name": "Scala Driver", "url": "https://mongodb.com/docs/languages/scala/scala-driver/current/connect/mongoclient", "title": "Create a MongoClient", "text": "# Create a MongoClient\n\n## Overview\n\nTo connect to a MongoDB deployment, you need two things:\n\n- A **connection URI**, also known as a *connection string*, which tells the Scala driver which MongoDB deployment to connect to.\n\n- A **MongoClient** object, which creates the connection to and allows you to perform operations on the MongoDB deployment.\n\nYou can also use `MongoClientSettings` to customize the way the Scala driver behaves while connected to MongoDB.\n\nThis guide shows you how to create a connection string and use a `MongoClient` object to connect to MongoDB.\n\n## Connection URI\n\nA standard connection string includes the following components:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nComponent\n\n\nDescription\n\n
\n`mongodb://`\n\n\nRequired. A prefix that identifies this as a string in the standard connection format.\n\n
\n`username:password`\n\n\nOptional. Authentication credentials. If you include these, the client authenticates the user against the database specified in `authSource`. To learn more about the `authSource` connection option, see the Authentication Mechanisms guide.\n\n
\n`host[:port]`\n\n\nRequired. The host and optional port number where MongoDB is running. If you don't include the port number, the driver uses the default port, `27017`.\n\n
\n`/defaultauthdb`\n\n\nOptional. The authentication database to use if the connection string includes `username:password@` authentication credentials but not the `authSource` option. If you don't include this component, the client authenticates the user against the `admin` database.\n\n
\n`?`\n\n\nOptional. A query string that specifies connection-specific options as `=` pairs.\n\n
For more information about creating a connection string, see Connection Strings in the MongoDB Server manual.\n\n## Atlas Connection Example\n\nTo connect to a MongoDB deployment on Atlas, you must first create a client.\n\nYou can pass a connection URI as a string to the `MongoClient.create()` method to connect to a MongoDB instance:\n\n```scala\n// Replace the placeholder with your Atlas connection string\nval connectionString = \"\"\n\n// Create a new client and connect to the server\nval mongoClient = MongoClient(connectionString)\nval database = mongoClient.getDatabase(\"sample_mflix\")\n```\n\nYou can also create a client with your desired configurations by passing a `MongoClientSettings` object to a `MongoClient` object.\n\nTo instantiate a `MongoClientSettings` object, call the `builder()` method, then chain the `applyConnectionString()` method and pass in your connection string. You can also use the `builder()` method to specify any other client options. Once you have your desired configuration, call the `build()` method.\n\nYou can set the Stable API version client option to avoid breaking changes when you upgrade to a new server version. To learn more about the Stable API feature, see the Stable API page.\n\nThe following code shows how you can specify the connection string and the Stable API client option when connecting to a MongoDB deployment on Atlas and verify that the connection is successful:\n\n```scala\nimport com.mongodb.{ServerApi, ServerApiVersion}\nimport org.mongodb.scala.{ConnectionString, MongoClient, MongoClientSettings}\nimport org.mongodb.scala.bson.Document\n\nimport scala.concurrent.Await\nimport scala.concurrent.duration.DurationInt\nimport scala.util.Using\n\nobject MongoClientConnectionExample {\n\n def main(args: Array[String]): Unit = {\n\n // Replace the placeholder with your Atlas connection string\n val connectionString = \"\"\n\n // Construct a ServerApi instance using the ServerApi.builder() method\n val serverApi = ServerApi.builder.version(ServerApiVersion.V1).build()\n\n val settings = MongoClientSettings\n .builder()\n .applyConnectionString(ConnectionString(connectionString))\n .serverApi(serverApi)\n .build()\n\n // Create a new client and connect to the server\n Using(MongoClient(settings)) { mongoClient =>\n // Send a ping to confirm a successful connection\n val database = mongoClient.getDatabase(\"admin\")\n val ping = database.runCommand(Document(\"ping\" -> 1)).head()\n\n Await.result(ping, 10.seconds)\n System.out.println(\"Pinged your deployment. You successfully connected to MongoDB!\")\n }\n }\n}\n```\n\n## API Documentation\n\nFor more information about creating a `MongoClient` object with the Scala driver, see the following API documentation:\n\n- MongoClient\n\n- MongoClientSettings"} -{"chunk_id": "68a95c355e79d242619e0a9f-0", "page_id": "68a95c355e79d242619e0a9f", "source_name": "scala", "product_name": "Scala Driver", "url": "https://mongodb.com/docs/languages/scala/scala-driver/current/security/encrypt", "title": "In-Use Encryption", "text": "Version 8.2.0 of `mongocryptd` might not run on Windows. This bug affects In-Use Encryption with the driver if you specify the `--logpath NUL` argument when starting `mongocryptd`.\n\nTo learn more about this issue and how to resolve it, see Known Issues in the MongoDB 8.2 Release Notes.\n\nThe Scala driver uses the mongodb-crypt encryption library for in-use encryption. This driver version is compatible with `mongodb-crypt` v5.13.0.\n\nSelect from the following Maven and sbt tabs to see how to add the `mongodb-crypt` dependency to your project by using the specified manager:\n\n\n\n\n\n```xml\n\n \n org.mongodb\n mongodb-crypt\n 5.13.0\n \n\n```\n\n\n\n\n\n```none\nlibraryDependencies += \"org.mongodb\" % \"mongodb-crypt\" % \"5.13.0\"\n```\n\n\n\n\n\n# In-Use Encryption\n\n## Overview\n\nYou can use the Scala driver to encrypt specific document fields by using a set of features called **in-use encryption**. In-use encryption allows your application to encrypt data *before* sending it to MongoDB and query documents with encrypted fields.\n\nVersion 8.2.0 of `mongocryptd` might not run on Windows. This bug affects In-Use Encryption with the driver if you specify the `--logpath NUL` argument when starting `mongocryptd`.\n\nTo learn more about this issue and how to resolve it, see Known Issues in the MongoDB 8.2 Release Notes.\n\nThe Scala driver uses the mongodb-crypt encryption library for in-use encryption. This driver version is compatible with `mongodb-crypt` v5.13.0.\n\nSelect from the following Maven and sbt tabs to see how to add the `mongodb-crypt` dependency to your project by using the specified manager:\n\n\n\n\n\n```xml\n\n \n org.mongodb\n mongodb-crypt\n 5.13.0\n \n\n```\n\n\n\n\n\n```none\nlibraryDependencies += \"org.mongodb\" % \"mongodb-crypt\" % \"5.13.0\"\n```\n\n\n\n\n\nIn-use encryption prevents unauthorized users from viewing plaintext data as it is sent to MongoDB or while it is in an encrypted database. To enable in-use encryption in an application and authorize it to decrypt data, you must create encryption keys that only your application can access. Only applications that have access to your encryption keys can access the decrypted, plaintext data. If an attacker gains access to the database, they can only see the encrypted ciphertext data because they lack access to the encryption keys.\n\nYou might use in-use encryption to encrypt fields in your MongoDB documents that contain the following types of sensitive data:\n\n- Credit card numbers\n\n- Addresses\n\n- Health information\n\n- Financial information\n\n- Any other sensitive or personally identifiable information (PII)\n\nMongoDB offers the following features to enable in-use encryption:\n\n- Queryable Encryption\n\n- Client-side Field Level Encryption\n\n### Queryable Encryption\n\nQueryable Encryption (QE) is an in-use encryption feature that supports querying uniquely encrypted field values, including equality, range, prefix, suffix, and substring queries. Range query support requires MongoDB Server 8.0 or later. Prefix, suffix, and substring query support requires MongoDB Server 9.0 or later.\n\nTo learn more about Queryable Encryption, see Queryable Encryption in the Server manual.\n\n### Client-side Field Level Encryption\n\nClient-side Field Level Encryption (CSFLE) supports searching encrypted fields for equality. MongoDB Server version 4.2 introduced CSFLE.\n\nUnlike QE, CSFLE requires you to select an encryption algorithm for each field, and that choice determines whether you can query the field. Deterministic encryption always produces the same output value for the same input value. Because matching values look the same after encryption, you can run equality queries on these fields. Randomized encryption produces a different output value each time it encrypts the same input value. Drivers can decrypt these fields, but you cannot query them.\n\nDeterministic encryption trades some confidentiality for query support. When an encrypted field has low cardinality, an attacker can compare how often each encrypted value appears and infer the original values. This technique is called frequency analysis. To protect fields that you do not query, use randomized encryption.\n\nTo learn more about these concepts, see the following Wikipedia entries:\n\n- Cardinality\n\n- Frequency Analysis\n\nTo learn more about CSFLE, see CSFLE in the Server manual."} -{"chunk_id": "6a29037dcf3722a2e3ce8b83-0", "page_id": "6a29037dcf3722a2e3ce8b83", "source_name": "search", "product_name": "Atlas Search", "url": "https://mongodb.com/docs/search/query/accuracy", "title": "Improve Accuracy", "text": "# Improve Accuracy\n\n## How do I improve the accuracy of my search results?\n\nTo improve the accuracy of your search results, you can use MongoDB Search support for the following features.\n\n### Customize the Score\n\nMongoDB Search assigns a score to every document in the result set based on relevance and returns the results in order from the highest to the lowest score. To learn more, see Score the Documents in the Results.\n\nWhen you run your MongoDB Search query, you can tune the relevance of the documents in the results to ensure that the most pertinent documents are ranked and returned higher in the results.\n\nTo learn more, see Customize the Score of the Documents in the Results.\n\n### Hybrid Search\n\nHybrid search combines full-text search and semantic search to ensure synonymous and contextually similar matches are included in the combined results of both search methods for the same criteria in the same query.\n\nUse hybrid search for the following scenarios:\n\n- Use MongoDB Search (full-text search) to handle keyword queries and rank documents based on relevance by measuring how frequently a keyword appears in a document and across the documents in the collection.\n\n- Use MongoDB Vector Search (semantic search) to retrieve semantically similar documents.\n\n- Combine the scores of both search methods to retrieve more accurate and relevant results.\n\nTo learn more, see How to Perform Hybrid Search.\n\n### Native Reranking\n\nNative Reranking reorders `$search` results by running the top N documents and query through Voyage AI reranking models to provide more accurate relevancy scores.\n\nTo learn more, see $rerank Aggregation Pipeline Stage.\n\n### Synonyms Search\n\nSynonyms search ensures that your query results contain relevant results even when the exact keywords aren't present in the documents that you search.\n\nWhen you perform a synonyms search, you apply the indexed synonyms mapping collection.\n\nTo learn more, see Define Synonym Mappings in Your MongoDB Search Index.\n\n### Explain Your Search\n\nMongoDB `explain` provides information about how queries execute and why certain documents return over others.\n\nUse `explain` in your query for the following reasons:\n\n- Understand how MongoDB Search computes scores for your search queries and the factors that contribute to the relevance of the documents in the results.\n\n- Improve your index and query based on the performance of your search and ranking.\n\nTo learn more, see How to Retrieve Query Plan and Execution Statistics.\n\n## How can I improve the relevancy of my search results?\n\nYou can tune the relevance in MongoDB Search to ensure that the more pertinent documents return in your MongoDB Search query results. Consider the following to optimize the relevance of your MongoDB Search results.\n\n### Assess Your Data\n\nTo structure and format your data to return optimal results for your search:\n\n- Review the schema of your documents to determine which fields to index. For polymorphic data, MongoDB Search indexes only documents that correspond to the mappings specified in the index definition for that field and ignores documents that contain values that aren't the data type specified in the index definition for that field. To learn more about supported field types and field mappings, see Define Field Mappings for a MongoDB Search Index.\n\n- Normalize the data, if needed, to ensure consistency for fields used in filtering and sorting. For example, convert date and time values to a standard format, such as ISO-8601.\n\n- Analyze the frequency of common terms in key fields to determine the analyzer and tokenization strategy to apply. For example, some terms might require special handling like stemming or synonym mapping. To learn more about creating tokens for your data with MongoDB Search analyzers, see Process Data with Analyzers.\n\n- Analyze the volume of data and plan for scale. Large datasets might require strategic indexing and partitioning.\n\n### Configure Your MongoDB Search Index\n\nTo configure your MongoDB Search index to return optimal results for your search:\n\n- Select the appropriate analyzer for each field that you want to index. Analyzers combine filters with tokenizers to create indexable terms that correct for differences in punctuation, capitalization, filler words, and more. You can choose built-in analyzers or build custom analyzers. To learn more, see Process Data with Analyzers.\n\n- Create a source synonym collection and define synonym mappings that reference the synonym source collection in your MongoDB Search index. You can use synonyms to expand the scope of your search and to return related terms in the results. To learn more, see Define Synonym Mappings in Your MongoDB Search Index.\n\n### Define Your MongoDB Search Query\n\nTo build your query to return optimal results:\n\n- Select the appropriate aggregation pipeline stage. For example, use `$searchMeta` if you want to only retrieve metadata. To learn more, see Pipeline Stages.\n\n- Choose an operator that is optimal for retrieving the relevant results. For example, consider the compound operator if you want to combine multiple clauses such as `must`, `should`, `mustnot` in your query. To learn more, see Operators and Collectors.\n\n- Apply more processes on your search results by using MongoDB Search support for sorting, scoring, grouping, and more.\n\n## Prerequisites\n\nMongoDB Search`$search`To complete the tutorials, you must have:\n\n- An Atlas cluster with MongoDB version 6.0 or later or a MongoDB self-managed cluster with MongoDB version 8.2 or later.\n\n- The sample data loaded into your cluster.\n\n- `Project Data Access Admin` or higher access to your project to create MongoDB Search indexes.\n\n- Search Tester, `mongosh`, Compass, or a supported MongoDB Driver to run queries on your cluster.\n\nYou can run MongoDB Search queries by using any driver through the `$search` aggregation stage. These tutorials include examples for a selection of clients. Refer to the specific tutorial page for details.\n\nYou can also complete these tutorials with local deployments that you create with the Atlas CLI or with an on-prem deployment. To learn more, see Create a Local Atlas Deployment and Self-Managed Deployments."} -{"chunk_id": "6a927b9e4f25feb7b9028f40-0", "page_id": "6a927b9e4f25feb7b9028f40", "source_name": "search", "product_name": "Atlas Search", "url": "https://mongodb.com/docs/search/indexes/field-types/date-facet-type", "title": "How to Index Date Fields For Faceted Search", "text": "# How to Index Date Fields For Faceted Search\n\ndateDateFacet`dateFacet`Field Propertiessample_mflix.moviesdateYou can use the MongoDB Search `dateFacet` type for indexing date values for faceting.\n\nMongoDB Search only supports facet operator queries against fields indexed as the `dateFacet` type. To perform a normal search also on the same field, you must index the field as type date also.\n\nTo facet on string fields in embedded documents, you must index the parent fields as the document type. When you facet on a string field inside embedded documents, MongoDB Search returns facet count for only the number of matching parent documents.\n\nMongoDB Search doesn't dynamically index date values for faceting. You must use static mappings to index date values for faceting. You can use the **Visual Editor** or the **JSON Editor** in the Atlas UI to index date fields as the `number` type.\n\n## `dateFacet` Type Limitations\n\nThe following limitations apply:\n\n- You can't index a date field for faceting if it's inside an array or if it's inside a document in an array.\n\n- MongoDB Search doesn't support date faceting over fields indexed as part of an `embeddedDocuments` field.\n\n To request this feature and provide your feedback, use the MongoDB Feedback.\n\n## Define the Index for `dateFacet` Type\n\nTo define the index for the `dateFacet` type, choose your preferred configuration method in the Atlas UI and then select the database and collection.\n\n\n\n\n\n1. Click Refine Your Index to configure your index.\n\n2. In the Field Mappings section, click Add Field Mapping to open the Add Field Mapping window.\n\n3. Click Customized Configuration.\n\n4. Select the field to index from the Field Name dropdown.\n\n You can't index fields that contain the dollar (`$`) sign at the start of the field name.\n\n5. Click the Data Type dropdown and select DateFacet. To learn more more about this type, see Field Properties.\n\n6. Click Add.\n\n\n\n\n\nThe following is the JSON (Javascript Object Notation) syntax for the `dateFacet` type. Replace the default index definition with the following. To learn more about the fields, see Field Properties.\n\n```json\n{\n \"mappings\": {\n \"dynamic\": true|false,\n \"fields\": {\n \"\": {\n \"type\": \"dateFacet\"\n }\n }\n }\n}\n```\n\n\n\n\n\n## Configure `dateFacet` Field Properties\n\nThe MongoDB Search `dateFacet` type takes the following parameter:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nUI Field Name\n\n\nJSON Option\n\n\nType\n\n\nNecessity\n\n\nDescription\n\n
\nData Type\n\n\n`type`\n\n\nstring\n\n\nrequired\n\n\nHuman-readable label that identifies this field type. Value must be `dateFacet`.\n\n
\n\n## Try an Example for `dateFacet` Type\n\nThe following index definition example uses the sample_mflix.movies collection. If you have the sample data already loaded on your cluster, you can use the Visual Editor or JSON (Javascript Object Notation) Editor in the Atlas UI to configure the index. After you select your preferred configuration method, select the database and collection, and refine your index to add field mappings.\n\n### Basic Example\n\nThe following example index definition indexes the `released` field as the MongoDB Search `dateFacet` type to support queries against that field using MongoDB Search `facet` (MongoDB Search Operator).\n\n\n\n\n\n- In the Add Field Mapping window, select released from the Field Name dropdown.\n\n- Click the Data Type dropdown and select DateFacet.\n\n- Click Add.\n\n\n\n\n\nReplace the default index definition with the following index definition.\n\n```json\n{\n \"mappings\": {\n \"dynamic\": false,\n \"fields\": {\n \"released\": {\n \"type\": \"dateFacet\"\n }\n }\n }\n}\n```\n\n\n\n\n\n### Multiple Types Example\n\nThe following example index definition indexes the `released` field as the `dateFacet` and `date` types to return the following types of results for your queries:\n\n- Metadata results for queries using MongoDB Search `facet` (MongoDB Search Operator).\n\n- Search results for queries using MongoDB Search operators like near, equals, and range.\n\n\n\n\n\n1. In the Add Field Mapping window, select released from the Field Name dropdown.\n\n2. Click the Data Type dropdown and select DateFacet.\n\n3. Click Add.\n\n4. Repeat step **1** and select Date from the Data Type dropdown.\n\n5. Click Add.\n\n\n\n\n\nReplace the default index definition with the following index definition.\n\n```json\n{\n \"mappings\": {\n \"dynamic\": false,\n \"fields\": {\n \"released\": [\n {\n \"type\": \"dateFacet\"\n },\n {\n \"type\": \"date\"\n }\n ]\n }\n }\n}\n```\n\n\n\n\n\n## Learn More\n\nTo learn more about the `facet` collector and see example queries, see Examples.\n\nTo learn how to create an index with a facet definition and query that index using the `facet` collector, see the How to Use Facets with MongoDB Search tutorial."} -{"chunk_id": "6a29037dcf3722a2e3ce8bc1-0", "page_id": "6a29037dcf3722a2e3ce8bc1", "source_name": "search", "product_name": "Atlas Search", "url": "https://mongodb.com/docs/search/query/operators-collectors/text", "title": "`text` (MongoDB Search Operator)", "text": "# `text` (MongoDB Search Operator)\n\n## Definition\n\nThe `text` operator performs a full-text search using the analyzer that you specify in the index configuration. If you omit an analyzer, the `text` operator uses the default standard analyzer.\n\nYou can use the `text` operator to search for exact matches to single-word terms.\n\n## Syntax\n\n`text` has the following syntax:\n\n```json\n{\n $search: {\n \"index\": , // optional, defaults to \"default\"\n \"text\": {\n \"query\": \"\",\n \"path\": \"\",\n \"fuzzy\": ,\n \"matchCriteria\": \"any\" | \"all\"\n \"score\": ,\n \"synonyms\": \"\"\n }\n }\n}\n```\n\n## Options\n\n`text` uses the following terms to construct a query:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nField\n\n\nType\n\n\nDescription\n\n\nNecessity\n\n
\n`query`\n\n\nstring or array of strings\n\n\nThe string or strings to search for. If there are multiple terms in a string, MongoDB Search also looks for a match for each term in the string separately.\n\n\nRequired\n\n
\n`path`\n\n\nstring or array of strings\n\n\nThe indexed field or fields to search. You can also specify a wildcard path to search.\n\n\nRequired\n\n
\n`fuzzy`\n\n\ndocument\n\n\nEnable fuzzy search. Find strings which are similar to the search term or terms. You can't use `fuzzy` with `synonyms`.\n\n\nOptional\n\n
\n`fuzzy.maxEdits`\n\n\ninteger\n\n\nMaximum number of single-character edits required to match the specified search term. Value can be `1` or `2`. The default value is `2`. Uses Damerau-Levenshtein distance.\n\n\nOptional\n\n
\n`fuzzy.prefixLength`\n\n\ninteger\n\n\nNumber of characters at the beginning of each term in the result that must exactly match. The default value is `0`.\n\n\nOptional\n\n
\n`fuzzy.maxExpansions`\n\n\ninteger\n\n\nMaximum number of variations to generate and search for. This limit applies on a per-token basis. The default value is `50`.\n\n\nOptional\n\n
\n`matchCriteria`\n\n\nstring\n\n\nCriteria to use to match the terms in the query. If omitted, defaults to `any`. Value can be one of the following:\n\n- `any` - to return documents that contain any of the terms from the `query` field.\n\n- `all` - to only return documents that contain all of the terms from the `query` field.\n\n\nOptional, Recommended\n\n
\n`score`\n\n\ndocument\n\n\nScore assigned to matching search term results. Use one of the following options to modify the score:\n\n- `boost`: multiply the result score by the given number.\n\n- `constant`: replace the result score with the given number.\n\n- `function`: replace the result score using the given expression.\n\nWhen querying array values, MongoDB Search assigns higher scores if more values in the array match the query.\n\n\nOptional\n\n
\n`synonyms`\n\n\nstring\n\n\nRequired for running queries using synonyms.\n\nName of the synonym mapping definition in the index definition. Value can't be an empty string. You can't use `fuzzy` with `synonyms`.\n\nIMPORTANT: To use the `synonyms` option, you must index the query field as type `string` with the `indexOptions` property set to `positions` or the default value, `offsets`. To learn more, see Configure String Field Properties.\n\nAlways use `matchCriteria` when using `synonyms`. For `text` queries that use `synonyms` without `matchCriteria`, MongoDB Search only matches documents where all the terms are exactly in the same position as the query. This behavior might change in the future and your query results might also change.\n\nThe amount of time that MongoDB Search takes to execute queries that use synonym mappings depends on the number and size of documents in the synonym source collection. A query that uses a synonym mapping that is based on very few synonym documents might be faster than a query that uses a synonym mapping that is based on many synonym documents.\n\n\nOptional\n\n
\n\n## Scoring Behavior\n\ntext`string`How to Index String FieldsBy default, the text operator uses the `bm25` similarity algorithm to score documents depending on their relevance to the query.\n\nYou can change which similarity algorithm is used by specifying a different similarity algorithm in the `similarity.type` property for the `string` fields in your MongoDB Search index definition. To learn how to configure a MongoDB Search index for the `string` type, see How to Index String Fields.\n\nTo learn more about the supported similarity algorithms, see Score Details.\n\n## Behavior\n\nFor `text` queries that use `synonyms` without `matchCriteria`, MongoDB Search only matches documents which contain an exact match of the query terms (with or without the expanded synonyms).\n\nThis behavior might change in the future and your query results might also change. To avoid service disruptions, always use `matchCriteria` when using `synonyms`. Or, use synonyms with the phrase operator.\n\nFor example, suppose equivalent synonym mappings for `nyc` and `new york city`. A search for `i like nyc` returns the following:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nOperator Specification\n\n\nDefault Behavior\n\n\n`\"matchCriteria\": \"any\"`\n\n\n`\"matchCriteria\": \"all\"`\n\n
\n`text` without `synonyms`\n\n\nMatches `i` OR `like` OR `nyc`\n\n\nMatches `i` OR `like` OR `nyc`\n\n\nMatches `i` AND `like` AND `nyc`\n\n
\n`text` with `synonyms`\n\n\nMatches `i like nyc` OR `i like new york city`\n\n\nMatches `i` OR `like` OR (`nyc` OR `new york city`)\n\n\nMatches `i` AND `like` AND (`nyc` OR `new york city`)\n\n
The amount of time that MongoDB Search takes to execute queries that use synonym mappings depends on the number and size of documents in the synonym source collection. A query that uses a synonym mapping that is based on very few synonym documents might be faster than a query that uses a synonym mapping that is based on many synonym documents.\n\n## Examples\n\nThe examples in this page use the `movies` collection in the `sample_mflix` database. After loading the sample dataset into your cluster, create the MongoDB Search index with dynamic mappings and run the example queries on your cluster. You must also define a `synonyms` mapping collection in the index as shown in the Index Definition Examples to try the synonyms examples below."} -{"chunk_id": "6a29037dcf3722a2e3ce8bc1-1", "page_id": "6a29037dcf3722a2e3ce8bc1", "source_name": "search", "product_name": "Atlas Search", "url": "https://mongodb.com/docs/search/query/operators-collectors/text", "title": "`text` (MongoDB Search Operator)", "text": "### Basic Example\n\nThe following MongoDB Search query uses the `text` operator to search the `title` field in the `movies` collection for the term `surfer`. It includes a `$project` stage to:\n\n- Exclude all fields except `title`\n\n- Add a field named `score`\n\n```json\ndb.movies.aggregate([\n {\n $search: {\n \"text\": {\n \"path\": \"title\",\n \"query\": \"surfer\"\n }\n }\n },\n {\n $project: {\n \"_id\": 0,\n \"title\": 1,\n score: { $meta: \"searchScore\" }\n }\n }\n])\n```\n\n```json\n{ \"title\" : \"Soul Surfer\", \"score\" : 4.518949508666992 }\n{ \"title\" : \"Little Surfer Girl\", \"score\" : 3.8856077194213867 }\n{ \"title\" : \"Fantastic 4: Rise of the Silver Surfer\", \"score\" : 2.489800453186035 }\n```\n\n### Metadata Example\n\nThe following query searches the `title` field for the term `summer`. It uses the `$searchMeta` stage to retrieve the number of movies in the following buckets (years) that match the search criteria:\n\n- 1970, inclusive lower bound for this bucket\n\n- 1980, exclusive upper bound for the 1970 bucket and inclusive lower bound for this bucket\n\n- 1990, exclusive upper bound for the 1980 bucket and inclusive lower bound for this bucket\n\n- 2000, exclusive upper bound for the 1990 bucket and inclusive lower bound for this bucket\n\n- 2010, exclusive upper bound for the 2000 bucket and inclusive lower bound for this bucket\n\n- 2015, exclusive upper bound for the 2010 bucket\n\n```json\ndb.movies.aggregate([\n {\n \"$searchMeta\": {\n \"facet\": {\n \"operator\": {\n \"text\": {\n \"path\": \"title\",\n \"query\": \"summer\"\n }\n },\n \"facets\": {\n \"yearFacet\": {\n \"type\": \"number\",\n \"path\": \"year\",\n \"boundaries\": [1970, 1980, 1990, 2000, 2010, 2020 ]\n }\n }\n }\n }\n }\n])\n```\n\n```javascript\n[\n {\n count: { lowerBound: Long('65') },\n facet: {\n yearFacet: {\n buckets: [\n { _id: 1970, count: Long('6') },\n { _id: 1980, count: Long('7') },\n { _id: 1990, count: Long('11') },\n { _id: 2000, count: Long('19') },\n { _id: 2010, count: Long('14') }\n ]\n }\n }\n }\n]\n```"} -{"chunk_id": "6a29037dcf3722a2e3ce8bc1-2", "page_id": "6a29037dcf3722a2e3ce8bc1", "source_name": "search", "product_name": "Atlas Search", "url": "https://mongodb.com/docs/search/query/operators-collectors/text", "title": "`text` (MongoDB Search Operator)", "text": "### Fuzzy Examples\n\nThe following queries use the `text` operator to search the `title` field in the `movies` collection for terms that are within one character variation of each term in the `query` phrase `naw yark`. MongoDB Search returns different results depending on whether you use the default `fuzzy` options or define the `maxExpansions`, `prefixLength`, or `maxEdits` fields.\n\nClick the following tabs for example queries that use default and specified options:\n\n\n\n\n\nThe following query searches the `title` field for the phrase `naw yark`. It uses the `fuzzy` default options where:\n\n- `maxEdits` allows up to two character variation of each term in the given phrase to match the query to a document.\n\n- `maxExpansions` considers up to fifty similar terms for each term in `naw yark` to find matches.\n\n- `prefixLength` is disabled.\n\nThe query also includes a `$limit` stage to limit the output to 10 results and a `$project` stage to:\n\n- Exclude all fields except `title`\n\n- Add a field named `score`\n\n```json\ndb.movies.aggregate([\n {\n $search: {\n \"text\": {\n \"path\": \"title\",\n \"query\": \"naw yark\",\n \"fuzzy\": {}\n }\n }\n },\n {\n $limit: 10\n },\n {\n $project: {\n \"_id\": 0,\n \"title\": 1,\n score: { $meta: \"searchScore\" }\n }\n }\n])\n```\n\n```json\n{ \"title\" : \"New York, New York\", \"score\" : 3.6040148735046387 }\n{ \"title\" : \"New York\", \"score\" : 3.323730945587158 }\n{ \"title\" : \"New York Stories\", \"score\" : 2.8579015731811523 }\n{ \"title\" : \"New York Minute\", \"score\" : 2.8579015731811523 }\n{ \"title\" : \"Synecdoche, New York\", \"score\" : 2.8579015731811523 }\n{ \"title\" : \"New York Doll\", \"score\" : 2.8579015731811523 }\n{ \"title\" : \"Little New York\", \"score\" : 2.8579015731811523 }\n{ \"title\" : \"Escape from New York\", \"score\" : 2.506596088409424 }\n{ \"title\" : \"Naked in New York\", \"score\" : 2.506596088409424 }\n{ \"title\" : \"Autumn in New York\", \"score\" : 2.506596088409424 }\n```\n\n\n\n\n\nThe following query searches the `title` field for terms that are within one character of each term in the string `naw yark`. It uses:\n\n- The `maxEdits` field to indicate that only one character variation is allowed for each term to match the query to a document.\n\n- The `maxExpansions` field to indicate that up to one hundred similar terms for `naw` and one hundred similar terms to `yark` must be considered when matching the query to a document.\n\nThe query also includes a `$limit` stage to limit the output to 10 results and a `$project` stage to:\n\n- Exclude all fields except `title`\n\n- Add a field named `score`\n\n```json\ndb.movies.aggregate([\n {\n $search: {\n \"text\": {\n \"path\": \"title\",\n \"query\": \"naw yark\",\n \"fuzzy\": {\n \"maxEdits\": 1,\n \"maxExpansions\": 100,\n }\n }\n }\n },\n {\n $limit: 10\n },\n {\n $project: {\n \"_id\": 0,\n \"title\": 1,\n score: { $meta: \"searchScore\" }\n }\n }\n])\n```\n\n```shell\n{ \"title\" : \"New York, New York\", \"score\" : 4.38106107711792 }\n{ \"title\" : \"New York\", \"score\" : 4.040346145629883 }\n{ \"title\" : \"New York Stories\", \"score\" : 3.4740817546844482 }\n{ \"title\" : \"New York Minute\", \"score\" : 3.4740817546844482 }\n{ \"title\" : \"Synecdoche, New York\", \"score\" : 3.4740817546844482 }\n{ \"title\" : \"New York Doll\", \"score\" : 3.4740817546844482 }\n{ \"title\" : \"Little New York\", \"score\" : 3.4740817546844482 }\n{ \"title\" : \"Escape from New York\", \"score\" : 3.047032356262207 }\n{ \"title\" : \"Naked in New York\", \"score\" : 3.047032356262207 }\n{ \"title\" : \"Autumn in New York\", \"score\" : 3.047032356262207 }\n```\n\n\n\n\n\nThe following query searches the `title` field for terms that are within one character of each term in the string `naw yark`. It uses:\n\n- The `maxEdits` field to indicate that only one character variation is allowed to match the query to a document.\n\n- The `prefixLength` field to indicate that the first two characters of each term in the string `naw yark` may not be changed to match the query to a document.\n\nThe query also includes a `$limit` stage to limit the output to 8 results and a `$project` stage to:\n\n- Exclude all fields except `_id` and `title`\n\n- Add a field named `score`\n\n```json\ndb.movies.aggregate([\n {\n $search: {\n \"text\": {\n \"path\": \"title\",\n \"query\": \"naw yark\",\n \"fuzzy\": {\n \"maxEdits\": 1,\n \"prefixLength\": 2,\n }\n }\n }\n },\n {\n $limit: 8\n },\n {\n $project: {\n \"_id\": 1,\n \"title\": 1,\n score: { $meta: \"searchScore\" }\n }\n }\n])\n```\n\n```shell\n{ \"_id\" : ObjectId(\"573a1396f29313caabce5646\", \"title\" : \"The Longest Yard\", \"score\" : 2.914206027984619 }\n{ \"_id\" : ObjectId(\"573a13aff29313caabd31ed8\", \"title\" : \"The Longest Yard\", \"score\" : 2.914206027984619 }\n{ \"_id\" : ObjectId(\"573a13b7f29313caabd4ad8b\", \"title\" : \"Stomp the Yard\", \"score\" : 2.914206027984619 }\n{ \"_id\" : ObjectId(\"573a13eaf29313caabdcf410\", \"title\" : \"Naz & Maalik\", \"score\" : 2.5460386276245117 }\n{ \"_id\" : ObjectId(\"573a1393f29313caabcddbed\", \"title\" : \"La nao capitana\", \"score\" : 2.1892051696777344 }\n{ \"_id\" : ObjectId(\"573a1399f29313caabcee781\", \"title\" : \"Kabhi Haan Kabhi Naa\", \"score\" : 1.9200985431671143 }\n{ \"_id\" : ObjectId(\"573a13a2f29313caabd0b815\", \"title\" : \"Kaho Naa... Pyaar Hai\", \"score\" : 1.9200985431671143 }\n{ \"_id\" : ObjectId(\"573a13a7f29313caabd1b5c0\", \"title\" : \"Oysters at Nam Kee's\", \"score\" : 1.9200985431671143 }\n```\n\n\n\n\n\n#### Match `all`\n\nThe following query uses the `text` operator to search the `plot` field in the `movies` collection for all the terms in the query string `automobile race`.\n\n```json\ndb.movies.aggregate([\n {\n \"$search\": {\n \"text\": {\n \"path\": \"plot\",\n \"query\": \"automobile race\",\n \"matchCriteria\": \"all\"\n }\n }\n },\n {\n \"$limit\": 20\n },\n {\n \"$project\": {\n \"_id\": 0,\n \"plot\": 1,\n \"title\": 1,\n \"score\": { \"$meta\": \"searchScore\" }\n }\n }\n])\n```\n\n```shell\n[\n {\n plot: 'A young driver, Speed Racer, aspires to be champion of the racing world with the help of his family and his high-tech Mach 5 automobile.',\n title: 'Speed Racer',\n score: 6.122188568115234\n },\n {\n plot: 'A gorgeous young automobile fanatic--and front to the hottest unsigned band on the West coast--finds herself caught up in illegal drag-racing competitions organized by exotic car fanatics.',\n title: 'Redline',\n score: 5.497724533081055\n },\n {\n plot: 'When a popular daredevil proposes an automobile race across three continents, his arch rival vows to beat him, while an ambitious female reporter has her own plans for victory.',\n title: 'The Great Race',\n score: 5.282209396362305\n }\n]\n```\n\nMongoDB Search returns documents that contain the terms `automobile` and `race` anywhere in the `plot` field."} -{"chunk_id": "6a29037dcf3722a2e3ce8bc1-3", "page_id": "6a29037dcf3722a2e3ce8bc1", "source_name": "search", "product_name": "Atlas Search", "url": "https://mongodb.com/docs/search/query/operators-collectors/text", "title": "`text` (MongoDB Search Operator)", "text": "### Synonyms Examples\n\nThe following examples use the `text` operator to search the `plot` field in the `sample_mflix.movies` namespace. MongoDB Search returns results based on the type of mapping in the synonym source collection, `synonymous_terms`, specified in the synonym mapping definition of the index for the `sample_mflix.movies` collection.\n\n#### Match `any` Using `equivalent` Mapping\n\nThe following query searches the `plot` field for the phrase `attire`. It uses the synonym mapping named `mySynonyms` in the index for the collection to also search for words that are configured to be synonyms of the word `dress`.\n\n```json\ndb.movies.aggregate([\n {\n \"$search\": {\n \"text\": {\n \"path\": \"plot\",\n \"query\": \"attire\",\n \"synonyms\": \"my_synonyms\",\n \"matchCriteria\": \"any\"\n }\n }\n },\n {\n \"$limit\": 5\n },\n {\n \"$project\": {\n \"_id\": 0,\n \"plot\": 1,\n \"title\": 1,\n \"score\": { \"$meta\": \"searchScore\" }\n }\n }\n])\n```\n\n```json\n[\n {\n plot: 'The Sanguiwon are responsible for the attire worn by royalty. Dol-Seok (Han Suk-Kyu) is the best master artisan in charge of royal attire. He views set rules as paramount to his job. ...',\n title: 'The Royal Tailor',\n score: 15.825017929077148\n },\n {\n plot: \"During Christmas' holidays, the children of a village split in two gang to play a snowball war. But that half-tone war scattered some bitterness and make more difficult the mutual attirance...\",\n title: 'La guerre des tuques',\n score: 11.863945007324219\n },\n {\n plot: 'The Dress is a tale filled with sex, violence, comedy and drama as it follows the life of a dress. Conceived under a cloud of frustration and despair, the dress serves as the hub in a great...',\n title: 'The Dress',\n score: 5.061710834503174\n },\n {\n plot: \"Boardroom and dressing-room intrigues spill on to the field at the Australian Rules football club.\",\n title: 'The Club',\n score: 3.991994857788086\n },\n {\n plot: 'Deserting soldier dresses as a woman to escape detection; liking the female role he goes to a dance with another soldier and is exposed.',\n title: 'The Triple Echo',\n score: 3.5169785022735596\n }\n]\n```\n\nMongoDB Search returns the documents that contain the terms `attire`, `apparel`, and `dress` because we configured all these terms to be `equivalent` synonym in the synonyms source collection, `synonymous_terms`, which mean all these terms are synonyms of one another. Therefore, MongoDB Search returns similar documents for searches on `dress` and `attire`.\n\n#### Match `any` Using `explicit` Mapping\n\nThe following query searches the `plot` field for the phrase `boat race`. It uses the synonym mapping named `my_synonyms` in the index for the collection to also search for words that are configured to be synonyms of the word `boat` and `race`.\n\n```json\ndb.movies.aggregate([\n {\n \"$search\": {\n \"text\": {\n \"path\": \"plot\",\n \"query\": \"boat race\",\n \"synonyms\": \"my_synonyms\",\n \"matchCriteria\": \"any\"\n }\n }\n },\n {\n \"$limit\": 10\n },\n {\n \"$project\": {\n \"_id\": 0,\n \"plot\": 1,\n \"title\": 1,\n \"score\": { \"$meta\": \"searchScore\" }\n }\n }\n])\n```\n\n```json\n[\n {\n plot: 'A man is picked up by a fishing boat, bullet-riddled and suffering from amnesia, before racing to elude assassins and regain his memory.',\n title: 'The Bourne Identity',\n score: 15.405073165893555\n },\n {\n plot: 'A few friends builds a sailing boat together. They plan trips and during the completion of the boat marriages crumble, new relations blossom and the boat burns. They rebuild it and the ...',\n title: 's/y Gl\u00e8djen',\n score: 13.40434741973877\n },\n {\n plot: 'Famous motor-racing champion Joe Greer returns to his hometown to compete in a local race. He discovers his younger brother has aspirations to become a racing champion and during the race ...',\n title: 'The Crowd Roars',\n score: 10.466073036193848\n },\n {\n plot: 'The claustrophobic world of a WWII German U-boat; boredom, filth, and sheer terror.',\n title: 'Das Boot',\n score: 10.304922103881836\n },\n {\n plot: 'Several survivors of a torpedoed ship find themselves in the same boat with one of the men who sunk it.',\n title: 'Lifeboat',\n score: 9.776729583740234\n },\n {\n plot: 'A fishing-boat crew takes on a dangerous commission to smuggle a group of illegal immigrants from China to Korea.',\n title: 'Haemoo',\n score: 9.532430648803711\n },\n {\n plot: 'A land baron tries to reconnect with his two daughters after his wife is seriously injured in a boating accident.',\n title: 'The Descendants',\n score: 9.300044059753418\n },\n {\n plot: 'A weekend boating party turns into a nightmare for a group of young Londoners when they stumble upon a terrifying secret hidden in the reeds.',\n title: 'The Reeds',\n score: 9.078716278076172\n },\n {\n plot: 'Documentary telling the true story of the sinking of the liner Laconia by a German U-boat in 1942 through the eyes of six survivors.',\n title: 'The Sinking of the Laconia',\n score: 9.078716278076172\n },\n {\n plot: 'Sabotage efforts damage an international air race.',\n title: 'Those Magnificent Men in Their Flying Machines or How I Flew from London to Paris in 25 hours 11 minutes',\n score: 8.983794212341309\n }\n]\n```\n\nMongoDB Search returns documents that contain the term `boat`, `vessel,` or `sail`, or `race`, `rally`, or `contest` because we configured `boat` to be an `explicit` synonym or `vessel` and `sail` and we configured `race` to be an `explicit` synonym of `rally` and `contest`. MongoDB Search doesn't return any results for a query on `vessel` and `sail` or `rally` and `contest` because we didn't configure these words to consider any of the other words as synonyms.\n\n#### Match `all` Using Synonyms\n\nThe following query uses the `text` operator to search the `plot` field in the `movies` collection for all terms in the query string `automobile race`.\n\nMongoDB Search returns results based on the type of mapping in the synonym source collection, `synonymous_terms`, specified in the synonym mapping definition of the index for the `sample_mflix.movies` collection.\n\n```json\ndb.movies.aggregate([\n {\n \"$search\": {\n \"text\": {\n \"path\": \"plot\",\n \"query\": \"automobile race\",\n \"matchCriteria\": \"all\",\n \"synonyms\": \"my_synonyms\"\n }\n }\n },\n {\n \"$limit\": 20\n },\n {\n \"$project\": {\n \"_id\": 0,\n \"plot\": 1,\n \"title\": 1,\n \"score\": { \"$meta\": \"searchScore\" }\n }\n }\n])\n```"} -{"chunk_id": "6a29037dcf3722a2e3ce8bc1-4", "page_id": "6a29037dcf3722a2e3ce8bc1", "source_name": "search", "product_name": "Atlas Search", "url": "https://mongodb.com/docs/search/query/operators-collectors/text", "title": "`text` (MongoDB Search Operator)", "text": "```json\n[\n {\n plot: 'A young driver, Speed Racer, aspires to be champion of the racing world with the help of his family and his high-tech Mach 5 automobile.',\n title: 'Speed Racer',\n score: 17.354578018188477\n },\n {\n plot: 'A gorgeous young automobile fanatic--and front to the hottest unsigned band on the West coast--finds herself caught up in illegal drag-racing competitions organized by exotic car fanatics.',\n title: 'Redline',\n score: 16.085742950439453\n },\n {\n plot: 'When a popular daredevil proposes an automobile race across three continents, his arch rival vows to beat him, while an ambitious female reporter has her own plans for victory.',\n title: 'The Great Race',\n score: 15.087226867675781\n },\n {\n plot: 'A race car driver becomes a champion with a Volkswagen Beetle with a mind of its own.',\n title: 'The Love Bug',\n score: 5.1777167320251465\n },\n {\n plot: 'A wide variety of eccentric competitors participate in a wild and illegal cross-country car race.',\n title: 'The Cannonball Run',\n score: 5.041530609130859\n },\n {\n plot: 'The original characters from the first Cannonball movie race across the country once more in various cars and trucks.',\n title: 'Cannonball Run II',\n score: 4.67281436920166\n },\n {\n plot: 'After a tied 1st place in a local stunt race, two drivers start a contest to decide who of them will own the prize, a dune buggy. But when a mobster destroys the car, they are determined to get it back.',\n title: \"Watch Out, We're Mad\",\n score: 4.500225067138672\n },\n {\n plot: 'Four teenagers are killed in a car accident. Two of the teenagers refuse to go with \"The Grim Reaper\" and a race between life and death ensues!',\n title: 'Soultaker',\n score: 4.455573081970215\n },\n {\n plot: \"The driver races to locate a kidnapped victim locked in the trunk of an abandoned car somewhere on the water's edge. Linked to her only by cell phone, the driver narrows in on her location in a desperate race against time and tide.\",\n title: 'Hostage',\n score: 4.429774284362793\n },\n {\n plot: 'Race car driver Lucky Jackson goes to Las Vegas to earn money to pay for a new engine for his motor car. Working as a waiter, he still finds the time to court young Rusty Martin.',\n title: 'Viva Las Vegas',\n score: 4.379656791687012\n },\n {\n plot: 'Barry Pepper portrays legendary race car drive Dale Earnhardt, who died in 2001 during the last lap of the Daytona 500.',\n title: '3: The Dale Earnhardt Story',\n score: 4.3543548583984375\n },\n {\n plot: 'Bounty hunters from the future transport a doomed race-car driver to 2009 New York, where his mind will be replaced with that of a dead billionaire.',\n title: 'Freejack',\n score: 4.257633209228516\n },\n {\n plot: 'A mechanic takes his family to a car race and a series of events occur which brings problems, betrayals, violence and the unexpected death of an elderly person.',\n title: 'National Mechanics',\n score: 4.257633209228516\n },\n {\n plot: 'A hot-shot race-car named Lightning McQueen gets waylaid in Radiator Springs, where he finds the true meaning of friendship and family.',\n title: 'Cars',\n score: 4.257633209228516\n },\n {\n plot: 'Star race car Lightning McQueen and his pal Mater head overseas to compete in the World Grand Prix race. But the road to the championship becomes rocky as Mater gets caught up in an intriguing adventure of his own: international espionage.',\n title: 'Cars 2',\n score: 4.231379985809326\n },\n {\n plot: \"An illegal race that takes place over the United States and nothing will stop this bunch of racers except for the occasional cop or a damsel in distress. Jackie Chan's car is not in this ...\",\n title: 'Cannonball Fever',\n score: 4.1651153564453125\n },\n {\n plot: 'Roy is mad about cars, and runs Stallion Parts while attending to his yellow Mustang, far away from his daughter, which comes on holiday, while he is to attend a race. Soon he is challenged in a illegal race through the length of Norway.',\n title: 'B\u00e8rning',\n score: 4.050384521484375\n },\n {\n plot: \"It's time for the annual London to Brighton antique car rally, and Alan McKim and Ambrose Claverhouse are not going to let their friendship stop them from trying to humiliate each other. ...\",\n title: 'Genevieve',\n score: 3.9916391372680664\n },\n {\n plot: \"After a young man's premonition of a deadly race-car crash helps saves the lives of his peers, Death sets out to collect those who evaded their end.\",\n title: 'The Final Destination',\n score: 3.9916391372680664\n },\n {\n plot: \"A fast-paced comedy about a young Belgian car nut and hairdresser's apprentice, his girlfriend, and their legal and illegal attempts to get a Porsche under him for his nearing debut race.\",\n title: 'The Departure',\n score: 3.832036256790161\n }\n]\n```\n\nMongoDB Search returns documents that contain the query terms `automobile`, `car`, or `vehicle` and `race`, `context`, or `rally` because we configured `automobile`, `vehicle`, and `car` to be `equivalent` synonyms and we configured `rally` and `contest` to be `explicit` synonyms of `race` in the `synonymous_terms` collection."} -{"chunk_id": "6a29037dcf3722a2e3ce8bbb-0", "page_id": "6a29037dcf3722a2e3ce8bbb", "source_name": "search", "product_name": "Atlas Search", "url": "https://mongodb.com/docs/search/query/operators-collectors/regex", "title": "`regex` (MongoDB Search Operator)", "text": "# `regex` (MongoDB Search Operator)\n\n## Definition\n\n`regex`\n`regex` interprets the `query` field as a regular expression. `regex` is a term-level operator, meaning that the `query` field isn't analyzed.\n\n- Analyzers.\n\n- Analyzed field example.\n\nThe regular expression language available to the `regex` operator is a limited subset of the PCRE (Perl Compatible Regular Expressions) library.\n\nFor detailed information, see the Class RegExp documentation.\n\n## Syntax\n\n`regex` has the following syntax:\n\n```javascript\n{\n $search: {\n \"index\": , // optional, defaults to \"default\"\n \"regex\": {\n \"query\": \"\",\n \"path\": \"\",\n \"allowAnalyzedField\": ,\n \"score\": \n }\n }\n}\n```\n\n## Options\n\n`regex` uses the following terms to construct a query:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nField\n\n\nType\n\n\nDescription\n\n\nNecessity\n\n\nDefault\n\n
\n`query`\n\n\nstring or array of strings\n\n\nString or strings to search for.\n\n\nyes\n\n\n\n
\n`path`\n\n\nstring or array of strings\n\n\nIndexed field or fields to search. You can also specify a wildcard path to search.\n\n\nyes\n\n\n\n
\n`allowAnalyzedField`\n\n\nboolean\n\n\nMust be set to `true` if the query is run against an analyzed field.\n\n\nno\n\n\n`false`\n\n
\n`score`\n\n\nobject\n\n\nScore to assign to matching search term results. Options are:\n\n- `boost`: multiply the result score by the given number.\n\n- `constant`: replace the result score with the given number.\n\n- `function`: replace the result score with the given expression.\n\n\nno\n\n\n\n
\n\n## Behavior\n\n`regex` is a term-level operator, meaning that the `query` field is not analyzed. Regular expression searches work well with the keyword analyzer, because it indexes fields one word at a time. To do a case-sensitive search, do not use the default analyzer, standard analyzer, because the `standard` analyzer lower cases all terms. Specify a different analyzer instead.\n\nIt is possible to use the `regex` operator to perform searches on an analyzed field by setting the `allowAnalyzedField` option to `true`, but you may get unexpected results.\n\nSearching for `.*Star Trek.*` on a field indexed with the keyword analyzer finds all documents in which the field contains the string `Star Trek` in any context. Searching for `.*Star Trek.*` on a field indexed with the standard analyzer finds nothing, because there is a space between `Star` and `Trek`, and the index contains no spaces.\n\n## Lucene Regular Expression Behavior\n\nThe MongoDB Search `regex` operator uses the Lucene regular expression engine, which differs from Perl Compatible Regular Expressions.\n\n### Reserved characters\n\nThe following characters are reserved as operators when used in regular expressions:\n\n`. ? + * | { } [ ] ( ) < > \" \\ @ #`\n\nTo use any of the above characters literally in a matching expression, precede it with a `\\` character.\n\n`who\\?` *matches \"who?\"*\n\nWhen using the escape character in `mongosh` or with a driver, you must use a double backslash before the character to be escaped.\n\nTo create a wildcard expression which searches for any string containing a literal asterisk in an aggregation pipeline, use the following expression:\n\n```none\n\"*\\\\**\"\n```\n\nThe first and last asterisks act as wildcards which match any characters, and the `\\\\*` matches a literal asterisk.\n\nUse the following expression to escape a literal backslash:\n\n```none\n\"*\\\\\\*\"\n```\n\n### Supported Operators\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nOperator\n\n\nDescription\n\n\nExample\n\n
\n`.`\n\n\nMatches any character.\n\n\n`x.z` *matches \"xyz\", \"xaz\", etc.*\n\n
\n`?`\n\n\nThe preceding character is optional and matches if it occurs no more than once.\n\n\n`xyz?` *matches \"xy\" and \"xyz\"*\n\n
\n`+`\n\n\nThe preceding character matches if it occurs one or more times.\n\n\n`xy+` *matches \"xy\", \"xyy\", \"xyyy\", etc.*\n\n
\n`*`\n\n\nThe preceding character matches if it occurs any number of times.\n\n\n`xyz*` *matches \"xy\", \"xyz\", \"xyzz\", etc.*\n\n
\n`|`\n\n\nThe `OR` operator. The expression matches if either of the two patterns on either side of the `|` operator matches.\n\n\n`abc|xyz` *matches \"abc\" or \"xyz\"*\n\n
\n`{}`\n\n\nThe preceding character matches if it occurs exactly times.\n\n\n`xyz{3}` *matches \"xyzzz\"*\n\n
\n`()`\n\n\nCharacters inside parentheses are treated as a single unit for matching purposes.\n\n\n`xyz(abc)[2]` *matches \"xyzabcabc\"*\n\n
\n`[]`\n\n\nMatches any of the characters inside the square brackets.\n\nAdding a `^` to the beginning matches any character except those within the square brackets.\n\nInside the square brackets, `-` indicates a range, unless `-` is the first character or is escaped with a `\\`.\n\n\n`[xyz]` *matches \"x\", \"y\", and \"z\"*`[^abc]` *matches any character except \"a\", \"b\", or \"c\"*`[a-d]` *matches \"a\", \"b\", \"c\", or \"d\"*`[0-9]` *matches any numeric character from 0 through 9*\n\n
\n`<>`\n\n\nMatch a numeric range.\n\n\n`<1-3>` *matches \"1\", \"2\", and \"3\"*\n\n
\n`#`\n\n\nThe empty language operator. The `#` operator does not match any string, including an empty string.\n\n\n`#|xyz` *matches \"xyz\" and nothing else*\n\n
\n\n### Unsupported Operators\n\n`regex` does not support anchor operators. For example, these operators are not supported:\n\n- `^`, which matches the beginning of a line.\n\n- `$`, which matches the end of a line.\n\nTo match a term, the regular expression must match the entire string.\n\n## Examples\n\nThe following examples use the `movies` collection in the `sample_mflix` database with a custom index definition that uses the keyword analyzer. If you have the sample dataset on your cluster, you can create a MongoDB Search index on the `movies` collection and run the example queries on your cluster.\n\n### Index Definition\n\nThe following index definition indexes the `title` field in the `movies` collection with the keyword analyzer:\n\n```javascript\n{\n \"mappings\": {\n \"fields\": {\n \"title\": {\n \"analyzer\": \"lucene.keyword\",\n \"type\": \"string\"\n },\n \"genres\": {\n \"type\": \"token\"\n }\n }\n }\n}\n```"} -{"chunk_id": "6a29037dcf3722a2e3ce8bbb-1", "page_id": "6a29037dcf3722a2e3ce8bbb", "source_name": "search", "product_name": "Atlas Search", "url": "https://mongodb.com/docs/search/query/operators-collectors/regex", "title": "`regex` (MongoDB Search Operator)", "text": "### Term Position\n\nThe following example uses the regular expression `.*` to find movie titles that contain the term `summer` anywhere in the `title` and returns the number of movies that match the criteria in each genre.\n\n```javascript\ndb.movies.aggregate([\n {\n \"$searchMeta\": {\n \"facet\": {\n \"operator\": {\n \"regex\": {\n \"path\": \"title\",\n \"query\": \".*summer.*\"\n }\n },\n \"facets\": {\n \"genresFacet\": {\n \"type\": \"string\",\n \"path\": \"genres\"\n }\n }\n }\n }\n }\n])\n```\n\n```javascript\n[\n {\n count: { lowerBound: Long('6') },\n facet: {\n genresFacet: {\n buckets: [\n { _id: 'Comedy', count: Long('5') },\n { _id: 'Fantasy', count: Long('3') },\n { _id: 'Romance', count: Long('3') },\n { _id: 'Drama', count: Long('2') },\n { _id: 'Horror', count: Long('1') },\n { _id: 'Mystery', count: Long('1') }\n ]\n }\n }\n }\n]\n```\n\nThe following example searches all `title` fields for movie titles that end with the word `Seattle`. The `(.*)` regular expression matches any number of characters.\n\n```javascript\ndb.movies.aggregate([\n {\n \"$search\": {\n \"regex\": {\n \"path\": \"title\",\n \"query\": \"(.*) Seattle\"\n }\n }\n },\n {\n $project: {\n \"_id\": 0,\n \"title\": 1\n }\n }\n])\n```\n\n```javascript\n[ { title: 'Sleepless in Seattle' }, { title: 'Battle in Seattle' } ]\n```\n\n### Range of Numbers\n\nThe following example uses the regular expression `[0-9]{2} (.){4}s` to find movie titles which begin with a 2-digit number followed by a space, and end with a 5-letter word ending in `s`.\n\n```javascript\ndb.movies.aggregate([\n {\n \"$search\": {\n \"regex\": {\n \"path\": \"title\",\n \"query\": \"[0-9]{2} (.){4}s\"\n }\n }\n },\n {\n $project: {\n \"_id\": 0,\n \"title\": 1\n }\n }\n])\n```\n\n```javascript\n[\n { title: '20 Dates' },\n { title: '25 Watts' },\n { title: '21 Grams' },\n { title: '13 Lakes' },\n { title: '18 Meals' },\n { title: '26 Years' },\n { title: '99 Homes' },\n { title: '45 Years' }\n]\n```\n\n### Multi-Word Phrase\n\nThe following example uses the regular expression `.*Toy Story.*` to find all movie titles that contain the phrase `Toy Story`. Because the search field uses the keyword analyzer, the regex matches the phrase exactly as stored, including the space between words.\n\n```javascript\ndb.movies.aggregate([\n {\n \"$search\": {\n \"regex\": {\n \"path\": \"title\",\n \"query\": \".*Toy Story.*\"\n }\n }\n },\n {\n $project: {\n \"_id\": 0,\n \"title\": 1\n }\n }\n])\n```\n\n```javascript\n[\n { title: 'Toy Story' },\n { title: 'Toy Story 2' },\n { title: 'Toy Story 3' },\n { title: 'Toy Story of Terror' },\n { title: 'Toy Story That Time Forgot' }\n]\n```\n\n### Array of Strings\n\nThe following example uses an array of regular expressions to find movie titles that match any of the specified patterns. The query finds titles that end with `Seattle` or contain `Toy Story`.\n\n```javascript\ndb.movies.aggregate([\n {\n \"$search\": {\n \"regex\": {\n \"path\": \"title\",\n \"query\": [\"(.*) Seattle\", \".*Toy Story.*\"]\n }\n }\n },\n {\n $project: {\n \"_id\": 0,\n \"title\": 1\n }\n }\n])\n```\n\n```javascript\n[\n { title: 'Sleepless in Seattle' },\n { title: 'Toy Story' },\n { title: 'Toy Story 2' },\n { title: 'Toy Story 3' },\n { title: 'Battle in Seattle' },\n { title: 'Toy Story of Terror' },\n { title: 'Toy Story That Time Forgot' }\n]\n```\n\n### Case-Sensitive Search\n\nThe following example demonstrates case-sensitive matching. Because the index uses the `lucene.keyword` analyzer, which preserves the original capitalization of each indexed value, the query must match the exact case of stored titles. The query `.*Sleepless.*` matches `Sleepless in Seattle`, but `.*sleepless.*` returns no results.\n\n```javascript\ndb.movies.aggregate([\n {\n \"$search\": {\n \"regex\": {\n \"path\": \"title\",\n \"query\": \".*sleepless.*\"\n }\n }\n },\n {\n $project: {\n \"_id\": 0,\n \"title\": 1\n }\n }\n])\n```\n\n```javascript\n\n```"} -{"chunk_id": "6a29037dcf3722a2e3ce8ae0-0", "page_id": "6a29037dcf3722a2e3ce8ae0", "source_name": "search", "product_name": "Atlas Search", "url": "https://mongodb.com/docs/search/about/design-patterns", "title": "Design Search for Your Data Model", "text": "# Design Search for Your Data Model\n\nMongoDB Search provides several methods to help you optimize queries for different data models. Use the following tutorials to learn common design patterns so you can effectively query your data with MongoDB Search.\n\nMongoDB Search`$search`These tutorials\n\n## Prerequisites\n\nMongoDB Search`$search`To complete the tutorials, you must have:\n\n- An Atlas cluster with MongoDB version 6.0 or later or a MongoDB self-managed cluster with MongoDB version 8.2 or later.\n\n- The sample data loaded into your cluster.\n\n- `Project Data Access Admin` or higher access to your project to create MongoDB Search indexes.\n\n- Search Tester, `mongosh`, Compass, or a supported MongoDB Driver to run queries on your cluster.\n\nYou can run MongoDB Search queries by using any driver through the `$search` aggregation stage. These tutorials include examples for a selection of clients. Refer to the specific tutorial page for details.\n\nYou can also complete these tutorials with local deployments that you create with the Atlas CLI or with an on-prem deployment. To learn more, see Create a Local Atlas Deployment and Self-Managed Deployments.\n\n## Query Non-String Fields with String-Specific Operators\n\nCertain MongoDB Search operators, like queryString and autocomplete, support only string fields. If you need to query non-string fields using these operators, you can convert the values of these fields to strings and store the converted fields in a materialized view. A materialized view lets you use string-specific operators to query the converted fields and keep the original data intact in the source collection.\n\nTo get started, see How to Search Non-Alphabetical Data as Strings.\n\n## Query Fields Inside Embedded Documents\n\nYou can use MongoDB Search to query fields inside an array of documents, even when the array of documents is nested. After you index the document fields as the embeddedDocuments type, you can run queries against the fields inside these documents, including fields inside the following types of arrays:\n\n- Array of documents.\n\n- Array of documents inside a document.\n\n- Array of documents inside an array of documents.\n\nTo get started, see How to Run MongoDB Search Queries Against Fields in Embedded Documents.\n\n## Query Across Multiple Collections\n\nWhen your search must span multiple collections, you can use the following methods to search across them:\n\n- To join collections and search across them, use the `$lookup` stage with `$search`.\n\n- To combine search results from multiple collections, use the `$unionWith` stage.\n\n- To consolidate multiple collections so you can index and search them together, create a materialized view.\n\nTo get started, see How to Run MongoDB Search Queries Across Multiple Collections."} -{"chunk_id": "6a29037dcf3722a2e3ce8ae9-0", "page_id": "6a29037dcf3722a2e3ce8ae9", "source_name": "search", "product_name": "Atlas Search", "url": "https://mongodb.com/docs/search/deployment/multi-tenant-architecture", "title": "Build a Multi-Tenant Architecture for MongoDB Search", "text": "# Build a Multi-Tenant Architecture for MongoDB Search\n\nYou can implement multi-tenancy with MongoDB Search so that a single instance of an application serves multiple tenants. This page describes design recommendations that apply specifically to MongoDB Search for structuring data and MongoDB Search indexes to scale safely while maintaining tenant isolation.\n\nThis guidance assumes that you can colocate tenants within a single VPC (Virtual Private Cloud). If strict network isolation is required, you must maintain separate projects for each tenant.\n\n## Choosing a Strategy\n\nSelect a strategy based on your isolation needs, scaling goals, and write-load requirements. The most common strategies are:\n\n- **A single collection for all tenants** - This strategy is **recommended** for most workloads.\n\n- **One Database per tenant** - This strategy offers high isolation but increases index count.\n\n- **One Collection per tenant** - This strategy is **not recommended** for MongoDB Search workloads.\n\n### A Single Collection for All Tenants (Recommended)\n\nWe recommend applying the *one collection for all tenants* strategy. In this architecture, you store all tenant data in a single collection within a single database. You can distinguish between tenants by including a `tenant_id` field within each document. This field can be any unique identifier for the tenant, such as a UUID or a tenant name.\n\nThis centralized approach offers the following benefits:\n\n- Reduces the number of indexes\n\n Since all tenant data is stored in one collection, you need only a single index that serves documents for all tenants. You avoid hitting the cluster resource limits. For example, you can include the `tenant_id` and other shared or tenant-specific fields in a single index.\n\n- Simplifies maintenance operations\n\n With only a single collection storing all data, you don't have to maintain multiple collections or scale resources across multiple databases. You also simplify backup, sharding, and replication operations as you need to target only a single collection in a single database.\n\n- Processes query efficiently\n\n You provide the `tenant_id` field in your queries as a filter using the equals operator within the `$search.compound.filter` clause.\n\n Your query results will only include documents from the matching tenant, preventing data from leaking across tenants.\n\nIf the tenants you colocate share similar access patterns and resource sizes, this strategy also keeps the Lucene index field count low.\n\nWhen every tenant has a high write load, colocating all tenants into a single collection might create write contention. In that scenario, consider splitting tenants with the most writes into separate collections so that you can distribute the write load across more underlying resources.\n\nIf you have large tenants with unique resourcing or indexing requirements, use a View:\n\n- Isolate a tenant. Create a View using a `$match` with a `$expr` operation to filter only the tenant's documents.\n\n- Index separately. Create a MongoDB Search index on the View.\n\n This allows you to customize the index definition for the large tenant without impacting the shared index used by others. All other tenants can use a single index.\n\n A high index count generates significant load on the base cluster and might disrupt your workload. The number of indexes your cluster can support depends on your cluster tier and workload. Smaller cluster tiers like `M10` can experience performance degradation or out-of-memory errors as index count increases. Start with a small number of indexes and monitor your cluster's resource usage as you scale.\n\nIf you currently apply the *one collection per tenant* strategy, we recommend scaling up the base tier to prevent increased replication lag or OOM (Out of Memory) errors due to resource contention from a high number of indexes. We also recommend migrating to the *one collection for all tenants* strategy.\n\n#### Handling High-Write Tenants\n\nIf specific tenants have massive write loads, they might cause contention in a shared collection. We recommend that you move only the highest-volume tenants to separate collections to distribute the I/O load.\n\n#### Handling Unique Requirements (Views)\n\nIf a tenant requires unique indexing or is significantly larger than others, use a MongoDB View:\n\n- Create a View using\n\n- `$match` to filter only that tenant's documents.\n\n- Create a MongoDB Search index on that View. This allows customization for outlier tenants without disrupting the shared index used by the majority.\n\n### One Database Per Tenant\n\nIn a database-per-tenant setup, each tenant contains its own database. This setup isolates tenant data, but it also multiplies the number of indexes in the cluster. As the number of tenant databases grows, the index count can exceed what your cluster tier and workload can support.\n\nA high index count generates significant load on the base cluster and might disrupt your workload. The number of indexes your cluster can support depends on your cluster tier and workload. Smaller cluster tiers like `M10` can experience performance degradation or out-of-memory errors as index count increases. Start with a small number of indexes and monitor your cluster's resource usage as you scale.\n\n### One Collection Per Tenant (Not Recommended)\n\nThe collection-per-tenant strategy maps each tenant to its own collection within a shared database. The overhead of maintaining an index per collection might cause:\n\n- Increased replication lag\n\n- OOM (Out of Memory) errors due to resource contention\n\n- Instability in the base tier\n\nWe **do not recommend** this strategy for MongoDB Search unless tenants have very predictable, lightweight workloads. If you currently use this strategy, migrate toward the *one collection for all tenants*\nstrategy.\n\n## Managing Indexed Fields\n\nConsider the following recommendations to manage indexed fields:\n\nMulti-tenant applications often require custom per-tenant fields that can be searched, sorted, faceted, and filtered. Use a `typeSet` to dynamically index sub-fields of a path so that MongoDB Search picks up new fields automatically without a full index rebuild. Avoid statically indexing these fields, as doing so triggers a rebuild that adds CPU pressure and consumes up to 2x the index's disk space.\n\nLucene index performance can degrade if there are more than 1000 distinct fields. You can monitor the number of unique fields in the MongoDB Search index in the MongoDB Search metrics. If you need to support one thousand or more fields, we recommend the following:\n\n- Separating a subset of tenants into a separate index using a View, so that the distinct number of fields existing in a single Lucene index remains less than one thousand.\n\n- Limiting the number of fields that a single tenant can add.\n\nIf you use the attribute pattern to store different keys per tenant, we recommend that you do the following:\n\n- Flatten the embedded array of documents using a View.\n\n- Create a MongoDB Search index on the View, which is stored on disk.\n\nIf you don't flatten the array of documents, you will need to use embeddedDocuments operator queries (similar to `$elemMatch`) to query the attributes, which is less performant than querying a flattened structure."} -{"chunk_id": "6a29037dcf3722a2e3ce8b1a-0", "page_id": "6a29037dcf3722a2e3ce8b1a", "source_name": "search", "product_name": "Atlas Search", "url": "https://mongodb.com/docs/search/deployment/deployment-options", "title": "MongoDB Search Deployment Options", "text": "# MongoDB Search Deployment Options\n\n## Overview\n\nThe following sections describe deployment options for MongoDB Search on Atlas.\n\nYou can structure your cluster with different deployment types, cloud providers, and cluster tiers to meet the needs of a pre-production or production environment. Use these recommendations to select the deployment type, cloud provider and region, and cluster and search tiers for performing vector search.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nEnvironment\n\n\nDeployment Type\n\n\nCluster Tier\n\n\nCloud Provider Region\n\n\nNode Architecture\n\n
\nTesting Queries\n\n\nFlex or dedicated clusterLocal deployment\n\n\nFree cluster, Flex, or higher tierN/A\n\n\nAllN/A\n\n\nMongoDB and Search processes run on the same node.\n\n
\nPrototyping Applications\n\n\nDedicated cluster, sharded or unsharded\n\n\n`M10`, `M20`, or higher tier\n\n\nAll\n\n\nMongoDB and Search processes run on the same node.\n\n
\nProduction\n\n\nDedicated cluster with separate Search Nodes, sharded or unsharded\n\n\n`M10` or higher cluster tier and `S20` or higher search tier\n\n\nAWS (Amazon Web Services) and Azure (Microsoft Azure) in some regions or Google Cloud in all regions\n\n\nMongoDB and Search processes run on different nodes.\n\n
\nCommunity Edition\n\n\nSelf-managed deployment. You install and operate `mongod` and `mongot` yourself.\n\n\nN/A. You provide your own hardware or cloud instances.\n\n\nN/A. You choose your own infrastructure.\n\n\nMongoDB and Search processes run on either a single or separate self-managed hosts.\n\n
The following sections describe each environment:\n\n- Testing and Prototyping Environments\n\n- Production Environment\n\n- MongoDB Community Edition\n\n## Testing and Prototyping Environments\n\nFor testing your search queries and prototyping your application, we recommend the deployment type and node architecture described in the following sections.\n\nThis configuration is best suited for the following use cases:\n\n- Less than 2M total documents to index\n\n- Less than 10GB of indexed data\n\n- Less than 10,000 queries in a 7-day period\n\nIf your usage exceeds the listed values, migrate to dedicated search nodes.\n\nThe following sections describe this node architecture in more detail.\n\nTo test MongoDB Search queries on clusters in the cloud, you can deploy a Flex or dedicated cluster.\n\nTo test MongoDB Search queries locally, create a local Atlas deployment using the Atlas CLI. This could be a single-node replica set hosted on your local computer. Local deployments are limited by the CPU, memory, and storage resources of your local machine. When your application is ready for production, migrate your local Atlas deployment to a production environment.\n\nFor testing your MongoDB Search queries, use Free clusters (formerly known as `M0`) and Flex clusters.\n\nFor prototyping your application, use dedicated `M10`, `M20`, and higher tier clusters or deploy dedicated Search Nodes for workload isolation. When your application is ready for production and to handle large datasets, scale to higher tiers.\n\nUse any supported cloud provider region.\n\nThe cloud provider and region that you choose affect the configuration options available for the cluster tiers and the cost of running the cluster.\n\n### Node Architecture\n\nMongoDB SearchFor testing and prototyping environments, we recommend a node architecture in which MongoDB processes and MongoDB Search processes run on the same node. In the following diagram of this deployment model, the MongoDB Search `mongot` process runs alongside `mongod` on each node in the Atlas cluster and they share the same resources.\n\nBy default, Atlas enables the MongoDB Search `mongot` process on the same node that runs the `mongod` process when you create your first MongoDB Search index.\n\nTo learn how MongoDB Search processes queries on this architecture, see Query Processing.\n\nYou can define stored source fields in your MongoDB Search index so that the `mongot` process can store the specified fields on `mongot`. You can then use the returnStoredSource Option in your MongoDB Search query to retrieve the stored fields for matching documents directly from `mongot` instead of doing a full document lookup on the database.\n\n- Supported Clients\n\n- Queries and Indexes\n\n### Benefits\n\nWhen you enable MongoDB Search, you can easily build search on top of your data with an integrated, fully managed search engine that automatically syncs to your database. MongoDB Search provides a rich query language that uses MongoDB Search aggregation pipeline stages like `$search` and `$searchMeta` for full-text search and `$vectorSearch` for semantic search in conjunction with other MongoDB aggregation pipeline stages, and score-based results ranking.\n\nDepending on the resources provisioned for your cluster, deploying both processes on the same node might be more cost-efficient than running the search process on a separate, dedicated node.\n\n### Limitations\n\nYou might experience resource contention between the database `mongod` and the search `mongot` processes. This could negatively impact the performance of your index and latency of your queries. To support production-ready applications and their search workloads migrate to dedicated Search Nodes.\n\n### Cost\n\nThere are no additional fees or charges when you enable MongoDB Search on your cluster. However, you might observe an increase in resource utilization on the cluster for large indexed collections or index definitions."} -{"chunk_id": "6a29037dcf3722a2e3ce8b1a-1", "page_id": "6a29037dcf3722a2e3ce8b1a", "source_name": "search", "product_name": "Atlas Search", "url": "https://mongodb.com/docs/search/deployment/deployment-options", "title": "MongoDB Search Deployment Options", "text": "### Considerations\n\nSince both the `mongod` and `mongot` processes run on the same node, `mongot` might become unavailable under certain circumstances. The following table describes potential causes:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nCause\n\n\nDescription\n\n
\ncluster Tier Scaling - Network Storage\n\n\nWhen you scale a cluster up or down, Atlas provisions a new instance. Once the instance is ready, Atlas attaches network storage and starts both `mongod` and `mongot` on the new nodes.\n\nIf `mongod` starts before `mongot`, MongoDB Search queries fail until `mongot` is running.\n\n
\ncluster Tier Scaling - Local SSD (Solid State Disk)\n\n\nWhen you scale an Atlas cluster using local SSD (Solid State Disk), you can't retain storage and reattach it to the new nodes. Therefore, Atlas performs an initial sync to rebuild the search indexes. Search queries fail until the initial sync is complete.\n\n
\nLucene Downgrade\n\n\nIn rare cases where you require downgrading Lucene, you might not be able to read newer Lucene index formats.\n\n
\nStorage Adjustment\n\n\nYou can retain network storage attached to Atlas cluster nodes. This allows you to expand or contract the volume capacity with no impact to `mongot`.\n\nHowever, retaining network storage might not be possible in certain regions, when your cluster is using local NVMe (non-volatile memory express) disks, or under other rare circumstances. In these cases, Atlas performs an initial sync and search queries fail until the initial sync is complete.\n\n
\n`mongot` Version Update\n\n\nDuring a `mongot` version update, Atlas stops the old version of `mongot` and starts the new version. During this brief period, search queries fail until the new `mongot` is up.\n\n
\nNew `mongod` Node\n\n\nWhen you add a new node to your cluster, Atlas performs an initial sync to create the search indexes. Search queries that use the new `mongod` node fail until the initial sync is complete.\n\n
\nInstance Reboot or Replacement\n\n\n- Your Atlas instance might reboot during a new security policy rollout or if your cloud provider requires it. While Atlas reboots, if `mongod` starts before `mongot`, search queries fail until `mongot` is running.\n\n- Your Atlas instance might require a replacement if you have unhealthy hardware or if you've migrated system architectures. When you replace the instance, `mongot` performs an initial sync and search queries fail until the initial sync is complete.\n\n
\n`mongot` Restart\n\n\nAny time the `mongot` process restarts from configuration changes, search queries fail until `mongot` becomes available.\n\n
\n\n## Production Environment\n\nFor your production-ready application, we recommend using the deployment type and node architecture described in the following sections.\n\nThis configuration is best suited for the following use cases:\n\n- If you choose to migrate your existing testing environment to production, add dedicated Search Nodes to your cluster. To learn more, see Migrate to Dedicated Search Nodes.\n\n- If you create a new production deployment from scratch, ensure that you use `M10` or larger tier clusters that support MongoDB Search in the regions and zones where MongoDB Search is available, and add dedicated Search Nodes to your environment. To learn more, see Add Dedicated Search Nodes.\n\nFor production-ready applications, use `M10`, `M20`, and higher dedicated cluster tiers. These higher tier clusters can handle large datasets and production workloads.\n\nWe recommend that you also deploy dedicated Search Nodes. If your search requirements increase, you can scale up your search deployment independently of scaling up the MongoDB nodes.\n\nUse Search Nodes in all Google Cloud regions and in a subset of AWS (Amazon Web Services) and Azure (Microsoft Azure)\nregions. You *must* select a cloud provider and region where Search Nodes are available for your deployment.\n\nAll cluster tiers are available in supported cloud provider regions. The cloud provider and region that you choose affect the configuration options and search tiers available for the cluster and the cost of running the cluster.\n\n### Node Architecture\n\nMongoDB SearchSupported ClientsQueries and IndexesFor production environments, we recommend a node architecture in which MongoDB processes and MongoDB Search processes run on separate nodes. To deploy separate Search Nodes, see Migrate to Dedicated Search Nodes.\n\nIn the following diagram of this deployment model, the MongoDB Search `mongot` process runs on dedicated Search Nodes, which are separate from the cluster nodes on which the `mongod` process runs.\n\nAtlas deploys Search Nodes with each cluster or with each shard on the cluster. For example, if you deploy two Search Nodes for a cluster with three shards, Atlas deploys six Search Nodes (two per shard). You can also configure the number of Search Nodes and the amount of resources provisioned for each search node.\n\nTo learn how MongoDB Search processes queries on this architecture, see Query Processing.\n\nYou can define stored source fields in your MongoDB Search index so that the `mongot` process can store the specified fields on `mongot`. You can then use the returnStoredSource Option in your MongoDB Search query to retrieve the stored fields for matching documents directly from `mongot` instead of doing a full document lookup on the database.\n\n### Benefits\n\nDeploying separate Search Nodes provides the following benefits:\n\nWhen you deploy separate Search Nodes, Atlas enforces a minimum of two Search Nodes to ensure your workload remains operational, with minimal downtime, in the event of a failure or disruption.\n\nWhen you deploy separate Search Nodes, you can scale the storage and compute independently of your MongoDB cluster. This allows you to also scale the query load independently of MongoDB.\n\nTo scale Search Nodes horizontally, increase or reduce the number of Search Nodes. You can provision from a minimum of 2 up to a maximum of 32 Search Nodes per region per shard. To balance the query load, MongoDB Search distributes search queries across all available Search Nodes.\n\nTo scale Search Nodes vertically, select different search tiers, CPU, RAM and storage configurations that support your full-text workloads.\n\nWhen you deploy dedicated Search Nodes, you improve the performance and resource utilization for both the `mongod` and `mongot` processes and eliminate resource contention between these processes.\n\nDedicated Search Nodes support concurrent segment search, which allows MongoDB Search to search multiple index segments at the same time. Using concurrent segment search improves query response time in some cases.\n\nDeploying dedicated Search Nodes does not directly affect data transfer to the main database nodes. Search Nodes handle search queries separately from the main database operations, providing workload isolation while you incur network charges only for traffic between Search Nodes and database nodes."} -{"chunk_id": "6a29037dcf3722a2e3ce8b1a-2", "page_id": "6a29037dcf3722a2e3ce8b1a", "source_name": "search", "product_name": "Atlas Search", "url": "https://mongodb.com/docs/search/deployment/deployment-options", "title": "MongoDB Search Deployment Options", "text": "### Tips for Sizing and Scaling Search Nodes\n\nTo determine the memory requirements for Search Nodes, use the following Atlas metrics:\n\n- Size of the Search Index\n\n- Total RAM on the Search Node\n\nConsider an application that has a 10GB Search Index and 4GB total RAM on the Search Node. In this case, if 1GB of RAM is used by other processes and only 3GB are available for the index data, the remaining 7GB of the index data (10GB - 3GB = 7GB) is paged in, as needed, from the disk. Frequent paging from disk causes increased page faults, disk I/O, and CPU IOWait, resulting in performance degradation.\n\nIf you use a higher search cluster tier with more RAM, such as 8GB or more, this allows Atlas to serve most of the data for the Search Index from memory, minimizing disk reads and page faults, thereby improving performance.\n\nThe local SSD (Solid State Disk)s used for Search Nodes require a 20% storage overhead to support index operations.\n\n### Search Nodes Cost\n\nMongoDB supports separate Search Nodes on dedicated (`M10` or higher) clusters. Search Nodes are deployed on compute-intensive instances with high-performance local storage. You must deploy a minimum of two nodes. You will be billed daily for hourly resource usage per node. To learn more, see Search Node Costs.\n\n### Enable Encryption at Rest\n\nMongoDB SearchBy default, MongoDB and search processes run on the same nodes. With this architecture, customer-managed encryption applies to your database data, but it does not apply to search indexes.\n\nWhen you enable dedicated Search Nodes, search processes run on separate nodes. This allows you to enable Search Node Data Encryption, so you can encrypt both database data and search indexes with the same customer-managed keys for comprehensive encryption coverage.\n\nDedicated Search Nodes are not supported on Atlas Infinite clusters clusters in public preview.\n\nDatabase nodes and Search Nodes use different encryption methods with the same customer-managed keys. Database nodes use the WiredTiger Encrypted Storage Engine, while Search Nodes use encryption at the disk level.\n\nTo learn more, see Enable Customer Key Management for Search Nodes.\n\n### Add Dedicated Search Nodes\n\nAdding dedicated Search Nodes to a new cluster allows you to:\n\n- Change the size and scale of your search deployment independently from your database deployment.\n\n- Eliminate resource contention that you might experience on a cluster that runs both the MongoDB database and search processes on the same node.\n\nTo deploy dedicated Search Nodes, you must have `Project Owner` access to the project.\n\nTo add dedicated Search Nodes:\n\n1. Create your cluster as an `M10` or higher tier in a cloud provider and region that supports node isolation. To learn more, see Create an Atlas Infinite or Atlas Core Cluster.\n\n Dedicated Search Nodes are supported only for `M10` and higher cluster tiers and in cloud provider regions that support node isolation.\n\n2. Enable Search Nodes for workload isolation and Configure Search Nodes.\n\n### Migrate to Dedicated Search Nodes\n\nTo migrate from staging to production and add dedicated Search Nodes, make the following changes to your existing staging and prototyping deployment:\n\n1. If your deployment uses a Flex cluster, change the cluster tier to a higher tier. Dedicated Search Nodes are supported only for `M10` and higher cluster tiers.\n\n2. Deploy your cluster in regions where Search Nodes are also available. Dedicated Search Nodes are available on a subset of the AWS (Amazon Web Services) and Azure (Microsoft Azure) regions and in all supported Google Cloud regions. If your existing cluster is hosted in regions where Search Nodes aren't available, migrate your cluster to regions where Search Nodes are available. To learn more, see Cloud Provider Regions that Support Node Isolation.\n\n3. Enable Search Nodes for workload isolation and configure Search Nodes. To learn more, see Add Search Nodes.\n\n When you deploy dedicated Search Nodes, the following sequence of actions takes place:\n\n - Atlas builds the search indexes on the Search Nodes and removes the indexes from the cluster nodes.\n\n - Atlas routes search queries to the Search Nodes.\n\n - MongoDB Search uses the search indexes to serve queries on your cluster.\n\n### Troubleshoot Deployment\n\n#### `Failed to Execute search Command` Error\n\nIf you deploy `mongot` to run alongside `mongod` and **don't configure** Search Nodes, `mongot` might terminate and return the `Failed to Execute search Command` error during any of the following events:\n\n- Scaling up a cluster\n\n- Node failover\n\n- Upgrading `mongot`\n\nIf you deploy `mongot` on dedicated Search Nodes, `mongod` uses a proxy that routes search queries only to the healthy nodes where the `mongot` process is active.\n\n## MongoDB Community Edition\n\nIf you run MongoDB Search on MongoDB Community Edition or another self-managed deployment, Atlas does not manage `mongot` for you. Instead, you install, configure, and operate `mongot` yourself. The following sections summarize the available architecture patterns and sizing options. For complete deployment and sizing guidance, see MongoDB Search and MongoDB Vector Search on Self-Managed Deployments and Introduction to mongot Deployment Sizing.\n\n### Architecture Patterns\n\nAs with MongoDB Search on Atlas, self-managed deployments use one of the same two architecture patterns: co-located or dedicated. The only exception is that on self-managed deployments, you provision and manage the hosts yourself.\n\n### Sizing\n\nUnlike Atlas, self-managed deployments have no predefined cluster or search tiers. You provision your own hardware or cloud instances. To choose a starting configuration and refine it based on your workload, see Introduction to mongot Deployment Sizing."} -{"chunk_id": "6a29037dcf3722a2e3ce8bd7-0", "page_id": "6a29037dcf3722a2e3ce8bd7", "source_name": "search", "product_name": "Atlas Search", "url": "https://mongodb.com/docs/search/query/query-ref", "title": "Query Reference", "text": "# Query Reference\n\n## Pipeline Stages\n\nMongoDB Search queries take the form of an aggregation pipeline stage. MongoDB Search provides `$search` and `$searchMeta` stages, both of which must be the first stage in any query pipeline, including the `$lookup` and `$unionWith` sub-pipelines. These stages can be used in conjunction with other aggregation pipeline stages in your query pipeline.\n\nBased on the pipeline stage that you choose, your query returns either the search results of a full-text search or metadata about your search results:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nAggregation Pipeline Stage\n\n\nPurpose\n\n
\n`$search`\n\n\nReturn the search results of a full-text search.\n\n
\n`$searchMeta`\n\n\nReturn metadata about your search results.\n\n
\n\n## Operators and Collectors\n\nMongoDB Search also provides query operators and collectors that you can use inside the `$search` and `$searchMeta` aggregation pipeline stages. The MongoDB Search operators allow you to locate and retrieve relevant data from the collection on your cluster. The collector returns a document representing the search metadata results.\n\nYou can use MongoDB Search operators to query terms, phrases, geographic shapes and points, numeric values, similar documents, synonymous terms, and more.\n\nYou can also search using regex and wildcard expressions. The MongoDB Search\ncompound operator allows you to combine multiple operators inside your `$search` stage to perform a complex search and filter of data based on what *must*, *must not*, or *should* be present in the documents returned by MongoDB Search. You can use the compound operator to also match or filter documents in the `$search` stage itself. Running `$match` after `$search` is less performant than running `$search` with the compound operator.\n\nTo learn more about operators and collectors, see Operators and Collectors.\n\n## Query Processing\n\nWhen you run a query, MongoDB Search uses the configured read preference to identify the node on which to run the query. The query first goes to the MongoDB process, which is `mongod` for a replica set cluster or `mongos` for a sharded cluster.\n\nFor a replica set cluster, the MongoDB process routes the query to the `mongot` on the same node. For sharded clusters, your cluster data is partitioned across `mongod` instances and each `mongot` knows about the data on the `mongod` on the same node only. Therefore, you can't run MongoDB Search queries that target a particular shard. `mongos` directs the queries to all shards, making these *scatter gather* queries. If you use zones to distribute a sharded collection over a subset of the shards in the cluster, MongoDB Search routes the query to the zone that contains the shards for the collection that you are querying and runs your `$search` queries on just the shards where the collection is located.\n\nMongoDB Search performs the search and scoring and returns the document IDs and other search metadata for the matching results to `mongod`. The `mongod` then performs a full document lookup implicitly for the matching results and returns the results to the client.\n\nIf you use the `$search` concurrent option in your query, MongoDB Search enables intra-query parallelism. To learn more, see Parallelize Query Execution Across Segments.\n\nWhen you run a query, the query first goes to the `mongod` based on the configured read preference. By default, the `mongod` process routes the search query through a load balancer on the same node, which distributes the requests across all of the `mongot` processes. Alternatively, if you set the `searchNodePreference` parameter for your `$search` stage, MongoDB Search runs your query against the same search node each time.\n\nThe MongoDB Search `mongot` process performs the search and scoring and returns the document IDs and metadata for the matching results to `mongod`. The `mongod` then performs a full document lookup for the matching results and returns the results to the client. If you use the `$search` concurrent option in your query, MongoDB Search enables intra-query parallelism. To learn more, see Parallelize Query Execution Across Segments.\n\n## Scoring\n\nMongoDB Search associates a relevance-based score with every document in the result set. The relevance-based scoring allows MongoDB Search to return documents in the order from the highest score to the lowest. MongoDB Search scores documents higher if the query term appears frequently in a document and lower if the query term appears across many documents in the collection. MongoDB Search also supports customizing the relevance-based default score by boosting, decaying, or other modifying options. To learn more about customizing the resulting scores, see Score the Documents in the Results.\n\nWatch this video for an overview of searching and tracking your queries with MongoDB Search. In this video, you can learn more about MongoDB Search\noperators and how MongoDB Search scores documents in the results.\n\n*Duration: 15 Minutes*\n\n## Supported Clients\n\nYou can create and run MongoDB Search queries using the following clients:\n\n- Search Tester\n\n- `mongosh`\n\n- Compass\n\n- MongoDB drivers\n\n## Troubleshoot Queries\n\n### Empty Result Set\n\n`mongot` doesn't return any errors, but returns an empty result set if your `$search` query:\n\n- References an index that doesn't exist. If you don't specify an index by name in the query, MongoDB Search defaults to an index named `default`. If you don't have an index named `default` or if the index that you specified doesn't exist, MongoDB Search doesn't return an error and returns an empty result set. You can specify a valid index by its name using the `index` option.\n\n- Specifies a non-indexed field. If you run a query against a field that isn't indexed, MongoDB Search doesn't return an error and returns an empty result set. You must specify only indexed fields as values for the `path` parameter. You can enable dynamic mapping in your index definition for the collection to ensure that all the dynamically indexable fields in the collection are automatically indexed. To learn more, see dynamic mapping.\n\n- Uses the `text` operator on a field path which is not indexed as a `string` type. If a field is indexed as a MongoDB Search field type other than `string`, such as `stringFacet` or `autocomplete`, MongoDB Search doesn't return an error and returns an empty result set. You *must* index the fields with `string` BSON (Binary Javascript Object Notation) data type values as string type to query the fields using the text operator.\n\n### `PlanExecutor` Error\n\n`mongot` returns a `PlanExecutor` error if your `$search` query:\n\n- Specifies a field that is indexed as an incorrect data type. In this case, if you run a query, MongoDB Search returns an error message identifying the field that was indexed incorrectly and its correct data type. For example:\n\n ```shell\n PlanExecutor error during aggregation :: caused by :: Cannot facet on field \"genres\" because\n it was not indexed as a \"stringFacet\" field.\n ```\n\n For example, to run `facet` (MongoDB Search Operator) queries against `string`, `number`, or `date` fields, create an index for the fields using the corresponding MongoDB Search field type such as `stringFacet`, `number`, and `date` respectively. To learn more, see Supported and Unsupported Data Types."} -{"chunk_id": "6a29037dcf3722a2e3ce8be0-0", "page_id": "6a29037dcf3722a2e3ce8be0", "source_name": "search", "product_name": "Atlas Search", "url": "https://mongodb.com/docs/search/query/score/overview", "title": "Score the Documents in the Results", "text": "# Score the Documents in the Results\n\nEvery document returned by a MongoDB Search or MongoDB Vector Search query is assigned a score based on relevance, and the documents included in a result set are returned in order from highest score to lowest.\n\n## Usage\n\nTo include the score of each document in your search results, use the `$project` stage in your aggregation pipeline.\n\n- For the `$search` stage, the `score` field takes the `$meta` expression, which requires the `searchScore` value. You can also specify the `searchScoreDetails` value for the `scoreDetails` field `$meta` expression for a detailed breakdown of the score.\n\n- For the `$vectorSearch` stage, the `score` field takes the `$meta` expression, which requires the `vectorSearchScore` value to return the score of each document in your vector search results.\n\nYou can use:\n\n- `searchScore` only in `$search` queries\n\n- `vectorSearchScore` only in `$vectorSearch` queries\n\nIf you use `searchScore` and `vectorSearchScore` in any other query, MongoDB logs a warning starting in MongoDB v8.2.\n\nThe following query uses a `$project` stage to add a field named `score` to the returned documents:\n\n\n\n\n\n```javascript\ndb.movies.aggregate([\n {\n \"$search\": {\n \"text\": {\n \n }\n }\n },\n {\n \"$project\": {\n \"\": 1,\n \"\": 0,\n \"score\": { \"$meta\": \"searchScore\" }\n }\n }\n])\n```\n\n\n\n\n\n```javascript\ndb.movies.aggregate([\n {\n \"$search\": {\n \"text\": {\n \n },\n \"scoreDetails\": true\n }\n },\n {\n \"$project\": {\n \"\": 1,\n \"\": 0,\n \"scoreDetails\": { \"$meta\": \"searchScoreDetails\" }\n }\n }\n])\n```\n\nTo learn more, see return the search score details.\n\n\n\n\n\n```javascript\ndb.movies.aggregate([\n {\n \"$vectorSearch\": {\n \n }\n },\n {\n \"$project\": {\n \"\": 1,\n \"\": 0,\n \"score\": { \"$meta\": \"vectorSearchScore\" }\n }\n }\n])\n```\n\nTo learn more, see MongoDB Vector Search Scoring.\n\n\n\n\n\n## Behavior\n\nThe score assigned to a returned document is part of the document's metadata. You can use a `$project` stage in your aggregation pipeline to include each returned document's score along with the result set. Documents return from highest score to lowest. Many factors can influence a document's score, including the following:\n\n- Position of the search term in the document.\n\n- Frequency of occurrence of the search term in the document.\n\n- Type of operator or analyzer a MongoDB Search query uses.\n\nTo learn more about the Lucene scoring algorithm, see Lucene documentation.\n\n### Additional Options\n\nIn addition to the default scoring behavior, MongoDB Search supports the following options:\n\n- Modifying the score assigned to certain documents.\n\n- Returning a detailed breakdown of the score by using the score details option.\n\n- Normalizing the search score.\n\n### Considerations\n\nIf multiple documents in the results have identical scores, the ordering of the documents in the results is non-deterministic. If you want your MongoDB Search results to have a determined order, include the sort option in your `$search` stage to sort the results by a unique field. You can use the sort option to also return an ascending sort of the results by score. To learn more, see Sort MongoDB Search Results and Sort by Score Examples.\n\nOn separate Search Nodes, each node assigns documents different internal Lucene IDs used for sorting when scores are identical. When sorting and paginating results, the `mongot` process on the node that is processing the query might include documents from other nodes if their internal IDs have greater pagination order than the token. To prevent this, use `$match` after `$search` to exclude documents by their `_id`.\n\nWhen querying array values, MongoDB Search assigns higher scores if more values in the array match the query.\n\n## Tutorials\n\n\n\n\n\n\n\n\n\n\n\n
\nFor examples on how to use additional `score` options in your MongoDB Search queries, see the following pages:\n\n\n- Modify the Score\n\n- Return the Score Details\n\n- Example Queries\n\n
\nFor examples on how to use the `score` field in some common MongoDB Search queries, see the following pages:\n\n\n- Compound Query Examples\n\n- Embedded Document Examples\n\n- String Sort Example\n\n
"} -{"chunk_id": "6a29037dcf3722a2e3ce8ba9-0", "page_id": "6a29037dcf3722a2e3ce8ba9", "source_name": "search", "product_name": "Atlas Search", "url": "https://mongodb.com/docs/search/query/operators-collectors/hasAncestor", "title": "`hasAncestor` Operator", "text": "# `hasAncestor` Operator\n\n## Definition\n\n`hasAncestor`\nThe `hasAncestor` operator queries an `embeddedDocuments` type field that you specify in the `ancestorPath`. The `ancestorPath` is a parent of the field that you specify in the `returnScope`. The `returnScope` specifies the nested field, including the level of nesting, that you want to retrieve.\n\nYou can use this operator when scoring and retrieving objects within arrays as independent documents to:\n\n- Filter on ancestor fields (higher level of nesting).\n\n- Filter on sibling fields (equal level of nesting).\n\n## Syntax\n\nThe `hasAncestor` operator has the following syntax:\n\n```javascript\n{\n $search: {\n \"index\": \"\", // optional, defaults to \"default\"\n \"hasAncestor\": {\n \"ancestorPath\": \"\",\n \"operator\": {\n \n }\n },\n \"returnScope\": {\n \"path\": \"\"\n }\n }\n}\n```\n\n## Fields\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nField\n\n\nType\n\n\nDescription\n\n\nNecessity\n\n
\n`ancestorPath`\n\n\nString\n\n\nName of the `embeddedDocuments` type field that is an intermediary ancestor of the nested field used in the query. This is the parent document that the operator evaluates.\n\n\nRequired\n\n
\n`operator`\n\n\nObject\n\n\nOperator to use to query the nested field inside the `embeddedDocuments` type field specified in the `ancestorPath`. The query path must be a child of the `ancestorPath`, regardless of the level of nesting. This specifies the search criteria to filter the parent document.\n\nYou can't use the `hasAncestor` operator inside the operator specification.\n\n\nRequired\n\n
\n\n## Requirements\n\nTo use this operator, you must:\n\n- Index the ancestor fields as the embeddedDocuments type. In the query, specify `ancestorPath` as this field. If the field is on the root level, use hasRoot.\n\n- Specify returnScope to set the scope of the document to query and retrieve.\n\n## Examples\n\nThe examples in this section use the `sample_training.companies` dataset. If you load the sample dataset and create the index on the collection, you can try the sample queries demonstrated in this section.\n\n### Sample Index\n\nThe queries in this section use the following index. This index definition configures MongoDB Search to do the following:\n\n- Automatically index all the dynamically indexable fields in the collection.\n\n- Index the `funding_rounds` and `funding_rounds.investments` fields as the embeddedDocuments type.\n\n- Store the following fields on `mongot`:\n\n - `funding_rounds.investments.financial_org`\n\n - `funding_rounds.investments.person`\n\n```json\n{\n \"mappings\": {\n \"dynamic\": true,\n \"fields\": {\n \"funding_rounds\": {\n \"dynamic\": true,\n \"fields\": {\n \"investments\": [\n {\n \"dynamic\": true,\n \"storedSource\": {\n \"include\": [\n \"financial_org\",\n \"person\"\n ]\n },\n \"type\": \"embeddedDocuments\"\n }\n ]\n },\n \"type\": \"embeddedDocuments\"\n }\n }\n }\n}\n```\n\n### Sample Query\n\nThe following query searches the `funding_rounds.founded_year` field for companies that were founded in the year `2005` using the `equals` operator to retrieve investment details such as the financial organizations or individuals that invested in the companies.\n\n```javascript\ndb.companies.aggregate([\n {\n \"$search\": {\n \"returnStoredSource\": true,\n \"returnScope\": { \"path\": \"funding_rounds.investments\" },\n \"hasAncestor\": {\n \"ancestorPath\": \"funding_rounds\",\n \"operator\": {\n \"equals\": {\n \"path\": \"funding_rounds.funded_year\",\n \"value\": 2005\n }\n }\n }\n }\n }\n])\n```\n\n```javascript\n[\n {\n financial_org: {\n name: 'Frazier Technology Ventures',\n permalink: 'frazier-technology-ventures'\n },\n person: null\n },\n {\n financial_org: { name: 'Trinity Ventures', permalink: 'trinity-ventures' },\n person: null\n },\n {\n financial_org: { name: 'Accel Partners', permalink: 'accel-partners' },\n person: null\n },\n {\n financial_org: null,\n person: {\n first_name: 'Mark',\n last_name: 'Pincus',\n permalink: 'mark-pincus'\n }\n },\n {\n financial_org: null,\n person: {\n first_name: 'Reid',\n last_name: 'Hoffman',\n permalink: 'reid-hoffman'\n }\n },\n {\n financial_org: { name: 'First Round Capital', permalink: 'first-round-capital' },\n person: null\n },\n {\n financial_org: null,\n person: {\n first_name: 'Ram',\n last_name: 'Shriram',\n permalink: 'ram-shriram'\n }\n },\n {\n financial_org: null,\n person: {\n first_name: 'Mitch',\n last_name: 'Kapor',\n permalink: 'mitch-kapor'\n }\n },\n {\n financial_org: null,\n person: { first_name: 'Ron', last_name: 'Conway', permalink: 'ron-conway' }\n },\n {\n financial_org: null,\n person: {\n first_name: 'Silvio',\n last_name: 'Scaglia',\n permalink: 'silvio-scaglia'\n }\n },\n {\n financial_org: {\n name: 'Shelter Capital Partners',\n permalink: 'shelter-capital-partners'\n },\n person: null\n },\n {\n financial_org: { name: 'First Round Capital', permalink: 'first-round-capital' },\n person: null\n },\n {\n financial_org: {\n name: 'Liberty Associated Partners',\n permalink: 'liberty-associated-partners'\n },\n person: null\n },\n {\n financial_org: { name: 'Rose Tech Ventures', permalink: 'rose-tech-ventures' },\n person: null\n },\n {\n financial_org: { name: 'First Round Capital', permalink: 'first-round-capital' },\n person: null\n },\n {\n financial_org: { name: 'Lead Dog Ventures', permalink: 'lead-dog-ventures' },\n person: null\n },\n {\n financial_org: { name: 'Accel Partners', permalink: 'accel-partners' },\n person: null\n },\n {\n financial_org: { name: 'Benchmark', permalink: 'benchmark-2' },\n person: null\n },\n {\n financial_org: { name: 'Sequoia Capital', permalink: 'sequoia-capital' },\n person: null\n },\n { financial_org: null, person: null }\n]\n\n```"} -{"chunk_id": "6a869dda8824e6129431dfa4-0", "page_id": "6a869dda8824e6129431dfa4", "source_name": "self-managed-search", "product_name": null, "url": "https://mongodb.com/docs/search/self-managed/current/connection/verify-connection", "title": "Verify Your mongot Connection", "text": "# Verify Your mongot Connection\n\nUse the tutorial on this page to verify that your `mongot` deployment is active and connected to your MongoDB Community deployment.\n\n## Before You Begin\n\nInstall MongoDB Community and MongoDB Search. For installation tutorials, see Install MongoDB Community Edition and Procedure.\n\n## Steps\n\n### Verify that your `mongot` instance is active.\n\nTo check the status of your `mongot` instance, run one of the following commands in your terminal, based on your installation method:\n\n```shell\nps aux | grep '[m]ongot'\n```\n\nIf `mongot` is active, this command returns the `mongot` process with a reference to your configuration file.\n\n```shell\n# standalone mongot container\ndocker ps --filter \"name=\"\n\n# atlas-local\ndocker ps --filter \"ancestor=mongodb/mongodb-atlas-local\"\n```\n\nIf `mongot` is active, this command returns the active container.\n\n### Verify the health of your `mongot` instance.\n\nTo check the health of your `mongot` instance, use the `/health` and `/ready` endpoints.\n\nTo check if `mongot` is live, `curl` against the `/health` endpoint:\n\nThe default `healthCheck` address is `localhost:8080`. However, you can define the address in the `healthCheck.address` option in your `mongot` configuration file.\n\n```shell\ncurl localhost:8080/health\n```\n\nThe endpoint returns one of the following responses:\n\n- `{\"status\":\"SERVING\"}`, if the `mongot` process is running.\n\n- `{\"status\":\"NOT_SERVING\"}`, if the `mongot` process isn't running.\n\nTo check if `mongot` is ready for queries, `curl` against the `/ready` endpoint:\n\n```shell\ncurl localhost:8080/ready\n```\n\nThe endpoint returns one of the following responses:\n\n- `{\"status\":\"SERVING\"}`, if the `mongot` process is ready for queries.\n\n- `{\"status\":\"NOT_SERVING\"}`, if the `mongot` process isn't ready for queries.\n\n### Check `mongot` Prometheus metrics.\n\nIf you enabled the Prometheus metrics endpoint in your `mongot` configuration file, `curl` the `/metrics` endpoint to retrieve process-level metrics:\n\n```shell\ncurl localhost:9946/metrics\n```\n\nThe default `metrics` address is `localhost:9946`. To use a different address, set the `metrics.address` option in your `mongot` configuration file.\n\nTo view the state of search index replication, filter for the `mongot_replication_mongodb_indexManagerState` metric:\n\n```shell\ncurl -s localhost:9946/metrics | grep -E \\\n \"^(# (HELP|TYPE) mongot_replication_mongodb_indexManagerState|mongot_replication_mongodb_indexManagerState)\"\n```\n\n### Verify that index management is active.\n\nTo verify that index management is active, run a search index management method against any collection.\n\nFor example, the following command checks if any search indexes exist on a `movies` collection:\n\n```javascript\ndb.movies.getSearchIndexes()\n```\n\nIf the operation succeeds without an error, index management is functional.\n\n### Run a search query.\n\nRun an end-to-end search query to confirm that the full query path is functional.\n\nFor example, create a `test` collection with a search index:\n\n```javascript\ndb.test.insertMany([\n { name: \"alpha\" },\n { name: \"beta\" },\n { name: \"alphabet\" }\n])\n\ndb.test.createSearchIndex(\n \"verify-index\",\n { mappings: { dynamic: true } }\n)\n```\n\nVerify that MongoDB builds the index:\n\n```javascript\ndb.test.getSearchIndexes()\n```\n\nThe index is ready for queries if the command returns the following response:\n\n```javascript\nstatus: 'READY',\nqueryable: true,\n```\n\nThen, run a search query:\n\n```javascript\ndb.test.aggregate([\n {\n $search: {\n index: \"verify-index\",\n text: { query: \"alpha\", path: \"name\" }\n }\n }\n])\n```\n\nA successful query confirms that you configured `mongod` and `mongot` correctly.\n\nFor troubleshooting your `mongot` and `mongod` connection, see Troubleshoot MongoDB Search for Self-Managed Deployments.\n\n## Next Steps\n\n- Create MongoDB Search indexes.\n\n- Create MongoDB Vector Search indexes."} -{"chunk_id": "6a869dda8824e6129431dfb7-0", "page_id": "6a869dda8824e6129431dfb7", "source_name": "self-managed-search", "product_name": null, "url": "https://mongodb.com/docs/search/self-managed/current/monitoring/tool-integrations", "title": "Monitoring Tool Integrations", "text": "# Monitoring Tool Integrations\n\nThis page describes how to integrate `mongot` metrics and logs with common monitoring platforms. These instructions assume that you already run one of these tools and need the `mongot`-specific configuration. This page does not teach Prometheus, Grafana, or another platform from scratch.\n\nThis guidance targets site reliability engineers and platform teams who integrate `mongot` into an existing observability stack.\n\n## Available Monitoring Surfaces\n\nThe following table summarizes the surfaces that `mongot` exposes for monitoring:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nSurface\n\n\nProtocol\n\n\nDefault endpoint\n\n\nConfigured under\n\n\nNotes\n\n
\nMetrics\n\n\nHTTP, Prometheus text format\n\n\n`localhost:9946/metrics`\n\n\n`metrics``.address`\n\n\nThe included `config.default.yml` binds to `localhost:9946` only. Override it to `0.0.0.0:9946` for off-host scraping. `mongot` applies no authentication by default. Protect the endpoint at the network layer.\n\n
\nLiveness\n\n\nHTTP\n\n\n`localhost:8080/health`\n\n\n`healthCheck``.address`\n\n\nReturns `{\"status\":\"SERVING\"}` after `mongot` binds its services.\n\n
\nReadiness\n\n\nHTTP\n\n\n`localhost:8080/ready`\n\n\n`healthCheck``.address`\n\n\nReturns `{\"status\":\"SERVING\"}` when `mongot` is ready to receive traffic. This means replication is initialized and catalog indexes are queryable. If no indexes exist, `mongot` reports ready.\n\n
\nLogs\n\n\nstdout and stderr, or a file\n\n\nPer logging configuration\n\n\n`logging`\n\n\nJSON or text, depending on the configuration.\n\n
\nFTDC\n\n\nOn-disk binary stream\n\n\n`/diagnostic.data/`\n\n\n`advancedConfigs.ftdc`\n\n\nEnabled by default. Tune or disable with `advancedConfigs.ftdc`. To learn more, see mongot Logs and FTDC.\n\n
\n\n## Prometheus and Grafana\n\nPrometheus with Grafana is the recommended monitoring stack for most self-managed deployments. The stack is free, widely supported, and works directly with the `mongot` metrics endpoint. Prometheus works on both Community and Enterprise editions, and does not require Ops Manager configuration.\n\n### Scrape Configuration\n\nAdd a scrape job to your Prometheus configuration:\n\n```yaml\nscrape_configs:\n - job_name: mongot\n scrape_interval: 15s\n scrape_timeout: 10s\n static_configs:\n - targets:\n - mongot-host-1.internal:9946\n - mongot-host-2.internal:9946\n labels:\n deployment: prod\n edition: ce\n```\n\nFor Kubernetes deployments that the MongoDB Controllers for Kubernetes Operator manages, use a `PodMonitor` or `ServiceMonitor` resource with the Prometheus Operator. Target the pods labeled `app=-search`:\n\n```yaml\napiVersion: monitoring.coreos.com/v1\nkind: PodMonitor\nmetadata:\n name: mongot\n namespace: \nspec:\n selector:\n matchLabels:\n app: -search\n podMetricsEndpoints:\n - port: metrics\n interval: 15s\n```\n\n### Recording Rules\n\nRecording rules reduce PromQL repetition and make Grafana queries faster. The following rules use the metric names that self-managed `mongot` exposes:\n\n```yaml\ngroups:\n - name: mongot_recording\n interval: 30s\n rules:\n - record: mongot:search_latency_p99\n expr: max(mongot_command_searchCommandTotalLatency_seconds{quantile=\"0.99\"})\n\n - record: mongot:vector_search_latency_p99\n expr: max(mongot_command_vectorSearchCommandTotalLatency_seconds{quantile=\"0.99\"})\n\n - record: mongot:search_rate:rate5m\n expr: sum(rate(mongot_command_searchCommandTotalLatency_seconds_count[5m]))\n\n - record: mongot:search_failure_rate:rate5m\n expr: sum(rate(mongot_command_searchCommandFailure_total[5m]))\n\n - record: mongot:replication_lag_ms:max\n expr: max(mongot_index_stats_indexing_replicationLagMs)\n\n - record: mongot:heap_utilization_post_gc\n expr: mongot_jvm_gc_live_data_size_bytes / mongot_jvm_gc_max_data_size_bytes\n\n - record: mongot:gc_pause_worst\n expr: max(mongot_jvm_gc_pause_seconds_max)\n```\n\n### Alert Rules\n\nTranslate the recommended alerts into Prometheus alert rules. For example:\n\n```yaml\ngroups:\n - name: mongot_alerts\n rules:\n - alert: MongotDown\n expr: up{job=\"mongot\"} == 0\n for: 1m\n labels:\n severity: page\n annotations:\n summary: \"mongot is down ({{ $labels.instance }})\"\n\n - alert: MongotReplicationLagGrowing\n expr: deriv(max(mongot_index_stats_indexing_replicationLagMs)[15m:1m]) > 500\n for: 10m\n labels:\n severity: page\n\n - alert: MongotHeapPressure\n expr: mongot:heap_utilization_post_gc > 0.85\n for: 5m\n labels:\n severity: page\n```\n\nTo translate the full set of alerts into PromQL, see Recommended Alerts for mongot.\n\n### Grafana Dashboard Skeleton\n\nA starter Grafana dashboard for `mongot` should include the following panel groups:\n\n- **Process**: uptime, restart count, CPU, and resident memory.\n\n- **JVM**: heap used compared to max, post-GC heap, GC pause time, and threads.\n\n- **Replication**: current state, lag in milliseconds and rate, and events applied per second.\n\n- **Indexing**: active builds, per-index status, indexing failures, and merge backlog.\n\n- **Query**: rate by operator, latency p50, p95, and p99 by operator, and error rate.\n\n- **Executors**: queue depth by pool and rejected tasks.\n\n- **Storage**: free bytes, IOPS, and page-fault rate.\n\n- **Embedding** (if enabled): request rate, latency, errors, and token throughput.\n\n## OpenTelemetry\n\nIf your organization standardizes on OpenTelemetry, the OpenTelemetry Collector can ingest `mongot` metrics from the Prometheus endpoint and forward them to any OTLP-compatible backend:\n\n```yaml\nreceivers:\n prometheus:\n config:\n scrape_configs:\n - job_name: mongot\n scrape_interval: 15s\n static_configs:\n - targets:\n - localhost:9946\n\nexporters:\n otlphttp:\n endpoint: https://\n\nservice:\n pipelines:\n metrics:\n receivers:\n - prometheus\n exporters:\n - otlphttp\n```\n\nThis pattern is provider-neutral. The same collector configuration works for Honeycomb, Grafana Cloud, New Relic, and other backends.\n\nTo forward logs, configure `mongot` to write JSON to stdout. The collector can then parse the structured fields and route the logs to your backend.\n\n## Log Forwarding\n\n`mongot` writes structured JSON logs to stdout and stderr by default. Forward stdout to your centralized log platform and ingest the logs as JSON.\n\n### Fluent Bit and Vector\n\nFluent Bit and Vector both work for `mongot` log collection. Treat the logs as a tagged stream. To learn which log patterns matter most, see mongot Logs and FTDC.\n\n### CloudWatch Logs\n\nFor AWS-hosted deployments, the CloudWatch agent can tail the log file directly. Create a CloudWatch metric filter on key log patterns, such as `Exception requiring resync`, to convert log events into metrics."} -{"chunk_id": "6a869dda8824e6129431dfb7-1", "page_id": "6a869dda8824e6129431dfb7", "source_name": "self-managed-search", "product_name": null, "url": "https://mongodb.com/docs/search/self-managed/current/monitoring/tool-integrations", "title": "Monitoring Tool Integrations", "text": "## Health Checks\n\n`mongot` exposes two HTTP endpoints on port `8080` by default:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nEndpoint\n\n\nUse For\n\n\nMeaning\n\n
\n`/health`\n\n\nLiveness\n\n\n`mongot` has bound its services. Use this endpoint to detect a crashed or hung process. It does not indicate that `mongot` can serve queries.\n\n
\n`/ready`\n\n\nReadiness\n\n\n`mongot` has finished initializing index replication. Use this endpoint to gate traffic into a pod.\n\n
Both endpoints return JSON with HTTP 200. Treat `{\"status\":\"SERVING\"}` as healthy and `{\"status\":\"NOT_SERVING\"}` as unhealthy. An invalid query parameter returns HTTP 400 with `{\"error\":\"BAD_REQUEST\"}`.\n\nLike the metrics endpoint, the `/health` and `/ready` endpoints are unauthenticated by default. Protect them at the network layer.\n\nIn Kubernetes, map the liveness probe to `/health` and the readiness probe to `/ready`:\n\n```yaml\nlivenessProbe:\n httpGet:\n path: /health\n port: 8080\n initialDelaySeconds: 30\n periodSeconds: 10\n failureThreshold: 3\n\nreadinessProbe:\n httpGet:\n path: /ready\n port: 8080\n initialDelaySeconds: 5\n periodSeconds: 5\n failureThreshold: 3\n```\n\nIf you use `/health` for both probes, a pod can receive traffic before its indexes initialize, because `/health` returns `SERVING` as soon as the services bind. The two-endpoint split exists to separate these signals.\n\nWhen the MongoDB Controllers for Kubernetes Operator manages more than one `mongot` pod, it provisions a default load balancer and routes traffic based on the `/ready` endpoint for you. For self-managed deployments that run their own load balancer in front of multiple `mongot` instances, configure the load balancer to route traffic only to instances that return `SERVING` on `/ready`.\n\nTo keep a pod ready even when some indexes fail to initialize, set the readiness probe path to `/ready?allowFailedIndexes=true`. This setting is a deliberate tradeoff, because failed indexes return empty results for queries that reach them.\n\n## Multi-Instance Considerations\n\nIf your deployment runs more than one `mongot` instance, each instance exposes its own metrics endpoint. Scrape each instance individually, then use Prometheus aggregations, such as `sum`, `max`, and `avg`, to see a combined view of the metrics.\n\nTrack replication lag, executor queue depth, and query latency for each instance and in aggregate. A single saturated instance can degrade latency for the queries it serves, and fleet-wide averages can hide this degradation.\n\nFor sharded clusters, label each scrape with the shard name so that you can roll the metrics up per shard.\n\n## FTDC and Support Cases\n\nWhen you open a MongoDB Support case, attach the FTDC capture from the affected `mongot` instance. To learn the capture procedure, see mongot Logs and FTDC."} -{"chunk_id": "6a869dda8824e6129431dfac-0", "page_id": "6a869dda8824e6129431dfac", "source_name": "self-managed-search", "product_name": null, "url": "https://mongodb.com/docs/search/self-managed/current/configuration/automated-embedding", "title": "Configure `mongot` for MongoDB Vector Search Automated Embedding", "text": "# Configure `mongot` for MongoDB Vector Search Automated Embedding\n\nAutomated Embedding is in Preview for self-managed `mongot`. The feature and corresponding documentation might change at any time during the Preview period. To learn more, see Preview Features.\n\nThis tutorial describes how to configure Automated Embedding on a self-managed `mongot` deployment. With Automated Embedding, `mongot` generates vector embeddings for your text data at index-time and for query text at query-time. You don't have to maintain a separate embedding pipeline in your application.\n\nThis tutorial is for developers who are building semantic search or RAG (Retrieval-Augmented Generation) features and want `mongot` to manage embeddings. For MongoDB Controllers for Kubernetes Operator deployments, see Automated Embedding.\n\n## What Automated Embedding Does\n\nWithout Automated Embedding, your application must:\n\n1. Generate an embedding for each document that you insert or update.\n\n2. Store that embedding alongside the document in your collection.\n\n3. Generate an embedding for every query, using the same model, at query-time.\n\n4. Submit the query embedding to `$vectorSearch`.\n\nWith Automated Embedding, `mongot` handles steps 1, 2, and 3. Your application:\n\n1. Configures a MongoDB Vector Search index with the `autoEmbed` field type for the text field.\n\n2. Inserts and updates documents normally.\n\n `mongot` reads the text field, generates the embedding through the configured embedding model, and stores it.\n\n3. Issues `$vectorSearch` queries with the query text, not a pre-computed embedding.\n\n `mongot` generates the embedding for the query text.\n\n## Supported Embedding Providers\n\nSelf-managed `mongot` Automated Embedding integrates with Voyage AI embedding models.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nModel\n\n\nDescription\n\n
\n`voyage-4`\n\n\nRecommended. Balanced performance for general text search.\n\n
\n`voyage-4-lite`\n\n\nHigh-volume, cost-sensitive applications.\n\n
\n`voyage-4-large`\n\n\nMaximum accuracy for complex semantic relationships.\n\n
\n`voyage-code-3`\n\n\nSpecialized for code search and technical documentation.\n\n
You incur costs for embedding generation. To learn more, see Manage Billing for Automated Embedding.\n\n## Prerequisites\n\nYou must have the following prerequisites to use Automated Embedding:\n\n- `mongot` 1.70.1 or later on a self-managed deployment (Community tarball or container, Local Development, and Enterprise Edition through Kubernetes Operator).\n\n- MongoDB 8.3 or later for standalone and Kubernetes Operator-managed deployments. To learn more, see Compatibility and Requirements for `mongot`.\n\n- Two Voyage AI API (Application Programming Interface) keys.\n\n Use two separate keys, one for index-time embedding generation and one for query-time. Separate keys isolate query workload from indexing workload and allow independent rate-limit accounting. To learn more, see Rate Limits.\n\n- Outbound network access from `mongot` to the embedding endpoint.\n\n The default endpoint is `https://ai.mongodb.com/v1/embeddings`. This endpoint proxies Voyage AI with MongoDB-managed billing, for keys generated using the Atlas UI. You can also use `https://api.voyageai.com/v1/embeddings` for direct Voyage AI access if you generated the API (Application Programming Interface) key directly from Voyage AI.\n\n## Procedure\n\n### Generate Voyage AI API (Application Programming Interface) Keys.\n\nYou can generate Voyage AI API (Application Programming Interface) keys through either of the following methods:\n\n- (Recommended) Through your Atlas account. Atlas provides API (Application Programming Interface) key management with built-in rate-limit configuration. The keys are not tied to an Atlas cluster. To learn more, see Manage API Keys.\n\n- Through Voyage AI directly at voyageai.com.\n\nGenerate two keys and name them clearly, for example, `mongot-prod-index` and `mongot-prod-query`. Store the keys in secure secret storage.\n\n### Configure `mongot` for Automated Embedding.\n\nThe configuration depends on your deployment path. Select the tab for your deployment.\n\n\n\n\n\nAutomated Embedding requires the `preview` Local Development image (`mongodb/mongodb-atlas-local:preview`). The `preview` image bundles the Community build of `mongot`, which includes the Automated Embedding integration.\n\nIf you launch the container directly with `docker run`, pass the Voyage AI API (Application Programming Interface) key with the `VOYAGE_API_KEY` environment variable and use the `:preview` tag:\n\n```shell\ndocker run \\\n -e VOYAGE_API_KEY= \\\n -p 27017:27017 \\\n mongodb/mongodb-atlas-local:preview\n```\n\nIf you issued your Voyage AI key directly through Voyage AI rather than through Atlas, override the default endpoint:\n\n```shell\ndocker run \\\n -e VOYAGE_API_KEY= \\\n -e EMBEDDING_PROVIDER_ENDPOINT=https://api.voyageai.com/v1/embeddings \\\n -p 27017:27017 \\\n mongodb/mongodb-atlas-local:preview\n```\n\nLocal Development accepts only a single Voyage AI API (Application Programming Interface) key and uses it for both index-time and query-time embedding generation. A single key is acceptable for development. For production deployments that need separate index-time and query-time keys, use the Community Edition or Kubernetes Operator deployment path.\n\n\n\n\n\nAdd the `embedding` block to your `mongot` configuration file:\n\n```yaml\nembedding:\n queryKeyFile: /etc/mongot/secrets/voyage-api-query-key\n indexingKeyFile: /etc/mongot/secrets/voyage-api-indexing-key\n providerEndpoint: https://ai.mongodb.com/v1/embeddings\n```\n\nEach key file contains the API (Application Programming Interface) key as its only content. Set the file permissions to `0600` and set the file owner to the user that runs the `mongot` process.\n\n\n\n"} -{"chunk_id": "6a869dda8824e6129431dfac-1", "page_id": "6a869dda8824e6129431dfac", "source_name": "self-managed-search", "product_name": null, "url": "https://mongodb.com/docs/search/self-managed/current/configuration/automated-embedding", "title": "Configure `mongot` for MongoDB Vector Search Automated Embedding", "text": "### Create an Automated Embedding index.\n\nAfter you configure `mongot` with your Voyage AI API (Application Programming Interface) keys, define a MongoDB Vector Search index that uses the `autoEmbed` field type. The index definition specifies which text field `mongot` embeds and which model it uses. It also specifies the indexing method, quantization, and other parameters.\n\n```javascript\ndb.movies.createSearchIndex(\n \"movie-semantic-index\",\n \"vectorSearch\",\n {\n \"fields\": [\n {\n \"type\": \"autoEmbed\",\n \"modality\": \"text\",\n \"path\": \"plot\",\n \"model\": \"voyage-4\",\n \"numDimensions\": 1024,\n \"similarity\": \"cosine\",\n \"indexingMethod\": \"hnsw\",\n \"hnswOptions\": {\n \"maxEdges\": 16,\n \"numEdgeCandidates\": 50\n },\n \"quantization\": \"scalar\"\n },\n {\n \"type\": \"filter\",\n \"path\": \"genre\"\n }\n ]\n }\n)\n```\n\nThe following table describes the `autoEmbed` index definition fields:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nField\n\n\nPurpose\n\n
\n`type: \"autoEmbed\"`\n\n\nMarks the field for automatic embedding.\n\n
\n`modality: \"text\"`\n\n\nThe data modality. `text` is the only supported modality.\n\n
\n`path`\n\n\nThe field in your collection to embed.\n\n
\n`model`\n\n\nThe Voyage AI model name. The model must be one that your API (Application Programming Interface) key has access to.\n\n
\n`numDimensions`\n\n\nThe number of dimensions for the embedding vector. The model determines the supported dimensions.\n\n
\n`similarity`\n\n\nThe similarity function to use for vector search. The supported functions are `cosine`, `dotProduct`, and `euclidean`.\n\n
\n`indexingMethod`\n\n\nThe indexing method to use. The supported methods are `flat` and `hnsw`.\n\n
\n`hnswOptions`\n\n\n(Optional) The HNSW (Hierarchical Navigable Small Worlds) index options. Required if `indexingMethod` is `hnsw`.\n\n
\n`quantization`\n\n\n(Optional) The quantization type to use. The supported types are `float`, `scalar`, `binary`, and `binaryNoRescore`.\n\n
You can mix `autoEmbed` fields with `filter` fields in the same index. You cannot mix `autoEmbed` with raw vector fields on the same path. Choose one approach per field.\n\n### Run an Automated Embedding Query.\n\nSubmit query text, not a pre-computed embedding. `mongot` generates the query embedding for you.\n\n```javascript\ndb.movies.aggregate([\n {\n \"$vectorSearch\": {\n \"index\": \"movie-semantic-index\",\n \"path\": \"plot\",\n \"query\": \"a heist gone wrong in a rainy city\",\n \"model\": \"voyage-4\",\n \"numCandidates\": 100,\n \"limit\": 10\n }\n },\n {\n \"$project\": {\n \"_id\": 0,\n \"title\": 1,\n \"score\": { $meta: \"vectorSearchScore\" }\n }\n }\n])\n```\n\nTo learn more, see Run Vector Search ANN and ENN Queries.\n\n## Embedding Storage\n\n`mongot` persists embeddings in a dedicated internal database on the cluster. `mongot` does not store embeddings in your source collection. `mongot` can regenerate embeddings from the source text, and you incur charges for embedding generation.\n\nChanges to the embedding model, output dimensions, or quantization trigger a full re-embedding of the affected index, for which you incur charges for embedding generation. See When `mongot` Regenerates Embeddings.\n\nTo learn more, see Generated Embeddings Collection.\n\n## When `mongot` Regenerates Embeddings\n\n`mongot` regenerates embeddings for an `autoEmbed` field when any of the following occur:\n\n- You insert a document.\n\n- You change the embedded field in a document. `mongot` detects the change through change streams.\n\n- You change the embedding model in the index definition.\n\n- You change the embedding output dimension or data type.\n\n- You change the text field path.\n\nIf you change any of the last three items, `mongot` rebuilds the entire index from scratch. The rebuild can be costly for large collections. Plan model changes deliberately.\n\n## Cost and Rate Limiting\n\nMongoDB charges per million tokens at model-specific rates. Indexing cost is proportional to the total text volume of the indexed field across the collection. Query cost is proportional to the volume of query text.\n\nIf you use the Voyage AI API (Application Programming Interface) key that you created using your Atlas account, you can view API (Application Programming Interface) key usage and rate limits in the Atlas UI. To learn more, see Manage Billing for the Embedding and Reranking API. If you use keys created directly from Voyage AI, you must monitor your usage and rate limits in the Voyage AI dashboard.\n\nVoyage AI-side rate-limit errors appear in `mongot` logs and as failed-document indicators on the affected index. These errors do not disable the index, but they can delay indexing of new documents.\n\n## Failure Modes\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nSymptom\n\n\nLikely Cause\n\n\nAction\n\n
\nThe index stays in `PENDING` status past a few minutes.\n\n\n`mongot` cannot reach the embedding endpoint, or the API (Application Programming Interface) key is invalid.\n\n\nCheck `mongot` logs for HTTP errors against the embedding endpoint.\n\n
\nIndexing delays appear intermittently.\n\n\nVoyage AI-side rate limiting.\n\n\nEither increase your rate limit or reduce indexing-time embedding load.\n\n
\nQueries against the index return an error that mentions embeddings.\n\n\nThe query API (Application Programming Interface) key is invalid or expired.\n\n\nVerify the contents of `queryKeyFile`.\n\n
\nAll queries against the index return empty results.\n\n\nThe index might have been rebuilt and is still re-embedding the corpus.\n\n\nCheck the index status with `db.collection.getSearchIndexes()`.\n\n
\n\n## Limitations\n\nThe following limitations apply to Automated Embedding:\n\n- **Preview status.** Configuration shape, supported models, and default endpoints might change before Automated Embedding is generally available.\n\n- **One embedding model per field.** Mixed-model indexes are not supported.\n\n- **No embedding model failover.** If the Voyage AI endpoint is unreachable, indexing of new documents stalls.\n\n## Next Steps\n\n- Automated Embedding Overview for the cross-platform conceptual overview.\n\n- Configure mongot for the full `mongot` configuration reference."} -{"chunk_id": "6a869dda8824e6129431dfc0-0", "page_id": "6a869dda8824e6129431dfc0", "source_name": "self-managed-search", "product_name": null, "url": "https://mongodb.com/docs/search/self-managed/current/installation/quick-start", "title": "MongoDB Search and MongoDB Vector Search Local Development Quickstart", "text": "# MongoDB Search and MongoDB Vector Search Local Development Quickstart\n\nYou can use the `mongodb/mongodb-atlas-local` Docker image to create a single node replica set with MongoDB Search and MongoDB Vector Search. The `mongodb/mongodb-atlas-local` Docker image is a self-contained MongoDB deployment that includes `mongot` and is meant only for local development and testing purposes. The single node replica set deployment runs on port 27017 and doesn't support multiple `mongot` processes. This deployment is not suitable for production use.\n\nThis tutorial shows you how to deploy `mongot` with a single node replica set using Docker Compose.\n\n## Prerequisites\n\nBefore you begin, you must have the following installed:\n\n- Docker\n\n- Docker Compose\n\n- `mongosh` locally or in Docker\n\n## Deploy MongoDB Search and MongoDB Vector Search with Docker Compose\n\n### Pull the latest `mongodb/mongodb-atlas-local` Docker image.\n\nTo pull the `mongodb/mongodb-atlas-local` Docker image, run the following command:\n\n```shell\ndocker pull mongodb/mongodb-atlas-local:preview\n```\n\nYou must use the `preview` tag to get the latest version of `mongot`. The `preview` tag bundles the Community build of `mongot`, which supports automated embedding. Images without the `preview` tag don't include the Community build of `mongot` or support automated embedding. Use the `latest` tag only if you have existing tooling or scripts pinned to `latest` and you do not need automated embedding.\n\nTo create a reproducible environment, pin the image to a specific version tag instead of a moving tag like `preview` or `latest`. Replace `` with the version tag you want:\n\n```shell\ndocker pull mongodb/mongodb-atlas-local:\n```\n\n### Create a `docker-compose.yaml` file.\n\nCreate the `docker-compose.yaml` file. For a complete and detailed example, see Docker Compose Example.\n\n```yaml\nservices:\n mongodb:\n image: mongodb/mongodb-atlas-local:preview\n hostname: mongodb\n environment:\n - MONGODB_INITDB_ROOT_USERNAME=\n - MONGODB_INITDB_ROOT_PASSWORD=\n ports:\n - 27017:27017\n volumes:\n - ./init:/docker-entrypoint-initdb.d\n - db:/data/db\n - configdb:/data/configdb\n - mongot:/data/mongot\nvolumes:\n db:\n configdb:\n mongot:\n```\n\n### Replace the placeholder values and save the file.\n\nReplace the `` and `` placeholder values with your own values and save the file. You can also set the username and password through a file for an extra layer of security. Use the `MONGODB_INITDB_ROOT_USERNAME_FILE` and `MONGODB_INITDB_ROOT_PASSWORD_FILE` environment variables to specify the path to the files that contain the username and password.\n\nTo use Automated Embedding, provide your Voyage AI API key (created from the Atlas UI) through the environment variable `VOYAGE_API_KEY`. By default, the embedding provider endpoint is `https://ai.mongodb.com/v1/embeddings` (for keys created from the Atlas UI).\n\nIf you created your API key directly from Voyage AI, you must also provide the embedding provider endpoint through the environment variable `VOYAGE_EMBEDDING_PROVIDER_ENDPOINT`. The value for this variable is `https://api.voyageai.com/v1/embeddings`.\n\nTo learn more, see Configure `mongot` for MongoDB Vector Search Automated Embedding.\n\nTo automatically load the MongoDB sample dataset during initialization, set the `MONGODB_LOAD_SAMPLE_DATA` environment variable to `true`.\n\n```yaml\nservices:\n mongodb:\n image: mongodb/mongodb-atlas-local:preview\n hostname: mongodb\n environment:\n - MONGODB_INITDB_ROOT_USERNAME_FILE=\n - MONGODB_INITDB_ROOT_PASSWORD_FILE=\n - MONGODB_LOAD_SAMPLE_DATA=true\n - VOYAGE_API_KEY=\n```\n\n### Run Docker Compose.\n\nRun the following command to create a single node replica set with MongoDB Search and MongoDB Vector Search.\n\n```shell\ndocker compose up -d\n```\n\n### Verify the deployment.\n\nTo verify the deployment, run the following command:\n\n```shell\ndocker ps\n```\n\nThe output should resemble the following:\n\n```sh\nCONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES\nf68ee6df9907 mongodb/mongodb-atlas-local:preview \"/usr/local/bin/runn\u2026\" 4 hours ago Up 4 hours (healthy) 0.0.0.0:27017->27017/tcp, [::]:27017->27017/tcp search-in-community-mongodb-1\n```\n\n## Connect and Use MongoDB Search and MongoDB Vector Search with `mongosh`\n\n### Connect to the single node replica set.\n\nTo connect to the single node replica set, run the following command after replacing `` with the username you specified in the `docker-compose.yaml` file:\n\n```shell\nmongosh \"mongodb://localhost:27017\" -u \n```"} -{"chunk_id": "6a869dda8824e6129431dfc0-1", "page_id": "6a869dda8824e6129431dfc0", "source_name": "self-managed-search", "product_name": null, "url": "https://mongodb.com/docs/search/self-managed/current/installation/quick-start", "title": "MongoDB Search and MongoDB Vector Search Local Development Quickstart", "text": "### (Optional). If you loaded the sample dataset, create an index.\n\n- To verify that the same data is loaded, run the following command:\n\n ```shell\n show dbs\n ```\n\n ```shell\n __mdb_internal_search 56.00 KiB\n admin 252.00 KiB\n config 172.00 KiB\n local 193.25 MiB\n sample_airbnb 52.52 MiB\n sample_analytics 9.48 MiB\n sample_geospatial 1.15 MiB\n sample_guides 40.00 KiB\n sample_mflix 96.16 MiB\n sample_restaurants 6.43 MiB\n sample_supplies 1.04 MiB\n sample_training 46.91 MiB\n sample_weatherdata 2.58 MiB\n ```\n\n- To create indexes, switch to the `sample_mflix` database.\n\n ```shell\n use sample_mflix\n ```\n\n- To create a MongoDB Search index named `movie-title-index` on the `sample_mflix.movies` collection, run the following command:\n\n The following index definition creates a MongoDB Search index named `movie-index` on the `movies` collection. The index definition specifies the `mappings` as `dynamic: true` to automatically index all dynamically indexable fields in the documents of the collection.\n\n ```javascript\n db.movies.createSearchIndex(\n \"movie-index\",\n { mappings: { dynamic: true } }\n )\n ```\n\n- To create a MongoDB Vector Search index named `movie-vector-index` on the `sample_mflix.embedded_movies` collection, run the following command:\n\n The following index definition creates a MongoDB Vector Search index named `movie-vector-index` on the `plot_embedding_voyage_4_large` field of the `embedded_movies` collection. The index definition specifies the following:\n\n - The `type` as `vectorSearch` to create a MongoDB Vector Search index.\n\n - The `path` as `plot_embedding_voyage_4_large` to index the vector embeddings in the field.\n\n - The `numDimensions` as `2048` to specify the number of dimensions in the vector embeddings.\n\n - The `similarity` as `dotProduct` to specify the similarity function to use to measure the similarity between the query vector and the indexed vectors.\n\n ```javascript\n db.embedded_movies.createSearchIndex(\n \"movie-vector-index\",\n \"vectorSearch\",\n {\n fields: [\n { type: \"vector\", path: \"plot_embedding_voyage_4_large\", numDimensions: 2048, similarity: \"dotProduct\" }\n ]\n }\n )\n ```\n\n- To verify that the indexes were created, run the following command:\n\n ```shell\n db.movies.getSearchIndexes().forEach(printjson)\n ```\n\n ```javascript\n [\n {\n id: '6a22ddd3709bac3ce7a37252',\n name: 'movie-index',\n status: 'READY',\n queryable: true,\n latestDefinitionVersion: {\n version: 0,\n createdAt: ISODate('2026-06-05T14:31:47.000Z')\n },\n latestDefinition: {\n mappings: {\n dynamic: true\n }\n },\n statusDetail: [ {\n hostname: '6a22dbdcb2393a40012a14b2',\n status: 'READY',\n queryable: true,\n mainIndex: {\n status: 'READY',\n queryable: true,\n definitionVersion: {\n version: 0,\n createdAt: ISODate('2026-06-05T14:31:47.000Z')\n },\n definition: {\n mappings: {\n dynamic: true,\n fields: {}\n }\n }\n }\n } ],\n numDocs: 21349\n },\n {\n id: '6a22dde9709bac3ce7a37254',\n name: 'movie-vector-index',\n status: 'READY',\n queryable: true,\n latestDefinitionVersion: {\n version: 0,\n createdAt: ISODate('2026-06-05T14:32:09.000Z')\n },\n latestDefinition: {\n fields: [\n {\n type: 'vector',\n path: 'plot_embedding_voyage_4_large',\n numDimensions: 2048,\n similarity: 'dotProduct'\n }\n ]\n },\n statusDetail: [\n {\n hostname: '6a22dbdcb2393a40012a14b2',\n status: 'READY',\n queryable: true,\n mainIndex: {\n status: 'READY',\n queryable: true,\n definitionVersion: {\n version: 0,\n createdAt: ISODate('2026-06-05T14:32:09.000Z')\n },\n definition: {\n fields: [\n {\n type: 'vector',\n path: 'plot_embedding_voyage_4_large',\n numDimensions: 2048,\n similarity: 'dotProduct'\n }\n ]\n }\n }\n }\n ],\n numDocs: 21349\n }\n ]\n ```"} -{"chunk_id": "6a869dda8824e6129431dfc0-2", "page_id": "6a869dda8824e6129431dfc0", "source_name": "self-managed-search", "product_name": null, "url": "https://mongodb.com/docs/search/self-managed/current/installation/quick-start", "title": "MongoDB Search and MongoDB Vector Search Local Development Quickstart", "text": "### (Optional). If you created the index, run a query on the index.\n\n- To run a MongoDB Search query on the `movie-index` index, run the following command:\n\n This query searches for the term `courtroom lawyer` in the `plot` field of the `movies` collection using the `movie-index` index. The query uses the `fuzzy` option to enable fuzzy matching. The query returns the top 3 results and projects only the `title` and `plot` fields.\n\n ```javascript\n db.movies.aggregate([\n {\n \"$search\": {\n \"index\": \"movie-index\",\n \"text\": {\n \"query\": \"courtroom lawyer\",\n \"path\": \"plot\",\n \"fuzzy\": {}\n }\n }\n },\n {\n \"$limit\": 3\n },\n {\n \"$project\": {\n \"_id\": 0,\n \"title\": 1,\n \"plot\": 1\n }\n }\n ])\n ```\n\n ```json\n [\n {\n plot: 'Academy Award-winning documentary filmmaker, Jean-Xavier de Lestrade, presents a gripping courtroom thriller, offering a rare and revealing inside look at a high-profile murder trial. In ...',\n title: 'Death on the Staircase'\n },\n {\n plot: 'William Kunstler was one of the most famous lawyers of the 20th century. The New York Times called him \"the most hated and most loved lawyer in America.\" His clients included Martin Luther ...',\n title: 'William Kunstler: Disturbing the Universe'\n },\n {\n plot: \"A dying millionnaire has her soul transferred into a younger, willing woman. But something goes wrong, and she finds herself in her lawyer's body - together with the lawyer.\",\n title: 'All of Me'\n }\n ]\n ```\n\n- To run a MongoDB Vector Search query on the `movie-vector-index` index, perform the following steps:\n\n - Create a file named `query-embeddings.js`:\n\n ```shell\n touch query-embeddings.js\n ```\n\n - Copy and paste the following embeddings for the phrase `courtroom lawyer` into the `query-embeddings.js` file:\n\n ```javascript\n QUERY_EMBEDDING=[0.021390099078416824, 0.0055892206728458405, ..., 2.0180674255243503e-05, 0.0018958032596856356, -0.025378083810210228, ..., -5.0274662498850375e-05, 0.00041352681000716984, -0.015045578591525555, ..., 1.261292140952719e-06, -0.020302467048168182, -0.054623305797576904, ..., 1.0090337127621751e-05, 0.006253885105252266, 0.02308197133243084, ..., 5.0274662498850375e-05, 0.007371729239821434, 0.011903529986739159, ..., 8.072269702097401e-05, -0.016797874122858047, 0.024290451779961586, ..., 5.0274662498850375e-05, -0.0018655912717804313, 0.011480561457574368, ...];\n ```\n\n - Load the `query-embeddings.js` file into `mongosh`:\n\n ```shell\n load('//query-embeddings.js')\n ```\n\n - Run the following query:\n\n The following query uses the `$vectorSearch` stage to:\n\n - Search the `plot_embedding_voyage_4_large` field for approximate nearest neighbors by using vector embeddings for the string `courtroom lawyer`.\n\n - Consider up to `100` nearest neighbors, but limit the output to only 3 results.\n\n ```javascript\n db.embedded_movies.aggregate([\n {\n \"$vectorSearch\": {\n \"index\": \"movie-vector-index\",\n \"path\": \"plot_embedding_voyage_4_large\",\n \"queryVector\": QUERY_EMBEDDING,\n \"numCandidates\": 100,\n \"limit\": 3\n }\n },\n {\n \"$project\": {\n \"_id\": 0,\n \"title\": 1,\n \"plot\": 1,\n \"score\": { $meta: \"vectorSearchScore\" }\n }\n }\n ])\n ```\n\n ```json\n [\n {\n plot: 'An attorney defends an officer on trial for ordering his troops to fire on civilians after they stormed a U.S. embassy in a third world country.',\n title: 'Rules of Engagement',\n score: 0.695757269859314\n },\n {\n plot: 'An American attorney on business in China, ends up wrongfully on trial for murder and his only key to innocence is a female defense lawyer from the country.',\n title: 'Red Corner',\n score: 0.6952665448188782\n },\n {\n plot: 'A lawyer becomes a target by a corrupt politician and his NSA goons when he accidentally receives key evidence to a serious politically motivated crime.',\n title: 'Enemy of the State',\n score: 0.6868826150894165\n }\n ]\n ```\n\n## Learn More\n\n**To deploy Atlas Local** using:\n\n- Docker (`run`), see Create a Local Atlas Deployment.\n\n- Atlas CLI (`setup`), see Create a Local Atlas Deployment.\n\n- MongoDB MCP Server, see Get Started with the MongoDB MCP Server.\n\n**To deploy mongot with MongoDB Community Edition** on:\n\n- Linux distributions like Red Hat, Ubuntu, Debian, SUSE, or Amazon Linux, see Deploy MongoDB Search and MongoDB Vector Search with a Tarball.\n\n- Docker, see Deploy MongoDB Search and MongoDB Vector Search on Docker.\n\n- MongoDB Controllers for Kubernetes Operator, see Deploy MongoDB Search and MongoDB Vector Search Using MongoDB Controllers for Kubernetes Operator.\n\n**To deploy mongot with MongoDB Enterprise Edition**, see Deploy MongoDB Search and MongoDB Vector Search Using MongoDB Controllers for Kubernetes Operator."} -{"chunk_id": "6a869dda8824e6129431dfb5-0", "page_id": "6a869dda8824e6129431dfb5", "source_name": "self-managed-search", "product_name": null, "url": "https://mongodb.com/docs/search/self-managed/current/release-notes", "title": "Release Notes", "text": "# Release Notes\n\n\u2705## mongot v1.70.5\n\n**Release date**: September 29, 2026\n\n### Bug Fixes\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nDescription\n\n\nAvailable in Community Edition\n\n\nAvailable in Enterprise Advanced\n\n
\n**Security dependency upgrades.** Third-party libraries with known CVEs were updated: Netty upgraded to 4.2.18.Final (CVE-2026-89044), reactor-netty upgraded to 1.3.7 (CVE-2026-47848), reactor-core upgraded to 3.8.7 (CVE-2026-47863), Apache httpclient5 upgraded to 5.6.3 (CVE-2026-64607), and zstd-jni upgraded to 1.5.7-14 (CVE-2026-89045). *Fixed in v1.70.5.*\n\n\n\u2705\n\n\n\u2705\n\n
\n**Docker base image change.** The default `mongot` Docker images now use a distroless base image built on Red Hat Universal Base Image 9 (UBI9) instead of Amazon Linux 2 and Amazon Linux 2023. *Fixed in v1.70.5.*\n\n\n\u2705\n\n\n\u2705\n\n
\n\n## mongot v1.70.4\n\n**Release date**: August 27, 2026\n\n### Bug Fixes\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nDescription\n\n\nAvailable in Community Edition\n\n\nAvailable in Enterprise Advanced\n\n
\n**httpcore5 security upgrade.** `mongot` used httpcore5 and httpcore5-h2 versions affected by CVE-2026-54428. Both libraries are upgraded to 5.4.3. *Fixed in v1.70.4.*\n\n\n\u2705\n\n\n\u2705\n\n
\n**Unauthenticated requests could exhaust memory or crash**\n`mongot`. Before authentication, a client could send messages with oversized or forged length fields, including in SCRAM authentication payloads. These messages could cause `mongot` to exhaust memory or stop with an `OutOfMemoryError`. `mongot` now limits these payload sizes before authentication. *Fixed in v1.70.4.*\n\n\n\u2705\n\n\n\u2705\n\n
\n**Security dependency upgrades.** Third-party libraries with known CVEs were updated: Jackson upgraded to 2.18.9 (CVE-2026-54515), Netty (CVE-2026-59903), Micrometer (CVE-2026-59296), and Bouncy Castle. The Docker base images were also upgraded. *Fixed in v1.70.4.*\n\n\n\u2705\n\n\n\u2705\n\n
\n\n## mongot v1.70.3\n\n**Release date**: August 4, 2026\n\nThis release contains no user-facing changes for self-managed deployments.\n\n## mongot v1.70.2\n\n**Release date**: July 31, 2026\n\n### Bug Fixes\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nDescription\n\n\nAvailable in Community Edition\n\n\nAvailable in Enterprise Advanced\n\n
\n**Docker base image security update.** The `mongot` Docker image used a base image with known CVEs. The image now uses an updated base image. *Fixed in v1.70.2.*\n\n\n\u2705\n\n\n\u2705\n\n
\n**Netty security upgrade.** `mongot` used a Netty version with known CVEs. Netty is upgraded to a newer 4.1 release. *Fixed in v1.70.2.*\n\n\n\u2705\n\n\n\u2705\n\n
\n\n## mongot v1.70.1\n\n**Release date**: June 30, 2026\n\nThese release notes cover changes from the public preview release (0.40.0, October 2025) through the general availability release (1.70.1). Changes are scoped to Community Edition and Enterprise Advanced self-managed deployments. Atlas-managed deployments are excluded."} -{"chunk_id": "6a869dda8824e6129431dfb5-1", "page_id": "6a869dda8824e6129431dfb5", "source_name": "self-managed-search", "product_name": null, "url": "https://mongodb.com/docs/search/self-managed/current/release-notes", "title": "Release Notes", "text": "### New Features and Improvements\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nDescription\n\n\nAvailable in Community Edition\n\n\nAvailable in Enterprise Advanced\n\n
\n**Authentication restructured into** `scramAuth` **and**\n`x509` **blocks.** The sync-source authentication config now uses explicit `scramAuth` (username/password) and `x509` (certificate) sub-blocks rather than flat fields, with stronger validation at startup. Existing configurations must be migrated to the new structure. *Introduced in v1.70.1.*\n\n\n\u2705\n\n\n\u2705\n\n
\n**X.509 certificate authentication for sync-source connections.** `mongot` can now authenticate to `mongod` and `mongos` using TLS client certificates as a fully supported alternative to SCRAM. Configure `syncSource.replicaSet.x509` or `syncSource.router.x509` with your certificate key file and CA file. *Introduced in v1.70.1.*\n\n\n\u2705\n\n\n\u2705\n\n
\n**Encrypted key file support for TLS.** Both the sync-source TLS connection and the gRPC server TLS accept a `certificateKeyFilePasswordFile` so private keys no longer need to be stored unencrypted on disk. *Introduced in v1.70.1.*\n\n\n\u2705\n\n\n\u2705\n\n
\n**New** `syncSource.replicationReader` **config block.** Operators can now control which replica-set member `mongot` reads from during initial sync and change-stream replication. Accepts a `readPreference` value and optional `tagSets` for targeting members with specific replica-set tags. The deprecated `replicaSet.readPreference` field has been removed. *Introduced in v0.66.0.*\n\n\n\u2705\n\n\n\u2705\n\n
\n**New** `advancedConfigs` **top-level config block.** Optional performance-tuning parameters are now grouped under a single `advancedConfigs:` block with sub-blocks for `indexing`, `querying`, `replication`, `autoEmbedding`, and `ftdc`. FTDC and disk monitoring settings have moved here from the top level. *Introduced in v1.70.1.*\n\n\n\u2705\n\n\n\u2705\n\n
\n**Sharded cluster support through** `syncSource.router`. A `router` sub-block in `syncSource` enables connecting to a `mongos` router for sharded deployments. Each shard requires its own dedicated `mongot` instance, with `replicaSet` mapping the instance to its specific shard and `router` handling cluster-wide coordination. *Available since v0.40.0.*\n\n\n\u2705\n\n\n\u2705\n\n
\n**Sorted indexes (index-sort).** Search indexes can now be configured with a sort order on one or more fields. Queries with a `$sort` matching the index sort key skip the full-collection sort phase, significantly improving latency for sort-heavy workloads such as recency or price-sorted results. *Introduced in v0.66.0.*\n\n\n\u2705\n\n\n\u2705\n\n
\n**Nested vector search.** `$vectorSearch` now supports querying vector fields embedded inside nested document arrays. Define a `nestedRoot` path in the index definition to issue per-item similarity searches within arrays of sub-documents. *Introduced in v1.70.1.*\n\n\n\u2705\n\n\n\u2705\n\n
\n**Vector stored source.** Vector search indexes can store original vector values alongside index data. When a `$vectorSearch` query requests `returnStoredSource`, raw vector values are returned directly from the index, reducing latency by eliminating a second read from `mongod`. *Introduced in v0.65.0.*\n\n\n\u2705\n\n\n\u2705\n\n
\n**Automatic ENN fallback for low-recall vector search.**\n`mongot` now detects when approximate nearest-neighbor (ANN) search would return too few results due to high document-deletion rates and automatically falls back to exact nearest-neighbor (ENN) search, improving recall quality without requiring query changes. *Introduced in v0.66.0.*\n\n\n\u2705\n\n\n\u2705\n\n
\n**Drill-sideways faceting.** Facet queries use Lucene's drill-sideways algorithm, computing facet counts across all documents in a single pass. This enables \"show counts as if this facet filter were not applied\" behavior common in navigation UIs, without a second query. *Introduced in v0.69.0.*\n\n\n\u2705\n\n\n\u2705\n\n
\n**Facet bucket limit raised to 10,000.** The maximum number of buckets returned for number and date facets has been raised from 1,000 to 10,000, enabling finer-grained aggregations over large value ranges. *Introduced in v1.70.1.*\n\n\n\u2705\n\n\n\u2705\n\n
\n**Aligned index definition syntax for self-managed**\n`mongot`. The index definition JSON format accepted by self-managed `mongot` has been unified with Atlas. Index definitions can be used interchangeably without modification. *Introduced in v1.70.1.*\n\n\n\u2705\n\n\n\u2705\n\n
\n**Auto-embedding with Voyage AI in self-managed** `mongot`. Self-managed `mongot` now supports automated embedding generation. Configure the `embedding:` block with API key files and `mongot` automatically generates and maintains vector embeddings from your text fields as documents are inserted or updated. *Introduced in v1.70.1.*\n\n\n\u2705\n\n\n\u2705\n\n
\n**HNSW parameters configurable for auto-embedding indexes.** The `m` and `efConstruction` HNSW graph construction parameters can now be specified in auto-embedding index definitions, giving control over the accuracy/throughput trade-off of the approximate nearest-neighbor index. *Introduced in v0.65.0.*\n\n\n\u2705\n\n\n\u2705\n\n
\n**Prometheus metrics endpoint for self-managed** `mongot`. Self-managed `mongot` exposes a Prometheus-compatible `/metrics` endpoint (configurable with `metrics.address`, default `localhost:9946`) for monitoring index health, replication lag, query latency, and resource usage. *Available since v0.40.0.*\n\n\n\u2705\n\n\n\u2705"} -{"chunk_id": "6a869dda8824e6129431dfb5-2", "page_id": "6a869dda8824e6129431dfb5", "source_name": "self-managed-search", "product_name": null, "url": "https://mongodb.com/docs/search/self-managed/current/release-notes", "title": "Release Notes", "text": "
\n**HTTP health and readiness endpoints.** The `/health` endpoint (configurable with `healthCheck.address`, default `localhost:8080`) returns `{\"status\":\"SERVING\"}` (HTTP 200) when `mongot` is ready and `{\"status\":\"NOT_SERVING\"}` (HTTP 503) otherwise, suitable for container liveness and readiness probes. *Available since v0.40.0.*\n\n\n\u2705\n\n\n\u2705\n\n
\n**$listSearchIndexes support for self-managed** `mongot`. Self-managed `mongot` now supports running `$listSearchIndexes` on a collection to inspect the state, definition, and status of all search indexes, matching the behavior available in Atlas. *Introduced in v1.70.1.*\n\n\n\u2705\n\n\n\u2705\n\n
\n**Container-aware memory metrics.** System memory metrics now read from cgroup limits when running inside a container rather than reporting total host physical memory, giving accurate available-memory figures in Docker and Kubernetes environments. *Introduced in v0.69.0.*\n\n\n\u2705\n\n\n\u2705\n\n
\n**Replication pause thresholds aligned with Atlas.** The thresholds at which `mongot` pauses index replication to avoid overwhelming `mongod` are now consistent between Atlas and self-managed deployments. *Introduced in v0.66.0.*\n\n\n\u2705\n\n\n\u2705\n\n
\n**Lucene upgraded to 10.1.** The underlying search library was upgraded from Lucene 9.x to Lucene 10.1, bringing query performance improvements, improved segment merge behavior, and correctness fixes for compound queries, sorted indexes, and vector search. *Introduced in v1.70.1.*\n\n\n\u2705\n\n\n\u2705\n\n
\n**Java runtime upgraded to Java 21.** The `mongot` binary now ships with Java 21 (LTS), replacing Java 17. Java 21 delivers JIT improvements, better garbage collection, and a longer support lifecycle. *Introduced in v0.69.0.*\n\n\n\u2705\n\n\n\u2705\n\n
\n**Docker base image upgraded to Amazon Linux 2023.** The `mongot` Docker image now uses Amazon Linux 2023, replacing Amazon Linux 2, providing newer glibc, updated OpenSSL, and a longer support lifecycle. *Introduced in v0.69.0.*\n\n\n\u2705\n\n\n\u2705\n\n
"} -{"chunk_id": "6a869dda8824e6129431dfb5-3", "page_id": "6a869dda8824e6129431dfb5", "source_name": "self-managed-search", "product_name": null, "url": "https://mongodb.com/docs/search/self-managed/current/release-notes", "title": "Release Notes", "text": "### Bug Fixes\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nDescription\n\n\nAvailable in Community Edition\n\n\nAvailable in Enterprise Advanced\n\n
\n**Search indexes protected from deletion when router configuration is inconsistent with cluster topology.** In a sharded cluster where `mongot` lacked router configuration, a search index could be deleted when catalog metadata moved to another shard. `mongot` now protects search indexes from deletion and preserves catalog metadata integrity in this scenario. *Fixed in v0.69.0.*\n\n\n\u2705\n\n\n\u2705\n\n
\n**Startup crash when** `syncSource.router` **topology mismatched** `replicaSet`. `mongot` could crash during bootstrap in a sharded cluster if the router topology was inconsistent with the configured `replicaSet`. This is now caught at startup and reported as a configuration error with a clear message. *Fixed in v1.70.1.*\n\n\n\u2705\n\n\n\u2705\n\n
\n**Indexes that failed during initial sync are now automatically recovered.** A search index that failed partway through initial sync would remain in a FAILED state permanently, requiring manual intervention. `mongot` now detects and retries failed initial syncs on restart. *Fixed in v1.70.1.*\n\n\n\u2705\n\n\n\u2705\n\n
\n**Incorrect STEADY to INITIAL_SYNC status transition.** A bug in the Lucene-layer status computation could incorrectly transition a fully-indexed search index from STEADY back to INITIAL_SYNC, triggering unnecessary re-indexing. Indexes now correctly remain in STEADY state. *Fixed in v0.67.0.*\n\n\n\u2705\n\n\n\u2705\n\n
\n**Replication shutdown when sync-source host is unavailable.** When all configured replica-set members are unreachable for an extended period, `mongot` now cleanly shuts down replication rather than spinning indefinitely, preventing resource exhaustion and surfacing the outage through health-check failures. *Fixed in v0.67.0.*\n\n\n\u2705\n\n\n\u2705\n\n
\n**Stale system metrics.** System metrics reported through the Prometheus endpoint could become stale after extended uptime. The metrics collection loop is now correctly reset on each scrape cycle. *Fixed in v1.70.1.*\n\n\n\u2705\n\n\n\u2705\n\n
\n**Leading wildcard query regression (Lucene 10).** A regression introduced during the Lucene 10 migration caused leading-wildcard queries to return incorrect or missing results. Resolved in Lucene 10.1. *Fixed in v1.70.1.*\n\n\n\u2705\n\n\n\u2705\n\n
\n**Pure** `should` **-clause query regressions (Lucene 10).** Queries composed entirely of `should` clauses returned incorrect scores or missed documents after the Lucene 10 upgrade. Resolved in Lucene 10.1. *Fixed in v1.70.1.*\n\n\n\u2705\n\n\n\u2705\n\n
\n**Nested vector search score inflation with**\n`scoreMode: \"avg\"`. `$vectorSearch` with nested vectors and `scoreMode: \"avg\"` returned inflated ANN scores compared to ENN results. ANN and ENN scoring are now consistent. *Fixed in v0.67.0.*\n\n\n\u2705\n\n\n\u2705\n\n
\n**Nested vector search with binary quantization returned incorrect results.** `$vectorSearch` on nested vector fields using binary quantization could return incorrect results due to a bug in the child-filter path. *Fixed in v0.69.0.*\n\n\n\u2705\n\n\n\u2705\n\n
\n**Drill-sideways token facets on empty fields threw an exception.** Facet queries using the `token` field type on collections where no documents had indexed the field would throw an `invalid dim` exception. The empty case is now handled correctly. *Fixed in v0.69.0.*\n\n\n\u2705\n\n\n\u2705\n\n
\n**Sparse facet double-counting.** Iterating the key array of a sparse SSDV field could double-count or skip entries in facet results. Facet counts are now accurate for fields with sparse data. *Fixed in v0.69.0.*\n\n\n\u2705\n\n\n\u2705\n\n
\n**Autocomplete operator dropped the final prefix token.** When a user typed a word mid-completion, the autocomplete operator would sometimes discard the prefix token for the last word, returning results only for prior complete words. *Fixed in v0.65.0.*\n\n\n\u2705\n\n\n\u2705\n\n
\n**Dropped collection metadata not cleaned up.** When a MongoDB collection was dropped, stale index catalog metadata could accumulate and cause incorrect state if the collection was subsequently recreated. Metadata is now correctly removed on collection drop. *Fixed in v1.70.1.*\n\n\n\u2705\n\n\n\u2705\n\n
\n**Native memory leak in FTDC data collection.** A native memory leak in the FTDC collection routine caused `mongot`'s off-heap memory footprint to grow over time. *Fixed in v0.66.0.*\n\n\n\u2705\n\n\n\u2705\n\n
\n**Auto-embedding zombie lease race condition.** A race between heartbeat checks and state-transition logic could leave an auto-embedding leader lease in a zombie state after the holder stopped. The lease state machine now uses atomic state checks to eliminate this window. *Fixed in v0.69.0.*\n\n\n\u2705\n\n\n\u2705\n\n
\n**Materialized view full-replace incorrectly scoped for**\n`_id.` **filters.** Auto-embedding indexes whose filter included a sub-field of `_id` would incorrectly replace the entire materialized view on update, discarding out-of-filter documents. The update is now correctly scoped. *Fixed in v1.70.1.*\n\n\n\u2705\n\n\n\u2705\n\n
\n**Security dependency upgrades.** Third-party libraries with known CVEs were updated: Netty upgraded to 4.1.132+, Jackson upgraded to 2.18.6, Logback-core updated, Plexus-Utils upgraded to 4.0.3, and netty-tcnative upgraded to 2.0.79.Final. *Applied in v0.69.0.*"} -{"chunk_id": "6a869dda8824e6129431dfb5-4", "page_id": "6a869dda8824e6129431dfb5", "source_name": "self-managed-search", "product_name": null, "url": "https://mongodb.com/docs/search/self-managed/current/release-notes", "title": "Release Notes", "text": "\n\u2705\n\n\n\u2705\n\n
"} -{"chunk_id": "6a869dda8824e6129431dfbd-0", "page_id": "6a869dda8824e6129431dfbd", "source_name": "self-managed-search", "product_name": null, "url": "https://mongodb.com/docs/search/self-managed/current/security/tls-encryption", "title": "Configure TLS Encryption for `mongot`", "text": "# Configure TLS Encryption for `mongot`\n\n## Overview\n\nMongoDB Search and Vector Search use two internal communication channels between `mongot` and `mongod`:\n\n- **Sync source connections** (`mongot` \u2192 `mongod`/`mongos`): `mongot` reads data and metadata from the replica set to build and maintain search indexes. You can configure TLS for this connection in the `syncSource` section of the `mongot` configuration file.\n\n- **Query Server connections** (`mongod` \u2192 `mongot`): `mongod` forwards MongoDB Search and Vector Search queries and index management commands to `mongot` over gRPC. You configure TLS for this connection in the `server.grpc.tls` section of the `mongot` configuration file.\n\n## Configure TLS for Sync Source Connections\n\n`mongot` connects to the replica set as a MongoDB client to sync data for indexing. To encrypt this connection, configure the `scramAuth.tls` block in the `syncSource.replicaSet` section of your `mongot` configuration file.\n\n```yaml\nsyncSource:\n replicaset:\n hostAndPort: \"localhost:27017\" #Replace with the mongod host and port.\n scramAuth:\n username: \"mongot\"\n passwordFile: \"/etc/mongot/secrets/passwordFile\"\n tls:\n enabled: true\n tlsCertificateKeyFile: \"/path/to/mongot-client.pem\"\n tlsCertificateKeyFilePasswordFile: \"etc\"\n caFile: \"/path/to/ca.pem\"\n```\n\nIf you don't specify `caFile` in the `scramAuth.tls` configuration, `mongot` uses the system keystore to verify the server certificate. Specify a CA file to control the certificates that `mongot` trusts.\n\nIf `mongot` connects to a sharded cluster through a `mongos` router, you must also set `syncSource.router.scramAuth.tls` to `true`.\n\n## Configure TLS for the Query Server\n\n`mongod` connects to `mongot` over gRPC to send MongoDB Search and Vector Search queries. To encrypt this connection, configure `server.grpc.tls` in your `mongot` configuration file.\n\nThe Query Server supports the following TLS modes:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nMode\n\n\nDescription\n\n
\n`\"disabled\"`\n\n\nDisable TLS. `mongod` connects to `mongot` without encryption. This is the default value.\n\n
\n`\"TLS\"`\n\n\nEnable TLS. `mongot` presents a server certificate to `mongod`. `mongod` validates the certificate using the `--tlsCAFile` option.\n\n
\n`\"mTLS\"`\n\n\nEnable Mutual TLS. Both `mongot` and `mongod` present certificates and authenticate each other before any search traffic flows.\n\n
### Enable TLS on the Query Server\n\nTo enable TLS on the Query Server, set `server.grpc.tls.mode` to `\"TLS\"` and specify the path to the `mongot` certificate and private key PEM file:\n\n```yaml\nserver:\n grpc:\n address: \":\"\n tls:\n mode: \"TLS\"\n certificateKeyFile: \"/etc/mongot-tls/mongot-combined.pem\"\n```\n\n### Enable mTLS on the Query Server\n\nTo enable mutual TLS on the Query Server, set `server.grpc.tls.mode` to `\"mTLS\"`. Specify the certificate key file and CA file so that `mongot` can authenticate to `mongod`:\n\n```yaml\nserver:\n grpc:\n address: \":\"\n tls:\n mode: \"mTLS\"\n certificateKeyFile: \"/etc/mongot-tls/mongot-combined.pem\"\n caFile: \"/etc/mongot-tls/ca.pem\"\n```"} -{"chunk_id": "6a869dda8824e6129431dfbe-0", "page_id": "6a869dda8824e6129431dfbe", "source_name": "self-managed-search", "product_name": null, "url": "https://mongodb.com/docs/search/self-managed/current/troubleshooting", "title": "Troubleshoot Self-Managed mongot Deployments", "text": "# Troubleshoot Self-Managed mongot Deployments\n\nThis page covers the most common problems in a self-managed `mongot` deployment that you run directly on Linux or in a Docker container, with step-by-step recovery procedures. Each scenario assumes you have already identified the failure mode and need a procedure to resolve it.\n\nThis page applies to `mongot` deployments that you run directly, such as a Linux tarball installation or a Docker container. If you deploy `mongot` with the MongoDB Controllers for Kubernetes Operator, see the MongoDB Controllers for Kubernetes Operator documentation for Kubernetes-specific troubleshooting.\n\n## Before You Begin\n\nBefore you work through a scenario, confirm where your deployment stands:\n\n- If you have a metric anomaly but don't yet know what's wrong, start with the metric definitions in Metrics Reference for mongot and the thresholds in Recommended Alerts for mongot.\n\n- If you recently completed a deployment or configuration change, start with Verify Your mongot Connection.\n\nIf your symptom doesn't match any scenario, capture artifacts as described in Capture Diagnostics for Support and open a support case.\n\n## `mongot` Doesn't Start\n\nThe `mongot` process fails to come up after you start it.\n\n- The process exits within seconds of startup.\n\n- In a container, the process restarts in a loop.\n\n- No \"ready\" log message appears.\n\nIn priority order:\n\n1. The configuration file is malformed or missing required fields.\n\n2. Authentication to `mongod` fails at startup.\n\n3. `mongot` can't reach `mongod` at the configured address.\n\n4. A TLS configuration error occurs.\n\n5. The configured port is already in use.\n\n6. The data path isn't writable.\n\nReview the most recent startup log lines. The error message identifies the failing subsystem.\n\n\n\n\n\n```sh\ndocker logs --tail 100 \n```\n\n\n\n\n\n```sh\njournalctl -u mongot --no-pager | tail -n 200\n```\n\n\n\n\n\n```sh\ntail -n 200 /var/log/mongot/mongot.log\n```\n\n\n\n\n\nLook for the following patterns:\n\n- `Failed to parse config file` indicates invalid YAML.\n\n- `Exactly one authentication mechanism must be used (x509 or scram)` indicates that the `syncSource` connection is missing an authentication block or defines more than one. Nest the authentication fields under a single `scramAuth` or `x509` block. See Configure Authentication and Authorization for `mongot`.\n\n- `Authentication failed` or `Unauthorized` indicates a credentials or x.509 trust issue.\n\n- `Connection refused` or `unable to connect to host` indicates a wrong host or port, or that `mongod` isn't running.\n\n- `SSL handshake failed` indicates a CA trust or certificate SAN mismatch.\n\n- `Address already in use` indicates that another process is bound to the same port.\n\n- `Cannot write to ` indicates a permission or path issue.\n\n- **Configuration:** Fix the YAML. To learn about valid settings, see Configure mongot. If the error is `Exactly one authentication mechanism must be used (x509 or scram)`, nest the `syncSource` authentication fields under a single `scramAuth` or `x509` block. See Configure Authentication and Authorization for `mongot`.\n\n- **Authentication:** Verify that the user exists on `mongod` with the required role. See Configure Authentication and Authorization for `mongot`.\n\n- **Reachability:** Run `nc -zv ` from the `mongot` host. Check firewalls, DNS, and the `mongod` `bindIp` setting.\n\n- **TLS:** Verify that both `mongot` and `mongod` trust the same certificate authority (CA) so that each side's certificate chains up to a trusted CA. Also verify that the certificate SAN matches the hostname that `mongot` uses. See Configure TLS Encryption for `mongot`.\n\n- **Port in use:** Identify the conflicting process with `ss -lntp` or `lsof -i :`. Change the `mongot` port or stop the other process.\n\n- **Data path:** Verify that the directory exists and is writable by the `mongot` process user. Update ownership and permissions as needed.\n\n## Query Fails With a Connection Error\n\nA query fails because `mongod` can't reach `mongot`.\n\n- A `$search`, `$searchMeta`, or `$vectorSearch` query returns a connection error such as `Error connecting to : :: Connection refused`.\n\n- Or the query returns `Error connecting to Search Index Management service`.\n\n1. `mongot` isn't running on the host that `mongod` tries to reach.\n\n2. The `mongod` host or port setting for `mongot` is wrong and doesn't match the `mongot` listener.\n\n3. `mongot` is running but crashed or is restarting.\n\n4. TLS is mismatched. The `mongod` is configured for TLS but `mongot` isn't, or the reverse.\n\nFrom the `mongod` host, test connectivity to `mongot`:\n\n```sh\nnc -zv \n```\n\nFrom the `mongot` host, confirm the process is running and listening:\n\n```sh\nps aux | grep '[m]ongot'\nss -lntp | grep \n```\n\nInspect the `mongod` log for the matching error and the configured `mongot` host:\n\n```sh\ngrep -E 'mongotHost|searchIndexManagementHostAndPort' \\\n /var/log/mongodb/mongod.log\n```\n\n- If `mongot` isn't running, restart it. If it fails to come up, follow mongot Doesn't Start.\n\n- If the `mongot` host setting is wrong, correct the `mongod` parameter and restart `mongod`.\n\n- If TLS is mismatched, reconcile the TLS configuration on both sides. See Configure TLS Encryption for `mongot`.\n\n## `mongot` Keeps Re-Syncing\n\nAn index repeatedly drops out of steady state and starts an initial sync.\n\n- Logs repeat `Initial sync starting` followed by exceptions.\n\n- In steady state, logs show `Exception requiring resync occurred during steady state replication`.\n\n- The index-manager state transitions back into `INITIAL_SYNC`.\n\n- Search returns stale results during the re-sync window.\n\n1. The `mongod` oplog rolled over before `mongot` could catch up, usually because `mongot` was too slow or down, or because the oplog is too small.\n\n2. A transient issue, such as a network interruption or a brief `mongod` restart, caused a steady-state exception. A single occurrence is recoverable, but repeated occurrences aren't.\n\n3. A document mapping explosion repeatedly fills the `mongot` heap, triggering an out-of-memory error and a re-sync.\n\n4. The index data is corrupted.\n\n5. A very large number of indexes, dynamic mappings, or expensive field choices drive sustained replication lag.\n\nReview the following metrics:\n\n- `mongot_replication_mongodb_indexManagerState` cycles between `INITIAL_SYNC` and `STEADY_STATE`.\n\n- `mongot_index_stats_numLuceneMaxDocs` is cyclic or stuck.\n\n- `mongot_index_stats_indexing_replicationLagMs` continues to climb.\n\n- `mongot_jvm_memory_used_bytes` and `mongot_jvm_gc_pause_seconds_sum` rise under memory pressure.\n\nLook in the `mongot` log for the error that precedes the re-sync, then check the oplog window and heap:\n\n```sh\ngrep -E 'SteadyStateException|CappedPositionLost|OutOfMemoryError' \\\n mongot.log\n```\n\nIn `mongosh`, check the `mongod` oplog size with `db.getReplicationInfo()`.\n\n- If the oplog is too small for the `mongot` apply rate, increase the `mongod` oplog size, or close the gap with more `mongot` capacity or fewer concurrent indexes.\n\n- If steady-state exceptions repeat, capture FTDC and open a support case.\n\n- For a document mapping explosion, find the offending index, usually one with a `dynamic: true` mapping that ingests documents with arbitrary keys. Switch to a static mapping or restrict the field set, then restart `mongot` to clear the heap state.\n\n- For index corruption, which is rare, capture FTDC, then drop and recreate the affected index. Don't delete files under the data path manually."} -{"chunk_id": "6a869dda8824e6129431dfbe-1", "page_id": "6a869dda8824e6129431dfbe", "source_name": "self-managed-search", "product_name": null, "url": "https://mongodb.com/docs/search/self-managed/current/troubleshooting", "title": "Troubleshoot Self-Managed mongot Deployments", "text": "## OutOfMemory Error or `mongot` Killed by the OS\n\n`mongot` exits because it runs out of memory.\n\n- `mongot` exits unexpectedly and the container restart count climbs.\n\n- Logs end with `OutOfMemoryError: Java heap space`, a JVM-side out-of-memory error.\n\n- System logs from `dmesg` or `journalctl` show that the OOM killer terminated the process, a host-side out-of-memory error.\n\n1. The heap is too small for the workload, especially during a large initial sync or merge.\n\n2. A document mapping explosion consumes the heap. See mongot Keeps Re-Syncing.\n\n3. The container memory limit is too low. Even with a correctly sized heap, the JVM non-heap overhead can push past the limit.\n\n4. Poor index definitions, such as too many indexes or expensive definitions, increase memory pressure.\n\n5. A memory leak occurs, which is rare but possible in preview builds.\n\nReview the following metrics:\n\n- `mongot_jvm_memory_used_bytes` increases with memory-intensive queries and index definitions.\n\n- `mongot_jvm_gc_pause_seconds_sum` shows the cumulative time spent in garbage-collection pauses.\n\n- `machine_swap_bytes` stays near zero in a healthy deployment. Swap usage indicates severe memory pressure.\n\nCheck the `mongot` log for the out-of-memory stack trace and the configured heap size:\n\n```sh\ngrep -E 'OutOfMemoryError|Java heap space' mongot.log\nps -ef | grep '[m]ongot' | grep -oE '\\-Xmx[0-9a-zA-Z]+'\n```\n\nFor a container, check the configured memory limit:\n\n```sh\ndocker inspect | grep -i memory\n```\n\n- Increase `-Xmx` if the host has memory headroom.\n\n- In a container, set the memory limit noticeably larger than `-Xmx` to accommodate non-heap overhead. As a starting point, set the container limit to at least the `-Xmx` value plus 30%.\n\n- If the heap is large enough but you still run out of memory, look for indexing patterns that cause the explosion. The `mongot` log identifies the index.\n\n- Reduce the number of indexes or simplify expensive index definitions if they're the source of memory pressure.\n\n- If you suspect a memory leak, capture FTDC and a heap dump for support.\n\n## Initial Sync Is Slow or Stuck\n\nA new index takes a long time to complete its initial sync.\n\n- The index state remains in `INITIAL_SYNC` for a long time.\n\n- In some cases, the replication manager enters `INITIAL_SYNC_BACKOFF` before retrying initial sync.\n\n- `mongot_index_stats_numLuceneMaxDocs` grows only slowly.\n\n- The index isn't queryable while the initial sync runs.\n\n1. The `mongod` source host is underprovisioned and can't feed the initial sync fast enough.\n\n2. Disk, CPU, or memory pressure elsewhere slows the build.\n\n3. A large initial backfill exceeds the current hardware envelope.\n\nWatch `mongot_replication_mongodb_indexManagerState` and `mongot_index_stats_numLuceneMaxDocs` for document growth.\n\nDon't treat `mongot_index_stats_indexing_replicationLagMs` as authoritative during initial sync. This metric doesn't populate meaningfully during initial sync. Instead, review system-health metrics to confirm that the system has sufficient resources.\n\n- Scale the `mongod` source host if it's the bottleneck.\n\n- Add CPU or memory where the system is resource-constrained.\n\n- Re-check disk headroom before you retry a large initial build.\n\n## Indexes Stuck in PENDING or BUILDING status\n\nAn index doesn't progress past the `PENDING` or `BUILDING` state.\n\n- An index remains in `PENDING` or `BUILDING` for more than a few minutes on a collection that isn't large.\n\n- The `mongot` log shows no failures, only a lack of progress.\n\n1. `mongot` isn't making sync progress. See Large Replication Lag.\n\n2. The embedding endpoint is failing for Automated Embedding indexes.\n\n3. The indexing executor pool is saturated by other indexes building concurrently.\n\n4. `mongot` was recently restarted and indexes are catching up.\n\n5. Disk pressure paused a new build or rebuild even though the definition was accepted.\n\nReview `mongot_replication_mongodb_indexManagerState` and `mongot_index_stats_numLuceneMaxDocs` for progress.\n\nIn `mongosh`, check the index status and any error field:\n\n```javascript\ndb..getSearchIndexes()\n```\n\nConfirm that indexing throughput is increasing:\n\n```sh\nrate(mongot_index_stats_indexing_insert_total[5m])\n```\n\nFor Automated Embedding indexes, check whether the embedding retry counters are greater than zero:\n\n```sh\nrate(mongot_indexing_steadyStateChangeStream_rescheduledEmbeddingGetMores_total[5m])\nrate(mongot_initialsync_queue_requeuedEmbeddingInitialSyncs_total[5m])\n```\n\n- If indexing throughput is flat, review the `mongot` log for the index name and any exceptions.\n\n- If embedding retries are greater than zero, fix the embedding path. See Configure `mongot` for MongoDB Vector Search Automated Embedding.\n\n- If the executor pool is saturated, reduce concurrent index builds or scale `mongot`.\n\n- If disk is the blocker, add headroom or move the build to a larger node.\n\n## Queries Return Empty Results\n\nA query returns no results even though matching documents exist.\n\n- You can run `findOne()` on a document that you expect to find in the search index.\n\n- A `$search` query against the same field returns nothing, or fewer results than expected.\n\n1. The index hasn't finished building for the documents you expect to match.\n\n2. Replication lag means `mongot` hasn't received the documents yet.\n\n3. The index definition doesn't cover the field you search on.\n\n4. The query expression is wrong, such as a numeric expression against a field indexed as a string.\n\n5. Indexing failed on the specific documents.\n\nIn `mongosh`, check the index status and confirm whether the index has seen the document:\n\n```javascript\ndb..getSearchIndexes()\n```\n\nThen review `mongot_index_stats_indexing_replicationLagMs` to check for replication lag.\n\n- Wait for the index to reach the ready state.\n\n- Wait for replication lag to clear.\n\n- Adjust the index definition or the query.\n\n- If indexing fails on specific documents, the `mongot` log identifies the failure reason. Fix or filter those documents.\n\n## CPU Saturation or Throttling\n\nSustained CPU pressure degrades query and replication performance.\n\n- Query latency rises under sustained CPU pressure.\n\n- Replication lag increases because query work and indexing work contend for CPU.\n\n- In severe cases, health checks fail and the process restarts.\n\n1. The `mongot` host is underprovisioned for the current mix of query and indexing work.\n\n2. Too much concurrent indexing work competes with query execution.\n\n3. The workload needs load shedding or capacity scaling.\n\nReview the following metrics:\n\n- `mongot_command_searchCommandTotalLatency_seconds_max`\n\n- `mongot_index_stats_indexing_replicationLagMs`\n\n- Host CPU and load metrics, which spike under saturation.\n\nNo explicit log message indicates that the host is CPU-throttled.\n\n- Scale CPU on the `mongot` host.\n\n- Reduce load through load-shedding practices if available.\n\n- Simplify indexing work if replication activity competes with queries."} -{"chunk_id": "6a869dda8824e6129431dfbe-2", "page_id": "6a869dda8824e6129431dfbe", "source_name": "self-managed-search", "product_name": null, "url": "https://mongodb.com/docs/search/self-managed/current/troubleshooting", "title": "Troubleshoot Self-Managed mongot Deployments", "text": "## Disk Pressure or Data Path Nearly Full\n\nThe `mongot` data path runs low on free space.\n\n- Free space on the `mongot` data path falls toward zero.\n\n- Existing indexes accumulate replication lag once disk usage is high.\n\n- A new or rebuilt index may stay in `INITIAL_SYNC` when disk pressure is severe.\n\n- Queries continue to succeed even while replication is paused for disk protection.\n\n1. The host doesn't have enough free space for normal indexing growth.\n\n2. A new or rebuilt index needs more temporary headroom than the current disk can provide.\n\nReview the following metrics:\n\n- `mongot_system_disk_space_data_path_free_bytes` reports free bytes in the data directory.\n\n- `mongot_system_disk_space_data_path_total_bytes` reports total bytes in the data directory.\n\nWatch for replication-pause behavior tied to disk thresholds. Replication stops when disk usage exceeds roughly 90% and resumes after usage drops below roughly 85%. For a new index or rebuild, expect the definition to be accepted but the build to stay stuck if disk pressure is already above the protective threshold.\n\n- Add disk capacity if the host or volume can be safely expanded.\n\n- Delete unneeded indexes to free space if that's operationally acceptable.\n\n- Keep extra headroom before you build or rebuild large indexes. Plan for roughly 125% of the expected steady-state footprint during a rebuild.\n\n- On local instance-store NVMe, don't assume you can resize in place. You generally need a larger machine class and a reindex when you outgrow local instance-store capacity.\n\n- If you use EBS-backed storage, a live resize is more feasible, but NVMe remains the preferred guidance for `mongot` performance. See Storage Class Recommendations for `mongot`.\n\n## Replication Lag From the 16 MB BSON Limit\n\nA change-stream event exceeds the 16 MB BSON limit and stalls replication.\n\n- An index becomes stale or starts rebuilding after a steady-state replication error.\n\n- The `mongot` log shows `change stream payload exceeding 16MB BSON limit`, `BSONObjectTooLarge`, or error code `10334` during `getMore`.\n\n- Your stored documents may appear smaller than 16 MB, but the failure still occurs.\n\n1. The change-stream event exceeds 16 MB because it includes both the document and additional change-stream metadata.\n\n2. Large updates to already-large documents make the change-stream payload bigger than the stored document size alone suggests.\n\nReview the following metrics:\n\n- `mongot_changestream_numSplitEvents_total` counts events that exceeded the 16 MB payload size.\n\n- `mongot_index_stats_indexing_replicationLagMs` reports replication lag for a specific index.\n\nSearch the `mongot` log for the following strings:\n\n- `change stream payload exceeding 16MB BSON limit`\n\n- `BSONObjectTooLarge`\n\n- `Executor error during getMore`\n\n- `code 10334`\n\nIf a document-size check shows the largest documents are below 16 MB, don't rule out this scenario. The change event includes metadata in addition to the document itself.\n\n- Reduce document size and avoid large updates to already-large documents where possible.\n\n- Where possible, replace the document instead of applying a large update to an existing large document.\n\n- If most writes are updates, review the update query to reduce the change-stream event metadata size.\n\n- After you correct the workload, allow the rebuild to complete. If the workload pattern doesn't change, the index may hit the same failure again.\n\n- If the issue recurs after you adjust the workload, capture logs and escalate with the incident details.\n\n## Large Replication Lag\n\nReplication lag grows steadily over time.\n\n- Replication lag grows steadily and may reach many hours or multiple days.\n\n- `mongot` becomes memory-constrained or repeatedly runs out of memory while trying to keep up.\n\n- The host may still serve queries, but query performance can degrade because of replication work and large index footprints.\n\n1. A very large number of indexes increases replication and indexing overhead.\n\n2. Broad use of `dynamic: true` increases field count and index size, which raises memory pressure.\n\n3. Repeated out-of-memory events worsen lag and make metrics appear choppy or incomplete.\n\n4. The bottleneck is on the source database. Underprovisioned `mongod` secondaries with high CPU and cache pressure can prevent change-stream events from emitting fast enough.\n\nReview the following metrics:\n\n- `mongot_index_stats_indexing_replicationLagMs` reports replication lag for a specific index.\n\n- `mongot_indexing_steadyStateChangeStream_getMoresScheduled` reports scheduled `getMore` operations.\n\n- `mongot_replication_mongodb_indexManagerState` identifies which indexes aren't progressing.\n\n- `mongot_jvm_memory_used_bytes` and host CPU and load metrics show resource pressure.\n\nCount the total number of indexes and review whether many rely on `dynamic: true` or index unnecessary high-cardinality fields.\n\n- Scale `mongot` CPU and memory first if the nodes run out of memory or are memory-constrained.\n\n- Reduce the total number of indexes. At very high index counts, adding more search nodes can worsen the load pattern unless you first bring the change-stream load under control.\n\n- Turn off dynamic schema mapping where it isn't required. Prefer `dynamic: false` and explicitly map only the subfields needed for queries.\n\n- Reduce the number of indexed fields, especially high-cardinality fields such as timestamps or user IDs, and remove deep facet mappings that aren't used for faceting.\n\n- If `mongod` secondaries are the bottleneck, scale the core database to improve change-stream throughput.\n\n## TLS Handshake Failures\n\nThe TLS handshake between `mongot` and `mongod` fails.\n\n- The `mongot` log shows `SSL handshake failed`, `Certificate verification failed`, or `bad certificate`.\n\n- The `mongod` log shows similar errors when it tries to reach `mongot`.\n\n1. CA mismatch: both ends don't trust the same CA.\n\n2. The certificate SAN doesn't include the hostname in use.\n\n3. The certificate is expired.\n\n4. TLS mode mismatch: one side requires TLS and the other disabled it.\n\n5. Cipher suite or TLS version mismatch, which is rare.\n\nInspect the certificates that each side serves and verify the chain against your CA:\n\n```sh\nopenssl s_client -connect : -showcerts\nopenssl s_client -connect : -showcerts\nopenssl verify -CAfile \nopenssl x509 -in -text -noout\n```\n\n- Distribute the correct CA to both endpoints.\n\n- Reissue certificates with the correct SAN list.\n\n- Renew expired certificates.\n\n- Reconcile the TLS modes on both sides. See Configure TLS Encryption for `mongot`."} -{"chunk_id": "6a869dda8824e6129431dfbe-3", "page_id": "6a869dda8824e6129431dfbe", "source_name": "self-managed-search", "product_name": null, "url": "https://mongodb.com/docs/search/self-managed/current/troubleshooting", "title": "Troubleshoot Self-Managed mongot Deployments", "text": "## Index Reaches the Lucene Document Limit\n\nA single unpartitioned search index exceeds Lucene's maximum document count and can no longer index new documents.\n\nThis scenario applies to `mongot` deployments that you run directly on Linux or in a Docker container. If you deploy `mongot` with the MongoDB Controllers for Kubernetes Operator, see the MongoDB Controllers for Kubernetes Operator documentation for Kubernetes-specific troubleshooting.\n\nBefore you change the partition count, confirm the following:\n\n- Your `mongot` version supports increasing `numPartitions` for an existing search index.\n\n- You have enough free space to retain the existing index while the replacement index builds. Plan for temporary storage for both index generations.\n\n- You have recorded baseline query latency and replication health for the affected index.\n\n- You know the current index definition and the target `numPartitions` value.\n\nIf the index is approaching the limit but is still indexing normally, start the procedure before the index reaches the limit. If the index has already reached the limit, expect the existing index to remain stale until the replacement index finishes building.\n\n- The index stops making forward progress near the Lucene document-count limit.\n\n- Logs show `java.lang.IllegalArgumentException: number of documents in the index cannot exceed 2147483519`.\n\n- `mongot_index_stats_numLuceneMaxDocs` approaches the hard limit or stops advancing after the limit is reached.\n\n- The index manager reports a failed state.\n\n- Search queries continue to return results, but newly inserted or updated documents are not reflected in the index.\n\n1. A single unpartitioned index exceeded Lucene's maximum document count.\n\n2. Lucene accepts a new index and begins building, but reaches the same limit before the build completed.\n\n3. The index was partitioned with too few partitions for the expected document volume.\n\n4. The index reached the limit before partitioning was planned, leaving insufficient time to complete the replacement build before the existing index became stale.\n\n1. Check the index status from `mongosh`:\n\n ```javascript\n db..getSearchIndexes()\n ```\n\n2. Review `mongot_index_stats_numLuceneMaxDocs` for the affected index.\n\n3. Search the `mongot` log for the following string:\n\n ```text\n java.lang.IllegalArgumentException: number of documents in the index cannot exceed 2147483519\n ```\n\n4. Check the index manager state and confirm whether the index is in `INITIAL_SYNC`, `STEADY_STATE`, or a failed state.\n\n5. Check available space on the `mongot` data path. A partitioning operation builds a replacement index and can temporarily require substantially more storage than the steady-state index.\n\n6. Review query latency and replication lag before the change. Partitioned indexes can introduce query fan-out and affect search performance, particularly for workloads that use facets, sorts, or other operations that coordinate work across partitions.\n\nPartition the index so that each partition remains below Lucene's document-count limit, then rebuild the index with an appropriate `numPartitions` value.\n\nIncreasing `numPartitions` starts an asynchronous index rebuild. Updating the index definition does not make the new partitioned index immediately queryable.\n\n1. **Choose a partition count.** Choose a partition count that keeps the projected document count per partition comfortably below the Lucene limit. Account for future growth, deleted documents that have not yet been purged, rebuild duration, and available disk capacity.\n\n As a planning guideline, begin evaluating partitioning well before the index approaches the Lucene document-count limit of `2147483519` documents. Treat an index near the limit as urgent because the existing index can become stale before the replacement build completes.\n\n Increasing the number of partitions increases index capacity, but it can also increase query latency. Benchmark representative production queries before and after the change.\n\n2. **Update the index definition.** Reissue the `updateSearchIndex` command with the existing index definition and a higher `numPartitions` value. Preserve the rest of the index definition.\n\n The following example increases an index from one partition to four:\n\n ```javascript\n db.runCommand({\n updateSearchIndex: \"myCollection\",\n name: \"mySearchIndex\",\n definition: {\n mappings: {\n dynamic: true\n },\n numPartitions: 4\n }\n })\n ```\n\n The command updates the definition and starts the replacement build. The build runs asynchronously in the background.\n\n3. **Monitor the replacement build.** Monitor the index until the replacement build completes:\n\n - Check the index state with `db..getSearchIndexes()`.\n\n - Confirm that document counts continue to increase during `INITIAL_SYNC` or `BUILDING`.\n\n - Monitor `mongot_index_stats_numLuceneMaxDocs`.\n\n - Monitor disk usage on the `mongot` data path.\n\n - Monitor CPU, memory, storage performance, and replication lag.\n\n - Monitor query latency while the existing index serves production traffic.\n\n A large replacement build can take a substantial amount of time. The new index is not queryable while its initial sync is in progress.\n\n Do not treat an accepted `updateSearchIndex` command as proof that the index is already partitioned. Verify the index state and wait for the replacement build to complete.\n\nAfter the replacement index becomes ready, measure query latency. Partitioning might require `mongot` to coordinate work across multiple partitions, which can increase latency for some workloads, including facet-heavy queries, sorted queries, and queries that combine range or wildcard predicates with sorting. Do not use a single latency estimate for all workloads. Measure the queries that matter to your application, including p50, p95, and p99 latency, before and after the change.\n\n## Automated Embedding Failures\n\nAn Automated Embedding index can't reach the embedding endpoint.\n\n- An Automated Embedding index stays in `PENDING` or `BUILDING`.\n\n- The `mongot` log shows errors against the embedding endpoint.\n\n- The embedding retry counters `mongot_indexing_steadyStateChangeStream_rescheduledEmbeddingGetMores_total` or `mongot_initialsync_queue_requeuedEmbeddingInitialSyncs_total` are greater than zero. Use these counters as indirect indicators and check the log for the actual HTTP error from the embedding endpoint.\n\n1. The model API key is invalid or expired.\n\n2. The network can't reach the embedding endpoint.\n\n3. The embedding provider is rate limiting requests.\n\n4. The embedding provider has an outage.\n\nTest connectivity to the embedding endpoint from the `mongot` host, then check the log:\n\n```sh\ngrep -E 'voyage|embedding' mongot.log\n```\n\n- Replace the model API key and restart `mongot`.\n\n- Open network egress to the embedding endpoint.\n\n- If the provider rate limits requests, raise the limit or reduce indexing concurrency.\n\n- If the provider has an outage, monitor Voyage AI status and consider switching endpoints.\n\nFor the full embedding configuration model, see Configure `mongot` for MongoDB Vector Search Automated Embedding.\n\n## Storage Signals Such as Sustained IOPS or Page Faults\n\nSustained storage IOPS or page faults indicate a storage bottleneck. If you run on local NVMe, look first at memory headroom. If you run on any other storage class, such as a SAN, general-purpose cloud SSD, or SATA SSD, the storage class is the likely root cause and a migration is warranted. See Storage Class Recommendations for `mongot`."} -{"chunk_id": "6a869dda8824e6129431dfbe-4", "page_id": "6a869dda8824e6129431dfbe", "source_name": "self-managed-search", "product_name": null, "url": "https://mongodb.com/docs/search/self-managed/current/troubleshooting", "title": "Troubleshoot Self-Managed mongot Deployments", "text": "## Performance Degrades Without an Obvious Cause\n\nPerformance regresses without a recent deployment change.\n\n- Query latency rose without an obvious deployment change.\n\n- CPU or memory usage climbed.\n\n1. The workload changed, with more or larger queries.\n\n2. A new index now consumes resources.\n\n3. A document mapping explosion consumes the heap.\n\n4. Storage degraded, such as a noisy neighbor, a RAID rebuild, or a cloud-provider issue.\n\n5. A garbage-collection tuning regression occurred after a JVM update.\n\nPivot through the metrics by symptom, such as query latency, heap, executor queue, and storage IOPS. For metric definitions and thresholds, see Metrics Reference for mongot and Recommended Alerts for mongot.\n\nThe resolution depends on the root cause. Options include scaling, capacity planning, or index review, such as dropping unused indexes and refining mappings.\n\n## Capture Diagnostics for Support\n\nWhen you can't resolve an issue locally, capture the following before you open a support case:\n\n1. `mongot` logs that cover the issue time frame plus one hour before. Forward `mongod` logs for the same window.\n\n2. FTDC for the affected `mongot` instance. See mongot Logs and FTDC.\n\n3. Dashboard snapshots of the metrics over the issue time frame.\n\n4. Versions of `mongot` and `mongod`.\n\n5. What changed, such as recent deployments, configuration changes, or traffic patterns.\n\n6. Steps to reproduce the issue, if you can reproduce it on demand."} -{"chunk_id": "6a869dda8824e6129431dfaf-0", "page_id": "6a869dda8824e6129431dfaf", "source_name": "self-managed-search", "product_name": null, "url": "https://mongodb.com/docs/search/self-managed/current/limitations", "title": "Known Limitations for Self-managed mongot", "text": "# Known Limitations for Self-managed mongot\n\nThis page describes limitations and unsupported behavior for self-managed `mongot` deployments.\n\n## Limitations by Category\n\nThe following sections describe known limitations for self-managed `mongot` deployments, grouped by category.\n\n### Deployment, Topology, and Platform Support\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nLimitation\n\n\nApplies to\n\n\nDescription\n\n
\nmongot Standalone Tarball or Container Isn't a Supported Enterprise Production Path\n\n\nEnterprise Advanced.\n\n\nRunning `mongot` from a standalone tarball or container is not a supported production path for Enterprise Advanced. Enterprise production support assumes MCK-managed `mongot`, with the related operational tooling, monitoring integration, and support coverage.\n\n
\natlas-local Docker Image Is Not a Production Deployment Target\n\n\nThe `atlas-local` Docker image.\n\n\nThe `atlas-local` Docker image is a single-container, single-node setup that is intended for local development and testing, and is not suitable for production. For production, use a supported production deployment path.\n\n
\nmongot Isn't Supported on IBM Power (ppc64le) or IBM Z (s390x)\n\n\nAll editions and deployment paths.\n\n\n`mongot` isn't supported on IBM Power (`ppc64le`) or IBM Z (`s390x`). `mongot` is supported only on Linux for `x86_64` and `aarch64`.\n\n
\nWindows and macOS Aren't Supported as Native Deployment Targets\n\n\nAll editions and deployment paths.\n\n\nMongoDB doesn't provide native Windows or macOS `mongot` binaries, because `mongot` is built for Linux. For local development and testing, deploy `mongot` using the `atlas-local` Docker image. For more complex deployments, manage `mongot` using the MongoDB Controllers for Kubernetes Operator or configure the `mongodb-community-search` container image to connect to your MongoDB environment.\n\n
\n\n### Packaging and Installation\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nLimitation\n\n\nApplies to\n\n\nDescription\n\n
\nThe Linux Tarball Doesn't Install a systemd Service\n\n\nCommunity Edition tarball installs.\n\n\nThe Linux tarball doesn't include a `systemd` unit. You can author your own `systemd` unit or use the container image for process lifecycle management.\n\n
\nPackage Manager Installation Isn't Available for Community Edition\n\n\nCommunity Edition.\n\n\n`apt` and `yum` installation isn't available for Community Edition. To install `mongot`, use the tarball or container image.\n\n
\n\n### Authentication and Security\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nLimitation\n\n\nApplies to\n\n\nDescription\n\n
\nX.509 Certificate Rotation Requires a mongot Restart\n\n\nAll deployment paths.\n\n\n`mongot` reads X.509 certificates at startup. To pick up new certificates, you must restart `mongot` after rotating X.509 certificates. To minimize interruptions, schedule certificate rotations during maintenance windows.\n\n
\nSCRAM Password Rotation Requires a mongot Restart\n\n\nAll deployment paths.\n\n\n`mongot` reads SCRAM credentials at startup. To pick up new credentials, you must restart `mongot` after rotating SCRAM credentials. To minimize interruptions, schedule SCRAM credential rotations during maintenance windows.\n\n
\nmongot Doesn't Validate OCSP or CRL Revocation\n\n\nAll deployment paths that use X.509 or TLS authentication.\n\n\n`mongot` doesn't validate X.509 or TLS certificate revocation through OCSP (Online Certificate Status Protocol) or CRLs (Certificate Revocation Lists). To handle revocation, remove the corresponding `$external` user on `mongod`. After removal, the next handshake rejects the revoked certificate.\n\n
\nmongot Doesn't Provide Application-Level Encryption at Rest\n\n\nAll deployment paths.\n\n\n`mongot` doesn't provide native application-level encryption at rest. Instead, you can encrypt the underlying filesystem or block device, for example with LUKS or `dm-crypt` on Linux, cloud-provider-managed encrypted volumes, or KMS-backed disk encryption.\n\n
\nFIPS-Validated TLS Mode Is Not Supported\n\n\nAll deployment paths.\n\n\n`mongot` doesn't support running its TLS stack in a FIPS-validated cryptographic mode.\n\n
\n\n### Observability\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nLimitation\n\n\nApplies to\n\n\nDescription\n\n
\nAtlas Search Metrics UI Isn't Available for Self-Managed Deployments\n\n\nAll self-managed deployments.\n\n\nThe MongoDB Search Metrics UI isn't available with self-managed `mongot`. Use Prometheus and Grafana, or another monitoring stack, with the `mongot` `/metrics` endpoint. To learn more, see Monitoring Tool Integrations.\n\n
\nOps Manager Visibility Not Comprehensive for `mongot`\n\n\nEnterprise Advanced deployments that use Ops Manager and MongoDB Controllers for Kubernetes Operator.\n\n\nIn Enterprise Advanced, Ops Manager ingests and displays a limited set of metrics through an MongoDB Controllers for Kubernetes Operator-deployed OpenTelemetry pipeline. These metrics are curated for support triage and health visibility, but not for deep diagnostics.\n\n
"} -{"chunk_id": "6a869dda8824e6129431dfaf-1", "page_id": "6a869dda8824e6129431dfaf", "source_name": "self-managed-search", "product_name": null, "url": "https://mongodb.com/docs/search/self-managed/current/limitations", "title": "Known Limitations for Self-managed mongot", "text": "### Operations and Upgrades\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nLimitation\n\n\nApplies to\n\n\nDescription\n\n
\nOne mongot Instance Can't Serve Multiple mongod Deployments\n\n\nAll deployment paths.\n\n\nA single `mongot` instance can't be shared across multiple unrelated MongoDB deployments because a `mongot` instance is bound to exactly one replica set, or to one shard in a sharded cluster. To serve queries for multiple MongoDB deployments, deploy a separate `mongot` instance for each replica set or shard.\n\n
\nMajor-Version Downgrades Require Re-sync\n\n\nAll deployment paths.\n\n\nDowngrading `mongot` across major versions requires a re-sync between `mongod` and `mongot` because major versions aren't rollback-safe.\n\n
\nmongot Upgrades Require a Process Restart\n\n\nAll deployment paths.\n\n\n`mongot` upgrades require a process restart. To minimize interruptions, schedule maintenance windows or use a rolling restart pattern with multiple `mongot` instances under MongoDB Controllers for Kubernetes Operator.\n\n
\nmongot Configuration Changes Require a Restart\n\n\nAll deployment paths.\n\n\n`mongot` reads its configuration at startup. To apply configuration changes, you must restart `mongot` after editing the `mongot` configuration file.\n\n
\n\n## Atlas Versus Self-Managed Feature Comparison\n\nThe following sections compare support for MongoDB Search and MongoDB Vector Search features between Atlas and self-managed `mongot`. Use the tables in this section to compare options for a migration or hybrid deployment.\n\n### Search and Vector Search Behavior\n\nSearch and Vector Search share the same search engine on Atlas and self-managed `mongot`, so query behavior, scoring, and index semantics are generally consistent across platforms.\n\nThe following table compares which Search and Vector Search features are available between Atlas-managed and self-managed `mongot`.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nSearch and Vector Search Feature\n\n\nFeature Availability\n\n
\n`$search`, `$searchMeta`, and `$vectorSearch` aggregation stages\n\n\nSame on Atlas and self-managed\n\n
\nIndex definition syntax\n\n\n`nestedRoot` syntax not supported on self-managed `mongot`. To learn more, see How to Index Fields for Vector Search.\n\n
\n`createSearchIndex`, `dropSearchIndex`, `updateSearchIndex`, and `getSearchIndexes` helper methods\n\n\nSame on Atlas and self-managed\n\n
\n`$listSearchIndexes` aggregation stage\n\n\nOutput for self-managed `mongot` differs from Atlas Search. See `$listSearchIndexes` for the Atlas Search output shape. Self-managed `mongot` output differs in the following fields:\n\n- No top-level `type` field\n\n- `synonymMappingStatusDetail` is a flat list of status objects, not a nested document\n\n
\nLucene-based scoring and ranking\n\n\nSame on Atlas and self-managed\n\n
\nSynonyms, analyzers, and custom mappings\n\n\nSame on Atlas and self-managed\n\n
\nVector quantization options\n\n\nSame on Atlas and self-managed\n\n
\n`$rerank`\n\n\nAvailable only on Atlas.\n\n
\nAutomated Embedding through Voyage AI\n\n\nPreview on both platforms. To learn which Automated Embedding features are supported for self-managed `mongot`, see Automated Embedding.\n\n
\n#### Automated Embedding\n\nThe following table compares Automated Embedding feature support between Atlas and self-managed `mongot`. To learn more about automated embedding, see Automated Embedding Overview.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nAutomated Embedding Feature\n\n\nAtlas\n\n\nSelf-Managed `mongot`\n\n
\nVoyage AI integration\n\n\nAvailable with the same Voyage AI models and options as self-managed `mongot`.\n\n\nAvailable in Preview with the same Voyage AI models and options as Atlas.\n\n
\nRate-limit visibility\n\n\nAtlas exposes RPM and TPM limits in the UI.\n\n\nRate-limit visibility isn't surfaced in the product. Limits are enforced on the Voyage AI side.\n\n
\nBilling path\n\n\nAtlas can bill embeddings through the MongoDB proxy endpoint.\n\n\nBilling depends on whether you use the MongoDB proxy endpoint or connect directly to Voyage AI.\n\n
"} -{"chunk_id": "6a869dda8824e6129431dfaf-2", "page_id": "6a869dda8824e6129431dfaf", "source_name": "self-managed-search", "product_name": null, "url": "https://mongodb.com/docs/search/self-managed/current/limitations", "title": "Known Limitations for Self-managed mongot", "text": "### Deployment and Lifecycle Management\n\nThe following table compares how Atlas and self-managed deployments handle operational aspects of deploying and managing the lifecycle of `mongot`.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nOperational Aspect\n\n\nAtlas\n\n\nSelf-managed `mongot`\n\n
\nProvisioning\n\n\nMongoDB provisions and runs `mongot`.\n\n\nYou provision `mongot` by using a tarball, container, MongoDB Controllers for Kubernetes Operator, or `atlas-local`.\n\n
\n`mongot` version visibility\n\n\nAtlas exposes release timing rather than direct `mongot` version strings.\n\n\n`mongot` packages are versioned with explicit `MAJOR.MINOR.PATCH` versions.\n\n
\nUpgrades\n\n\nMongoDB performs Atlas upgrades on its own cadence.\n\n\nUpgrades are entirely self-managed.\n\n
\nSecurity patching\n\n\nMongoDB applies patches on Atlas.\n\n\nSecurity patching requires self-managed upgrades.\n\n
\nMulti-instance scaling\n\n\nMongoDB Search Nodes handle scale-out within the managed service.\n\n\nFor multiple search nodes or sharded topologies, use MongoDB Controllers for Kubernetes Operator or manage the topology yourself.\n\n
\nSharded clusters\n\n\nSupported in Atlas.\n\n\nSupported only with the MongoDB Controllers for Kubernetes Operator for Enterprise Advanced. The MongoDB Controllers for Kubernetes Operator doesn't support sharded architectures with Community Edition.\n\n
\n\n### Monitoring and Observability\n\nThe following table compares which monitoring tools and observability options are available for Atlas and self-managed `mongot`.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nMonitoring and Observability Option\n\n\nAtlas\n\n\nSelf-managed `mongot`\n\n
\nMongoDB Search Metrics UI\n\n\nAvailable in the Atlas UI.\n\n\nNot available. To learn more, see Observability.\n\n
\nMongoDB-managed alerts\n\n\nCurated alerts with default thresholds.\n\n\nYou define alerting yourself. To learn more, see Recommended Alerts for mongot.\n\n
\nFTDC retention\n\n\nManaged by MongoDB.\n\n\nYou manage rotation and retention.\n\n
\nLog retention\n\n\nManaged by MongoDB.\n\n\nYou forward and retain logs.\n\n
\n`mongot`-metric dashboards\n\n\nAvailable in the Atlas UI.\n\n\nNot provided in a UI component. To learn how to build dashboards from `mongot` metrics, see Metrics Reference for mongot.\n\n
\nOps Manager `mongot` visibility\n\n\nNot available in Atlas.\n\n\nIn Enterprise Advanced, Ops Manager exposes curated `mongot` metrics through an MongoDB Controllers for Kubernetes Operator-deployed OpenTelemetry pipeline. To learn more, see Observability.\n\n
\n\n### Reliability and Availability\n\nThe following table compares how Atlas and self-managed deployments handle reliability and availability capabilities for `mongod` and `mongot`.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nReliability and Availability Capability\n\n\nAtlas-managed Deployment\n\n\nSelf-managed Deployment\n\n
\n`mongot` instance availability\n\n\nAtlas manages recovery behavior.\n\n\nYou are responsible for supervision and recovery. Use MongoDB Controllers for Kubernetes Operator-managed replicas or your own process supervision.\n\n
\nBackup and restore\n\n\nAtlas Cloud Backup manages `mongod` snapshots. Search indexes in `mongot` can be rebuilt from data restored from MongoDB database snapshots.\n\n\nYou are responsible for backing up `mongod`. Search indexes in `mongot` can be rebuilt from data restored from MongoDB database snapshots.\n\n
\nDisaster recovery\n\n\nAtlas provides regional and cloud failover patterns.\n\n\nYou design the disaster recovery topology yourself.\n\n
\nCapacity scaling\n\n\nAtlas provides managed Search Node scaling.\n\n\nYou size capacity up front and rescale by changing `mongot` resources and restarting as needed.\n\n
\n\n### Security\n\nThe following table compares how Atlas-managed deployments and self-managed deployments handle security for `mongod` and `mongot`.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nSecurity Feature\n\n\nAtlas-managed Deployment\n\n\nSelf-managed Deployment\n\n
\nAuthentication between `mongod` and `mongot`\n\n\nManaged internally by Atlas.\n\n\nYou configure SCRAM or X.509 authentication.\n\n
\nTLS for `mongod` to `mongot`\n\n\nAlways on and managed by Atlas.\n\n\nYou configure TLS yourself.\n\n
\nEncryption at rest\n\n\nAtlas provides managed encryption-at-rest options, including KMS integrations.\n\n\n`mongot` doesn't provide native encryption at rest. To learn more, see Authentication and Security.\n\n
"} -{"chunk_id": "6a869dda8824e6129431dfb8-0", "page_id": "6a869dda8824e6129431dfb8", "source_name": "self-managed-search", "product_name": null, "url": "https://mongodb.com/docs/search/self-managed/current/resource-planning-sizing/introduction", "title": "Introduction to mongot Deployment Sizing", "text": "# Introduction to mongot Deployment Sizing\n\nThis guide helps you choose the right starting configuration for your `mongot` deployment. Follow these steps to determine an effective starting configuration and refine it for your specific needs.\n\n## Get Started\n\n### Identify your primary workload class\n\nFirst, determine whether your application fits into the **High-CPU** or **Low-CPU** workload class. This is the most important factor in selecting the right resources.\n\nChoose this class for general-purpose full-text search where query performance is critical and CPU-intensive. These nodes typically have a 2:1 RAM-to-CPU ratio.\n\nThis class is ideal for vector search applications, especially with low data volumes, where memory is prioritized over raw CPU power. These nodes usually have an 8:1 RAM-to-CPU ratio.\n\nIf you want to get started quickly or have a general use case, a small or medium High-CPU node is typically a balanced and effective starting point.\n\n### Select a starting size\n\nAfter you identify your workload class, use the following table to find a recommended starting CPU size based on your primary scaling dimension. These recommendations are a starting point. Adjust your CPU size based on your actual workload patterns.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nUse Case\n\n\nClass\n\n\nScaling dimension\n\n\nSize\n\n
\nDefault\n\n\nHigh-CPU\n\n\nGeneral purpose, Getting started\n\n\nSmall or Medium\n\n
\nVector Search, low data volumes\n\n\nLow CPU\n\n\n<= 10GB of vectors10GB - 50GB of vectors>= 50GB of vectors\n\n\nSmallMediumLarge\n\n
\nGeneral purpose full-text search with low data volumes\n\n\nHigh CPU\n\n\n20 - 40 QPS (queries per second), light indexing80 - 160 QPS320 - 480 QPS, heavy indexing\n\n\nSmallMediumLarge\n\n
For example, if you expect to handle 100 queries per second (QPS) for a full-text search application, a **Medium High-CPU** node is a suitable choice.\n\n#### Disk Sizing Guideline\n\nDue to index mapping, a collection's size and the resulting search index's size are not always correlated. For example, if your documents have 100 fields but your search index is configured for only 5 of those fields, the index will be much smaller than the collection. Conversely, mapping all fields or using features like autocomplete can increase index size.\n\n#### Estimate Index Size\n\nTo estimate the total index size based on your collection size, perform these steps:\n\n1. Insert 1-2 GB of data or create a small collection using `$out`.\n\n2. Create a search index with your chosen field mappings.\n\n3. Observe the resulting index size and index-to-collection size ratio. If you already use Atlas Search, you can find the index size in cluster metrics or on the index list page.\n\nUse the index-to-collection size ratio to estimate the total index size based on your expected collection size. For example, if a 1GB collection yields a 250MB index (a 0.25:1 ratio), a 12GB collection would likely result in an approximately 3GB index.\n\n### Refine, deploy, and monitor\n\nSizing is an iterative process. After you deploy your initial configuration, monitor its performance and adjust accordingly.\n\n1. **Refine your estimate**: Before deploying, review the Resource Allocation considerations. Carefully monitor factors that can impact resource needs, such as your indexing strategy (for example, nGram tokenization) or query complexity.\n\n For disk sizing, remember that index size is not directly correlated to collection size.\n\n2. **Deploy**: For a production-ready application, using dedicated Search Nodes is highly recommended to ensure resource isolation and high availability.\n\n3. **Monitor key metrics**: After launch, monitor performance to see if you need to scale up or down. For example:\n\n - **CPU**: If CPU usage is consistently above 80%, you likely need to scale up.\n\n - **Memory**: If `Search Page Faults` are consistently over 1000 per second, your system needs more memory. To measure Search Page Faults, use the `mongot_system_process_majorPageFaults_operations` metric.\n\n - **Disk:** Ensure you have enough free disk space to handle index rebuilds. Generally you should allocate double the disk space your index requires. This extra space allows indexes to be rebuilt when needed. `mongot` becomes read-only when disk utilization reaches 90%.\n\n## Learn More\n\n- mongot Sizing Quickstart\n\n- mongot Deployment Architecture Patterns\n\n- Resource Allocation Considerations for mongot Deployments\n\n- Hardware Considerations for mongot Deployments"} -{"chunk_id": "6a869dda8824e6129431dfbc-0", "page_id": "6a869dda8824e6129431dfbc", "source_name": "self-managed-search", "product_name": null, "url": "https://mongodb.com/docs/search/self-managed/current/security/authentication-and-authorization", "title": "Configure Authentication and Authorization for `mongot`", "text": "# Configure Authentication and Authorization for `mongot`\n\nUse this page to configure authentication and authorization for your `mongot` and MongoDB Community Edition deployments. For information on using `mongot` with MongoDB Controllers for Kubernetes Operator, see MongoDB Search and Vector Search with Kubernetes.\n\n`mongot` communicates over two distinct channels, each of which requires its own security configuration:\n\n- **Sync source** (`syncSource.replicaSet`, `syncSource.router`): `mongot`'s outbound connection to your MongoDB deployment for replication. You configure an authentication mechanism here so that `mongot` can authenticate to `mongod` or `mongos`.\n\n- **gRPC server** (`server.grpc`): The inbound channel over which `mongod` connects to `mongot` for search queries and index management commands. `mongod` and `mongot` authenticate to each other through mTLS.\n\nThe health check (`healthCheck`) and metrics (`metrics`) endpoints don't support TLS or authentication. Restrict access to these ports at the network layer.\n\n## Considerations\n\nBefore you configure authentication, review the following points:\n\n- You must configure exactly one authentication mechanism for the sync source: either **SCRAM** or **X.509**. The two mechanisms are mutually exclusive for each connection block.\n\n- For sharded clusters, you must specify both `syncSource.replicaSet` and `syncSource.router` in your `mongot` configuration file, and configure authentication on each connection independently. `syncSource.router` is not implied by `syncSource.replicaSet`, so you must configure it explicitly. Each shard requires its own dedicated `mongot` instance.\n\n - `syncSource.replicaSet` maps the `mongot` instance to its shard's replica set.\n\n - `syncSource.router` provides the `mongos` connection for cluster-wide coordination.\n\n- The `searchCoordinator` built-in role must exist on your MongoDB deployment before `mongot` can authenticate. This role is available in MongoDB 8.2 and later.\n\n## Before You Begin\n\nAdd the following `setParameter` options to your `mongod` configuration file, then restart `mongod`:\n\n```yaml\nsetParameter:\n mongotHost: :\n searchIndexManagementHostAndPort: :\n skipAuthenticationToSearchIndexManagementServer: false\n useGrpcForSearch: true\n```\n\nThe `setParameter` option sets server parameters that tell the `mongod` server how to locate and communicate with `mongot`. You must set these parameters before `mongot` can connect to your deployment.\n\nTo learn more about the `mongod` configuration file, see Self-Managed Configuration File Options.\n\n## Configure Sync Source Authentication\n\nConfigure one of the following authentication mechanisms on the sync source connection so that `mongot` can authenticate to your MongoDB deployment.\n\n\n\n\n\nSCRAM (Salted Challenge Response Authentication Mechanism) authenticates `mongot` to your MongoDB deployment with a username and password.\n\nTo configure SCRAM for `mongot`, complete the following steps:\n\n### Create the `mongot` user in the `admin` database.\n\nCreate the user on your MongoDB replica set with the `searchCoordinator` role.\n\nRun the following command in `mongosh`:\n\n```javascript\nuse admin\ndb.createUser({\n user: \"mongotUser\",\n pwd: \"\",\n roles: [ { role: \"searchCoordinator\", db: \"admin\" } ]\n})\n```\n\n### Create a password file on the `mongot` host.\n\nReplace `` with your password, then run the command for your operating system to create the password file. The file must **not** contain a trailing newline.\n\nFor Linux or macOS:\n\n```bash\necho -n \"\" > /etc/mongot/secrets/passwordFile\nchmod 400 /etc/mongot/secrets/passwordFile\n```\n\nFor Windows Command Prompt:\n\n```bat\necho|set /p=\"\" > passwordFile\n```\n\nFor Windows PowerShell:\n\n```powershell\n[System.IO.File]::WriteAllText(\"passwordFile\", \"\")\n```\n\n### Add the `scramAuth` block to your `mongot` configuration.\n\nAdd the `scramAuth` block under `syncSource.replicaSet`. For sharded clusters, also add the same block under `syncSource.router`. List multiple hosts in `hostAndPort` so `mongot` can still discover the replica set if one host is unavailable:\n\n```yaml\nsyncSource:\n replicaSet:\n hostAndPort:\n - \":27017\"\n - \":27017\"\n scramAuth:\n username: mongotUser\n authSource: admin\n passwordFile: /etc/mongot/secrets/passwordFile\n tls:\n enabled: false\n```\n\nFor sharded clusters, configure `scramAuth` under both `syncSource.replicaSet` and `syncSource.router`. `syncSource.replicaSet` authenticates `mongot` to the shard's replica set, and `syncSource.router` authenticates `mongot` to `mongos` for cluster-wide coordination. You can use the same credentials for both connections, or separate credentials if you administer them independently:\n\n```yaml\nsyncSource:\n replicaSet:\n hostAndPort:\n - \":27017\"\n - \":27017\"\n scramAuth:\n username: mongotShardUser\n authSource: admin\n passwordFile: /etc/mongot/secrets/shard-passwordFile\n tls:\n enabled: false\n router:\n hostAndPort:\n - \":27017\"\n - \":27017\"\n scramAuth:\n username: mongotRouterUser\n authSource: admin\n passwordFile: /etc/mongot/secrets/router-passwordFile\n tls:\n enabled: false\n```\n\nFor more information on the `mongot` configuration file, see Configure mongot.\n\n### Enable TLS for the sync source connection if needed.\n\nIf your MongoDB deployment has TLS enabled, set `tls.enabled` to `true` and provide the following fields to your `mongot` configuration file as needed:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nField\n\n\nDescription\n\n
\n`caFile`\n\n\nThe PEM file that contains one or more X.509 CA certificates that verify `mongod`'s server certificate. If you omit this field, `mongot` uses the JVM default trust store.\n\n
\n`tlsCertificateKeyFile`\n\n\nThe PEM file that contains both the client's X.509 certificate and its private key. Required only if `mongod` verifies client certificates.\n\n
\n`tlsCertificateKeyFilePasswordFile`\n\n\nThe password that decrypts the client certificate key. Required only if `tlsCertificateKeyFile` is password-protected.\n\n
\n\n
\n\n\n\nX.509 authentication allows `mongot` to authenticate to your MongoDB deployment with a TLS client certificate instead of a username and password. TLS is always enabled when you use X.509.\n\nTo configure X.509 for `mongot`, complete the following steps:\n\n### Create the `mongot` user in the `$external` database.\n\nCreate the user on your MongoDB replica set with the `searchCoordinator` role. The username must exactly match the subject of the client certificate.\n\nRun the following command in `mongosh`:\n\n```javascript\nuse $external\ndb.createUser({\n user: \"CN=mongot,OU=...\",\n roles: [ { role: \"searchCoordinator\", db: \"admin\" } ]\n})\n```"} -{"chunk_id": "6a869dda8824e6129431dfbc-1", "page_id": "6a869dda8824e6129431dfbc", "source_name": "self-managed-search", "product_name": null, "url": "https://mongodb.com/docs/search/self-managed/current/security/authentication-and-authorization", "title": "Configure Authentication and Authorization for `mongot`", "text": "### Add the `x509` block to your `mongot` configuration.\n\nAdd the `x509` block under `syncSource.replicaSet`. For sharded clusters, add the same block under `syncSource.router`.\n\nIn the `x509` block, `tlsCertificateKeyFile` and `caFile` are required. List multiple hosts in `hostAndPort` so `mongot` can still discover the replica set if one host is unavailable:\n\n```yaml\nsyncSource:\n replicaSet:\n hostAndPort:\n - \":27017\"\n - \":27017\"\n x509:\n tlsCertificateKeyFile: /etc/mongot/tls/mongot-client.pem\n caFile: /etc/mongot/tls/ca.pem\n # tlsCertificateKeyFilePasswordFile: /etc/mongot/secrets/cert-key-password\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nField\n\n\nDescription\n\n
\n`tlsCertificateKeyFile`\n\n\nRequired. The PEM file that contains both the X.509 certificate and its private key.\n\n
\n`caFile`\n\n\nRequired. The PEM file that contains one or more X.509 CA certificates that verify `mongod`'s certificate.\n\n
\n`tlsCertificateKeyFilePasswordFile`\n\n\nOptional. The file that contains the password that decrypts the private key in `tlsCertificateKeyFile`, if the key is encrypted.\n\n
For sharded clusters, configure `x509` under both `syncSource.replicaSet` and `syncSource.router`. Use the same field structure for both connections, and provide the `mongos` endpoints in `syncSource.router.hostAndPort`:\n\n```yaml\nsyncSource:\n replicaSet:\n hostAndPort:\n - \":27017\"\n - \":27017\"\n x509:\n tlsCertificateKeyFile: /etc/mongot/tls/mongot-client.pem\n caFile: /etc/mongot/tls/ca.pem\n # tlsCertificateKeyFilePasswordFile: /etc/mongot/secrets/cert-key-password\n router:\n hostAndPort:\n - \":27017\"\n - \":27017\"\n x509:\n tlsCertificateKeyFile: /etc/mongot/tls/mongot-client.pem\n caFile: /etc/mongot/tls/ca.pem\n # tlsCertificateKeyFilePasswordFile: /etc/mongot/secrets/cert-key-password\n```\n\n
\n\n
\n\n## Configure gRPC Server Transport Security\n\nThe gRPC server is the inbound channel over which `mongod` connects to `mongot` for search queries and index management commands. You secure this channel at the transport layer with TLS. To mutually authenticate `mongod` and `mongot`, use mTLS.\n\nYou configure the TLS mode with the `server.grpc.tls.mode` option on `mongot` and the `searchTLSMode` parameter on `mongod`. When you don't set `searchTLSMode`, `mongod` inherits the TLS mode from `net.tls.mode` for its connection to `mongot` because `searchTLSMode` defaults to `globalTLS`.\n\nYou can configure one of the following TLS modes in the `mongot` configuration file:\n\n### Disabled\n\nNo TLS. Use this mode only for deployments where `mongod` and `mongot` run on the same host:\n\n```yaml\nserver:\n grpc:\n address: \"localhost:27028\"\n tls:\n mode: \"disabled\"\n```\n\n### TLS\n\n`mongot` presents a server certificate, and `mongod` verifies it before establishing the connection. This mode requires `certificateKeyFile`:\n\n```yaml\nserver:\n grpc:\n address: \"0.0.0.0:27028\"\n tls:\n mode: \"tls\"\n certificateKeyFile: /etc/mongot/tls/mongot-server.pem\n # certificateKeyFilePasswordFile: /etc/mongot/secrets/server-key-password\n```\n\n### Mutual TLS (mTLS)\n\nBoth `mongot` and `mongod` present and verify each other's certificates. This mode requires `certificateKeyFile` and `caFile`. When you use `mtls`, you must also configure `mongod` with the corresponding TLS settings for its connection to `mongot`:\n\n```yaml\nserver:\n grpc:\n address: \"0.0.0.0:27028\"\n tls:\n mode: \"mtls\"\n certificateKeyFile: /etc/mongot/tls/mongot-server.pem\n caFile: /etc/mongot/tls/ca.pem\n```\n\n## Learn More\n\n- Configure mongot\n\n- Known Limitations for Self-managed mongot\n\n- Monitor mongot Deployment"} -{"chunk_id": "68a95c2c5e79d242619df768-0", "page_id": "68a95c2c5e79d242619df768", "source_name": "spark-connector", "product_name": "MongoDB Spark Connector", "url": "https://mongodb.com/docs/spark-connector/current/release-notes", "title": "Release Notes", "text": "# Release Notes\n\nLearn what's new in:\n\n- Version 11.1\n\n- Version 11.0\n\n- Version 10.7\n\n- Version 10.6\n\n- Version 10.5\n\n- Version 10.4\n\n- Version 10.3\n\n- Version 10.2\n\n- Version 10.1.1\n\n- Version 10.1.0\n\n- Version 10.0\n\n## MongoDB Connector for Spark 11.1\n\nThe 11.1 connector release includes the following changes and new features:\n\n- Adds the `change.stream.micro.batch.max.rows` read configuration property, which limits the number of change stream events consumed in each micro-batch. When you set this option, the connector limits micro-batches by event count rather than by elapsed time between batches. Rate limiting requires the `change.stream.micro.batch.max.partition.count` configuration property to be set to `1` and write access to the sidecar collection in the source database.\n\n- Adds the `change.stream.micro.batch.max.rows.offset.collection` read configuration property, which specifies the sidecar collection used to persist resume tokens when the `change.stream.micro.batch.max.rows` property is set. Defaults to `__spark_resume_tokens`.\n\n## MongoDB Connector for Spark 11.0\n\nThe 11.0 connector release adds support for Spark 4.0 and later. Spark 4.0 requires Scala 2.13. To learn more about Spark 4.0, see the Spark documentation.\n\n## MongoDB Connector for Spark 10.7\n\nThe 10.7 connector release includes the following changes and new features:\n\nIf you are using Spark 3.1.x, you must upgrade to Apache Spark 3.2 or later to use Spark Connector version 10.7. The Spark Connector now only supports Apache Spark versions 3.2 through 3.5.\n\n- Adds the `change.stream.micro.batch.max.rows` and `change.stream.micro.batch.max.rows.offset.collection` read configuration properties introduced in v11.1. These properties enable rate limiting for change stream micro-batches. To learn more, see the v11.1 release notes.\n\n## MongoDB Connector for Spark 10.6\n\nThe 10.6 connector release includes the following changes and new features:\n\n- Adds support for the `fullDocumentBeforeChange` option in change stream read configurations, which allows you to specify whether to include the full document before the change event in the change stream output. To learn more about this option, see the Change Stream Configuration section of the Streaming Read Configuration Options guide.\n\n- Adds the `truncateMode` write configuration option, which specifies how to truncate a collection when performing an overwrite. To learn more about this option, see the Streaming Write Configuration Options or the Batch Write Configuration Options guide for your relevant mode.\n\n- Adds the `ignoreDuplicatesOnInsert` write configuration option, which determines whether to ignore duplicate key errors when performing unordered insert operations. You can use this option in both batch and streaming write configurations. To learn more about this option, see the Batch Write Configuration Options and Streaming Write Configuration Options guides.\n\n## MongoDB Connector for Spark 10.5\n\nThe 10.5 connector release includes the following changes and new features:\n\n- Adds support for using Atlas Data Federation with the Spark Connector in the `SamplePartitioner`, `PaginateBySizePartitioner` and `AutoBucketPartitioner` batch reading configurations.\n\n For more information about batch configuration, see the Batch Read Configuration Options page.\n\n- Changes the default batch read partitioner configuration to be `AutoBucketPartitioner`\n\n## MongoDB Connector for Spark 10.4\n\nThe 10.4 connector release includes the following changes and new features:\n\n- Updates the Java Sync Driver version to v5.1.x.\n\n## MongoDB Connector for Spark 10.3\n\nThe 10.3 connector release includes the following new features:\n\n- Added support for Spark v3.3, v3.4, and v3.5.\n\n- Added support for reading multiple collections when using micro-batch or continuous streaming modes.\n\n Support for reading multiple collections introduces the following breaking changes:\n\n - If the name of a collection used in your `collection` configuration option contains a comma, the Spark Connector treats it as two different collections. To avoid this, you must escape the comma by preceding it with a backslash (\\).\n\n - If the name of a collection used in your `collection` configuration option is \"*\", the Spark Connector interprets it as a specification to scan all collections. To avoid this, you must escape the asterisk by preceding it with a backslash (\\).\n\n - If the name of a collection used in your `collection` configuration option contains a backslash (\\), the Spark Connector treats the backslash as an escape character, which might change how it interprets the value. To avoid this, you must escape the backslash by preceding it with another backslash.\n\n To learn more about scanning multiple collections, see the collection configuration property description.\n\n## MongoDB Connector for Spark 10.2\n\nThe 10.2 connector release includes the following new features:\n\n- Added the `ignoreNullValues` write-configuration property, which enables you to control whether the connector ignores null values. In previous versions, the connector always wrote `null` values to MongoDB.\n\n- Added options for the `convertJson` write-configuration property.\n\n- Added the `change.stream.micro.batch.max.partition.count` read-configuration property, which allows you to divide micro-batches into multiple partitions for parallel processing.\n\n- Improved change stream schema inference when using the `change.stream.publish.full.document.only` read-configuration property.\n\n- Added the `change.stream.startup.mode` read-configuration property, which specifies how the connector processes change events when no offset is available.\n\n- Support for adding a comment to operations.\n\n## MongoDB Connector for Spark 10.1.1\n\n- Corrected a bug in which aggregations including the `$collStats` pipeline stage did not return a count field for Time Series collections.\n\n## MongoDB Connector for Spark 10.1.0\n\n- Support for Scala 2.13.\n\n- Support for micro-batch mode with Spark Structured Streaming.\n\n- Support for BSON data types.\n\n- Improved partitioner support for empty collections.\n\n- Option to disable automatic upsert on write operations.\n\n- Improved schema inference for empty arrays.\n\n- Support for null values in arrays and lists. The Connector now writes these values to MongoDB instead of throwing an exception.\n\nSee this post on the MongoDB blog for more information.\n\n## MongoDB Connector for Spark 10.0.0\n\n- Support for Spark Structured Streaming."} -{"chunk_id": "68a95c2c5e79d242619df76b-0", "page_id": "68a95c2c5e79d242619df76b", "source_name": "spark-connector", "product_name": "MongoDB Spark Connector", "url": "https://mongodb.com/docs/spark-connector/current/batch-mode/batch-write-config", "title": "Batch Write Configuration Options", "text": "# Batch Write Configuration Options\n\n## Overview\n\nYou can configure the following properties when writing data to MongoDB in batch mode.\n\nIf you use `SparkConf` to set the connector's write configurations, prefix `spark.mongodb.write.` to each property.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nProperty name\n\n\nDescription\n\n
\n`connection.uri`\n\n\n**Required.**The connection string configuration key.**Default:** `mongodb://localhost:27017/`\n\n
\n`database`\n\n\n**Required.**The database name configuration.\n\n
\n`collection`\n\n\n**Required.**The collection name configuration.\n\n
\n`comment`\n\n\nThe comment to append to the write operation. Comments appear in the output of the Database Profiler.**Default:** None\n\n
\n`mongoClientFactory`\n\n\nMongoClientFactory configuration key.You can specify a custom implementation that must implement the `com.mongodb.spark.sql.connector.connection.MongoClientFactory` interface.**Default:** `com.mongodb.spark.sql.connector.connection.DefaultMongoClientFactory`\n\n
\n`convertJson`\n\n\nSpecifies if the connector parses string values and converts extended JSON into BSON.This setting accepts the following values:- `any`: The connector converts all JSON values to BSON.\n\n - `\"{a: 1}\"` becomes `{a: 1}`.\n\n - `\"[1, 2, 3]\"` becomes `[1, 2, 3]`.\n\n - `\"true\"` becomes `true`.\n\n - `\"01234\"` becomes `1234`.\n\n - `\"{a:b:c}\"` doesn't change.\n\n- `objectOrArrayOnly`: The connector converts only JSON objects and arrays to BSON.\n\n - `\"{a: 1}\"` becomes `{a: 1}`.\n\n - `\"[1, 2, 3]\"` becomes `[1, 2, 3]`.\n\n - `\"true\"` doesn't change.\n\n - `\"01234\"` doesn't change.\n\n - `\"{a:b:c}\"` doesn't change.\n\n- `false`: The connector leaves all values as strings.\n\n**Default:** `false`\n\n
\n`idFieldList`\n\n\nSpecifies a field or list of fields by which to split the collection data. To specify more than one field, separate them using a comma as shown in the following example:```none\n\"fieldName1,fieldName2\"\n```\n\n**Default:** `_id`\n\n
\n`ignoreNullValues`\n\n\nWhen `true`, the connector ignores any `null` values when writing, including `null` values in arrays and nested documents.**Default:** `false`\n\n
\n`maxBatchSize`\n\n\nSpecifies the maximum number of operations to batch in bulk operations.**Default:** `512`\n\n
\n`operationType`\n\n\nSpecifies the type of write operation to perform. You can set this to one of the following values:- `insert`: Insert the data.\n\n- `replace`: Replace an existing document that matches the `idFieldList` value with the new data. If no match exists, the value of `upsertDocument` indicates whether the connector inserts a new document.\n\n- `update`: Update an existing document that matches the `idFieldList` value with the new data. If no match exists, the value of `upsertDocument` indicates whether the connector inserts a new document.\n\n**Default:** `replace`\n\n
\n`ordered`\n\n\nSpecifies whether to perform ordered bulk operations.**Default:** `true`\n\n
\n`upsertDocument`\n\n\nWhen `true`, replace and update operations insert the data if no match exists.For time series collections, you must set `upsertDocument` to `false`.**Default:** `true`\n\n
\n`writeConcern.w`\n\n\nSpecifies `w`, a write-concern option requesting acknowledgment that the write operation has propagated to a specified number of MongoDB nodes.For a list of allowed values for this option, see WriteConcern w Option in the MongoDB Server manual.**Default:** `Acknowledged`\n\n
\n`writeConcern.journal`\n\n\nSpecifies `j`, a write-concern option requesting acknowledgment that the data has been written to the on-disk journal for the criteria specified in the `w` option. You can specify either `true` or `false`.For more information on `j` values, see WriteConcern j Option in the MongoDB Server manual.\n\n
\n`writeConcern.wTimeoutMS`\n\n\nSpecifies `wTimeoutMS`, a write-concern option to return an error when a write operation exceeds the specified number of milliseconds. If you use this optional setting, you must specify a nonnegative integer.For more information on `wTimeoutMS` values, see WriteConcern wtimeout in the MongoDB Server manual.\n\n
\n`truncateMode`\n\n\nSpecifies how to truncate a collection when performing an overwrite. You can set this option to one of the following values:- `TruncateMode.DROP`: *Default*. Drops the collection.\n\n- `TruncateMode.TRUNCATE`: Deletes all entries in the collection but preserves indexes, collection options, and any sharding configuration. This is slower than a drop operation.\n\n
\n`ignoreDuplicatesOnInsert`\n\n\nWhen set to `true`, the connector ignores duplicate key errors when performing unordered insert operations. The data being inserted must include an `_id` field value or whichever fields are specified in the `idFieldList` option.**Default:** `false`\n\n
\n\n## Specifying Properties in `connection.uri`\n\nIf you use SparkConf to specify any of the previous settings, you can either include them in the `connection.uri` setting or list them individually.\n\nThe following code example shows how to specify the database, collection, and `convertJson` setting as part of the `connection.uri` setting:\n\n```cfg\nspark.mongodb.write.connection.uri=mongodb://127.0.0.1/myDB.myCollection?convertJson=any\n```\n\nTo keep the `connection.uri` shorter and make the settings easier to read, you can specify them individually instead:\n\n```cfg\nspark.mongodb.write.connection.uri=mongodb://127.0.0.1/\nspark.mongodb.write.database=myDB\nspark.mongodb.write.collection=myCollection\nspark.mongodb.write.convertJson=any\n```\n\nIf you specify a setting in both the `connection.uri` and on its own line, the `connection.uri` setting takes precedence. For example, in the following configuration, the connection database is `foobar`:\n\n```cfg\nspark.mongodb.write.connection.uri=mongodb://127.0.0.1/foobar\nspark.mongodb.write.database=bar\n```"} -{"chunk_id": "68a95c2c5e79d242619df7df-0", "page_id": "68a95c2c5e79d242619df7df", "source_name": "spark-connector", "product_name": "MongoDB Spark Connector", "url": "https://mongodb.com/docs/spark-connector/current/streaming-mode/streaming-read-config", "title": "Streaming Read Configuration Options", "text": "# Streaming Read Configuration Options\n\n## Overview\n\nYou can configure the following properties when reading data from MongoDB in streaming mode.\n\nIf you use `SparkConf` to set the connector's read configurations, prefix `spark.mongodb.read.` to each property.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nProperty name\n\n\nDescription\n\n
\n`connection.uri`\n\n\n**Required.**The connection string configuration key.**Default:** `mongodb://localhost:27017/`\n\n
\n`database`\n\n\n**Required.**The database name configuration.\n\n
\n`collection`\n\n\n**Required.**The collection name configuration.You can specify multiple collections by separating the collection names with a comma.To learn more about specifying multiple collections, see Specifying Multiple Collections in the `collection` Property.\n\n
\n`comment`\n\n\nThe comment to append to the read operation. Comments appear in the output of the Database Profiler.**Default:** None\n\n
\n`mode`\n\n\nThe parsing strategy to use when handling documents that don't match the expected schema. This option accepts the following values:- `ReadConfig.ParseMode.FAILFAST`: Throws an exception when parsing a document that doesn't match the schema.\n\n- `ReadConfig.ParseMode.PERMISSIVE`: Sets fields to `null` when data types don't match the schema. To store each invalid document as an extended JSON string, combine this value with the `columnNameOfCorruptRecord` option.\n\n- `ReadConfig.ParseMode.DROPMALFORMED`: Ignores any document that doesn't match the schema.\n\n**Default:** `ReadConfig.ParseMode.FAILFAST`\n\n
\n`columnNameOfCorruptRecord`\n\n\nIf you set the `mode` option to `ReadConfig.ParseMode.PERMISSIVE`, this option specifies the name of the new column that stores the invalid document as extended JSON. If you're using an explicit schema, it must include the name of the new column. If you're using an inferred schema, the Spark Connector adds the new column to the end of the schema.**Default:** None\n\n
\n`mongoClientFactory`\n\n\nMongoClientFactory configuration key.You can specify a custom implementation, which must implement the `com.mongodb.spark.sql.connector.connection.MongoClientFactory` interface.**Default:** `com.mongodb.spark.sql.connector.connection.DefaultMongoClientFactory`\n\n
\n`aggregation.pipeline`\n\n\nSpecifies a custom aggregation pipeline to apply to the collection before sending data to Spark.The value must be either an extended JSON single document or list of documents.A single document resembles the following:```json\n{\"$match\": {\"closed\": false}}\n```\n\nA list of documents resembles the following:```json\n[{\"$match\": {\"closed\": false}}, {\"$project\": {\"status\": 1, \"name\": 1, \"description\": 1}}]\n```\n\nCustom aggregation pipelines must be compatible with the partitioner strategy. For example, aggregation stages such as `$group` do not work with any partitioner that creates more than one partition.\n\n
\n`aggregation.allowDiskUse`\n\n\nSpecifies whether to allow storage to disk when running the aggregation.**Default:** `true`\n\n
\n`change.stream.`\n\n\nChange stream configuration prefix.See the Change Stream Configuration section for more information about change streams.\n\n
\n`outputExtendedJson`\n\n\nWhen `true`, the connector converts BSON types not supported by Spark into extended JSON strings. When `false`, the connector uses the original relaxed JSON format for unsupported types.**Default:** `false`\n\n
\n`schemaHints`\n\n\nSpecifies a partial schema of known field types to use when inferring the schema for the collection. To learn more about the `schemaHints` option, see the Specify Known Fields with Schema Hints section.**Default:** None\n\n
"} -{"chunk_id": "68a95c2c5e79d242619df7df-1", "page_id": "68a95c2c5e79d242619df7df", "source_name": "spark-connector", "product_name": "MongoDB Spark Connector", "url": "https://mongodb.com/docs/spark-connector/current/streaming-mode/streaming-read-config", "title": "Streaming Read Configuration Options", "text": "## Change Stream Configuration\n\nYou can configure the following properties when reading a change stream from MongoDB:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nProperty name\n\n\nDescription\n\n
\n`change.stream.lookup.full.document`\n\n\nDetermines what values your change stream returns on update operations.\n\nThe default setting returns the differences between the original document and the updated document.\n\nThe `updateLookup` setting also returns the differences between the original document and updated document, but it also includes a copy of the entire updated document.\n\nFor more information on how this change stream option works, see the MongoDB server manual guide Lookup Full Document for Update Operation.\n\n**Default:** \"default\"\n\n
\n`change.stream.micro.batch.max.partition.count`\n\n\nThe maximum number of partitions the Spark Connector divides each micro-batch into. Spark workers can process these partitions in parallel.This setting applies only when using micro-batch streams.**Default**: `1`WARNING: Specifying a value larger than `1` can alter the order in which the Spark Connector processes change events. Avoid this setting if out-of-order processing could create data inconsistencies downstream.\n\n
\n`change.stream.publish.full.document.only`\n\n\nSpecifies whether to publish the changed document or the full change stream document.When this setting is `false`, you must specify a schema. The schema must include all fields that you want to read from the change stream. You can use optional fields to ensure that the schema is valid for all change-stream events.When this setting is `true`, the connector exhibits the following behavior:- The connector filters out messages that omit the `fullDocument` field and publishes only the value of the field.\n\n- If you don't specify a schema, the connector infers the schema from the change stream document.\n\nThis setting overrides the `change.stream.lookup.full.document` setting.\n\n**Default**: `false`\n\n
\n`change.stream.startup.mode`\n\n\nSpecifies how the connector starts up when no offset is available.This setting accepts the following values:- `latest`: The connector begins processing change events starting with the most recent event. It will not process any earlier unprocessed events.\n\n- `timestamp`: The connector begins processing change events at a specified time.\n\n To use the `timestamp` option, you must specify a time by using the `change.stream.startup.mode.timestamp.start.at.operation.time` setting. This setting accepts timestamps in the following formats:\n\n - An integer representing the number of seconds since the Unix epoch\n\n - A date and time in ISO-8601 format with one-second precision\n\n - An extended JSON `BsonTimestamp`\n\n **Default**: `latest`\n\n
\n`change.stream.lookup.full.document.before.change`\n\n\nDetermines whether to include the pre-image of modified documents in the change stream output.This setting accepts the following values:- `default`: This option is equivalent to the `off` value.\n\n- `off`: Does not include the pre-image of modified documents in the change stream output.\n\n- `whenAvailable`: Includes the pre-image of modified documents in the change stream output when pre-images are available.\n\n- `required`: Includes the pre-image of modified documents in the change stream output. If a pre-image is not available for a modified document, the connector throws an error.\n\n**Default:** `default`\n\n
\n\n## Specifying Properties in `connection.uri`\n\nIf you use SparkConf to specify any of the previous settings, you can either include them in the `connection.uri` setting or list them individually.\n\nThe following code example shows how to specify the database, collection, and read preference as part of the `connection.uri` setting:\n\n```cfg\nspark.mongodb.read.connection.uri=mongodb://127.0.0.1/myDB.myCollection?readPreference=primaryPreferred\n```\n\nTo keep the `connection.uri` shorter and make the settings easier to read, you can specify them individually instead:\n\n```cfg\nspark.mongodb.read.connection.uri=mongodb://127.0.0.1/\nspark.mongodb.read.database=myDB\nspark.mongodb.read.collection=myCollection\n```\n\nIf you specify a setting in both the `connection.uri` and on its own line, the `connection.uri` setting takes precedence. For example, in the following configuration, the connection database is `foobar`, because it's the value in the `connection.uri` setting:\n\n```cfg\nspark.mongodb.read.connection.uri=mongodb://127.0.0.1/foobar\nspark.mongodb.read.database=bar\n```\n\n## Specifying Multiple Collections in the `collection` Property\n\nYou can specify multiple collections in the `collection` change stream configuration property by separating the collection names with a comma. Do not add a space between the collections unless the space is a part of the collection name.\n\nSpecify multiple collections as shown in the following example:\n\n```java\n...\n.option(\"spark.mongodb.collection\", \"collectionOne,collectionTwo\")\n```\n\nIf a collection name is \"*\", or if the name includes a comma or a backslash (\\), you must escape the character as follows:\n\n- If the name of a collection used in your `collection` configuration option contains a comma, the Spark Connector treats it as two different collections. To avoid this, you must escape the comma by preceding it with a backslash (\\). Escape a collection named \"my,collection\" as follows:\n\n ```java\n \"my\\,collection\"\n ```\n\n- If the name of a collection used in your `collection` configuration option is \"*\", the Spark Connector interprets it as a specification to scan all collections. To avoid this, you must escape the asterisk by preceding it with a backslash (\\). Escape a collection named \"*\" as follows:\n\n ```java\n \"\\*\"\n ```\n\n- If the name of a collection used in your `collection` configuration option contains a backslash (\\), the Spark Connector treats the backslash as an escape character, which might change how it interprets the value. To avoid this, you must escape the backslash by preceding it with another backslash. Escape a collection named \"\\collection\" as follows:\n\n ```java\n \"\\\\collection\"\n ```\n\n When specifying the collection name as a string literal in Java, you must further escape each backslash with another one. For example, escape a collection named \"\\collection\" as follows:\n\n ```java\n \"\\\\\\\\collection\"\n ```\n\nYou can stream from all collections in the database by passing an asterisk (*) as a string for the collection name.\n\nSpecify all collections as shown in the following example:\n\n```java\n...\n.option(\"spark.mongodb.collection\", \"*\")\n```\n\nIf you create a collection while streaming from all collections, the new collection is automatically included in the stream.\n\nYou can drop collections at any time while streaming from multiple collections.\n\nIf you set the `change.stream.publish.full.document.only` option to `true`, the Spark Connector infers the schema of a `DataFrame` by using the schema of the scanned documents.\n\nSchema inference happens at the beginning of streaming, and does not take into account collections that are created during streaming.\n\nWhen streaming from multiple collections and inferring the schema, the connector samples each collection sequentially. Streaming from a large number of collections can cause the schema inference to have noticeably slower performance. This performance impact occurs only while inferring the schema."} -{"chunk_id": "68a95c2c5e79d242619df787-0", "page_id": "68a95c2c5e79d242619df787", "source_name": "spark-connector", "product_name": "MongoDB Spark Connector", "url": "https://mongodb.com/docs/spark-connector/current", "title": "MongoDB Connector for Spark", "text": "# MongoDB Connector for Spark\n\nThe MongoDB Connector for Spark provides integration between MongoDB and Apache Spark.\n\nWith the connector, you have access to all Spark libraries for use with MongoDB datasets: `Dataset` for analysis with SQL (benefiting from automatic schema inference), streaming, machine learning, and graph APIs. You can also use the connector with the Spark Shell.\n\nThe MongoDB Spark Connector is compatible with the following versions of Apache Spark and MongoDB:\n\n\n\n\n\n\n\n\n\n\n\n\n
\nMongoDB Spark Connector\n\n\nSpark Version\n\n\nMongoDB Version\n\n
\n**11.1.0**\n\n\n**4.0 or later**\n\n\n**4.2 or later**\n\n
"} -{"chunk_id": "68a95c2c5e79d242619df7ec-0", "page_id": "68a95c2c5e79d242619df7ec", "source_name": "spark-connector", "product_name": "MongoDB Spark Connector", "url": "https://mongodb.com/docs/spark-connector/current/streaming-mode/streaming-write-config", "title": "Streaming Write Configuration Options", "text": "# Streaming Write Configuration Options\n\n## Overview\n\nYou can configure the following properties when writing data to MongoDB in streaming mode.\n\nIf you use `SparkConf` to set the connector's write configurations, prefix `spark.mongodb.write.` to each property.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nProperty name\n\n\nDescription\n\n
\n`connection.uri`\n\n\n**Required.**The connection string configuration key.**Default:** `mongodb://localhost:27017/`\n\n
\n`database`\n\n\n**Required.**The database name configuration.\n\n
\n`collection`\n\n\n**Required.**The collection name configuration.\n\n
\n`comment`\n\n\nThe comment to append to the write operation. Comments appear in the output of the Database Profiler.**Default:** None\n\n
\n`mongoClientFactory`\n\n\nMongoClientFactory configuration key.You can specify a custom implementation that must implement the `com.mongodb.spark.sql.connector.connection.MongoClientFactory` interface.**Default:** `com.mongodb.spark.sql.connector.connection.DefaultMongoClientFactory`\n\n
\n`convertJson`\n\n\nSpecifies if the connector parses string values and converts extended JSON into BSON.This setting accepts the following values:- `any`: The connector converts all JSON values to BSON.\n\n - `\"{a: 1}\"` becomes `{a: 1}`.\n\n - `\"[1, 2, 3]\"` becomes `[1, 2, 3]`.\n\n - `\"true\"` becomes `true`.\n\n - `\"01234\"` becomes `1234`.\n\n - `\"{a:b:c}\"` doesn't change.\n\n- `objectOrArrayOnly`: The connector converts only JSON objects and arrays to BSON.\n\n - `\"{a: 1}\"` becomes `{a: 1}`.\n\n - `\"[1, 2, 3]\"` becomes `[1, 2, 3]`.\n\n - `\"true\"` doesn't change.\n\n - `\"01234\"` doesn't change.\n\n - `\"{a:b:c}\"` doesn't change.\n\n- `false`: The connector leaves all values as strings.\n\n**Default:** `false`\n\n
\n`idFieldList`\n\n\nSpecifies a field or list of fields by which to split the collection data. To specify more than one field, separate them using a comma as shown in the following example:```none\n\"fieldName1,fieldName2\"\n```\n\n**Default:** `_id`\n\n
\n`ignoreNullValues`\n\n\nWhen `true`, the connector ignores any `null` values when writing, including `null` values in arrays and nested documents.**Default:** `false`\n\n
\n`maxBatchSize`\n\n\nSpecifies the maximum number of operations to batch in bulk operations.**Default:** `512`\n\n
\n`operationType`\n\n\nSpecifies the type of write operation to perform. You can set this to one of the following values:- `insert`: Insert the data.\n\n- `replace`: Replace an existing document that matches the `idFieldList` value with the new data. If no match exists, the value of `upsertDocument` indicates whether the connector inserts a new document.\n\n- `update`: Update an existing document that matches the `idFieldList` value with the new data. If no match exists, the value of `upsertDocument` indicates whether the connector inserts a new document.\n\n**Default:** `replace`\n\n
\n`ordered`\n\n\nSpecifies whether to perform ordered bulk operations.**Default:** `true`\n\n
\n`upsertDocument`\n\n\nWhen `true`, replace and update operations insert the data if no match exists.For time series collections, you must set `upsertDocument` to `false`.**Default:** `true`\n\n
\n`writeConcern.w`\n\n\nSpecifies `w`, a write-concern option requesting acknowledgment that the write operation has propagated to a specified number of MongoDB nodes.For a list of allowed values for this option, see WriteConcern w Option in the MongoDB Server manual.**Default:** `Acknowledged`\n\n
\n`writeConcern.journal`\n\n\nSpecifies `j`, a write-concern option requesting acknowledgment that the data has been written to the on-disk journal for the criteria specified in the `w` option. You can specify either `true` or `false`.For more information on `j` values, see WriteConcern j Option in the MongoDB Server manual.\n\n
\n`writeConcern.wTimeoutMS`\n\n\nSpecifies `wTimeoutMS`, a write-concern option to return an error when a write operation exceeds the specified number of milliseconds. If you use this optional setting, you must specify a nonnegative integer.For more information on `wTimeoutMS` values, see WriteConcern wtimeout in the MongoDB Server manual.\n\n
\n`checkpointLocation`\n\n\nThe absolute file path of the directory where the connector writes checkpoint information.For more information about checkpoints, see the Spark Structured Streaming Programming Guide**Default:** None\n\n
\n`forceDeleteTempCheckpointLocation`\n\n\nA Boolean value that specifies whether to delete existing checkpoint data.**Default:** `false`\n\n
\n`truncateMode`\n\n\nSpecifies how to truncate a collection when performing an overwrite. You can set this option to one of the following values:- `TruncateMode.DROP`: *Default*. Drops the collection.\n\n- `TruncateMode.TRUNCATE`: Deletes all entries in the collection but preserves indexes, collection options, and any sharding configuration. This is slower than a drop operation.\n\n
\n`ignoreDuplicatesOnInsert`\n\n\nWhen set to `true`, the connector ignores duplicate key errors when performing unordered insert operations. The data being inserted must include an `_id` field value or whichever fields are specified in the `idFieldList` option.**Default:** `false`\n\n
\n\n## Specifying Properties in `connection.uri`\n\nIf you use SparkConf to specify any of the previous settings, you can either include them in the `connection.uri` setting or list them individually.\n\nThe following code example shows how to specify the database, collection, and `convertJson` setting as part of the `connection.uri` setting:\n\n```cfg\nspark.mongodb.write.connection.uri=mongodb://127.0.0.1/myDB.myCollection?convertJson=any\n```\n\nTo keep the `connection.uri` shorter and make the settings easier to read, you can specify them individually instead:\n\n```cfg\nspark.mongodb.write.connection.uri=mongodb://127.0.0.1/\nspark.mongodb.write.database=myDB\nspark.mongodb.write.collection=myCollection\nspark.mongodb.write.convertJson=any\n```\n\nIf you specify a setting in both the `connection.uri` and on its own line, the `connection.uri` setting takes precedence. For example, in the following configuration, the connection database is `foobar`:\n\n```cfg\nspark.mongodb.write.connection.uri=mongodb://127.0.0.1/foobar\nspark.mongodb.write.database=bar\n```"} -{"chunk_id": "68a95c2c5e79d242619df790-0", "page_id": "68a95c2c5e79d242619df790", "source_name": "spark-connector", "product_name": "MongoDB Spark Connector", "url": "https://mongodb.com/docs/spark-connector/current/batch-mode/batch-read-config", "title": "Batch Read Configuration Options", "text": "# Batch Read Configuration Options\n\n## Overview\n\nYou can configure the following properties when reading data from MongoDB in batch mode.\n\nIf you use `SparkConf` to set the connector's read configurations, prefix `spark.mongodb.read.` to each property.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nProperty name\n\n\nDescription\n\n
\n`connection.uri`\n\n\n**Required.**The connection string configuration key.**Default:** `mongodb://localhost:27017/`\n\n
\n`database`\n\n\n**Required.**The database name configuration.\n\n
\n`collection`\n\n\n**Required.**The collection name configuration.\n\n
\n`comment`\n\n\nThe comment to append to the read operation. Comments appear in the output of the Database Profiler.**Default:** None\n\n
\n`mode`\n\n\nThe parsing strategy to use when handling documents that don't match the expected schema. This option accepts the following values:- `ReadConfig.ParseMode.FAILFAST`: Throws an exception when parsing a document that doesn't match the schema.\n\n- `ReadConfig.ParseMode.PERMISSIVE`: Sets fields to `null` when data types don't match the schema. To store each invalid document as an extended JSON string, combine this value with the `columnNameOfCorruptRecord` option.\n\n- `ReadConfig.ParseMode.DROPMALFORMED`: Ignores any document that doesn't match the schema.\n\n**Default:** `ReadConfig.ParseMode.FAILFAST`\n\n
\n`columnNameOfCorruptRecord`\n\n\nIf you set the `mode` option to `ReadConfig.ParseMode.PERMISSIVE`, this option specifies the name of the new column that stores the invalid document as extended JSON. If you're using an explicit schema, it must include the name of the new column. If you're using an inferred schema, the Spark Connector adds the new column to the end of the schema.**Default:** None\n\n
\n`mongoClientFactory`\n\n\nMongoClientFactory configuration key.You can specify a custom implementation which must implement the `com.mongodb.spark.sql.connector.connection.MongoClientFactory` interface.**Default:** `com.mongodb.spark.sql.connector.connection.DefaultMongoClientFactory`\n\n
\n`partitioner`\n\n\nThe partitioner full class name.You can specify a custom implementation that must implement the `com.mongodb.spark.sql.connector.read.partitioner.Partitioner`\n interface.See the Partitioner Configuration section for more information about partitioners.**Default:** `com.mongodb.spark.sql.connector.read.partitioner.AutoBucketPartitioner`\n\n
\n`partitioner.options.`\n\n\nPartitioner configuration prefix.See the Partitioner Configuration section for more information about partitioners.\n\n
\n`sampleSize`\n\n\nThe number of documents to sample from the collection when inferringthe schema.**Default:** `1000`\n\n
\n`sql.inferSchema.mapTypes.enabled`\n\n\nWhether to enable Map types when inferring the schema.When enabled, large compatible struct types are inferred to a `MapType` instead.**Default:** `true`\n\n
\n`sql.inferSchema.mapTypes.minimum.key.size`\n\n\nMinimum size of a `StructType` before inferring as a `MapType`.**Default:** `250`\n\n
\n`aggregation.pipeline`\n\n\nSpecifies a custom aggregation pipeline to apply to the collection before sending data to Spark.The value must be either an extended JSON single document or list of documents.A single document resembles the following:```json\n{\"$match\": {\"closed\": false}}\n```\n\nA list of documents resembles the following:```json\n[{\"$match\": {\"closed\": false}}, {\"$project\": {\"status\": 1, \"name\": 1, \"description\": 1}}]\n```\n\nIMPORTANT: Custom aggregation pipelines must be compatible with the partitioner strategy. For example, aggregation stages such as `$group` do not work with any partitioner that creates more than one partition.\n\n
\n`aggregation.allowDiskUse`\n\n\nSpecifies whether to allow storage to disk when running the aggregation.**Default:** `true`\n\n
\n`outputExtendedJson`\n\n\nWhen `true`, the connector converts BSON types not supported by Spark into extended JSON strings. When `false`, the connector uses the original relaxed JSON format for unsupported types.**Default:** `false`\n\n
\n`schemaHints`\n\n\nSpecifies a partial schema of known field types to use when inferring the schema for the collection. To learn more about the `schemaHints` option, see the Specify Known Fields with Schema Hints section.**Default:** None\n\n
\n\n## Partitioner Configurations\n\nPartitioners change the read behavior of batch reads that use the Spark Connector. By dividing the data into partitions, you can run transformations in parallel.\n\nThis section contains configuration information for the following partitioner:\n\n- AutoBucketPartitioner\n\n- SamplePartitioner\n\n- ShardedPartitioner\n\n- PaginateBySizePartitioner\n\n- PaginateIntoPartitionsPartitioner\n\n- SinglePartitionPartitioner\n\nBecause the data-stream-processing engine produces a single data stream, partitioners do not affect streaming reads.\n\n### AutoBucketPartitioner Configuration (default)\n\nThe `AutoBucketPartitioner` is the default partitioner configuration. It samples the data to generate partitions and uses the $bucketAuto aggregation stage to paginate. By using this configuration, you can partition the data across single or multiple fields, including nested fields.\n\nThe `AutoBucketPartitioner` configuration requires MongoDB Server version 7.0 or higher to support compound keys.\n\nTo use this configuration, set the `partitioner` configuration option to `com.mongodb.spark.sql.connector.read.partitioner.AutoBucketPartitioner`.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nProperty name\n\n\nDescription\n\n
\n`partitioner.options.fieldList`\n\n\nThe list of fields to use for partitioning. The value can be either a single field name or a list of comma-separated fields.\n\n**Default:** `_id`\n\n
\n`partitioner.options.chunkSize`\n\n\nThe average size (MB) for each partition. Smaller partition sizes create more partitions containing fewer documents. Because this configuration uses the average document size to determine the number of documents per partition, partitions might not be the same size.\n\n**Default:** `64`\n\n
\n`partitioner.options.samplesPerPartition`\n\n\nThe number of samples to take per partition.\n\n**Default:** `100`\n\n
\n`partitioner.options.partitionKeyProjectionField`\n\n\nThe field name to use for a projected field that contains all the fields used to partition the collection. We recommend changing the value of this property only if each document already contains the `__idx` field.\n\n**Default:** `__idx`\n\n
"} -{"chunk_id": "68a95c2c5e79d242619df790-1", "page_id": "68a95c2c5e79d242619df790", "source_name": "spark-connector", "product_name": "MongoDB Spark Connector", "url": "https://mongodb.com/docs/spark-connector/current/batch-mode/batch-read-config", "title": "Batch Read Configuration Options", "text": "### SamplePartitioner Configuration\n\nThe `SamplePartitioner` configuration is similar to the AutoBucketPartitioner configuration, but does not use the `$bucketAuto` aggregation stage. This configuration lets you specify a partition field, partition size, and number of samples per partition.\n\nTo use this configuration, set the `partitioner` configuration option to `com.mongodb.spark.sql.connector.read.partitioner.SamplePartitioner`.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nProperty name\n\n\nDescription\n\n
\n`partitioner.options.partition.field`\n\n\nThe field to use for partitioning, which must be a unique field.\n\n**Default:** `_id`\n\n
\n`partitioner.options.partition.size`\n\n\nThe size (in MB) for each partition. Smaller partition sizes create more partitions containing fewer documents.\n\n**Default:** `64`\n\n
\n`partitioner.options.samples.per.partition`\n\n\nThe number of samples to take per partition. The total number of samples taken is:\n\n```none\nsamples per partition * ( count / number of documents per partition)\n```\n\n**Default:** `10`\n\n
For a collection with 640 documents with an average document size of 0.5 MB, the default `SamplePartitioner` configuration creates 5 partitions with 128 documents per partition.\n\nThe Spark Connector samples 50 documents (the default 10 per intended partition) and defines 5 partitions by selecting partition field ranges from the sampled documents.\n\n### ShardedPartitioner Configuration\n\nThe `ShardedPartitioner` configuration automatically partitions the data based on your shard configuration.\n\nTo use this configuration, set the `partitioner` configuration option to `com.mongodb.spark.sql.connector.read.partitioner.ShardedPartitioner`.\n\n1. In MongoDB Server v6.0 and later, the sharding operation creates one large initial chunk to cover all shard key values, making the sharded partitioner inefficient. We do not recommend using the sharded partitioner when connected to MongoDB v6.0 and later.\n\n2. The sharded partitioner is not compatible with hashed shard keys.\n\n### PaginateBySizePartitioner Configuration\n\nThe `PaginateBySizePartitioner` configuration paginates the data by using the average document size to split the collection into average-sized chunks.\n\nTo use this configuration, set the `partitioner` configuration option to `com.mongodb.spark.sql.connector.read.partitioner.PaginateBySizePartitioner`.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nProperty name\n\n\nDescription\n\n
\n`partitioner.options.partition.field`\n\n\nThe field to use for partitioning, which must be a unique field.\n\n**Default:** `_id`\n\n
\n`partitioner.options.partition.size`\n\n\nThe size (in MB) for each partition. Smaller partition sizes\n\ncreate more partitions containing fewer documents.\n\n**Default:** `64`\n\n
\n\n### PaginateIntoPartitionsPartitioner Configuration\n\nThe `PaginateIntoPartitionsPartitioner` configuration paginates the data by dividing the count of documents in the collection by the maximum number of allowable partitions.\n\nTo use this configuration, set the `partitioner` configuration option to `com.mongodb.spark.sql.connector.read.partitioner.PaginateIntoPartitionsPartitioner`.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nProperty name\n\n\nDescription\n\n
\n`partitioner.options.partition.field`\n\n\nThe field to use for partitioning, which must be a unique field.\n\n**Default:** `_id`\n\n
\n`partitioner.options.max.number.of.partitions`\n\n\nThe number of partitions to create.\n\n**Default:** `64`\n\n
\n\n### SinglePartitionPartitioner Configuration\n\nThe `SinglePartitionPartitioner` configuration creates a single partition.\n\nTo use this configuration, set the `partitioner` configuration option to `com.mongodb.spark.sql.connector.read.partitioner.SinglePartitionPartitioner`.\n\n## Specifying Properties in connection.uri\n\nIf you use SparkConf to specify any of the previous settings, you can either include them in the `connection.uri` setting or list them individually.\n\nThe following code example shows how to specify the database, collection, and read preference as part of the `connection.uri` setting:\n\n```cfg\nspark.mongodb.read.connection.uri=mongodb://127.0.0.1/myDB.myCollection?readPreference=primaryPreferred\n```\n\nTo keep the `connection.uri` shorter and make the settings easier to read, you can specify them individually instead:\n\n```cfg\nspark.mongodb.read.connection.uri=mongodb://127.0.0.1/\nspark.mongodb.read.database=myDB\nspark.mongodb.read.collection=myCollection\n```\n\nIf you specify a setting in both the `connection.uri` and on its own line, the `connection.uri` setting takes precedence. For example, in the following configuration, the connection database is `foobar`, because it's the value in the `connection.uri` setting:\n\n```cfg\nspark.mongodb.read.connection.uri=mongodb://127.0.0.1/foobar\nspark.mongodb.read.database=bar\n```"} -{"chunk_id": "68a95c2c5e79d242619df775-0", "page_id": "68a95c2c5e79d242619df775", "source_name": "spark-connector", "product_name": "MongoDB Spark Connector", "url": "https://mongodb.com/docs/spark-connector/current/streaming-mode", "title": "Streaming Mode", "text": "# Streaming Mode\n\n## Overview\n\nThe Spark Connector supports streaming mode, which uses Spark Structured Streaming to process data as soon as it's available instead of waiting for a time interval to pass. Spark Structured Streaming is a data-stream-processing engine that you can access by using the Dataset or DataFrame API.\n\nApache Spark contains two different stream-processing engines:\n\n- Spark Streaming with DStreams, now an unsupported legacy engine\n\n- Spark Structured Streaming.\n\nThis guide pertains only to Spark Structured Streaming.\n\nThe following sections show you how to use the Spark Connector to read data from MongoDB and write data to MongoDB in streaming mode:\n\n- Read from MongoDB in Streaming Mode\n\n- Write to MongoDB in Streaming Mode\n\nTo learn more about using Spark to process streams of data, see the Spark Programming Guide."} -{"chunk_id": "68a95c2c5e79d242619df7cf-0", "page_id": "68a95c2c5e79d242619df7cf", "source_name": "spark-connector", "product_name": "MongoDB Spark Connector", "url": "https://mongodb.com/docs/spark-connector/current/batch-mode", "title": "Batch Mode", "text": "# Batch Mode\n\n## Overview\n\nIn batch mode, you can use the Spark Dataset and DataFrame APIs to process data at a specified time interval.\n\nThe following sections show you how to use the Spark Connector to read data from MongoDB and write data to MongoDB in batch mode:\n\n- Read from MongoDB in Batch Mode\n\n- Write to MongoDB in Batch Mode\n\nTo learn more about using Spark to process batches of data, see the Spark Programming Guide."} -{"chunk_id": "68a95c2c5e79d242619df761-0", "page_id": "68a95c2c5e79d242619df761", "source_name": "spark-connector", "product_name": "MongoDB Spark Connector", "url": "https://mongodb.com/docs/spark-connector/current/streaming-mode/streaming-read", "title": "Read from MongoDB in Streaming Mode", "text": "# Read from MongoDB in Streaming Mode\n\n## Overview\n\nWhen reading a stream from a MongoDB database, the MongoDB Spark Connector supports both *micro-batch processing* and *continuous processing*. Micro-batch processing, the default processing engine, achieves end-to-end latencies as low as 100 milliseconds with exactly-once fault-tolerance guarantees. Continuous processing is an experimental feature introduced in Spark version 2.3 that achieves end-to-end latencies as low as 1 millisecond with at-least-once guarantees.\n\nTo learn more about continuous processing, see the Spark documentation.\n\nThe connector reads from your MongoDB deployment's change stream. To generate change events on the change stream, perform update operations on your database.\n\nTo learn more about change streams, see Change Streams in the MongoDB manual.\n\n\n\n\n\nTo read data from MongoDB, call the `readStream()` method on your `SparkSession` object. This method returns a `DataStreamReader` object, which you can use to specify the format and other configuration settings for your streaming read operation.\n\nYou must specify the following configuration settings to read from MongoDB:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nSetting\n\n\nDescription\n\n
\n`readStream.format()`\n\n\nSpecifies the format of the underlying input data source. Use `mongodb` to read from MongoDB.\n\n
\n`readStream.option()`\n\n\nSpecifies stream settings, including the MongoDB deployment connection string, MongoDB database and collection, and aggregation pipeline stages.\n\nFor a list of read stream configuration options, see the Streaming Read Configuration Options guide.\n\n
\n`readStream.schema()`\n\n\nSpecifies the input schema.\n\n
The following code snippet shows how to use the preceding configuration settings to continuously process data streamed from MongoDB. The connector appends all new data to the existing data and asynchronously writes checkpoints to `/tmp/checkpointDir` once per second. Passing the `Trigger.Continuous` parameter to the `trigger()` method enables continuous processing.\n\n```java\nimport org.apache.spark.sql.streaming.Trigger;\n\nDataset streamingDataset = .readStream()\n .format(\"mongodb\")\n .load();\n\nDataStreamWriter dataStreamWriter = streamingDataset.writeStream()\n .trigger(Trigger.Continuous(\"1 second\"))\n .format(\"memory\")\n .option(\"checkpointLocation\", \"/tmp/checkpointDir\")\n .outputMode(\"append\");\n\nStreamingQuery query = dataStreamWriter.start();\n```\n\nSpark does not begin streaming until you call the `start()` method on a streaming query.\n\nFor a complete list of methods, see the Java Structured Streaming reference.\n\n
\n\n\n\nTo read data from MongoDB, call the `readStream` function on your `SparkSession` object. This function returns a `DataStreamReader` object, which you can use to specify the format and other configuration settings for your streaming read operation.\n\nYou must specify the following configuration settings to read from MongoDB:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nSetting\n\n\nDescription\n\n
\n`readStream.format()`\n\n\nSpecifies the format of the underlying input data source. Use `mongodb` to read from MongoDB.\n\n
\n`readStream.option()`\n\n\nSpecifies stream settings, including the MongoDB deployment connection string, MongoDB database and collection, and aggregation pipeline stages.\n\nFor a list of read stream configuration options, see the Streaming Read Configuration Options guide.\n\n
\n`readStream.schema()`\n\n\nSpecifies the input schema.\n\n
The following code snippet shows how to use the preceding configuration settings to continuously process data streamed from MongoDB. The connector appends all new data to the existing data and asynchronously writes checkpoints to `/tmp/checkpointDir` once per second. Passing the `continuous` parameter to the `trigger()` method enables continuous processing.\n\n```python\nstreamingDataFrame = (.readStream\n .format(\"mongodb\")\n .load()\n)\n\ndataStreamWriter = (streamingDataFrame.writeStream\n .trigger(continuous=\"1 second\")\n .format(\"memory\")\n .option(\"checkpointLocation\", \"/tmp/checkpointDir\")\n .outputMode(\"append\")\n)\n\nquery = dataStreamWriter.start()\n```\n\nSpark does not begin streaming until you call the `start()` method on a streaming query.\n\nFor a complete list of methods, see the pyspark Structured Streaming reference.\n\n
\n\n\n\nTo read data from MongoDB, call the `readStream` method on your `SparkSession` object. This method returns a `DataStreamReader` object, which you can use to specify the format and other configuration settings for your streaming read operation.\n\nYou must specify the following configuration settings to read from MongoDB:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nSetting\n\n\nDescription\n\n
\n`readStream.format()`\n\n\nSpecifies the format of the underlying input data source. Use `mongodb` to read from MongoDB.\n\n
\n`readStream.option()`\n\n\nSpecifies stream settings, including the MongoDB deployment connection string, MongoDB database and collection, and aggregation pipeline stages.\n\nFor a list of read stream configuration options, see the Streaming Read Configuration Options guide.\n\n
\n`readStream.schema()`\n\n\nSpecifies the input schema.\n\n
The following code snippet shows how to use the preceding configuration settings to continuously process data streamed from MongoDB. The connector appends all new data to the existing data and asynchronously writes checkpoints to `/tmp/checkpointDir` once per second. Passing the `Trigger.Continuous` parameter to the `trigger()` method enables continuous processing.\n\n```scala\nimport org.apache.spark.sql.streaming.Trigger\n\nval streamingDataFrame = .readStream\n .format(\"mongodb\")\n .load()\n\nval dataStreamWriter = streamingDataFrame.writeStream\n .trigger(Trigger.Continuous(\"1 second\"))\n .format(\"memory\")\n .option(\"checkpointLocation\", \"/tmp/checkpointDir\")\n .outputMode(\"append\")\n\nval query = dataStreamWriter.start()\n```\n\nSpark does not begin streaming until you call the `start()` method on a streaming query.\n\nFor a complete list of methods, see the Scala Structured Streaming reference.\n\n
\n\n
"} -{"chunk_id": "68a95c2c5e79d242619df761-1", "page_id": "68a95c2c5e79d242619df761", "source_name": "spark-connector", "product_name": "MongoDB Spark Connector", "url": "https://mongodb.com/docs/spark-connector/current/streaming-mode/streaming-read", "title": "Read from MongoDB in Streaming Mode", "text": "## Example\n\nThe following example shows how to stream data from MongoDB to your console.\n\n\n\n\n\n1. Create a `DataStreamReader` object that reads from MongoDB.\n\n2. Create a `DataStreamWriter` object by calling the `writeStream()` method on the streaming `Dataset` object that you created with a `DataStreamReader`. Specify the format `console` using the `format()` method.\n\n3. Call the `start()` method on the `DataStreamWriter` instance to begin the stream.\n\nAs new data is inserted into MongoDB, MongoDB streams that data out to your console according to the `outputMode` you specify.\n\nAvoid streaming large Datasets to your console. Streaming to your console is memory intensive and intended only for testing purposes.\n\n```java\n// create a local SparkSession\nSparkSession spark = SparkSession.builder()\n .appName(\"readExample\")\n .master(\"spark://spark-master:\")\n .config(\"spark.jars\", \"\")\n .getOrCreate();\n\n// define the schema of the source collection\nStructType readSchema = new StructType()\n .add(\"company_symbol\", DataTypes.StringType)\n .add(\"company_name\", DataTypes.StringType)\n .add(\"price\", DataTypes.DoubleType)\n .add(\"tx_time\", DataTypes.TimestampType);\n\n// define a streaming query\nDataStreamWriter dataStreamWriter = spark.readStream()\n .format(\"mongodb\")\n .option(\"spark.mongodb.connection.uri\", \"\")\n .option(\"spark.mongodb.database\", \"\")\n .option(\"spark.mongodb.collection\", \"\")\n .schema(readSchema)\n .load()\n // manipulate your streaming data\n .writeStream()\n .format(\"console\")\n .trigger(Trigger.Continuous(\"1 second\"))\n .outputMode(\"append\");\n\n// run the query\nStreamingQuery query = dataStreamWriter.start();\n```\n\n\n\n\n\n1. Create a `DataStreamReader` object that reads from MongoDB.\n\n2. Create a `DataStreamWriter` object by calling the `writeStream()` method on the streaming `DataFrame` that you created with a `DataStreamReader`. Specify the format `console` by using the `format()` method.\n\n3. Call the `start()` method on the `DataStreamWriter` instance to begin the stream.\n\nAs new data is inserted into MongoDB, MongoDB streams that data out to your console according to the `outputMode` you specify.\n\nAvoid streaming large Datasets to your console. Streaming to your console is memory intensive and intended only for testing purposes.\n\n```python\n# create a local SparkSession\nspark = SparkSession.builder \\\n .appName(\"readExample\") \\\n .master(\"spark://spark-master:\") \\\n .config(\"spark.jars\", \"\") \\\n .getOrCreate()\n\n# define the schema of the source collection\nreadSchema = (StructType()\n .add('company_symbol', StringType())\n .add('company_name', StringType())\n .add('price', DoubleType())\n .add('tx_time', TimestampType())\n)\n\n# define a streaming query\ndataStreamWriter = (spark.readStream\n .format(\"mongodb\")\n .option(\"spark.mongodb.connection.uri\", )\n .option('spark.mongodb.database', )\n .option('spark.mongodb.collection', )\n .schema(readSchema)\n .load()\n # manipulate your streaming data\n .writeStream\n .format(\"console\")\n .trigger(continuous=\"1 second\")\n .outputMode(\"append\")\n)\n\n# run the query\nquery = dataStreamWriter.start()\n```\n\n\n\n\n\n1. Create a `DataStreamReader` object that reads from MongoDB.\n\n2. Create a `DataStreamWriter` object by calling the `writeStream()` method on the streaming `DataFrame` object that you created by using the `DataStreamReader`. Specify the format `console` by using the `format()` method.\n\n3. Call the `start()` method on the `DataStreamWriter` instance to begin the stream.\n\nAs new data is inserted into MongoDB, MongoDB streams that data out to your console according to the `outputMode` you specify.\n\nAvoid streaming large Datasets to your console. Streaming to your console is memory intensive and intended only for testing purposes.\n\n```scala\n// create a local SparkSession\nval spark = SparkSession.builder\n .appName(\"readExample\")\n .master(\"spark://spark-master:\")\n .config(\"spark.jars\", \"\")\n .getOrCreate()\n\n// define the schema of the source collection\nval readSchema = StructType()\n .add(\"company_symbol\", StringType())\n .add(\"company_name\", StringType())\n .add(\"price\", DoubleType())\n .add(\"tx_time\", TimestampType())\n\n// define a streaming query\nval dataStreamWriter = spark.readStream\n .format(\"mongodb\")\n .option(\"spark.mongodb.connection.uri\", )\n .option(\"spark.mongodb.database\", )\n .option(\"spark.mongodb.collection\", )\n .schema(readSchema)\n .load()\n // manipulate your streaming data\n .writeStream\n .format(\"console\")\n .trigger(Trigger.Continuous(\"1 second\"))\n .outputMode(\"append\")\n\n// run the query\nval query = dataStreamWriter.start()\n```\n\n\n\n\n\nIf you set the `change.stream.publish.full.document.only` option to `true`, the Spark Connector infers the schema of a `DataFrame` by using the schema of the scanned documents. If you set the option to `false`, you must specify a schema.\n\nFor more information about this setting, and to see a full list of change stream configuration options, see the Read Configuration Options guide.\n\n## API Documentation\n\nTo learn more about the types used in these examples, see the following Apache Spark API documentation:\n\n\n\n\n\n- Dataset\n\n- DataStreamReader\n\n- DataStreamWriter\n\n\n\n\n\n- DataFrame\n\n- DataStreamReader\n\n- DataStreamWriter\n\n\n\n\n\n- Dataset[T]\n\n- DataStreamReader\n\n- DataStreamWriter\n\n\n\n"} -{"chunk_id": "68a95c2c5e79d242619df76f-0", "page_id": "68a95c2c5e79d242619df76f", "source_name": "spark-connector", "product_name": "MongoDB Spark Connector", "url": "https://mongodb.com/docs/spark-connector/current/configuration", "title": "Configuring Spark", "text": "# Configuring Spark\n\n## Overview\n\nYou can configure read and write operations in both batch and streaming mode. To learn more about the available configuration options, see the following pages:\n\n- Batch Read Configuration Options\n\n- Batch Write Configuration Options\n\n- Streaming Read Configuration Options\n\n- Streaming Write Configuration Options\n\n## Specify Configuration\n\n### Using `SparkConf`\n\nYou can specify configuration options with `SparkConf` using any of the following approaches:\n\n\n\n\n\n- The `SparkConf` constructor in your application. To learn more, see the Java SparkConf documentation.\n\n\n\n\n\n- The `SparkConf` constructor in your application. To learn more, see the Python SparkConf documentation.\n\n\n\n\n\n- The `SparkConf` constructor in your application. To learn more, see the Scala SparkConf documentation.\n\n\n\n\n\n- The `--conf` flag at runtime. To learn more, see Dynamically Loading Spark Properties in the Spark documentation.\n\n- The `$SPARK_HOME/conf/spark-default.conf` file.\n\nThe MongoDB Spark Connector will use the settings in `SparkConf` as defaults.\n\n### Using an Options Map\n\nIn the Spark API, the `DataFrameReader`, `DataFrameWriter`, `DataStreamReader`, and `DataStreamWriter` classes each contain an `option()` method. You can use this method to specify options for the underlying read or write operation.\n\nOptions specified in this way override any corresponding settings in `SparkConf`.\n\n#### Short-Form Syntax\n\nOptions maps support short-form syntax. You may omit the prefix when specifying an option key string.\n\nThe following syntaxes are equivalent to one another:\n\n- `dfw.option(\"spark.mongodb.write.collection\", \"myCollection\").save()`\n\n- `dfw.option(\"spark.mongodb.collection\", \"myCollection\").save()`\n\n- `dfw.option(\"collection\", \"myCollection\").save()`\n\nTo learn more about the `option()` method, see the following Spark documentation pages:\n\n\n\n\n\n- DataFrameReader\n\n- DataFrameWriter\n\n- DataStreamReader\n\n- DataStreamWriter\n\n\n\n\n\n- DataFrameReader\n\n- DataFrameWriter\n\n- DataStreamReader\n\n- DataStreamWriter\n\n\n\n\n\n- DataFrameReader\n\n- DataFrameWriter\n\n- DataStreamReader\n\n- DataStreamWriter\n\n\n\n\n\n### Using a System Property\n\nThe Spark Connector reads some configuration settings before `SparkConf` is available. You must specify these settings by using a JVM system property.\n\nFor more information on Java system properties, see the Java documentation.\n\nIf the Spark Connector throws a `ConfigException`, confirm that your `SparkConf` or options map uses correct syntax and contains only valid configuration options."} -{"chunk_id": "6997fd716fd39a1e7ec5abd2-0", "page_id": "6997fd716fd39a1e7ec5abd2", "source_name": "sql-interface", "product_name": "MongoDB SQL Interface", "url": "https://mongodb.com/docs/sql-interface/tutorials/connect-tutorial", "title": "Connect to and Query Data with Free SQL Tools", "text": "# Connect to and Query Data with Free SQL Tools\n\nThis tutorial guides you through connecting to an Atlas dedicated cluster or a federated database instance with the free tools MongoDB JDBC (Java Database Connectivity) Driver and DBeaver (Community Edition).\n\nIf you loaded sample data into your deployment, this tutorial also guides you through querying it.\n\nBefore you start, configure your deployment to accept SQL connections. To learn how, see SQL Interface Server Setup.\n\n## Install Client Software\n\nInstall the following client software to connect to and query your data with MongoSQL.\n\n### Install DBeaver\n\nDBeaver is a free, universal database tool. You can use it to explore your sample data in this tutorial. Download and install DBeaver (Community Edition).\n\n### Install the JDBC Driver\n\n- Download the latest MongoDB JDBC Driver version.\n\n- Verify the integrity of the downloaded package:\n\n The MongoDB release team digitally signs all software packages to certify that a particular MongoDB package is a valid and unaltered MongoDB release. MongoDB signs each release branch with a different PGP key in `.asc` format.\n\n - Run the following command to download the `.asc` file from the Maven Central Repository. Replace `{version-number}` with the version of the driver you downloaded and `{artifact_to_verify}` with the name of the file you downloaded.\n\n ```sh\n curl -O https://repo1.maven.org/maven2/org/mongodb/mongodb-jdbc/{version-number}/{artifact_to_verify}.asc\n ```\n\n For example, if you downloaded `mongodb-jdbc-2.2.3-all.jar`, you would run the following command.\n\n ```sh\n curl -O https://repo1.maven.org/maven2/org/mongodb/mongodb-jdbc/2.2.3/mongodb-jdbc-2.2.3-all.jar.asc\n ```\n\n - Run the following command to download then import the key file. Replace `{server_url}` with one of the current GPG key servers supported by Maven:\n\n - `keyserver.ubuntu.com`\n\n - `keys.openpgp.org`\n\n - `pgp.mit.edu`\n\n ```shell\n gpg --keyserver {server_url} --recv-keys BDDC8671F1BE6F4D5464096624A4A8409351E954\n ```\n\n ```shell\n gpg: key BDDC8671F1BE6F4D5464096624A4A8409351E954: public key \"MongoDB JDBC Driver Release Signing Key \" imported\n gpg: Total number processed: 1\n gpg: imported: 1\n ```\n\n - Run the following command to verify the MongoDB JDBC Driver installation file. Replace `detached_signature_file` and `artifact_to_verify` with the names of the files you downloaded.\n\n ```\n gpg --verify {detached_signature_file} {artifact_to_verify}\n ```\n\n For example, if you downloaded `mongodb-jdbc-2.2.3-all.jar` and `mongodb-jdbc-2.2.3-all.jar.asc` to your current directory, you would run the following.\n\n ```\n gpg --verify mongodb-jdbc-2.2.3-all.jar.asc mongodb-jdbc-2.2.3-all.jar\n ```\n\n GPG should return a response similar to the following:\n\n ```shell\n gpg: Signature made Wed May 22 13:24:36 2024 MDT\n gpg: using RSA key BDDC8671F1BE6F4D5464096624A4A8409351E954\n gpg: Good signature from \"MongoDB JDBC Driver Release Signing Key \"\n ```\n\n If the package is properly signed, but you don't yet trust the signing key in your local `trustdb`, `gpg` will also return the following message:\n\n ```shell\n gpg: WARNING: This key is not certified with a trusted signature!\n gpg: There is no indication that the signature belongs to the owner.\n Primary key fingerprint: D2C4 5B7E 66A5 DCA1 8B76 57A8 91A2 1577 3066 6110\n ```\n\n If you receive the following error message, confirm that you imported the correct public key:\n\n ```shell\n gpg: Can't check signature: public key not found\n ```\n\n## Connect from DBeaver\n\nChoose your deployment type to get your connection string and configure DBeaver:\n\n### In Atlas, go to the Clusters page for your project.\n\n- If it's not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.\n\n- If it's not already displayed, select your desired project from the Projects menu in the navigation bar.\n\n- In the sidebar, click Clusters under the Database heading.\n\nThe Clusters page displays.\n\n### On the cluster card, click Connect.\n\n### Click Atlas SQL.\n\nThe option is under Access your data through tools.\n\nIf the cluster reports that the SQL Interface isn't enabled, click Configure Atlas SQL and enable it first. Atlas applies the change asynchronously, so the connection details can take a few minutes to appear.\n\n### Select your driver.\n\nFrom Select your driver, select JDBC Driver.\n\n### Copy your connection information.\n\nUnder Get Connection String, copy the Connection URL. You'll need this in a later step.\n\n### Open your DBeaver application.\n\n### Add a driver to DBeaver.\n\n- In DBeaver, click Database and select Driver Manager from the dropdown menu.\n\n- Click New to open the Create new driver modal.\n\n- In the Settings tab, specify the following information:\n\n \n\n \n \n \n \n \n \n \n \n
\n Driver Name\n\n \n `MongoSQL`\n\n
\n Class Name\n\n \n `com.mongodb.jdbc.MongoDriver`\n\n
\n\n- In the Libraries tab, click Add File and add your JDBC driver `all.jar` file.\n\n Click Find Class.\n\n- Click OK. The Create new driver modal closes.\n\n### Create a database connection.\n\n- In DBeaver, click Database and select New Database Connection from the dropdown menu to open the Connect to a database modal.\n\n- From the list of databases, select the `MongoDB` database driver that you created in the previous step.\n\n If you don't see `MongoDB`, select the All category inside the modal.\n\n Click Next.\n\n- In the Main tab, enter the following information:\n\n \n\n \n \n \n \n \n \n \n \n \n \n \n \n
\n JDBC URL\n\n \n Connection string obtained from a previous step.\n\n
\n Username\n\n \n MongoDB user authorized for the connection.\n\n
\n Password\n\n \n Password associated with the MongoDB user.\n\n
\n\n- In the Driver properties tab, expand User Properties. Add the following key-value properties:\n\n \n\n \n \n \n \n \n \n \n \n
\n database\n\n \n The name of your virtual database.\n\n
\n user\n\n \n The MongoDB user to connect with. Not required if you entered a `Username` in the previous step.\n\n
\n\n### In Atlas, go to your federated database instance for your project.\n\n- If it's not already displayed, select the organization that contains your project from the Organizations menu in the navigation bar.\n\n- If it's not already displayed, select your project from the Projects menu in the navigation bar.\n\n- In the sidebar, click Data Federation under the Services heading.\n\nThe Data Federation page displays.\n\nOn the federated database card, click Connect.\n\nA connection dialog box opens.\n\n### Click Atlas SQL.\n\n### Select your driver.\n\nFrom Select your driver, select JDBC Driver.\n\n### Copy your connection information.\n\nSelect a database from the Database dropdown, then click to copy the connection string. You'll need this in a later step.\n\n### Open your DBeaver application.\n\n### Add a driver to DBeaver.\n\n- In DBeaver, click Database and select Driver Manager from the dropdown menu.\n\n- Click New to open the Create new driver modal.\n\n- In the Settings tab, specify the following information:\n\n \n\n \n \n \n \n \n \n \n \n
\n Driver Name\n\n \n `MongoSQL`\n\n
\n Class Name\n\n \n `com.mongodb.jdbc.MongoDriver`\n\n
\n\n- In the Libraries tab, click Add File and add your JDBC driver `all.jar` file.\n\n Click Find Class.\n\n- Click OK. The Create new driver modal closes."} -{"chunk_id": "6997fd716fd39a1e7ec5abd2-1", "page_id": "6997fd716fd39a1e7ec5abd2", "source_name": "sql-interface", "product_name": "MongoDB SQL Interface", "url": "https://mongodb.com/docs/sql-interface/tutorials/connect-tutorial", "title": "Connect to and Query Data with Free SQL Tools", "text": "### Create a database connection.\n\n- In DBeaver, click Database and select New Database Connection from the dropdown menu to open the Connect to a database modal.\n\n- From the list of databases, select the `MongoDB` database driver that you created in the previous step.\n\n If you don't see `MongoDB`, select the All category inside the modal.\n\n Click Next.\n\n- In the Main tab, enter the following information:\n\n \n\n \n \n \n \n \n \n \n \n \n \n \n \n
\n JDBC URL\n\n \n Connection string obtained from a previous step.\n\n
\n Username\n\n \n MongoDB user authorized for the connection.\n\n
\n Password\n\n \n Password associated with the MongoDB user.\n\n
\n\n- In the Driver properties tab, expand User Properties. Add the following key-value properties:\n\n \n\n \n \n \n \n \n \n \n \n
\n database\n\n \n The name of your virtual database.\n\n
\n user\n\n \n The MongoDB user to connect with. Not required if you entered a `Username` in the previous step.\n\n
\n\nTo learn more about the different methods you can use to connect, see Connect Your SQL Tool to MongoDB.\n\n## Run MongoSQL Queries\n\nTo run MongoSQL queries in DBeaver:\n\n### Expand your MongoDB connection.\n\nThe DBeaver Database Navigator displays your virtual databases.\n\n### Open a SQL console.\n\n- Right-click the virtual database you want to query.\n\n- Select SQL Editor.\n\n- Select Open SQL console.\n\n A new SQL console window opens connected to the virtual database you selected.\n\n### Enter a SQL query in the console.\n\n### Click Execute SQL Statement to run your SQL query.\n\nIf the query is successful, MongoSQL displays the results in a table view below your query.\n\n### Example MongoSQL Queries\n\nIf you loaded sample data into your deployment, try running the following MongoSQL queries against it.\n\nOtherwise, you can modify these example queries for your namespaces.\n\n#### SELECT Statement\n\n```sh\nSELECT *\nFROM Sessions\n```\n\nMongoSQL returns all documents from the `Sessions` collection.\n\n#### LIMIT Statement\n\n```sh\nSELECT *\nFROM Users\nLIMIT 2\n```\n\nMongoSQL returns two documents from the `Users` collection.\n\n#### WHERE Statement\n\n```sh\nSELECT *\nFROM Users\nWHERE name = 'Jon Snow'\n```\n\nMongoSQL returns documents from the `Users` collection where the user's `name` is `Jon Snow`.\n\nFor an MongoSQL command reference, see MongoSQL Language Reference."} -{"chunk_id": "6a630539d3c0cfaf89e39ced-0", "page_id": "6a630539d3c0cfaf89e39ced", "source_name": "sql-interface", "product_name": "MongoDB SQL Interface", "url": "https://mongodb.com/docs/sql-interface/schema/adf", "title": "Atlas Data Federation Schema Commands", "text": "# Atlas Data Federation Schema Commands\n\nIn Atlas Data Federation, you manage the schema that the SQL Interface uses through three commands: `sqlGenerateSchema`, `sqlGetSchema`, and `sqlSetSchema`. You run these commands from `mongosh` against a federated database instance, or you perform the equivalent actions in the Atlas UI. This page documents those commands and their UI equivalents.\n\nAtlas Data Federation samples documents from your collections to generate the initial schema. For background on schema management and the other supported deployment types, see Schema Management.\n\nThe `sqlGenerateSchema`, `sqlGetSchema`, and `sqlSetSchema` commands and their Atlas UI equivalents apply only to the Atlas Data Federation deployment type. They don't apply to self-managed Enterprise Advanced (EA) deployments, which use the MongoDB SQL Schema Builder CLI, or to queries against a standard Atlas cluster that doesn't use Atlas Data Federation.\n\n## sqlGenerateSchema\n\nThe `sqlGenerateSchema` command generates a SQL Interface schema for the specified collections or views. Atlas Data Federation samples documents from each namespace to derive the schema.\n\n### Syntax\n\nWhen you use the `sampleNamespaces` parameter, you must run the command against the `admin` database.\n\n```sh\nuse admin\ndb.runCommand({\n sqlGenerateSchema: 1,\n sampleNamespaces: [],\n sampleSize: ,\n setSchemas: true|false\n})\n```\n\n### Parameters\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nParameter\n\n\nType\n\n\nDescription\n\n\nNecessity\n\n
\n`sampleNamespaces`\n\n\narray of strings\n\n\nSpecifies the comma-separated list of namespaces for which to generate schemas. A namespace includes the database name, a dot (`.`) separator, and the collection or view name (that is, `.|`). To generate schemas for all the collections in a database, specify `*` instead of the collection or view name (that is, `.*`). If omitted, Atlas Data Federation generates schemas for all collections and views in the current database.\n\n\nOptional\n\n
\n`sampleSize`\n\n\ninteger\n\n\nSpecifies the number of documents to use as a sample to create the schema. If omitted, defaults to `1000`.\n\n\nOptional\n\n
\n`setSchemas`\n\n\nboolean\n\n\nSpecifies whether to store the generated schema for the collection or view. Value can be one of the following:\n\n- `true` to store the schema. If a schema already exists for the collection or view, Atlas Data Federation overwrites the existing schema.\n\n- `false` to not store the schema.\n\nIf omitted, defaults to `false`.\n\n\nOptional\n\n
\n\n### Output\n\nThe command returns the following output if it succeeds:\n\n```json\n{\n \"ok\" : 1,\n \"schemas\" : [\n {\n \"databaseName\" : \"\",\n \"namespaces\" : [\n {\n \"name\" : \"\",\n \"schema\" : {\n \"version\" : NumberLong(1),\n \"jsonSchema\" : { ... }\n }\n }\n ]\n },\n ...\n ]\n}\n```\n\nThe `schemas` object contains the following fields.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nParameter\n\n\nType\n\n\nDescription\n\n
\n`databaseName`\n\n\nstring\n\n\nName of the database.\n\n
\n`namespaces`\n\n\narray of objects\n\n\nName and generated schema of each collection or view.\n\n
\n`namespaces.name`\n\n\nstring\n\n\nName of the collection or view.\n\n
\n`namespaces[n].schema`\n\n\ndocument\n\n\nSchema of the collection or view.\n\n
\n`namespaces[n].schema.version`\n\n\ninteger\n\n\nFormat version of the schema. Value is always 1.\n\n
\n`namespaces[n].schema.jsonSchema`\n\n\ndocument\n\n\nJSON (Javascript Object Notation) schema of the collection or view. The JSON (Javascript Object Notation) schema can contain the following fields:\n\n- `bsonType`\n\n- `properties`\n\n- `items`\n\n- `additionalProperties`\n\n- `required`\n\nTo learn more about these fields, see JSON Schema Keywords.\n\n
If you set the schema for the collection or view with the `setSchemas` option, you can verify that the command succeeded by running the `sqlGetSchema` command. The `sqlGetSchema` command `metadata.description` field contains the following value:\n\n```json\n\"set using sqlGenerateSchema with setSchemas = true\"\n```\n\n### Errors\n\nThe command returns the following error if it fails:\n\n```none\n\"failedNamespaces\": [\n {\n \"namespace\" : \"\",\n \"error\" : \"no documents found in sample namespace\"\n }\n]\n```\n\nAtlas Data Federation returns this error if the specified namespaces do not exist in the storage configuration or are empty. Atlas Data Federation also returns this error if it could not set the schema for a given namespace.\n\n## sqlGetSchema\n\nThe `sqlGetSchema` command retrieves the schema stored for the specified collection or view.\n\n### Syntax\n\n```sh\ndb.getSiblingDB(\"\").runCommand({\n sqlGetSchema: \"|\"\n})\n```\n\n### Parameters\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nParameter\n\n\nType\n\n\nDescription\n\n\nNecessity\n\n
\n``\n\n\nstring\n\n\nName of the collection for which to retrieve the schema. Provide either the collection name or the view name.\n\n\nConditional\n\n
\n``\n\n\nstring\n\n\nName of the view for which to retrieve the schema. Provide either the view name or the collection name.\n\n\nConditional\n\n
"} -{"chunk_id": "6a630539d3c0cfaf89e39ced-1", "page_id": "6a630539d3c0cfaf89e39ced", "source_name": "sql-interface", "product_name": "MongoDB SQL Interface", "url": "https://mongodb.com/docs/sql-interface/schema/adf", "title": "Atlas Data Federation Schema Commands", "text": "### Output\n\nThe command returns the following output if the collection or view does not have a schema:\n\n```json\n{ \"ok\" : 1, \"metadata\" : { }, \"schema\" : { } }\n```\n\nThe command returns output similar to the following if the collection or view has a schema:\n\n```json\n{\n \"ok\": 1,\n \"metadata\": {\n \"description\": \"\"\n },\n \"schema\": {\n \"version\": NumberLong(1),\n \"jsonSchema\": { ... }\n }\n}\n```\n\nThe `metadata.description` field describes how the schema was set for the collection. Value can be one of the following:\n\n`generated automatically by Atlas Data Federation`\nIndicates that the schema was automatically generated by Atlas Data Federation.\n\n`set using sqlGenerateSchema with setSchemas = true`\nIndicates that the schema was set by the sqlGenerateSchema command because the `setSchema` option was set to `true`.\n\n`set using sqlSetSchema`\nIndicates that the schema was set using the sqlSetSchema command.\n\nThe `schema` document contains the following fields:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nParameter\n\n\nType\n\n\nDescription\n\n
\n`schema.version`\n\n\ninteger\n\n\nFormat version of the schema. Value is always 1.\n\n
\n`schema.jsonSchema`\n\n\ndocument\n\n\nJSON (Javascript Object Notation) schema of the collection or view. The JSON (Javascript Object Notation) schema can contain the following fields:\n\n- `bsonType`\n\n- `properties`\n\n- `items`\n\nTo learn more about these fields, see JSON Schema Keywords.\n\n
\n\n## sqlSetSchema\n\nThe `sqlSetSchema` command sets or removes the schema for a collection or view. The command applies the schema you provide directly. The command does not validate the provided schema against the data in the collection.\n\n### Syntax\n\n\n\n\n\n```sh\ndb.getSiblingDB(\"\").runCommand({\n sqlSetSchema: \"|\",\n schema: {\n \"version\": 1,\n \"jsonSchema\": \n }\n})\n```\n\n\n\n\n\n```sh\ndb.getSiblingDB(\"\").runCommand({\n sqlSetSchema: \"|\",\n schema: {}\n})\n```\n\n\n\n\n\n### Parameters\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nParameter\n\n\nType\n\n\nDescription\n\n\nNecessity\n\n
\n``\n\n\nstring\n\n\nName of the collection for which to set the schema. Provide either a collection name or a view name.\n\n\nConditional\n\n
\n``\n\n\nstring\n\n\nName of the view for which to set the schema. Provide either a view name or a collection name.\n\n\nConditional\n\n
\n`schema`\n\n\ndocument\n\n\nThe format version of the schema and either:\n\n- the JSON (Javascript Object Notation) schema for the collection or view\n\n- an empty document to remove the schema for the collection or view\n\nYou can provide a single document or an array of documents in the `items` field. When you retrieve the schema, `items` shows the form that you used to set the schema.\n\n\nRequired\n\n
\n\n### Output\n\nThe command returns the following output if it succeeds:\n\n```sh\n{ \"ok\" : 1 }\n```\n\nYou can verify that the command succeeded by running the `sqlGetSchema` command. The `metadata.description` field in the response contains the following value:\n\n```json\n\"set using sqlSetSchema\"\n```\n\n## Examples\n\nConsider a collection named `egData` in a database named `sampleDB` with the following documents:\n\n```json\n{\"a\": {\"b\": {\"c\": [1, 2, 3]}}, \"s\": 1}\n{\"a\": {\"b\": {\"c\": [4, 5, 6]}}, \"s\": 2}\n{\"a\": {\"b\": [7, 8, 9]}, \"s\": 3}\n{\"a\": {\"b\": {\"c\": []}}, \"s\": 4}\n{\"a\": {\"b\": {\"c\": \"hello\"}}, \"s\": 5}\n{\"a\": {\"b\": {\"c\": {\"d\": 1}}}, \"s\": 6}\n{\"a\": {\"b\": {\"c\": null}}}\n{\"s\": 7}\n```\n\nThe following examples use the Atlas Data Federation schema commands to generate, retrieve, set, and remove the schema for the preceding collection.\n\n### Generate a Schema\n\nThe following command generates a schema for the collection named `sampleDB.egData` in the storage configuration. The command uses two randomly selected documents from the collection to create the schema because `sampleSize` is `2`. The command does not set the schema for the collection because the `setSchemas` option is not specified and defaults to `false`.\n\n```sh\nuse admin\ndb.runCommand({\n sqlGenerateSchema: 1,\n sampleNamespaces: [\"sampleDB.egData\"],\n sampleSize: 2\n})\n```\n\nThe previous command returns the following output. To learn more about the fields in the output, see Output.\n\n```json\n{\n \"ok\" : 1,\n \"schemas\" : [\n {\n \"databaseName\" : \"sampleDB\",\n \"namespaces\" : [\n {\n \"name\" : \"egData\",\n \"schema\" : {\n \"version\" : NumberLong(1),\n \"jsonSchema\" : {\n \"bsonType\" : [ \"object\" ],\n \"properties\" : {\n \"a\" : {\n \"bsonType\" : [ \"object\" ],\n \"properties\" : {\n \"b\" : {\n \"bsonType\" : [ \"object\" ],\n \"properties\" : {\n \"c\" : {\n \"bsonType\" : [ \"array\" ],\n \"items\" : {\n \"bsonType\" : [ \"int\" ]\n }\n }\n }\n }\n }\n },\n \"s\" : {\n \"bsonType\" : [ \"int\" ]\n }\n }\n }\n }\n }\n ]\n }\n ]\n}\n```\n\n### Generate and Set a Schema\n\nThe following command generates a schema for the collection named `sampleDB.egData` in the storage configuration. The command uses up to 1000 documents in the collection to create the schema because the `sampleSize` option is not specified and defaults to `1000`. The command sets the generated schema as the schema to use for the collection because `setSchemas` is `true`.\n\n```sh\nuse admin\ndb.runCommand({\n sqlGenerateSchema: 1,\n sampleNamespaces: [\"sampleDB.egData\"],\n setSchemas: true\n})\n```\n\n### Retrieve a Schema\n\nThe following command retrieves the schema stored for the `egData` collection:\n\n```sh\ndb.getSiblingDB(\"sampleDB\").runCommand({\n sqlGetSchema: \"egData\"\n})\n```\n\nThe previous command returns the following output. To learn more about the fields in the output, see Output.\n\n```json\n{\n \"ok\" : 1,\n \"metadata\" : {\n \"description\" : \"set using sqlGenerateSchema with setSchemas = true\"\n },\n \"schema\" : {\n \"version\" : NumberLong(1),\n \"jsonSchema\" : {\n \"bsonType\" : [ \"object\" ],\n \"properties\" : {\n \"a\" : {\n \"bsonType\" : [ \"object\" ],\n \"properties\" : {\n \"b\" : {\n \"bsonType\" : [ \"object\", \"array\" ],\n \"properties\" : {\n \"c\" : {\n \"bsonType\" : [ \"array\", \"string\", \"object\", \"null\" ],\n \"properties\" : {\n \"d\" : {\n \"bsonType\" : [ \"int\" ]\n }\n },\n \"items\" : {\n \"bsonType\" : [ \"int\" ]\n }\n }\n },\n \"items\" : {\n \"bsonType\" : [ \"int\" ]\n }\n }\n }\n },\n \"s\" : {\n \"bsonType\" : [ \"int\", \"object\" ]\n }\n }\n }\n }\n}\n```"} -{"chunk_id": "6a630539d3c0cfaf89e39ced-2", "page_id": "6a630539d3c0cfaf89e39ced", "source_name": "sql-interface", "product_name": "MongoDB SQL Interface", "url": "https://mongodb.com/docs/sql-interface/schema/adf", "title": "Atlas Data Federation Schema Commands", "text": "### Set a Schema\n\nThe following `sqlSetSchema` command sets the schema for the `egData` collection:\n\n```sh\ndb.getSiblingDB(\"sampleDB\").runCommand({\n sqlSetSchema : \"egData\",\n \"schema\" : {\n \"version\" : NumberLong(1),\n \"jsonSchema\" : {\n \"bsonType\" : [ \"object\" ],\n \"properties\" : {\n \"a\" : {\n \"bsonType\" : [ \"object\" ],\n \"properties\" : {\n \"b\" : {\n \"bsonType\" : [ \"object\", \"array\" ],\n \"properties\" : {\n \"c\" : {\n \"bsonType\" : [ \"array\", \"string\", \"object\", \"null\" ],\n \"properties\" : {\n \"d\" : {\n \"bsonType\" : [ \"int\" ]\n }\n },\n \"items\" : {\n \"bsonType\" : [ \"int\" ]\n }\n }\n },\n \"items\" : {\n \"bsonType\" : [ \"int\" ]\n }\n }\n }\n },\n \"s\" : {\n \"bsonType\" : [ \"int\", \"object\" ]\n }\n }\n }\n }\n})\n```\n\nThe previous command returns the following output:\n\n```json\n{ \"ok\" : 1 }\n```\n\n### Remove a Schema\n\nThe following `sqlSetSchema` command removes the schema for the `egData` collection by passing an empty `schema` document:\n\n```sh\ndb.getSiblingDB(\"sampleDB\").runCommand({\n sqlSetSchema: \"egData\",\n schema: {}\n})\n```\n\nThe previous command returns the following output:\n\n```json\n{ \"ok\" : 1 }\n```\n\n## Manage Schemas in the Atlas UI\n\nYou can perform the same schema actions in the Atlas UI from the Manage SQL Schemas page. The UI samples documents to generate schemas, the same as the `sqlGenerateSchema` command.\n\n### Create a Schema\n\nWhen you create a quick start connection, Atlas Data Federation generates the schema automatically. To create a schema manually, use the following procedure.\n\n#### In Atlas, go to your federated database instance for your project.\n\n- If it's not already displayed, select the organization that contains your project from the Organizations menu in the navigation bar.\n\n- If it's not already displayed, select your project from the Projects menu in the navigation bar.\n\n- In the sidebar, click Data Federation under the Services heading.\n\nThe Data Federation page displays.\n\n#### Navigate to the Manage SQL Schemas page.\n\nFrom the Federated Database Instances section, click the icon to the right of the schema, and then select Manage SQL Schemas from the dropdown.\n\n#### Create a schema.\n\nOn a collection that has an empty schema:\n\n- Click the .\n\n- Click Generate new schema from sample, or provide your own JSON.\n\n- Click Save.\n\n### Regenerate a Schema\n\nRegenerate a schema any time the shape of your underlying data changes, such as when you add fields or change field types, so that your SQL queries reflect the current data. To keep schemas current automatically instead, see Schedule Schema Updates.\n\n#### In Atlas, go to your federated database instance for your project.\n\n- If it's not already displayed, select the organization that contains your project from the Organizations menu in the navigation bar.\n\n- If it's not already displayed, select your project from the Projects menu in the navigation bar.\n\n- In the sidebar, click Data Federation under the Services heading.\n\nThe Data Federation page displays.\n\n#### Navigate to the Manage SQL Schemas page.\n\nFrom the Federated Database Instances section, click the icon to the right of the schema, and then select Manage SQL Schemas from the dropdown.\n\n#### Regenerate the schema.\n\nOn a collection that already has a schema:\n\n- Click the .\n\n- Click Generate new schema from sample.\n\n- Click Save.\n\n### View a Schema\n\n#### In Atlas, go to your federated database instance for your project.\n\n- If it's not already displayed, select the organization that contains your project from the Organizations menu in the navigation bar.\n\n- If it's not already displayed, select your project from the Projects menu in the navigation bar.\n\n- In the sidebar, click Data Federation under the Services heading.\n\nThe Data Federation page displays.\n\n#### Navigate to the Manage SQL Schemas page.\n\nFrom the Federated Database Instances section, click the icon to the right of the schema, and then select Manage SQL Schemas from the dropdown.\n\nOn this page, you can view all existing schemas. To view a specific schema in JSON format, click the .\n\n### Edit a Schema\n\n#### In Atlas, go to your federated database instance for your project.\n\n- If it's not already displayed, select the organization that contains your project from the Organizations menu in the navigation bar.\n\n- If it's not already displayed, select your project from the Projects menu in the navigation bar.\n\n- In the sidebar, click Data Federation under the Services heading.\n\nThe Data Federation page displays.\n\n#### Navigate to the Manage SQL Schemas page.\n\nFrom the Federated Database Instances section, click the icon to the right of the schema, and then select Manage SQL Schemas from the dropdown.\n\n#### Edit the schema.\n\n- Next to a schema, click the .\n\n- Edit the JSON.\n\n- Click Save.\n\n### Delete a Schema\n\n#### In Atlas, go to your federated database instance for your project.\n\n- If it's not already displayed, select the organization that contains your project from the Organizations menu in the navigation bar.\n\n- If it's not already displayed, select your project from the Projects menu in the navigation bar.\n\n- In the sidebar, click Data Federation under the Services heading.\n\nThe Data Federation page displays.\n\n#### Navigate to the Manage SQL Schemas page.\n\nFrom the Federated Database Instances section, click the icon to the right of the schema, and then select Manage SQL Schemas from the dropdown.\n\nOn this page, you can view all existing schemas.\n\n#### Delete the schema.\n\n- For the schema that you want to delete, click the .\n\n- Click Clear....\n\n- Click Clear schema to confirm.\n\n### Delete All Schemas\n\n#### In Atlas, go to your federated database instance for your project.\n\n- If it's not already displayed, select the organization that contains your project from the Organizations menu in the navigation bar.\n\n- If it's not already displayed, select your project from the Projects menu in the navigation bar.\n\n- In the sidebar, click Data Federation under the Services heading.\n\nThe Data Federation page displays.\n\n#### Navigate to the Manage SQL Schemas page.\n\nFrom the Federated Database Instances section, click the icon to the right of the schema, and then select Manage SQL Schemas from the dropdown.\n\nOn this page, you can view all existing schemas.\n\n#### Delete all schemas.\n\n- Click the icon in the top-right corner.\n\n- Click Clear all schemas.\n\n- Click Clear all schemas again to confirm.\n\n### Schedule Schema Updates\n\nScheduled schema updates help you maintain schema accuracy over time. Scheduled schema updates sample each namespace and merge the new schema with the existing one. For example, scheduled schema updates allow Atlas Data Federation to automatically pick up new fields added to collections.\n\n#### In Atlas, go to your federated database instance for your project.\n\n- If it's not already displayed, select the organization that contains your project from the Organizations menu in the navigation bar.\n\n- If it's not already displayed, select your project from the Projects menu in the navigation bar.\n\n- In the sidebar, click Data Federation under the Services heading.\n\nThe Data Federation page displays.\n\n#### Navigate to the Manage SQL Schemas page.\n\nFrom the Federated Database Instances section, click the icon to the right of the schema, and then select Manage SQL Schemas from the dropdown.\n\n#### Enable scheduled schema updates.\n\n- Click Configure schema update schedule.\n\n- Select a frequency.\n\n- Click Save."} -{"chunk_id": "6a630539d3c0cfaf89e39ced-3", "page_id": "6a630539d3c0cfaf89e39ced", "source_name": "sql-interface", "product_name": "MongoDB SQL Interface", "url": "https://mongodb.com/docs/sql-interface/schema/adf", "title": "Atlas Data Federation Schema Commands", "text": "## Learn More\n\n- Schema Management\n\n- MongoDB SQL Interface Overview"} -{"chunk_id": "6997fd716fd39a1e7ec5abd7-0", "page_id": "6997fd716fd39a1e7ec5abd7", "source_name": "sql-interface", "product_name": "MongoDB SQL Interface", "url": "https://mongodb.com/docs/sql-interface/connect-with-sql-composable", "title": "SQL Interface Server Setup", "text": "# SQL Interface Server Setup\n\nYou can use the MongoDB SQL Interface with an Atlas dedicated cluster, an Atlas federated database instance, or a self-managed Enterprise Advanced (EA) database. Choose your deployment type to get started:\n\n## Prerequisites\n\n- A MongoDB database user with which to connect.\n\n## Procedure\n\nYou get the SQL Interface connection string for a federated database instance from the connection dialog box on the federated database instance card. This is the only place to get it.\n\n### In Atlas, go to your federated database instance for your project.\n\n- If it's not already displayed, select the organization that contains your project from the Organizations menu in the navigation bar.\n\n- If it's not already displayed, select your project from the Projects menu in the navigation bar.\n\n- In the sidebar, click Data Federation under the Services heading.\n\nThe Data Federation page displays.\n\nBefore you can query data, you must have a schema. To generate one, see Atlas Data Federation Schema Commands.\n\n### On the federated database card, click Connect.\n\nA connection dialog box opens.\n\n### In the connection dialog box, click Atlas SQL.\n\n### Select your driver.\n\nFrom the Select your driver dropdown, select the driver that matches your BI (Business Intelligence) tool.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nDriver\n\n\nBI Tool\n\n
\nPower BI Connector\n\n\nPower BI Desktop\n\n
\nTableau Connector\n\n\nTableau Desktop or Server\n\n
\nJDBC Driver\n\n\nJDBC-supported tool such as DBeaver, DataGrip, or a Maven project\n\n
\nODBC Driver\n\n\nODBC-supported tool such as Excel\n\n
\n\n### Copy connection string.\n\n- Select a database from the Database dropdown.\n\n- Click to copy the connection string. You'll need this when you connect your BI (Business Intelligence) tool.\n\n- Click Done.\n\n## Prerequisites\n\n- A MongoDB database user with which to connect.\n\n- To enable the SQL Interface on an Atlas dedicated cluster, an Atlas user with the `Project Cluster Manager` or `Project Replica Set Manager` role.\n\n- A dedicated cluster, `M10` and above, running MongoDB 6.0 or later. To review every requirement, see MongoDB SQL Interface Overview.\n\n- To generate a schema, a database user with the `read` privilege on the `__mdb_internal_sqlinterface` database. The MongoDB SQL Schema Builder CLI reads this database before it processes any schema and exits if the read fails. To review every privilege that the CLI requires, see MongoDB SQL Schema Builder CLI.\n\n## Procedure\n\nEnable the SQL Interface on the cluster before you connect. Enabling is per cluster.\n\nYou can enable the SQL Interface from the Atlas UI or with the Atlas Administration API. To use the API, skip to Enable with the Atlas Administration API.\n\n### Enable in the Atlas UI\n\n#### In Atlas, go to the Clusters page for your project.\n\n- If it's not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.\n\n- If it's not already displayed, select your desired project from the Projects menu in the navigation bar.\n\n- In the sidebar, click Clusters under the Database heading.\n\nThe Clusters page displays.\n\n#### On the cluster card, click Connect.\n\nA connection dialog box opens.\n\n#### In the connection dialog box, click Atlas SQL.\n\n#### Click Configure Atlas SQL.\n\nThis button appears when the SQL Interface is off. It opens the same cluster configuration form as Edit Configuration.\n\n#### Expand Additional Settings.\n\nUnder Advanced Settings, set Enable Atlas SQL Interface (M10 and up) to on.\n\nThe toggle appears only for eligible clusters. If you don't see it, confirm that the cluster is a dedicated cluster, `M10` and above, running MongoDB 6.0 or later.\n\n#### Click Review Changes, then apply the change.\n\nThe review page lists Atlas SQL Interface with its original and new state, Disabled and Enabled.\n\nEnabling can take a few minutes to take effect.\n\n### Enable with the Atlas Administration API\n\nThe endpoints are in preview and require the `Accept: application/vnd.atlas.preview+json` header. To learn more about resource versions, see Versioned Atlas Administration API Overview. For the full reference, see Atlas Administration API v2.\n\nTo enable the SQL Interface using the Atlas Administration API, use the following procedure. Authenticate with a service account access token; to generate one, see Generate Service Account Token.\n\n#### Confirm the cluster is supported.\n\nSend a `GET` request to read the current status:\n\n```shell\ncurl --include --header \"Authorization: Bearer ${ACCESS_TOKEN}\" \\\n --header \"Accept: application/vnd.atlas.preview+json\" \\\n -X GET \"https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/sqlInterface\"\n```\n\nFor a supported cluster, the response resembles the following:\n\n```json\n{\n \"status\": \"OFF\",\n \"supported\": true\n}\n```\n\nAtlas omits `unsupportedReason` when the cluster supports the SQL Interface. If `supported` is `false`, the field is present and explains why. To learn what each value means, see Dedicated Cluster Considerations.\n\n#### Turn on the SQL Interface.\n\nSend a `PATCH` request with `status` set to `ON`:\n\n```shell\ncurl --include --header \"Authorization: Bearer ${ACCESS_TOKEN}\" \\\n --header \"Accept: application/vnd.atlas.preview+json\" \\\n --header \"Content-Type: application/vnd.atlas.preview+json\" \\\n --data '{ \"status\": \"ON\" }' \\\n -X PATCH \"https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/sqlInterface\"\n```\n\nA successful request returns the updated status. Status propagation is asynchronous, so use the `GET` endpoint to confirm the state Atlas has applied.\n\nTo turn the SQL Interface off, send the same `PATCH` request with `status` set to `OFF`."} -{"chunk_id": "6997fd716fd39a1e7ec5abd7-1", "page_id": "6997fd716fd39a1e7ec5abd7", "source_name": "sql-interface", "product_name": "MongoDB SQL Interface", "url": "https://mongodb.com/docs/sql-interface/connect-with-sql-composable", "title": "SQL Interface Server Setup", "text": "### Generate a Schema\n\nDedicated clusters manage schemas with the MongoDB SQL Schema Builder CLI only, the same way self-managed Enterprise Advanced (EA) deployments do. After you enable the SQL Interface, download and run the CLI to generate a schema for the collections that you want to query. To learn more, see MongoDB SQL Schema Builder CLI.\n\n#### Download the MongoDB SQL Schema Builder.\n\nDownload the MongoDB SQL Schema Builder for your operating system from the MongoDB download center.\n\n#### Run the MongoDB SQL Schema Builder.\n\n\n\n\n\n- Move the downloaded file to a directory of your choice and rename it to `mongodb-schema-manager`.\n\n- Go to the directory where you placed the file and run the following command to make the MongoDB SQL Schema Builder executable:\n\n ```bash\n chmod +x mongodb-schema-manager\n ```\n\n- Run the MongoDB SQL Schema Builder with the connection string that you copy from the Atlas UI. This command generates or regenerates the schema for your collections within the database.\n\n ```bash\n ./mongodb-schema-manager --uri 'mongodb+srv://:@/'\n ```\n\n- Look for the `__sql_schemas` collection in your database to verify the created SQL schema. Inside this collection, there is a document for each collection with its schema map and data type assignments.\n\n\n\n\n\n- Move the downloaded file to a directory of your choice and rename it to `mongodb-schema-manager.exe`.\n\n- Run the MongoDB SQL Schema Builder with the connection string that you copy from the Atlas UI. This command generates or regenerates the schema for your collections within the database.\n\n ```bash\n ./mongodb-schema-manager.exe --uri 'mongodb+srv://:@/'\n ```\n\n- Verify the created SQL schema by looking for the `__sql_schemas` collection in your database. Inside this collection, there is a document for each collection with its schema map and data type assignments.\n\n\n\n\n\n### Dedicated Cluster Considerations\n\nThe following applies only to SQL Interface on dedicated clusters.\n\n- Atlas allows schema generation and refresh for the cluster through the MongoDB SQL Schema Builder CLI. To learn more, see Schema Management.\n\n- Client applications, including ODBC (Open Database Connectivity) and JDBC (Java Database Connectivity) driver connections, can connect to the cluster through the SQL Interface after you enable it for the cluster and a schema exists. To install a driver, see SQL Interface Driver Setup. To connect a BI (Business Intelligence) tool, see Connect Your SQL Tool to MongoDB.\n\n- Atlas uses the reserved internal database\n `__mdb_internal_sqlinterface`. Don't modify or drop it.\n\n- When you turn the SQL Interface off, client applications lose access and schemas can't be updated or used until you turn the SQL Interface back on.\n\n#### Atlas Administration API Error Codes\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nStatus\n\n\nError Code\n\n\nCause and Resolution\n\n
\n`400`\n\n\n`CLUSTER_INVALID_STATE`\n\n\nThe cluster is in a state that cannot accept SQL Interface changes, such as `CREATING`, `UPDATING`, `DELETING`, `REPAIRING`, or `PAUSED`. Wait for the cluster to become idle, then retry the request.\n\n
\n`409`\n\n\n`TENANT_SQL_INTERFACE_NOT_SUPPORTED`\n\n\nThe cluster's version, tier, or type does not support the SQL Interface. Use the `GET` endpoint to read `unsupportedReason`, then resolve the underlying constraint.\n\n
\n`409`\n\n\n`SQL_INTERFACE_DISABLED_FOR_CLUSTER`\n\n\nThe SQL Interface is `OFF` for the cluster. Enable the SQL Interface before you request schema metadata.\n\n
\n\n#### Unsupported Reasons\n\nWhen `supported` is `false`, the `unsupportedReason` field contains one of the following values:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nValue\n\n\nMeaning\n\n
\n`UNSUPPORTED_TIER`\n\n\nThe cluster tier does not support the SQL Interface. The feature requires a dedicated cluster, `M10` and above.\n\n
\n`UNSUPPORTED_TYPE`\n\n\nThe cluster type does not support the SQL Interface. Flex clusters return this value. Use a dedicated cluster instead.\n\n
\n`UNSUPPORTED_MONGODB_VERSION`\n\n\nThe cluster runs a MongoDB version earlier than 6.0. Upgrade the cluster to MongoDB 6.0 or later.\n\n
\n\n## Prerequisites\n\n- A MongoDB database user with which to connect.\n\n## Procedure\n\nFor local or self-managed deployments, you must generate a schema by downloading and running the MongoDB SQL Schema Builder. To learn more, see the MongoDB SQL Schema Builder README.\n\n### Download the MongoDB SQL Schema Builder.\n\nDownload the MongoDB SQL Schema Builder for your operating system from the MongoDB download center.\n\n### Run the MongoDB SQL Schema Builder.\n\n\n\n\n\n- Move the downloaded file to a directory of your choice and rename to `mongodb-schema-manager`.\n\n- Go to the directory where you placed the file and run the following command to make the MongoDB SQL Schema Builder executable:\n\n ```bash\n chmod +x mongodb-schema-manager\n ```\n\n- Run the MongoDB SQL Schema Builder using a terminal command with your connection string like the following example. This command generates or regenerates the schema for your collections within the database.\n\n ```bash\n ./mongodb-schema-manager --uri 'mongodb://:@:/?authSource=admin'\n ```\n\n- Look for the `__sql_schemas` collection in your database to verify the created SQL schema. Inside this collection, there will be a document for each collection with its schema map and data type assignments.\n\n\n\n\n\n- Move the downloaded file to a directory of your choice and rename to `mongodb-schema-manager.exe`.\n\n- Run the MongoDB SQL Schema Builder using a terminal command with your connection string like the example below. This command generates or regenerates the schema for your collections within the database.\n\n ```bash\n ./mongodb-schema-manager.exe --uri 'mongodb://:@:/?authSource=admin'\n ```\n\n- Verify the created SQL schema by looking for the `__sql_schemas` collection in your database. Inside this collection, there will be a document for each collection with its schema map and data type assignments.\n\n\n\n\n\n## Next Steps\n\nAfter you configure your database to accept SQL connections, you can install the correct driver for your BI tool."} -{"chunk_id": "6a630539d3c0cfaf89e39cee-0", "page_id": "6a630539d3c0cfaf89e39cee", "source_name": "sql-interface", "product_name": "MongoDB SQL Interface", "url": "https://mongodb.com/docs/sql-interface/schema/schema-builder-cli", "title": "MongoDB SQL Schema Builder CLI", "text": "# MongoDB SQL Schema Builder CLI\n\nThe MongoDB SQL Schema Builder CLI is the schema-management tool for the SQL Interface on Enterprise Advanced (EA) self-managed deployments and on Atlas dedicated clusters (`M10` and above). You download and run the CLI against your cluster to generate or update the schema for your collections. The SQL Interface uses those schemas to translate SQL queries into MongoDB operations.\n\nThe CLI does not sample your data. Instead, it analyzes every document in each collection it processes, so the generated schema precisely reflects the exact data in the collections. Even fields that appear in only a small fraction of documents are included in the schema.\n\nSchema regeneration is always user-initiated. The CLI does not refresh a schema automatically or on a schedule. You should regenerate a schema whenever the shape of your underlying data changes, so that the SQL Interface operates on the provided schema information. If you need periodic updates, you can automate this by setting up a cron job to run the regeneration command on a schedule.\n\n## Prerequisites\n\nBefore you run the MongoDB SQL Schema Builder CLI, ensure that you meet the following requirements:\n\n- Your deployment is either a MongoDB Enterprise cluster (Enterprise Advanced (EA) self-managed) or a dedicated cluster (`M10` and above) running MongoDB 6.0 or later (Atlas). The CLI does not support MongoDB Community clusters, Free clusters, Flex clusters, or `M2` and `M5` shared Atlas clusters.\n\n- On a dedicated cluster, the SQL Interface is enabled for each cluster that you want to query with SQL. To learn more, see SQL Interface Server Setup.\n\n- The MongoDB SQL Schema Builder CLI is compatible with your operating system and architecture:\n\n - Windows `x86_64`.\n\n - Linux `x86_64` and `arm64`: OpenSSL 1.0 with glibc 2.26 or later, OpenSSL 1.1 with glibc 2.28 or later, or OpenSSL 3.0 with glibc 2.28 or later. MongoDB recommends OpenSSL 3.0 or later for secure connections.\n\n- You can connect to the cluster from the machine where you run the CLI with a connection string.\n\n- The database user that the CLI authenticates as has, at minimum:\n\n - The `read` privilege on each database that you want to process. This privilege lets the CLI enumerate and analyze your collections.\n\n - The `find`, `insert`, and `update` privileges on the `__sql_schemas` collection in each database that you process, or the `readWrite` role on the database. The CLI writes each schema with an upsert, so the `update` privilege is required even on the first run.\n\n - On a dedicated cluster, the `read` privilege on the `__mdb_internal_sqlinterface` database.\n\nYou can supply credentials with the `--username` and `--password` flags or include them in the connection string. If you do not provide credentials, the CLI attempts to connect without authentication and logs a warning.\n\n## Invoke the CLI\n\nYou run the MongoDB SQL Schema Builder CLI from the command line against your cluster to generate or update a schema. The binary is named `mongodb-schema-manager`.\n\n### Obtain a Connection String\n\nThe CLI needs a connection string (`--uri`) to connect to your cluster. You can also provide a configuration file (`--file`) so that you don't have to retype arguments on each run.\n\nUse the connection string for your EA self-managed deployment, in the same form you use to connect with `mongosh` or a driver.\n\n#### In Atlas, go to the Clusters page for your project.\n\n- If it's not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.\n\n- If it's not already displayed, select your desired project from the Projects menu in the navigation bar.\n\n- In the sidebar, click Clusters under the Database heading.\n\nThe Clusters page displays.\n\n#### On the cluster card, click Connect.\n\nA connection dialog box opens.\n\nSelect a connection method and copy the connection string.\n\nChoose the driver or shell connection option that matches how you plan to authenticate, then click Copy to copy the connection string. You'll use this string as the CLI's `--uri` value.\n\nThe following example analyzes every collection in the `sales` database and writes trace logs to a `logs` directory:\n\n```sh\nmongodb-schema-manager \\\n --uri \"mongodb://:\" \\\n --ns-include \"sales.*\" \\\n --logpath ./logs \\\n --verbosity info\n```\n\nWhen the run completes, the CLI prints the databases and namespaces for which it created or modified a schema. If any namespace has a level of polymorphism too great for meaningful use, it is deemed unstable. The CLI lists those namespaces. For more information, see Unstable Schemas.\n\n#### Connect with TLS\n\nIf your self-managed Enterprise Advanced (EA) deployment requires TLS, specify the TLS options in the connection string that you pass to `--uri`. The MongoDB SQL Schema Builder CLI does not provide command-line flags for TLS.\n\nPercent-encode any option value that contains reserved characters, including the `/` characters in a file path. For example, the path `/etc/certs/ca.pem` becomes `%2Fetc%2Fcerts%2Fca.pem`.\n\nThe following example enables TLS and specifies a Certificate Authority file:\n\n```sh\nmongodb-schema-manager \\\n --uri \"mongodb://:/?tls=true&tlsCAFile=%2Fetc%2Fcerts%2Fca.pem\" \\\n --ns-include \"sales.*\"\n```\n\nIf your deployment requires client certificates, also set `tlsCertificateKeyFile`, and `tlsCertificateKeyFilePassword` if the key file is encrypted. For the full list of TLS connection string options, see TLS Options.\n\n## How Schemas Are Stored\n\nThe CLI writes one schema document per namespace to a `__sql_schemas` collection in each database that it processes.\n\nTreat the `__sql_schemas` collection as a reserved namespace for the SQL Interface. Do not modify it manually. Use the CLI to create and update the schemas it contains.\n\n### Inspect Stored Schemas\n\nTo review the schemas that the CLI generated, run an aggregation pipeline against the `__sql_schemas` collection in the database you want to inspect. Each document reports the following metadata:\n\n- `lastUpdated`: The date and time of the most recent schema write.\n\n- `unstable`: Whether the schema is unstable. For more information, see Unstable Schemas.\n\nTo list the status of every schema in a database without printing the full schema body, run the following pipeline in `mongosh`:\n\n```javascript\ndb.getCollection(\"__sql_schemas\").aggregate([\n { $project: { _id: 0, namespace: \"$_id\", type: 1, lastUpdated: 1, unstable: 1 } },\n { $sort: { namespace: 1 } }\n])\n```\n\nTo view the full schema for a specific collection, match on its name:\n\n```javascript\ndb.getCollection(\"__sql_schemas\").aggregate([\n { $match: { _id: \"\" } },\n { $project: { _id: 0, namespace: \"$_id\", type: 1, lastUpdated: 1, unstable: 1, schema: 1 } }\n])\n```\n\nBy default, the CLI implicitly excludes any database or collection whose name begins with two underscores (`__`), including the `__sql_schemas` collection itself. To include these namespaces, you must specify them explicitly with `--ns-include`. For example, `--ns-include \"*.__*\"` includes collections that begin with `__` in databases that do not begin with `__`.\n\nThe CLI derives the schema of a view from the view pipeline and the schemas of the source collections that the pipeline references. Under normal conditions, the CLI does not sample views. To ensure that a view's derived schema is accurate, first generate up-to-date schemas for the source collections.\n\nIf no schema exists for a source collection, or if the CLI cannot derive the schema from the available source collection schemas, the CLI falls back to executing the view and sampling its output documents."} -{"chunk_id": "6a630539d3c0cfaf89e39cee-1", "page_id": "6a630539d3c0cfaf89e39cee", "source_name": "sql-interface", "product_name": "MongoDB SQL Interface", "url": "https://mongodb.com/docs/sql-interface/schema/schema-builder-cli", "title": "MongoDB SQL Schema Builder CLI", "text": "## CLI Flag Reference\n\nThe MongoDB SQL Schema Builder CLI accepts the following flags. You must provide either `--uri` or `--file` so that the CLI can connect to your cluster.\n\nThe path to a configuration file. Command-line arguments take precedence over values in the configuration file.\n\nThe connection string for your cluster.\n\nThe username for authentication. You can also specify the username in the connection string.\n\nThe password for authentication. You can also specify the password in the connection string.\n\nThe databases and collections to include, in the format `.`. Glob syntax is supported, such as `mydb.*`. Repeat the flag to specify multiple patterns. If you omit this flag, the CLI includes all databases and collections. Namespaces that begin with `__` are implicitly excluded unless you specify them explicitly.\n\nThe databases and collections to exclude, in the same format as `--ns-include`. Repeat the flag to specify multiple patterns. This flag takes precedence over `--ns-include`.\n\nEnables quiet mode for less output. Default: `false`.\n\nThe directory where the CLI writes log files. Log files are named `mongodb-schema-manager.log.{date}`. If you omit this flag, the CLI does not write log files.\n\nThe logging level to capture in the log file. Requires `--logpath`. Accepts `trace`, `debug`, `info`, `warn`, or `error`. Default: `warn`.\n\nThe action to perform on the schema. Default: `merge`. Accepts the following values:\n\n- `merge`: Merges the new schema with the existing schema. If no schema exists, this action creates one. This action does not update unstable schemas.\n\n- `overwrite`: Ignores and overwrites the existing schema. If no schema exists, this action creates one. Use this action to update an unstable schema.\n\n- `clear`: Removes the `schema` field from the existing schema document. If no schema exists, this action captures only metadata.\n\nPerforms a dry run without analyzing schemas or writing to the database. Use this flag to test your `--ns-include` and `--ns-exclude` patterns. Default: `false`.\n\nThe DNS resolver to use if DNS resolution fails or is slow. Accepts `cloudflare`, `google`, or `quad9`.\n\nThe maximum number of concurrent schema-processing jobs. Must be an integer greater than `0`. Default: two times the number of physical cores.\n\n## Unstable Schemas\n\nWhen a collection's documents vary widely in shape, such as collections that use field names as map keys, the CLI marks the derived schema as unstable. An unstable schema sets `unstable` to `true` in the schema document, caps the number of captured fields, and sets `additionalProperties` to `true`. An unstable schema may not fully represent the data in the namespace.\n\nWhen a run produces one or more unstable schemas, the CLI prints the affected namespaces:\n\n```text\nThe following namespaces have unstable schemas. They may not\nfully represent the data in the namespace.\nUnstable schemas are not updated by the schema-manager by\ndefault. To update them, use the 'overwrite' action.\n```\n\nThe default `merge` action does not update an unstable schema. To update an unstable schema, run the CLI with `--action overwrite`.\n\n## When to Regenerate a Schema\n\nRegenerate a schema when the shape of your underlying data changes, such as when you add fields, remove fields, or change the data type of an existing field. The CLI does not detect data-shape changes on its own, so regeneration is always user-initiated. An outdated schema can cause the SQL Interface to map collections to the wrong tables and columns.\n\n## Learn More\n\n- Schema Management\n\n- Install the MongoDB SQL Interface\n\n- MongoDB SQL Interface Overview\n\n- MongoDB Schema Manager Overview (PDF): Complete technical reference for the MongoDB SQL Schema Builder."} -{"chunk_id": "6997fd716fd39a1e7ec5abd8-0", "page_id": "6997fd716fd39a1e7ec5abd8", "source_name": "sql-interface", "product_name": "MongoDB SQL Interface", "url": "https://mongodb.com/docs/sql-interface/connect", "title": "Connect Your SQL Tool to MongoDB", "text": "# Connect Your SQL Tool to MongoDB\n\nConnect your SQL tool, such as Tableau, Power BI, or DBeaver to your MongoDB Atlas or Enterprise Advanced (EA) database.\n\nAll three SQL Interface deployment options use the same JDBC (Java Database Connectivity) and ODBC (Open Database Connectivity) drivers, so the steps on this page are the same whether you connect to an Atlas dedicated cluster, an Atlas federated database instance, or a self-managed Enterprise Advanced (EA) deployment. Configure your deployment to accept SQL connections first. To learn how, see SQL Interface Server Setup.\n\nMongoDB officially supports Tableau (Desktop, Server, or Cloud) and Power BI Desktop (Desktop and Service) with its JDBC (Java Database Connectivity) and ODBC (Open Database Connectivity) drivers. You can use the JDBC (Java Database Connectivity) and ODBC (Open Database Connectivity) drivers with other SQL-92 compatible tools, but MongoDB cannot guarantee compatibility. Test your specific SQL Interface features to confirm support.\n\n## Connect Tableau\n\nConnect an Atlas dedicated cluster, an Atlas federated database instance, or a self-hosted Enterprise Advanced (EA) database to Tableau (Desktop or Server) using the Tableau Connector for MongoDB.\n\n### Prerequisites\n\n- A MongoDB database, configured for the SQL Interface:\n\n - An Atlas dedicated cluster or a self-managed Enterprise Advanced (EA) deployment must run MongoDB 6.0 or later.\n\n - An Atlas federated database instance must be mapped to one or more data stores, and each Atlas cluster that it reads from must run MongoDB 5.0 or later. To learn more, see Deploy a Federated Database Instance.\n\n- The MongoDB JDBC (Java Database Connectivity) driver. To install, see SQL Interface Driver Setup.\n\n- Tableau Desktop, Server, or Cloud. SCRAM authentication is preferred for Tableau Server, and X.509 authentication is also supported. Tableau Cloud supports SCRAM authentication only. To learn more about supported authentication mechanisms, see SQL Interface Authentication.\n\n### Procedure\n\nThe following steps show you how to connect to MongoDB with Tableau:\n\n#### Download the Tableau Connector for MongoDB.\n\nTableau Desktop and Tableau Server version 2025 and later bundle the Tableau Connector for MongoDB. If your version of Tableau already includes the connector, skip this step. To use a different version than the one bundled with Tableau, complete this step.\n\nFor Tableau Desktop, you can also install the connector from Tableau. Search the Tableau Exchange for MongoDB SQL interface by MongoDB, then click Install and restart Tableau.\n\n- Download the latest Tableau Connector `taco` file from the MongoDB download center.\n\n- Move the `taco` file into the appropriate directory for your operating system:\n\n - **Windows:** `C:\\Users\\\\Documents\\My Tableau Repository\\Connectors`\n\n - **MacOS:** `~/Documents/My Tableau Repository/Connectors`\n\n - **Linux:** `/opt/tableau/connectors`\n\nIf you download a new version of the Tableau Connector for MongoDB, delete the previous `taco` file from your `Connectors` directory to ensure that Tableau uses the latest version.\n\n#### Get your MongoDB database connection information.\n\nSelect the tab for your deployment type for instructions on how to get your connection information:\n\n\n\n\n\n- Go to your Atlas dedicated cluster or federated database instance for your project.\n\n- Click Connect.\n\n- Select the Atlas SQL Interface option.\n\n- Select the Tableau Connector option under the Select your driver dropdown.\n\n- Select Tableau from the dropdown.\n\n- Select the database you want to connect to from the Database dropdown.\n\n- Copy your connection string and connection parameters.\n\n Use this information to connect with Tableau in a later step.\n\n\n\n\n\nUse a connection string that is compatible with the MongoDB Java driver. To learn more, see Connection URI.\n\n\n\n\n\n#### Open Tableau Desktop or Tableau Server.\n\n#### Go to the Connect menu.\n\n#### Select MongoDB SQL Interface by MongoDB.\n\nA connection modal displays.\n\n#### Enter your database connection information:\n\n\n\n\n\nEnter your SQL Interface connection string you saved in a previous step.\n\n\n\n\n\nEnter the following connection string:\n\n```none\nmongodb://localhost:/?authSource=admin\n```\n\nReplace `` with the port number configured for the SQL Interface server to listen on.\n\nThe `authSource` parameter specifies the database used to authenticate the MongoDB user. If you omit `authSource`, the database specified in the Database field is used for authentication.\n\nIn the Database field, enter the name of the MongoDB database you want to query.\n\n\n\n\n\n#### Select your authentication method.\n\nChoose your Authentication Mechanism from the dropdown.\n\nFor information about all supported authentication mechanisms, see SQL Interface Authentication.\n\n\n\n\n\n- Username: Enter your MongoDB username.\n\n- Password: Enter your MongoDB password.\n\n\n\n\n\nConfigure your PEM certificate using one of the following methods:\n\n- **Use a PEM File Path:**\n\n In your `mongodb_jdbc.properties` file, set the `x509pempath` property to your PEM file's path. For example, `x509pempath=/certs/client-cert.pem`.\n\n - If your PEM file is **unencrypted**, do not select Provide PEM Contents. No further action is required.\n\n - If your PEM file is **encrypted**, select Provide PEM Contents and enter the file's passphrase in the Password field.\n\n- **Provide PEM Contents:**\n\n Select the checkbox next to Provide PEM Contents and enter your certificate data into the Password field:\n\n - **Unencrypted Content**: Paste the full certificate content directly into the field.\n\n - **Encrypted Content**: Paste a JSON object containing the content and passphrase:\n\n ```json\n { \"pem\": \"\", \"passphrase\": \"\" }\n ```\n\n\n\n\n\nEnter the Kerberos principal name in the Username field. For example, `user@EXAMPLE.COM`.\n\n\n\n\n\nNo additional properties or fields are required in the connection dialog for OIDC (OpenID Connect).\n\n\n\n\n\n#### Click Sign In."} -{"chunk_id": "6997fd716fd39a1e7ec5abd8-1", "page_id": "6997fd716fd39a1e7ec5abd8", "source_name": "sql-interface", "product_name": "MongoDB SQL Interface", "url": "https://mongodb.com/docs/sql-interface/connect", "title": "Connect Your SQL Tool to MongoDB", "text": "### Configure Tableau Logging\n\nTo change the logging configuration for the MongoDB JDBC (Java Database Connectivity) driver, add logging properties to the `mongodb_jdbc.properties` file. The location of this file depends on your platform:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nPlatform\n\n\nPath\n\n
\nmacOS\n\n\n`~/Documents/My Tableau Repository/Datasources/mongodb_jdbc.properties``~/Documents/My Tableau Prep Repository/Datasources/mongodb_jdbc.properties`\n\n
\nWindows\n\n\n`C:\\Users\\\\Documents\\My Tableau Repository\\Datasources\\mongodb_jdbc.properties``C:\\Users\\\\Documents\\My Tableau Prep Repository\\Datasources\\mongodb_jdbc.properties`\n\n
\nTableau Server (RHEL)\n\n\n`/var/opt/tableau/tableau_server/data/tabsvc/vizqlserver/Datasources/mongodb_jdbc.properties`\n\nCopy this file to all server nodes.\n\n
To configure logging, add the following properties to the file:\n\n```properties\nloglevel=INFO\nlogdir=\n```\n\nThe `loglevel` property sets the verbosity of the driver logs. It accepts the following values, in order of increasing verbosity: `OFF`, `SEVERE`, `WARNING`, `INFO`, `FINE`, and `FINER`. The default is `OFF`.\n\nThe `logdir` property sets the directory where the driver writes log files. The directory must already exist. If you omit `logdir` or set it to `console`, the driver writes logs to the console instead of to a file.\n\nIn production environments, start with the `SEVERE` log level. Raise the level only when you must diagnose an issue, because each level adds a large amount of output. At the `FINER` level, the driver logs every call that retrieves data for each cell of each result set.\n\nTo learn more about properties files in Tableau, see the Tableau documentation.\n\n## Connect Power BI\n\nConnect an Atlas dedicated cluster, an Atlas federated database instance, or a self-hosted Enterprise Advanced (EA) database to Power BI using the Power BI Connector for MongoDB.\n\n### Prerequisites\n\n- A MongoDB database, configured for the SQL Interface:\n\n - An Atlas dedicated cluster or a self-managed Enterprise Advanced (EA) deployment must run MongoDB 6.0 or later.\n\n - An Atlas federated database instance must be mapped to one or more data stores, and each Atlas cluster that it reads from must run MongoDB 5.0 or later. To learn more, see Deploy a Federated Database Instance.\n\n- The MongoDB ODBC (Open Database Connectivity) driver. To install, see SQL Interface Driver Setup. To use Direct Query, you must install version 1.2 or later.\n\n- Power BI Desktop 64 bit. Microsoft updates and releases Power BI monthly, and Atlas supports only the latest version of Power BI Desktop.\n\n- Windows operating system. To learn the Windows OS versions that Power BI Desktop supports, see the Microsoft documentation.\n\n### Procedure\n\nThe following steps show you how to connect to MongoDB with Power BI:\n\n#### Download the Power BI Connector for MongoDB.\n\n- Download the latest Power BI Connector `pqx` file from the MongoDB download center.\n\n The Power BI Connector for MongoDB ships with Power BI Desktop. If your version of Power BI Desktop already has the MongoDB Atlas SQL connector, skip this step. To use a different version than the one bundled with Power BI Desktop, complete this step.\n\n- Move the connector file to the following directory path:\n\n `C:\\Users\\\\Documents\\Power BI Desktop\\Custom Connectors`.\n\n Create this folder if it doesn't already exist.\n\n#### Get your MongoDB database connection information.\n\nSelect the tab for your deployment type for instructions on how to get your connection information:\n\n\n\n\n\n- Go to your Atlas dedicated cluster or federated database instance for your project.\n\n- Click the Connect button.\n\n- Select the Atlas SQL Interface option.\n\n- Select the Power BI Connector option under the Select your driver dropdown.\n\n- Copy your connection string.\n\n Use this information to connect with Power BI in a later step.\n\n\n\n\n\nUse your MongoDB deployment URI (Uniform Resource Identifier). To learn more, see Connection Strings.\n\n\n\n\n\n#### Connect from Power BI Desktop.\n\n- Open Power BI Desktop.\n\n- Select Get data from the Home menu.\n\n- Find and select the MongoDB Atlas SQL connector.\n\n - Type `mongo` in the search bar to find the new connector.\n\n - Select MongoDB Atlas SQL.\n\n - Click Connect.\n\n- Enter the URI and the database name and click OK.\n\n The MongoDB URI is the connection string that you copied in a previous step.\n\n In the Native query field, you can optionally enter a SQL query. Power BI uses the SQL query as the direct source for the data. You can also add or change the SQL query in the Power Query editor after you connect.\n\n- Enter your Atlas User name and Password and click Connect.\n\n By default, users can access all namespaces that their roles and connection URI permit. If you use custom roles to restrict access, you can grant users access to additional namespaces in the Edit User menu. To learn more, see Configure Database Users.\n\n For information about other supported authentication mechanisms, see SQL Interface Authentication.\n\n### Direct Query\n\nDirect Query is a connection mode available with the Power BI Connector for MongoDB version 1.2 and later. To use Direct Query, you must install MongoDB ODBC Driver version 1.2 or later. You don't need to configure a DSN.\n\nDirect Query is an alternative to the standard Import Mode, and allows you to query your database directly. This guarantees up-to-date data but may take longer to return results.\n\nDirect Query does not support some actions. If you try to perform an unsupported action, Power BI prompts you to switch to Import Mode.\n\n## Connect DBeaver\n\nConnect your Atlas dedicated cluster, Atlas federated database instance, or self-managed Enterprise Advanced (EA) deployment to DBeaver using the MongoDB JDBC (Java Database Connectivity) Driver.\n\n### Prerequisites\n\n- A MongoDB database, configured for the SQL Interface:\n\n - An Atlas dedicated cluster or a self-managed Enterprise Advanced (EA) deployment must run MongoDB 6.0 or later.\n\n - An Atlas federated database instance must be mapped to one or more data stores, and each Atlas cluster that it reads from must run MongoDB 5.0 or later. To learn more, see Deploy a Federated Database Instance.\n\n- DBeaver (Community Edition).\n\n- The MongoDB JDBC (Java Database Connectivity) driver. To install, see SQL Interface Driver Setup."} -{"chunk_id": "6997fd716fd39a1e7ec5abd8-2", "page_id": "6997fd716fd39a1e7ec5abd8", "source_name": "sql-interface", "product_name": "MongoDB SQL Interface", "url": "https://mongodb.com/docs/sql-interface/connect", "title": "Connect Your SQL Tool to MongoDB", "text": "### Procedure\n\nTo connect from DBeaver:\n\n#### Get your MongoDB database connection information.\n\nSelect the tab for your deployment type for instructions on how to get your connection information:\n\n\n\n\n\n- Go to your Atlas dedicated cluster or federated database instance for your project.\n\n- Click the Connect button.\n\n- Select the Atlas SQL Interface option.\n\n- Select the JDBC Driver option under the Select your driver dropdown.\n\n- Select the database you want to connect to from the Database dropdown.\n\n- Copy your connection string.\n\n Use this information to connect with DBeaver in a later step.\n\n\n\n\n\nUse a connection string that is compatible with the MongoDB Java driver. To learn more, see Connection URI.\n\n\n\n\n\n#### Open your DBeaver application.\n\n#### Add a driver to DBeaver.\n\n- In DBeaver, click Database and select Driver Manager from the dropdown menu.\n\n- Click New to open the Create new driver modal.\n\n- In the Settings tab, specify the following information:\n\n \n\n \n \n \n \n \n \n \n \n
\n Driver Name\n\n \n `MongoSQL`\n\n
\n Class Name\n\n \n `com.mongodb.jdbc.MongoDriver`\n\n
\n\n- In the Libraries tab, click Add File and add your JDBC driver `all.jar` file.\n\n Click Find Class.\n\n- Click OK. The Create new driver modal closes.\n\n#### Create a database connection.\n\n- In DBeaver, click Database and select New Database Connection from the dropdown menu to open the Connect to a database modal.\n\n- From the list of databases, select the `MongoDB` database driver that you created in the previous step.\n\n If you don't see `MongoDB`, select the All category inside the modal.\n\n Click Next.\n\n- In the Main tab, enter the following information:\n\n \n\n \n \n \n \n \n \n \n \n \n \n \n \n
\n JDBC URL\n\n \n Connection string obtained from a previous step.\n\n
\n Username\n\n \n MongoDB user authorized for the connection.\n\n
\n Password\n\n \n Password associated with the MongoDB user.\n\n
\n\n- In the Driver properties tab, expand User Properties. Add the following key-value properties:\n\n \n\n \n \n \n \n \n \n \n \n
\n database\n\n \n The name of your virtual database.\n\n
\n user\n\n \n The MongoDB user to connect with. Not required if you entered a `Username` in the previous step.\n\n
\n\n## Next Steps\n\nAfter you connect your SQL tool to your MongoDB database, you can query your data. To learn more, see:\n\n- Query with MongoSQL Statements\n\n- Connect to and Query Data with Free SQL Tools\n\nTo connect using a private endpoint, see Connect to the MongoDB SQL Interface with a Private Endpoint."} -{"chunk_id": "6997fd716fd39a1e7ec5abdf-0", "page_id": "6997fd716fd39a1e7ec5abdf", "source_name": "sql-interface", "product_name": "MongoDB SQL Interface", "url": "https://mongodb.com/docs/sql-interface/changelog", "title": "SQL Interface Changelog", "text": "# SQL Interface Changelog\n\nMongoDB releases SQL Interface drivers and connectors in a continuous deployment manner. This release cadence allows us to continuously improve SQL Interface performance and stability. These release notes capture only those releases that contain direct user feature changes. If a particular SQL Interface release contains only performance and stability improvements, it is not included in these release notes.\n\n*Released September 29, 2026*\n\n- Introduces general availability of the MongoDB SQL Interface (Atlas Dedicated). You can now enable the SQL Interface directly on an Atlas dedicated cluster, `M10` and above, running MongoDB 6.0 or later, with no federated database instance required.\n\n - Enable or disable the SQL Interface per cluster from the cluster configuration form in the Atlas UI or with the Atlas Administration API. To learn more, see SQL Interface Server Setup.\n\n - Manage schemas for a dedicated cluster with the MongoDB SQL Schema Builder CLI. To learn more, see Schema Management.\n\n - The SQL Interface supports dedicated clusters on both the Atlas Core Database Edition and the Atlas Infinite Database Edition. Atlas Infinite Database Edition is available as a public preview.\n\n- The Atlas Administration API endpoints for the SQL Interface are available in preview. Requests must send the `Accept: application/vnd.atlas.preview+json` header.\n\n- Updates the ODBC (Open Database Connectivity) driver to version 3.0.0.\n\n - To connect to the MongoDB SQL Interface (Atlas Dedicated) with the ODBC (Open Database Connectivity) driver, you must use version 3.0.0.\n\n - Updates the MongoSQL engine that the driver uses to version 2.0.1.\n\n*Released September 25, 2026*\n\n- Updates the MongoSQL engine to version 2.0.1.\n\n - Fixes an issue where the `IN` operator applied implicit type conversion to the values in the list even when the compared field is a string. This caused queries, such as `WHERE employeeId IN ('0035759', '1033282')`, to return incomplete results.\n\n*Released September 10, 2026*\n\n- Updates the MongoSQL engine to version 2.0.0.\n\n - Changes how MongoSQL translates `WHERE` clauses that compare a field to a literal value, such as `WHERE x > 20`. These comparisons are now translated to MongoDB match language instead of `$expr` expressions. MongoDB match language applies type bracketing. With type bracketing, MongoDB compares only values that have the same type as the predicate of your query. This change encourages index usage, but it may affect the results of your queries if your fields are polymorphic. MongoSQL queries that run through Atlas Data Federation are not affected.\n\n Consider the following collection, where one document stores `age` as the number `25` and the other stores it as the string `\"25\"`:\n\n ```javascript\n [\n { \"_id\": 1, \"name\": \"John Doe\", \"age\": 25 },\n { \"_id\": 2, \"name\": \"Jane Doe\", \"age\": \"25\" }\n ]\n ```\n\n To return all users where `age` is greater than `20`, you can write the aggregation pipeline with `$expr`:\n\n ```javascript\n [\n {\n $match: {\n $expr: { $gt: [ \"$age\", 20 ] }\n }\n }\n ]\n ```\n\n This pipeline returns both documents, even though the `$gt` clause compares against a number:\n\n ```javascript\n [\n { _id: 1, name: 'John Doe', age: 25 },\n { _id: 2, name: 'Jane Doe', age: '25' }\n ]\n ```\n\n You can also write the same query using match language:\n\n ```javascript\n [\n {\n $match: {\n age: { $gt: 20 }\n }\n }\n ]\n ```\n\n This pipeline returns only the document where `age` is a number. The `{ $gt: 20 }` condition matches only numbers. MongoDB returns only documents that contain numbers greater than `20`:\n\n ```javascript\n [ { _id: 1, name: 'John Doe', age: 25 } ]\n ```\n\n Compare the results of your queries as you upgrade to version 2.0. To learn more about type bracketing, see Type Bracketing.\n\n - Adds support for the higher order functions `MAP`, `FILTER`, and `REDUCE`. Also adds the following functions, which wrap `MAP`, `FILTER`, or `REDUCE` functionality: `ARRAY_CAST`, `ARRAY_EXTRACT`, `ARRAY_COMPACT`, `ARRAY_COUNT_IF`, `ARRAY_REMOVE`, `ARRAY_SUM`, `ARRAY_PRODUCT`, `ARRAY_AVG`, `ARRAY_ALL`, `ARRAY_ANY`, and `ARRAY_JOIN`.\n\n - Fixes a bug in `LEFT JOIN` and `RIGHT JOIN` operations that meet certain criteria. Specifically, the query used a `LEFT JOIN` or `RIGHT JOIN` with a single field-to-field equality condition in the `ON` predicate, where one field was from the left join source and the other was from the right join source. If the schema indicated that both fields were nullable, the result set omitted some rows. For `LEFT JOIN`, rows from the left source where the join key value was nullish (`NULL` or `MISSING`) were omitted from the result set even though they should have been included. Likewise, the same issue affects `RIGHT JOIN` for rows from the right source. Non-nullish rows that did not have a match were still included in the result sets. Only rows with nullish values were omitted.\n\n*Released August 26, 2026*\n\n- Updates the MongoSQL Transition Readiness Tool to version 1.1.3.\n\n - Escapes database, collection, and field names supplied by the server before the tool writes them to the generated HTML reports. Previously, a name that contained HTML markup could run script in the browser of the user who opened a report. This fix addresses CVE-2026-76798 and CVE-2026-76794.\n\n - Escapes query text and user names read from Atlas BI Connector logs before the tool writes them to the generated HTML reports.\n\n - Neutralizes formula elements in the cell values of the generated CSV reports. Previously, a collection or field name that began with `=`, `+`, `-`, or `@` could run as a formula when the user opened the report in a spreadsheet application. This fix addresses CVE-2026-76797.\n\n*Released July 30, 2026*\n\n- Updates the JDBC (Java Database Connectivity) driver to version 3.0.8 and the ODBC (Open Database Connectivity) driver to version 2.0.10.\n\n - Upgrades the SQL translation engine to the latest version, which adds query optimizations and fixes an intermittent error that occurred when resolving the right-hand side schema of a lateral join.\n\n*Released July 23, 2026*\n\n- Updates the ODBC (Open Database Connectivity) driver to version 2.0.9.\n\n - Adds support for Linux arm64 architectures.\n\n - Fixes an error that occurred when an application passed a null `catalogName` argument to `SQLTablesW`. The driver now treats a null pattern argument as equivalent to `%`, as the ODBC specification requires.\n\n - Fixes an issue where the driver could launch an operating system protocol handler for an OIDC authorization endpoint that did not use `https`. The driver now validates the endpoint scheme before opening the URL. This fix addresses CVE-2026-19502.\n\n - Removes the OpenSSL requirement. The driver now uses `rustls` for secure connections.\n\n*Released July 9, 2026*\n\n- Updates the MongoDB SQL Schema Builder CLI to version 1.2.1. The following fixes in this release address CVE-2026-19502:\n\n - Fixes an issue where the CLI could launch an arbitrary operating system protocol handler from an unchecked path scheme.\n\n - Fixes an issue where the CLI logged the connection string and password in plain text to the terminal and to the log file. The CLI now redacts these values.\n\n*Released June 9, 2026*\n\n- Updates the MongoDB SQL Schema Builder CLI to version 1.2.0.\n\n*Released June 4, 2026*\n\n- Updates the ODBC (Open Database Connectivity) driver to version 2.0.8.\n\n - Fixes a connection failure that occurred when using the LDAP (deprecated) authentication mechanism with a password containing a reserved symbol (`:`, `/`, `?`, `#`, `[`, `]`, or `@`).\n\n - Upgrades third-party dependencies.\n\n*Released April 20, 2026*\n\n- Updates the JDBC (Java Database Connectivity) driver to version 3.0.6.\n\n - Upgrades third-party dependencies.\n\n*Released April 14, 2026*"} -{"chunk_id": "6997fd716fd39a1e7ec5abdf-1", "page_id": "6997fd716fd39a1e7ec5abdf", "source_name": "sql-interface", "product_name": "MongoDB SQL Interface", "url": "https://mongodb.com/docs/sql-interface/changelog", "title": "SQL Interface Changelog", "text": "- Updates the ODBC (Open Database Connectivity) driver to version 2.0.7.\n\n - Improves compatibility with applications such as SAS that look up the data source name during connection setup.\n\n - Fixes an error that could occur when your Business Intelligence tool retrieves the list of databases from your MongoDB data source and tries to retrieve more rows after exhausting the result set.\n\n - Upgrades third-party dependencies.\n\n*Released April 13, 2026*\n\n- Updates the MongoDB SQL Schema Builder CLI to version 1.1.3.\n\n - Directs schema reads to a secondary or analytics node when one is available and falls back to the primary node otherwise.\n\n - Fixes an error that caused the CLI to crash if a view referenced a collection that didn't exist. The CLI now reports the error and continues.\n\n*Released March 17, 2026*\n\n- Updates the MongoDB SQL Schema Builder CLI to version 1.1.2.\n\n - Fixes an error that prevented the CLI from generating schemas for time series collections.\n\n*Released March 16, 2026*\n\n- Updates the ODBC (Open Database Connectivity) driver to version 2.0.6.\n\n - Improves connection performance on Windows by caching the DNS resolver after the initial fallback. The driver now performs DNS fallback only once and reuses the cached resolver for subsequent connections.\n\n - Adds automatic retry logic for transient errors. The driver now retries failed operations up to three times with exponential backoff, improving reliability when connections fail due to network instability or idle connection timeouts.\n\n*Released February 26, 2026*\n\n- Updates the MongoDB SQL Schema Builder CLI to version 1.1.1.\n\n - Directs schema reads to an analytics node when one is available and falls back to another available node otherwise.\n\n - Improves the schema production for large datasets with unstable data fields.\n\n - Limits the number of concurrent tasks that the CLI runs, which reduces memory use and the number of in-flight queries.\n\n*Released February 19, 2026*\n\n- Updates the ODBC (Open Database Connectivity) driver to version 2.0.5.\n\n - Fixes connectivity issues for SRV connection strings on Windows by ensuring the driver correctly falls back to the system DNS resolver if the primary Cloudflare DNS fails.\n\n*Released February 10, 2026*\n\n- Updates the JDBC (Java Database Connectivity) driver to 3.0.5 and the ODBC (Open Database Connectivity) driver to version 2.0.4.\n\n - Fixes an issue where SQL queries containing an `OR` condition in a `WHERE` clause incorrectly filtered out rows. This occurred when one operand of the `OR` condition evaluated to `UNKNOWN` (due to a `NULL` or missing value in a nullable field) while the other evaluated to `TRUE`. This behavior deviated from standard three-valued SQL semantics and could result in incomplete result sets.\n\n - On-premises (EA) users should upgrade to the latest driver versions (JDBC (Java Database Connectivity) driver 3.0.5 or later and ODBC (Open Database Connectivity) driver 2.0.4 or later).\n\n - Atlas SQL users receive this fix automatically. However, you should refresh impacted dashboards or re-execute queries to update existing results.\n\n - For the JDBC (Java Database Connectivity) driver, connection validation failures now include more descriptive error messages that tell you the underlying cause. This improvement specifically assists Tableau Cloud users in diagnosing issues where driver or system logs are not directly accessible.\n\n - Fixes the ODBC (Open Database Connectivity) driver compatibility issue with Power BI introduced by the previous version.\n\n- Updates the ODBC (Open Database Connectivity) driver to version 2.0.3.\n\n - Upgrades third-party dependencies.\n\n*Released January 8, 2026*\n\n- Updates the ODBC (Open Database Connectivity) driver to version 2.0.2.\n\n - Adds DNS resolver fallback logic on Windows. The ODBC (Open Database Connectivity) driver now reverts to the system default resolver if the primary Cloudflare resolver fails, ensuring reliable connectivity in restricted network environments.\n\n*Released November 24, 2025*\n\nIf you use Kerberos, OIDC (OpenID Connect), or x509 authentication methods, upgrade to JDBC (Java Database Connectivity) 3.0.4 or later and the Tableau custom connector to 1.4.5 or later.\n\n- Updates the Tableau custom connector (for the MongoDB JDBC driver) to version 1.4.5.\n\n - Adds sections to the connection dialog for specific authentication mechanisms: Username and Password, X509, GSSAPI, and OIDC.\n\n- Updates the JDBC (Java Database Connectivity) driver to version 3.0.4.\n\n - Introduces support for OIDC (OpenID Connect) machine flow authentication. This enables Tableau Server users to publish and refresh reports securely without relying on embedded usernames and passwords. The driver now natively supports machine flow authentication for Kubernetes, Google Cloud, and Azure (Microsoft Azure) environments, via the `authMechanismProperties` connection URI (Uniform Resource Identifier) parameter.\n\n - Introduces Kerberos support for Tableau Desktop. This includes the addition of the following configuration properties:\n\n - `jaasconfigpath`\n\n - `gssnativemode`\n\n - `gssapilogincontextname`\n\n - `gssapiserverauth`\n\n*Released October 23, 2025*\n\n- Updates the JDBC (Java Database Connectivity) driver to version 3.0.3.\n\n- Adds new option `tlsCaFile` support in the URI and as a property `tlscafile`.\n\n*Released October 14, 2025*\n\n- Updates the ODBC (Open Database Connectivity) driver to version 2.0.1.\n\n- Fixes a local privilege escalation vulnerability (CVE-2025-11575) in the Windows installer by correcting permissions for custom installation paths.\n\n*Released September 17, 2025*\n\n- Introduces general availability of MongoDB SQL Interface. This modern toolset replaces the legacy MongoDB Connector for BI and provides a unified and consistent set of SQL drivers and connectors for both Atlas and on-premises deployments. This feature is now available for all MongoDB Enterprise Advanced customers with the introduction of the schema builder for on-premises schema management. To learn more, see MongoDB SQL Interface Overview.\n\n- Introduces MongoDB SQL Schema Builder 1.1.0 for on-premises schema management.\n\n- Updates the ODBC (Open Database Connectivity) driver to version 2.0.0.\n\n - Introduces on-premises connectivity support.\n\n - Introduces support for Kerberos (GSSAPI) authentication, enabling secure connections in enterprise environments and providing a critical feature for users migrating from the legacy MongoDB Connector for BI.\n\n - Fixes an issue that prevented tables from being listed when connecting via certain tools, such as Microsoft SQL Server Linked Server. The driver now correctly handles `SQLTables` calls with null `TableType` parameters.\n\n- Updates the JDBC (Java Database Connectivity) driver to version 3.0.1.\n\n - Introduces on-premises connectivity support.\n\n*Released August 12, 2025*\n\n- Updates the ODBC (Open Database Connectivity) driver to version 1.4.6.\n\n- Fixes error in the ODBC (Open Database Connectivity) driver version 1.4.5 that caused the driver to panic when a user with the minimum set of permissions retrieves the list of accessible tables.\n\n*Released July 29, 2025*\n\n- Updates the Tableau custom connector (for the MongoDB JDBC (Java Database Connectivity) driver) to version 1.4.4.\n\n - Removes log-related fields from the connection dialog to enhance security. You can still configure logging options `loglevel` and `logdir` in Tableau using the properties file (`mongodb_jdbc.properties`) to customize the connection. See the Tableau documentation for more details.\n\n*Released July 15, 2025*\n\n- Updates the ODBC (Open Database Connectivity) driver to version 1.4.5.\n\n- Updates ODBC (Open Database Connectivity) OIDC (OpenID Connect) default scope to send `openid` with `offline_access` and only intersect with IdP reported scopes if the set is not empty.\n\n- Makes `SQLEndTran` a no-op.\n\n- Updates the Rust driver to version 3.2.4.\n\n*Released June 18, 2025*"} -{"chunk_id": "6997fd716fd39a1e7ec5abdf-2", "page_id": "6997fd716fd39a1e7ec5abdf", "source_name": "sql-interface", "product_name": "MongoDB SQL Interface", "url": "https://mongodb.com/docs/sql-interface/changelog", "title": "SQL Interface Changelog", "text": "- Updates the JDBC (Java Database Connectivity) driver to 2.3.0.\n\n- Introduces a new property `disableclientcache` to disable client caching in the JDBC driver. You must use this property with care and it is intended for server environments where the JDBC (Java Database Connectivity) driver is used to connect to a variable number of customer databases to run queries at varying frequencies.\n\n To avoid recurring re-authentication flows, do not use this property with the OIDC authentication mechanism.\n\n*Released June 12, 2025*\n\n- Updates the JDBC (Java Database Connectivity) driver to version 2.2.4.\n\n- Fixes an issue with the JDBC (Java Database Connectivity) driver so that it now rejects invalid values for `setFetchSize` and provides a clear error message.\n\n- Adds OIDC (OpenID Connect) default scope to support more IdPs configurations (for example, Azure OIDC (OpenID Connect)).\n\n*Released April 30, 2025*\n\n- Updates the ODBC (Open Database Connectivity) driver to version 1.4.4.\n\n*Released April 9, 2025*\n\n- Updates the JDBC (Java Database Connectivity) driver to version 2.2.3.\n\n- Fixes an issue with OIDC authentication not opening the browser for sign-on on macOS.\n\n- Enhances logging capabilities with additional information for the JDBC driver.\n\n*Released March 28, 2025*\n\n- Updates the ODBC (Open Database Connectivity) driver to version 1.4.3.\n\n- Fixes a bug in `SQLDriverConnect` where the driver crashes if `StringLength2Ptr` is `null`.\n\n*Released March 5, 2025*\n\n- Updates the Tableau custom connector (for the MongoDB JDBC driver) to version 1.4.2.\n\n- Renamed the connector from MongoDB Atlas to MongoDB SQL Interface.\n\n*Released January 6, 2025*\n\n- Updates the ODBC (Open Database Connectivity) driver to version 1.4.2.\n\n - Updates internal ODBC (Open Database Connectivity) processing to improve BI (Business Intelligence) tools integration.\n\n*Released Dec 18, 2024*\n\n- Updates the JDBC (Java Database Connectivity) driver to version 2.2.1.\n\n- Implements `getCursorName()` to improve compatibility with database tools.\n\n- Improves error message for authentication failures.\n\n*Released December 6, 2024*\n\n- Updates the Tableau custom connector (for the MongoDB JDBC driver) to version 1.4.0.\n\n- Moves the logging information UI for the Tableau Connector into an Advanced tab.\n\n*Released August 15, 2024*\n\n- Releases version 2.2.0 of the JDBC driver.\n\n- Introduces driver support for jBoss Log Manager for logging.\n\n- Updates UUID string representation to the extended json uuid format `{$uuid : \"val\"}` instead of the generic base64 binary data format `{ \"$binary\":{\"base64\": \"base64val\", \"subType\": \"xx\"}`. For `subType 03`, you can use the uuidRepresentation connection option.\n\n*Released July 8, 2024*\n\n- Introduces OIDC (OpenID Connect) authentication for the ODBC (Open Database Connectivity) driver.\n\n- Updates the ODBC (Open Database Connectivity) driver to version 1.4.1.\n\n- Adds conversion support for `wlongvarchar` and `wvarcchar` in the ODBC (Open Database Connectivity) driver.\n\n- Addresses the low and medium static code analysis findings for the ODBC (Open Database Connectivity) driver.\n\n*Released June 27, 2024*\n\n- Updates the JDBC (Java Database Connectivity) driver to version 2.1.4.\n\n- Updates the ODBC (Open Database Connectivity) driver to version 1.3.4.\n\n- Publishes checksum for validating the signed msi for ODBC (Open Database Connectivity).\n\n*Released June 24, 2024*\n\n- Updates the Tableau custom connector (for the MongoDB JDBC driver) to version 1.3.0.\n\n- Adds the ability to choose between two authentication types:\n\n - `Certificate / Token`\n\n - `Username and Password`\n\n If you choose `Certificate / Token`, the username and password are not required.\n\n*Released June 21, 2024*\n\n- Updates the JDBC (Java Database Connectivity) driver to version 2.1.3.\n\n- Introduces oidc authentication for the JDBC (Java Database Connectivity) driver.\n\n- Adds caching of `MongoClient` instances.\n\n*Released May 22, 2024*\n\n- Updates the ODBC (Open Database Connectivity) driver to version 1.3.3.\n\n- Adds a checkbox on the ODBC (Open Database Connectivity) driver DSN configuration UI to indicate whether to limit the maximum string length to 4000 characters. To work with BI tools, like Microsoft SQL Server Linked Server, which can't handle variable length string data with no known maximum length, you must enable this option.\n\n*Released April 24, 2024*\n\n- Updates the JDBC (Java Database Connectivity) driver to version 2.1.2, which now ignores both \"true\" and \"false\" `setAutoCommit` values instead of returning an exception when \"true\".\n\n*Released April 22, 2024*\n\n- Updates the ODBC (Open Database Connectivity) driver to version 1.3.0.\n\n- Adds support for result set data column-wise binding.\n\n- Adds support for SQLCancel.\n\n- Changes the non-standard data type (such as `document` and `oid`) default mapping from `SQL_UNKNOWN_TYPE` to `SQL_WVARCHAR`. This change affects only programmatic integrations relying on SQL type names; it doesn't affect Power BI.\n\n*Released March 4, 2024*\n\n- Updates the Power BI connector to version 1.2.0.\n\n- Adds support for Direct Query. Direct Query capabilities require ODBC (Open Database Connectivity) driver version 1.2.0 or later.\n\n*Released March 1, 2024*\n\n- Updates the ODBC (Open Database Connectivity) driver to version 1.2.0.\n\n- Adds support for ODBC (Open Database Connectivity) clients requesting the driver to exhibit ODBC (Open Database Connectivity) 2.0 behavior.\n\n- Adds support for `SQLFreeStatement`.\n\n- Adds support for `SQLFetchScroll`.\n\n- The column order in result sets now adheres to the SQL-92 specification. Result set columns appear in the order they are listed in the `SELECT` query. For `SELECT *`, the result set column order is unchanged.\n\n- Updates the information returned by `SQLGetInfo` to report all supported date functions, time functions, and join capabilities.\n\n- Removes log level configuration at the DSN and connection level. The log level can now only be set as a driver property.\n\n- Changes the BSON (Binary Javascript Object Notation)-to-SQL mapping of `Decimal128` from `SQL_DECIMAL` to `SQL_UNKNOWN` due to incompatibilities between `Decimal128` and `SQL_DECIMAL`.\n\n*Released February 23, 2024*\n\n- Updates the JDBC (Java Database Connectivity) driver to version 2.1.1, which removes the SnakeYaml dependency and fixes an issue introduced in version 2.1.0 where data retrieved by column name was pointing to the incorrect index. The driver now retrieves the data under the correct index or reports an error if there are duplicate column names.\n\n*Released January 22, 2024*\n\n- Updates the JDBC (Java Database Connectivity) driver to version 2.1.0, which returns result set columns in the same order as the one provided in the select list instead of the alphabetical order.\n\n- Fixes the logger to only apply the logging configuration to the driver handlers and not other applications handlers.\n\n*Released October 20, 2023*\n\n- Updates the Power BI connector to version 1.1.1, which fixes a bug where JSON values displayed as binary instead of JSON strings.\n\n*Released October 17, 2023*\n\n- Updates the Power BI connector to version 1.1.0, which adds the ability to pass a native query when you connect. To learn more, see Connect to Atlas SQL from Power BI.\n\n- Removes the log-level selector to comply with the Microsoft logging policy for Power BI.\n\n*Released August 17, 2023*\n\n- Updates the Power BI connector to version 1.0.1, which adds a log-level selector to allow setting the logging level for each connection.\n\n*Released June 16, 2023*\n\n- Updates the Power BI connector to version 1.0.0.\n\n*Released October 24, 2022*\n\n- Updates the Tableau custom connector (for the MongoDB JDBC driver) to version 1.2.0.\n\n*Released September 19, 2022*\n\n- Updates the Tableau custom connector (for the MongoDB JDBC driver) to version 1.1.0.\n\n*Released June 7, 2022*\n\n- Preview availability."} -{"chunk_id": "6997fd716fd39a1e7ec5abce-0", "page_id": "6997fd716fd39a1e7ec5abce", "source_name": "sql-interface", "product_name": "MongoDB SQL Interface", "url": "https://mongodb.com/docs/sql-interface/schema-management", "title": "Schema Management", "text": "# Schema Management\n\nThe SQL Interface schemas are JSON schemas that describe data as it exists in MongoDB, including its polymorphism, sparseness, and nested, structured data. Schemas are necessary when connecting SQL-based tools to MongoDB data sources. The SQL Interface also requires schema information to translate SQL queries into more optimized MongoDB operations. Schema management is the process of creating, maintaining, and updating that information as your data evolves.\n\nThe tool you use for schema management depends on the deployment type where you run the SQL Interface. Each deployment type uses a different tool, and those tools behave differently in important ways. Identify your deployment type in the table that follows, then follow the link to the appropriate guide.\n\nChoose the correct deployment type before starting. The MongoDB SQL Schema Builder CLI does not sample documents to derive a schema. The Atlas Data Federation path samples documents from your collections to build the initial schema. Using documentation for the wrong deployment type produces wrong results.\n\nSchemas are not shared between deployment types. A schema you create with the MongoDB SQL Schema Builder CLI is not available when you connect through Atlas Data Federation, and the reverse is also true.\n\nDedicated clusters (`M10` and above) manage schemas through the MongoDB SQL Schema Builder CLI only, the same tool used for self-managed EA deployments.\n\n## Get Started\n\nClick the appropriate link to learn more about managing the schema for your deployment type:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nDeployment Type\n\n\nDescription\n\n\nDocumentation\n\n
\nDedicated Cluster (`M10` and above)\n\n\nDownload and run the MongoDB SQL Schema Builder CLI against your cluster.\n\n\nTo manage schemas for dedicated clusters, see MongoDB SQL Schema Builder CLI.\n\n
\nEnterprise Advanced (EA) self-managed\n\n\nDownload and run the MongoDB SQL Schema Builder CLI against your cluster.\n\n\nTo manage schemas for EA self-managed deployments, see MongoDB SQL Schema Builder CLI.\n\n
\nAtlas Data Federation\n\n\nGenerate and manage schemas using the Atlas UI or `mongosh`.\n\n\nTo manage schemas for Atlas Data Federation deployments, see Atlas Data Federation Schema Commands.\n\n
\n\n## Learn More\n\n- MongoDB SQL Interface Overview\n\n- Install the MongoDB SQL Interface"} -{"chunk_id": "6997fd716fd39a1e7ec5abac-0", "page_id": "6997fd716fd39a1e7ec5abac", "source_name": "sql-interface", "product_name": "MongoDB SQL Interface", "url": "https://mongodb.com/docs/sql-interface/dbeaver/connect", "title": "Connect from DBeaver", "text": "# Connect from DBeaver\n\nThis page describes how to connect to your federated database instance with DBeaver.\n\n## Prerequisites\n\n- A federated database instance mapped to one or more data stores.\n\n If some or all of your data comes from an Atlas cluster, you must use MongoDB version 5.0 or greater for that cluster to take advantage of MongoSQL.\n\n- DBeaver (Community Edition).\n\n- The MongoDB JDBC Driver.\n\n## Procedure\n\nTo connect to your federated database instance from DBeaver:\n\n### In Atlas, go to your federated database instance for your project.\n\n- If it's not already displayed, select the organization that contains your project from the Organizations menu in the navigation bar.\n\n- If it's not already displayed, select your project from the Projects menu in the navigation bar.\n\n- In the sidebar, click Data Federation under the Services heading.\n\nThe Data Federation page displays.\n\nOn the federated database card, click Connect.\n\nA connection dialog box opens.\n\n### Click Atlas SQL.\n\n### Select your driver.\n\nFrom Select your driver, select JDBC Driver.\n\n### Copy your connection information.\n\nSelect a database from the Database dropdown, then click to copy the connection string. You'll need this in a later step.\n\n### Open your DBeaver application.\n\n### Add a driver to DBeaver.\n\n- In DBeaver, click Database and select Driver Manager from the dropdown menu.\n\n- Click New to open the Create new driver modal.\n\n- In the Settings tab, specify the following information:\n\n \n\n \n \n \n \n \n \n \n \n
\n Driver Name\n\n \n `MongoSQL`\n\n
\n Class Name\n\n \n `com.mongodb.jdbc.MongoDriver`\n\n
\n\n- In the Libraries tab, click Add File and add your JDBC driver `all.jar` file.\n\n Click Find Class.\n\n- Click OK. The Create new driver modal closes.\n\n### Create a database connection.\n\n- In DBeaver, click Database and select New Database Connection from the dropdown menu to open the Connect to a database modal.\n\n- From the list of databases, select the `MongoDB` database driver that you created in the previous step.\n\n If you don't see `MongoDB`, select the All category inside the modal.\n\n Click Next.\n\n- In the Main tab, enter the following information:\n\n \n\n \n \n \n \n \n \n \n \n \n \n \n \n
\n JDBC URL\n\n \n Connection string obtained from a previous step.\n\n
\n Username\n\n \n MongoDB user authorized for the connection.\n\n
\n Password\n\n \n Password associated with the MongoDB user.\n\n
\n\n- In the Driver properties tab, expand User Properties. Add the following key-value properties:\n\n \n\n \n \n \n \n \n \n \n \n
\n database\n\n \n The name of your virtual database.\n\n
\n user\n\n \n The MongoDB user to connect with. Not required if you entered a `Username` in the previous step.\n\n
\n\n## Run MongoSQL Queries\n\nTo run MongoSQL queries in DBeaver:\n\n### Expand your MongoDB connection.\n\nThe DBeaver Database Navigator displays your virtual databases.\n\n### Open a SQL console.\n\n- Right-click the virtual database you want to query.\n\n- Select SQL Editor.\n\n- Select Open SQL console.\n\n A new SQL console window that is connected to the virtual database you selected opens.\n\n### Enter a SQL query in the console.\n\nFor example queries, see Query with MongoSQL Statements.\n\n### Click Execute SQL Statement to run your SQL query.\n\nIf the query is successful, the results are displayed in a table view below your query."} -{"chunk_id": "6997fd716fd39a1e7ec5abc4-0", "page_id": "6997fd716fd39a1e7ec5abc4", "source_name": "sql-interface", "product_name": "MongoDB SQL Interface", "url": "https://mongodb.com/docs/sql-interface", "title": "MongoDB SQL Interface Overview", "text": "# MongoDB SQL Interface Overview\n\nSQL InterfaceThe SQL Interface for Atlas and Enterprise Advanced (EA) lets non-developers query MongoDB data from the SQL tools they already use. It provides live, read-only access over standard ODBC (Open Database Connectivity) and JDBC (Java Database Connectivity) connections, eliminating the need to learn MQL (MongoDB Query Language) or move data out of MongoDB for analytics. This simplifies operational reporting, accelerates insights, and ensures data remains accurate and consistent.\n\nYou can deploy the SQL Interface three ways: directly on an Atlas dedicated cluster, through an Atlas federated database instance, or on a self-managed Enterprise Advanced (EA) deployment. For direct SQL access to a single Atlas cluster, use a dedicated cluster. This is the recommended path for most Atlas connections, and it requires no federated database instance. Use a federated database instance when a single SQL query must span more than one data source, such as multiple clusters or S3 (Simple Storage Service) buckets.\n\n## Compare Deployment Options\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n\n\nDedicated Cluster (Recommended for Atlas)\n\n\nFederated Database Instance\n\n\nOn-Premises (EA)\n\n
\n**Best for**\n\n\nSQL access to the data in one Atlas cluster.\n\n\nA single SQL query that spans more than one data source.\n\n\nSQL access to a self-managed deployment you run yourself.\n\n
\n**Data sources**\n\n\nOne dedicated cluster.\n\n\nMultiple Atlas clusters, Atlas Data Federation collections, and storage objects including AWS (Amazon Web Services) S3 (Simple Storage Service) buckets, Azure (Microsoft Azure) Blob Storage containers, Google Cloud storage buckets, HTTP URLs, and Atlas Online Archives.\n\n\nOne self-managed Enterprise Advanced (EA) deployment.\n\n
\n**Deployment requirement**\n\n\nDedicated cluster, `M10` and above. Not available on Free clusters, Flex clusters, or `M2` and `M5` shared clusters.\n\n\nA federated database instance. No cluster tier requirement.\n\n\nA MongoDB Enterprise cluster. Community clusters are not supported.\n\n
\n**MongoDB version**\n\n\n6.0 and later.\n\n\n5.0 and later.\n\n\n6.0 and later.\n\n
\n**Database edition**\n\n\nAtlas Core Database Edition and Atlas Infinite Database Edition.\n\n\nAtlas Core Database Edition and Atlas Infinite Database Edition.\n\n\nNot applicable.\n\n
\n**Schema management**\n\n\nMongoDB SQL Schema Builder CLI.\n\n\nAtlas Data Federation SQL schema management, built into the Atlas UI.\n\n\nMongoDB SQL Schema Builder CLI.\n\n
\n**Architecture**\n\n\nConnects directly to the cluster.\n\n\nShared and multi-tenant. The Atlas Data Federation query engine retrieves data from all underlying data sources to aggregate them.\n\n\nRuns in your own environment.\n\n
\n**Connection and query limits**\n\n\nFollow the cluster itself.\n\n\nThe federated database instance enforces its own simultaneous connection and query limits.\n\n\nFollow the deployment itself.\n\n
All three options provide live, read-only access and use the MongoSQL dialect, which is SQL-92 compatible. You cannot use the SQL Interface to insert, update, or delete documents on any deployment, and the SQL Interface does not support other SQL dialects.\n\n## SQL Interface Components\n\nThe SQL Interface deployment consists of four components:\n\n- Your BI (Business Intelligence) visualization and reporting tool used to analyze data, such as Tableau or Power BI.\n\n- A JDBC (Java Database Connectivity) or ODBC (Open Database Connectivity) driver that connects your BI (Business Intelligence) tool to your MongoDB database. The driver you select depends on your BI (Business Intelligence) tool.\n\n- JSON schema are required to translate SQL queries between your BI (Business Intelligence) tool and MongoDB database. For federated database instances, schema management is built into the Atlas UI. For dedicated clusters and for self-managed Enterprise Advanced (EA) deployments, you download the MongoDB SQL Schema Builder as a CLI tool. To learn more, see Schema Management.\n\n- A MongoDB database where your data resides, either an Atlas cluster or a self-managed EA database.\n\n## Key Benefits of the MongoDB SQL Interface\n\nExperience significantly improved schema integration. Schema computations adapt to your data and represent your collections natively. Schemas aren't cached and you can refresh them at any time without impacting connectivity.\n\nEnjoy a simplified setup with no complex proxy configurations, allowing you to connect directly to your MongoDB cluster. It offers robust authentication with support for X509 and OIDC protocols.\n\nLeverage rich objects and arrays with native driver support, enhancing your data interactions. Server restarts are seamless, ensuring uninterrupted operations and high availability. The interface uses MongoSQL, a MongoDB-Native SQL-92 compatible dialect, which supports complex transformations like flattening nested objects and unwinding arrays directly within SQL queries.\n\nProvides the same drivers, connectors, and schema mapping for federated database instances, dedicated clusters, and self-managed EA databases.\n\nThe Power BI Connector is certified by Microsoft and the Tableau Connector is developed in partnership with Tableau. It supports Power BI with DirectQuery and Tableau Desktop, Tableau Server, Tableau Prep, and Tableau Cloud. Tableau Cloud supports SCRAM authentication only."} -{"chunk_id": "6997fd716fd39a1e7ec5abc4-1", "page_id": "6997fd716fd39a1e7ec5abc4", "source_name": "sql-interface", "product_name": "MongoDB SQL Interface", "url": "https://mongodb.com/docs/sql-interface", "title": "MongoDB SQL Interface Overview", "text": "## MongoDB SQL Interface Compatibility Considerations\n\nWhen using the SQL Interface, consider the following points to ensure your setup is compatible and up-to-date:\n\n- There is no official EOL (End of Life) for SQL Interface components, including drivers, connectors, and the MongoDB SQL Schema Builder. Instead, their lifecycle is tied to the compatibility of the MongoDB server versions and language runtimes they are designed to work with.\n\n- SQL Interface components remain compatible with a MongoDB server version for up to 3 years after that server version's EOL (End of Life). To learn more, see MongoDB Software Lifecycle Schedules.\n\n- We recommend upgrading your SQL Interface components to the latest version, especially when upgrading your MongoDB server. This ensures access to new features, performance enhancements, and long-term compatibility. To see the latest versions, go to the MongoDB download center.\n\n- Later versions of SQL Interface components might drop support for earlier MongoDB server versions. We recommend reviewing the SQL Interface Changelog to stay informed about compatibility changes and upgrade requirements.\n\n## Legacy Options\n\nThe MongoDB Connector for BI is the legacy tool for connecting BI (Business Intelligence) analytics tools to a MongoDB database or cluster. The BI Connector reaches **End-of-Life (EOL) in September 2026**.\n\n## Next Steps\n\nInstall the MongoDB SQL Interface"} -{"chunk_id": "6997fd716fd39a1e7ec5abd3-0", "page_id": "6997fd716fd39a1e7ec5abd3", "source_name": "sql-interface", "product_name": "MongoDB SQL Interface", "url": "https://mongodb.com/docs/sql-interface/query-with-asql-statements", "title": "Query with MongoSQL Statements", "text": "# Query with MongoSQL Statements\n\nThe page gives example MongoSQL queries. Basic examples use SQL syntax to query collections, and more advanced ones use `FLATTEN` and `UNWIND` to work with nested data.\n\nMongoDB doesn't provide a SQL IDE. Run these queries from your preferred SQL tool, such as DBeaver, Tableau, or Power BI. To learn how to connect a SQL tool, see Connect Your SQL Tool to MongoDB.\n\n## Example Queries\n\nTry running the following MongoSQL queries against your own data. To configure a deployment to accept SQL connections first, see SQL Interface Server Setup.\n\n### SELECT Statement\n\n```sh\nSELECT * FROM sessions;\n```\n\nMongoSQL returns all documents from the `Sessions` collection.\n\n### LIMIT Statement\n\n```sh\nSELECT * FROM users LIMIT 2;\n```\n\nMongoSQL returns two documents from the `Users` collection.\n\n### WHERE Statement\n\n```sh\nSELECT * FROM users WHERE name = 'Jon Snow';\n```\n\nMongoSQL returns documents from the `Users` collection where the user's `name` is `Jon Snow`.\n\n### WITH Keyword\n\nThe `WITH` keyword makes it easier to create derived data sources for subsequent use.\n\n```sh\nWITH RecentSales AS (\n SELECT customer_id, SUM(amount) AS total_sales\n FROM sales\n WHERE sale_date > '2025-01-01'\n GROUP BY customer_id\n)\nSELECT customer_id, total_sales\nFROM RecentSales\nWHERE total_sales > 1000;\n```\n\nMongoSQL returns documents from the `Sales` collection that have `customer_id` with total sales greater than 1000 after January 1, 2025.\n\n## FLATTEN and UNWIND\n\nThis section covers two MongoSQL capabilities that make it easier to interact with document structures. These are unique to MongoSQL.\n\n### FLATTEN\n\n`FLATTEN` flattens semi-structured data (name-value pairs in JSON) into separate columns. Field names become column names that hold all of the values for that field in rows.\n\nThe syntax for flattening nested documents is a `FLATTEN` function that you can use in the `FROM` clause with a data source and options.\n\n```\nSELECT *\nFROM FLATTEN(\n WITH DEPTH => ,\n SEPARATOR => \n)\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nVariable\n\n\nNecessity\n\n\nDescription\n\n
\n\n\n\nRequired\n\n\nData source to flatten.\n\n
\n`DEPTH`\n\n\nOptional\n\n\nPositive integer indicating how many levels of subdocuments to flatten. Defaults to flattening every level of subdocuments.\n\n
\n`SEPARATOR`\n\n\nOptional\n\n\nString to use as the delimiter when concatenating field names. Defaults to `_`.\n\n
\n\n### Flatten Example\n\nIn an example scenario, a `customerInfo` collection contains documents that are structured as follows:\n\n```json\n{\n id: 1,\n location: \"New York\",\n customer: {\n age: 50,\n email: \"customer@email.com\",\n satisfaction: 5\n }\n}\n```\n\nIf you run the query `SELECT * FROM customerInfo`, MongoSQL returns documents with the following top-level fields:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n`id`\n\n\n1\n\n
\n`location`\n\n\n\"New York\"\n\n
\n`customer`\n\n\n{ age: 50, email: \"customer@email.com\", satisfaction: 5 }\n\n
If you run the query `SELECT * FROM FLATTEN(customerInfo)`, MongoSQL returns documents with the following top-level fields:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n`id`\n\n\n1\n\n
\n`location`\n\n\n\"New York\"\n\n
\n`customer_age`\n\n\n50\n\n
\n`customer_email`\n\n\n\"customer@email.com\"\n\n
\n`customer_satisfaction`\n\n\n5\n\n
When you use `FLATTEN`, each flattened field from the original document becomes a top-level field in the result set. Nested fields are concatenated with their parent field names and separated by the default delimiter, `_`.\n\n### UNWIND\n\n`UNWIND` deconstructs an array field from the input data source to output one row for each item in that array. To learn more about unwinding, see the $unwind aggregation stage documentation.\n\nThe syntax for unwinding array fields is an `UNWIND` function that you can use in the `FROM` clause with a data source and options.\n\n```\nSELECT *\nFROM UNWIND(\n WITH PATH | PATHS => ,\n INDEX => ,\n OUTER => \n)\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nVariable\n\n\nNecessity\n\n\nDescription\n\n
\n\n\n\nRequired\n\n\nSource of the array field to unwind.\n\n
\n`PATH` | `PATHS`\n\n\nRequired\n\n\nPath to the field in the data source to unwind. Use parentheses to specify multiple paths.\n\n
\n`INDEX`\n\n\nOptional\n\n\nName to assign the index column. If omitted, MongoSQL does not create an index field.\n\n
\n`OUTER`\n\n\nOptional\n\n\nFlag that indicates whether documents with null, missing, or empty array values are preserved. If `true`, documents with null, missing, or empty array values are preserved. Defaults to `false`.\n\n
\n\n### Unwind Example: Top Level Fields\n\nIn an example scenario, a `customerInfo` collection contains documents that are structured as follows:\n\n```json\n{\n id: 1,\n location: \"New York\",\n customer: {\n age: 50,\n email: \"customer@email.com\",\n satisfaction: 5\n },\n visits: [\n {\n year: 2020,\n score: 10\n },\n {\n year: 2021,\n score: 8\n },\n {\n year: 2022\n score: 7\n }\n ]\n}\n```\n\nIf you run the query `SELECT * FROM customerInfo`, MongoSQL returns documents with the following top-level fields:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n`id`\n\n\n1\n\n
\n`location`\n\n\n\"New York\"\n\n
\n`customer`\n\n\n{ age: 50, email: \"customer@email.com\", satisfaction: 5 }\n\n
\n`visits`\n\n\n[ { year: 2020, score: 10 }, { year: 2021, score: 8 }, { year: 2022, score: 7 } ]\n\n
If you run the query `SELECT * FROM UNWIND(customerInfo WITH PATH => visits, INDEX => idx)`, MongoSQL returns documents with the following top-level fields:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n`id`\n\n\n1\n\n\n1\n\n\n1\n\n
\n`location`\n\n\n\"New York\"\n\n\n\"New York\"\n\n\n\"New York\"\n\n
\n`customer`\n\n\n{ age: 50, email: \"customer@email.com\", satisfaction: 5 }\n\n\n{ age: 50, email: \"customer@email.com\", satisfaction: 5 }\n\n\n{ age: 50, email: \"customer@email.com\", satisfaction: 5 }\n\n
\n`idx`\n\n\n0\n\n\n1\n\n\n2\n\n
\n`visits`\n\n\n{ year: 2020, score: 10 }\n\n\n{ year: 2021, score: 8 }\n\n\n{ year: 2022, score: 7 }\n\n
When you use `UNWIND` with `PATH => visits`, each `visits` object becomes a table row."} -{"chunk_id": "6997fd716fd39a1e7ec5abd3-1", "page_id": "6997fd716fd39a1e7ec5abd3", "source_name": "sql-interface", "product_name": "MongoDB SQL Interface", "url": "https://mongodb.com/docs/sql-interface/query-with-asql-statements", "title": "Query with MongoSQL Statements", "text": "### Unwind Example: Nested and Sibling Arrays\n\nIn an example scenario, a `customerInfo` collection contains documents that are structured as follows:\n\n```json\n{\n \"id\": 1,\n \"location\": \"New York\",\n \"customer\": {\n \"age\": 50,\n \"email\": \"customer@email.com\",\n \"satisfaction\": 5\n },\n \"visits\": [\n {\n \"year\": 2020,\n \"score\": 10\n },\n {\n \"year\": 2021,\n \"score\": 8\n },\n {\n \"year\": 2022,\n \"score\": 7\n }\n ],\n \"purchases\": [\n {\n \"transaction\": \"1A\",\n \"transactions\": [\n {\n \"amount\": 100\n },\n {\n \"amount\": 150\n }\n ]\n },\n {\n \"transaction\": \"2B\",\n \"transactions\": [\n {\n \"amount\": 200\n }\n ]\n }\n ]\n}\n```\n\nSuppose you run the following query:\n\n```javascript\nSELECT\n visits.year AS visit_year, visits.score AS visit_score,\n purchases.transaction AS transaction_id,\n purchases.transactions.amount AS purchase_amount,\n visit_idx, purchase_idx,\n purchases_transactions_idx AS transaction_idx\nFROM UNWIND(\n customerInfo WITH PATHS => (\n visits[OUTER => FALSE, INDEX => visit_idx],\n purchases[INDEX => purchase_idx].transactions[OUTER => FALSE]\n ),\n INDEX => idx,\n OUTER => TRUE\n)\n```\n\nThe preceding query does the following:\n\n- Unwinds the `visits` array and assigns an index name `visit_idx` to track the index position inside the unwound array. It does not include missing or empty `visits` by setting `OUTER => FALSE`.\n\n- Unwinds the `purchases` array and unwinds the `transactions` array inside each `purchases` object. It preserves any missing or empty `purchases` array by using `OUTER => TRUE`. It also assigns an index name `purchase_idx` to track the index position inside the unwound `purchases` array, and an index name `purchases_transactions_idx` to track the position inside the unwound `transactions` array inside each `purchases` object.\n\n- Selects the `year` and `score` subfields from the `visits` objects, the `transaction` subfield from the `purchases` objects, and the `amount` subfield from the `transactions` objects within each `purchases` object, and all the index fields.\n\nIn the preceding query:\n\n- `OUTER => TRUE` is set as a top-level parameter to the `UNWIND` datasource making it the default value used for all `PATHS` unless the path-level `OUTER` value is different.\n\n- `INDEX => idx` is set as a top-level parameter to the `UNWIND` datasource making it the default value used for all `PATHS` unless the path-level `INDEX` value is different.\n\n For example, `transactions` did not specify a specific `INDEX` value. Therefore, it uses this top-level value to create the index name by appending `_idx` to the full path.\n\nMongoSQL returns documents with the following fields:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n`visit_year`\n\n\n`visit_score`\n\n\n`transaction_id`\n\n\n`purchase_amount`\n\n\n`visit_idx`\n\n\n`purchase_idx`\n\n\n`transaction_idx`\n\n
\n2020\n\n\n10\n\n\n1A\n\n\n100\n\n\n0\n\n\n0\n\n\n0\n\n
\n2020\n\n\n10\n\n\n1A\n\n\n150\n\n\n0\n\n\n0\n\n\n1\n\n
\n2020\n\n\n10\n\n\n2B\n\n\n200\n\n\n0\n\n\n1\n\n\n0\n\n
\n2021\n\n\n8\n\n\n1A\n\n\n100\n\n\n1\n\n\n0\n\n\n0\n\n
\n2021\n\n\n8\n\n\n1A\n\n\n150\n\n\n1\n\n\n0\n\n\n1\n\n
\n2021\n\n\n8\n\n\n2B\n\n\n200\n\n\n1\n\n\n1\n\n\n0\n\n
\n2022\n\n\n7\n\n\n1A\n\n\n100\n\n\n2\n\n\n0\n\n\n0\n\n
\n2022\n\n\n7\n\n\n1A\n\n\n150\n\n\n2\n\n\n0\n\n\n1\n\n
\n2022\n\n\n7\n\n\n2B\n\n\n200\n\n\n2\n\n\n1\n\n\n0\n\n
\n\n### Combined FLATTEN and UNWIND Example\n\nThe following example combines the `FLATTEN` and `UNWIND` functions.\n\nIn an example scenario, a `customerInfo` collection contains documents that are structured as follows:\n\n```json\n{\n id: 1,\n location: \"New York\",\n customer: {\n age: 50,\n email: \"customer@email.com\",\n satisfaction: 5\n },\n visits: [\n {\n year: 2020,\n score: 10\n },\n {\n year: 2021,\n score: 8\n },\n {\n year: 2022\n score: 7\n }\n ]\n}\n```\n\nIf you run the query `SELECT * FROM customerInfo`, MongoSQL returns documents with the following top-level fields:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n`id`\n\n\n1\n\n
\n`location`\n\n\n\"New York\"\n\n
\n`satisfaction`\n\n\n5\n\n
\n`customer`\n\n\n{ age: 50, email: \"customer@email.com\", satisfaction: 5 }\n\n
\n`visits`\n\n\n[ { year: 2020, score: 10 }, { year: 2021, score: 8 }, { year: 2022, score: 7 } ]\n\n
If you run the query `Select * from FLATTEN(UNWIND(customerInfo WITH PATH => visits, INDEX => idx))`, MongoSQL returns documents with the following top-level fields:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n`id`\n\n\n1\n\n\n1\n\n\n1\n\n
\n`location`\n\n\n\"New York\"\n\n\n\"New York\"\n\n\n\"New York\"\n\n
\n`satisfaction`\n\n\n5\n\n\n5\n\n\n5\n\n
\n`customer_age`\n\n\n50\n\n\n50\n\n\n50\n\n
\n`customer_email`\n\n\n\"customer@email.com\"\n\n\n\"customer@email.com\"\n\n\n\"customer@email.com\"\n\n
\n`idx`\n\n\n0\n\n\n1\n\n\n2\n\n
\n`visits_year`\n\n\n2020\n\n\n2021\n\n\n2022\n\n
\n`visits_score`\n\n\n10\n\n\n8\n\n\n7\n\n
When you use both the `FLATTEN` and `UNWIND` functions, the `visits` array is unwound, and the resulting document is then flattened."} -{"chunk_id": "69eb0c75d0423fff078dfb02-0", "page_id": "69eb0c75d0423fff078dfb02", "source_name": "vector-search", "product_name": "Atlas Vector Search", "url": "https://mongodb.com/docs/vector-search/query/vector-search-playground", "title": "Chatbot Demo Builder in Search Playground", "text": "# Chatbot Demo Builder in Search Playground\n\nQuickly try MongoDB Vector Search in the MongoDB Search Playground by using a RAG chatbot that answers questions on your data with vector search. The Chatbot Demo Builder in the MongoDB Search Playground allows you to bring your own data, try different chunking strategies, generate embeddings using Voyage AI embedding models, and ask questions about the data without an Atlas account, cluster, or collection. You can also share a link to a snapshot of your MongoDB Search Playground with others.\n\n## Stages Used\n\nThe Chatbot Demo Builder uses two aggregation pipeline stages, `$vectorSearch` and `$project`.\n\n## Considerations\n\nThis is a generative AI chatbot. All information should be verified prior to use. Do not upload sensitive data. MongoDB logs your workload data for monitoring the system health and to help troubleshoot any issues in the Chatbot Demo Builder.\n\n## Chatbot Demo Builder Limitations\n\n- The Chatbot Demo Builder processes the imported PDF file or copy-pasted text as a single, unified knowledge source. You cannot define or combine separate data collections within the builder.\n\n- The Chatbot Demo Builder uses a pre-configured vector search index that is not editable. The query is generated based on the specified retrieval settings and cannot be directly edited using the code editor.\n\n- The Chatbot Demo Builder environment does not persist. To save an environment, use the Share button to generate a snapshot URL (Uniform Resource Locator) that persists for 30 days.\n\n- The Chatbot Demo Builder only supports text-based embeddings. If your PDF file contains images, the chatbot will not be able to process or answer questions about the content within those images.\n\n- The Chatbot Demo Builder has the following data limitations:\n\n - You cannot import files larger than 100 MB.\n\n - The total character count cannot exceed 100,000 characters.\n\n - You cannot bring your own vector embeddings or API credentials for embedding solutions.\n\n## Try the Chatbot Demo Builder\n\n### Access the Chatbot Demo Builder.\n\nNavigate to Chatbot Demo Builder.\n\n### Select your data source.\n\nThe Chatbot Demo Builder provides three data source options.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nUpload PDF\n\n\nUpload a PDF file from your local device with a maximum size of 100 MB. If the character count exceeds 100,000, you must use only the first 100,000 characters or upload a file with less characters. You can preview the text with SEE TEXT.\n\n
\nCopy & Paste Text\n\n\nCopy and paste text up to 100,000 characters. If the character count exceeds 100,000, you must use only the first 100,000 characters or reduce the text size.\n\n
\nSample Data\n\n\nUse sample data provided by MongoDB, which is a PDF about a fictional park.\n\n
Chatbot Demo Builder is a public demo. Do not upload sensitive data.\n\n### Configure data processing.\n\nCustomize your chunking settings and embedding model.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nChunking strategy\n\n\nChoose either Recursive Chunking (default option) or Fixed Token Count with Overlap.\n\n- **Recursive Chunking**: Splits text by paragraph and sentence boundaries, then recursively merges content up to the chunk size. Use this for text documents where you want to preserve natural content structure.\n\n- **Fixed Token Count with Overlap**: Splits text into chunks with a fixed number of tokens, with overlap between adjacent chunks. Use this for uniform content or when you need predictable chunk sizes.\n\nTo learn more about chunking strategies, see Chunking Strategies.\n\n
\nChunk size\n\n\nDefine the number of tokens per chunk. The number of tokens must be at least double the amount of chunk overlap.\n\n- Minimum: 40 tokens\n\n- Maximum: 1500 tokens\n\n
\nChunk overlap\n\n\nSpecify the size of the overlap of tokens between adjacent chunks. The overlap size must be at most half of the chunk size.\n\n- Minimum: 0 tokens\n\n- Maximum: 750 tokens\n\n
\nEmbedding model\n\n\nSelect one of the following embedding models:\n\n- voyage-3-large (default option)\n\n- voyage-finance-2\n\n- voyage-law-2\n\n
To modify these options after creating embeddings, use the side panel DATA SETTINGS. Changing the settings clears previous chat history.\n\n### Ask questions about your data and edit retrieval settings.\n\nEach question and answer pair is independent, with no reliance on previous interactions. When you select Share, the playground saves your data configurations and retrieval settings. Question and answer history is neither saved nor can be shared.\n\nFor every question that you ask, the Chatbot Demo Builder shows the following settings:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nSetting or Output\n\n\nLocation on Page\n\n\nDescription\n\n
\nSearch Query\n\n\nLinked in chat box with answer\n\n\nView the MongoDB Vector Search query syntax.\n\n
\n[number] DOCUMENTS\n\n\nLinked in chat box with answer\n\n\nView the documents retrieved from running the search query and how the results are scored.\n\n
\nData to Evaluate (numCandidates)\n\n\nRight side panel\n\n\nAdjust the number of potential matches the system reviews to select the best result. To exhaustively search all indexed vector embeddings, click the Evaluate all [number] documents (ENN) check box. This may impact query latency.\n\n
\nData to Retrieve (limit)\n\n\nRight side panel\n\n\nAdjust the number of documents (chunks) returned.\n\n
\nData Source\n\n\nBottom panel tab\n\n\nView your data as MongoDB Documents or Full Extracted Text.\n\n
\nIndex Definition\n\n\nBottom panel tab\n\n\nView the generated MongoDB Vector Search index definition.\n\n
\nSearch Query\n\n\nBottom panel tab\n\n\nView the MongoDB Vector Search query syntax used for the most recent question and answer.\n\n
\nLLM & Prompt\n\n\nBottom panel tab\n\n\nView the Large Language Model (LLM) used.\n\n
\n\n### Share your demo.\n\nUse the Share button to generate a snapshot URL (Uniform Resource Locator) that persists for 30 days.\n\nUse the Get Code button to access a GitHub repository with starter code on how to build a similar chatbot yourself.\n\nThe Chatbot Demo Builder performance might differ from production performance.\n\n## Learn more\n\nTo learn more about vector search queries, see Run Vector Search ANN and ENN Queries. To learn more about Retrieval-Augmented Generation (RAG), see Retrieval-Augmented Generation (RAG) with MongoDB."} -{"chunk_id": "69fc3180a8c6c8a96605288d-0", "page_id": "69fc3180a8c6c8a96605288d", "source_name": "vector-search", "product_name": "Atlas Vector Search", "url": "https://mongodb.com/docs/vector-search/crud-embeddings/automated-embedding/models", "title": "Models for Automated Embedding", "text": "# Models for Automated Embedding\n\nAutomated Embedding uses Voyage AI's embedding models, which Atlas hosts and manages in the Data Plane in a multi-tenant environment.\n\n## Supported Models\n\nAutomated Embedding supports the following Voyage AI embedding models:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nEmbedding Model\n\n\nDescription\n\n\nPrice Per 1M Tokens\n\n
\n`voyage-4-lite`\n\n\nOptimized for high-volume, cost-sensitive applications.\n\n\n$0.02\n\n
\n`voyage-4`\n\n\n(**Recommended**) Balanced performance for general text search.\n\n\n$0.06\n\n
\n`voyage-4-large`\n\n\nMaximum accuracy for complex semantic relationships.\n\n\n$0.12\n\n
\n`voyage-code-4`\n\n\n(**Recommended for code**) Specialized for code search and technical documentation.\n\n\n$0.12\n\n
\n`voyage-code-3`\n\n\nLegacy model specialized for code search and technical documentation. Use `voyage-code-4` instead.\n\n\n$0.18\n\n
`voyage-code-4` requires an Atlas deployment. On self-managed deployments, use `voyage-code-3` for code search and technical documentation.\n\n### Context Window Sizes\n\nA context window is the maximum amount of text (measured in tokens, not characters) that an embedding or LLM model can consider in a single request. The maximum context window size for each model is as follows:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nEmbedding Model\n\n\nContext Window Size\n\n
\n`voyage-4-large`\n\n\n32,000 tokens\n\n
\n`voyage-4`\n\n\n32,000 tokens\n\n
\n`voyage-4-lite`\n\n\n32,000 tokens\n\n
\n`voyage-code-4`\n\n\n32,000 tokens\n\n
\n`voyage-code-3`\n\n\n32,000 tokens\n\n
If the indexed text field is longer than the context window, the text is automatically truncated to the context window size for the model. If your query text exceeds this context window for the model, the `$vectorSearch` query fails with a `context-limit-exceeded` error.\n\n### Cost of Models\n\nModel tokens are consumed during index operations (first time creation, inserts, update) and query operations. For the index operations, only the fields in the MongoDB document that are indexed as the `autoEmbed` type are used for embedding generation and incur a token usage. For the query operation, the query text provided is used for embedding generation and incurs a token usage. The cost for tokens for each model is as follows:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nEmbedding Model\n\n\nCost per 1K Tokens\n\n\nCost per 1M Tokens\n\n
\n`voyage-4-large`\n\n\n$0.00012\n\n\n$0.12\n\n
\n`voyage-4`\n\n\n$0.00006\n\n\n$0.06\n\n
\n`voyage-4-lite`\n\n\n$0.00002\n\n\n$0.02\n\n
\n`voyage-code-4`\n\n\n$0.00012\n\n\n$0.12\n\n
\n`voyage-code-3`\n\n\n$0.00018\n\n\n$0.18\n\n
\n\n### Free Tokens\n\n\n\n\n\nAtlas includes a one-time allocation of 200 million free tokens for each model at the organization level. The organization shares free tokens across all Atlas projects and clusters within the organization.\n\n\n\n\n\nMongoDB Vector Search includes a one-time allocation of 200 million free tokens for each model. The free tokens are shared across all clusters in the deployment.\n\n\n\n\n\nFree tokens do not refresh. For example, when new models are released, the free tokens for legacy models do not get reset. You can continue to use the remaining free tokens for the legacy model.\n\n## Rate Limits\n\nRate limits are restrictions on the frequency and number of tokens you can request from Automated Embedding within a specified period of time. MongoDB enforces rate limits on embedding generation to ensure fair usage across all users in the multi-tenant environment. Rate limits are based on the requests per minute (RPM) and tokens per minute (TPM). These rate limits apply at a MongoDB Cluster level and are shared between all the indexes on that cluster using Automated embedding. To request higher rate limits, contact your MongoDB account team or MongoDB support.\n\nRate limits are applied separately to queries, first-time index builds, and index update operations (document inserts and updates), providing traffic isolation. Indexing build operations are strictly isolated from the real-time query traffic.\n\n### First-time Index build Rate Limits\n\nThe first-time index build rate limits restrict the maximum frequency and number of tokens at which embeddings are generated. For large workloads during the first-time index build (initial sync), Automated Embedding uses a separate inference mechanism that is not bound by standard rate limits. This mechanism is optimized for throughput to handle the initial index build, provides the following benefits:\n\n- Faster Initial Synchronization: Scale embedding generation throughput dynamically to handle massive bursts.\n\n- Unbounded Throughput: Bursts up to available GPU capacity, and eliminate manual rate-limit increase requests.\n\n- Fair Resource Sharing: Competing index builds converge to similar token-per-second allocation, avoiding starvation.\n\n- Safe Ramp-Up: Starts at low concurrency and grows only on explicit internal success signals dynamically."} -{"chunk_id": "69fc3180a8c6c8a96605288d-1", "page_id": "69fc3180a8c6c8a96605288d", "source_name": "vector-search", "product_name": "Atlas Vector Search", "url": "https://mongodb.com/docs/vector-search/crud-embeddings/automated-embedding/models", "title": "Models for Automated Embedding", "text": "### Index Insert and Update Rate Limits\n\nThe index rate limits restrict the maximum frequency and number of tokens at which embeddings are generated during certain operations on MongoDB Vector Search Automated Embedding indexes. These operations include inserts (new data is added to your index) or updates (existing data changes that require re-embedding).\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nModel\n\n\nRequests Per Minute (RPM)\n\n\nTokens Per Minute (TPM)\n\n
\n`voyage-4-large`\n\n\n2,000\n\n\n3,000,000\n\n
\n`voyage-4`\n\n\n2,000\n\n\n8,000,000\n\n
\n`voyage-4-lite`\n\n\n2,000\n\n\n16,000,000\n\n
\n`voyage-code-4`\n\n\n2,000\n\n\n3,000,000\n\n
\n`voyage-code-3`\n\n\n2,000\n\n\n3,000,000\n\n
\n\n### Query Operations Rate Limits\n\nThe query rate limits control the maximum embedding generation frequency and the number of tokens for all queries that use the `$vectorSearch` operations on your MongoDB Vector Search Automated Embedding indexes.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nModel\n\n\nRequests Per Minute (RPM)\n\n\nTokens Per Minute (TPM)\n\n
\n`voyage-4-large`\n\n\n3\n\n\n2,000\n\n
\n`voyage-4`\n\n\n3\n\n\n2,000\n\n
\n`voyage-4-lite`\n\n\n3\n\n\n2,000\n\n
\n`voyage-code-4`\n\n\n3\n\n\n2,000\n\n
\n`voyage-code-3`\n\n\n3\n\n\n2,000\n\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nModel\n\n\nRequests Per Minute (RPM)\n\n\nTokens Per Minute (TPM)\n\n
\n`voyage-4-large`\n\n\n2,000\n\n\n3,000,000\n\n
\n`voyage-4`\n\n\n2,000\n\n\n8,000,000\n\n
\n`voyage-4-lite`\n\n\n2,000\n\n\n16,000,000\n\n
\n`voyage-code-4`\n\n\n2,000\n\n\n3,000,000\n\n
\n`voyage-code-3`\n\n\n2,000\n\n\n3,000,000\n\n
\n\n## Best Practices\n\nTo optimize performance within rate limits:\n\n1. **Create an Index on Prepopulated Collections When Possible**: The first-time index build (initial sync) benefits from a special inference mechanism that is not throughput bounded. Therefore, we recommend prepopulating your collection before creating an index.\n\n2. **Batch Updates**: If you are performing bulk updates, monitor the index update throughput in the Automated Embedding dashboard's Usage page and space them out to avoid hitting rate limits.\n\n3. **Monitor Usage**: Track your embedding generation in the Automated Embedding dashboard's Usage page to identify patterns and optimize.\n\n4. **Upgrade When Needed**: If you consistently hit rate limits, consider adding a payment method for higher quotas, or reaching out to your MongoDB account team for higher rate limits."} -{"chunk_id": "69eb0c75d0423fff078dfade-0", "page_id": "69eb0c75d0423fff078dfade", "source_name": "vector-search", "product_name": "Atlas Vector Search", "url": "https://mongodb.com/docs/vector-search/deployment/deployment-options", "title": "Review Deployment Options", "text": "# Review Deployment Options\n\nThe following sections describe deployment options for MongoDB Vector Search on Atlas.\n\nYou can structure your cluster with different deployment types, cloud providers, and cluster tiers to meet the needs of a pre-production or production environment. Use these recommendations to select the deployment type, cloud provider and region, and cluster and search tiers for performing vector search.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nEnvironment\n\n\nDeployment Type\n\n\nCluster Tier\n\n\nCloud Provider Region\n\n\nNode Architecture\n\n
\nTesting Queries\n\n\nFlex cluster, dedicated clusterLocal deployment\n\n\nFree cluster or higher tierN/A\n\n\nAllN/A\n\n\nMongoDB and Search processes run on the same node.\n\n
\nPrototyping Applications\n\n\nDedicated cluster\n\n\nFlex cluster, `M10`, `M20`, or higher tier\n\n\nAll\n\n\nMongoDB and Search processes run on the same node.\n\n
\nProduction\n\n\nDedicated cluster with separate Search Nodes\n\n\n`M10` or higher cluster tier and `S30` or higher search tier\n\n\nAWS (Amazon Web Services) and Azure (Microsoft Azure) in some regions or Google Cloud in all regions\n\n\nMongoDB and Search processes run on different nodes.\n\n
\nCommunity Edition\n\n\nSelf-managed deployment. You install and operate `mongod` and `mongot` yourself.\n\n\nN/A. You provide your own hardware or cloud instances.\n\n\nN/A. You choose your own infrastructure.\n\n\nMongoDB and Search processes run on either a single or separate self-managed hosts.\n\n
To learn more about these deployment models, review the following sections:\n\n- Testing and Prototyping Environments\n\n- Production Environment\n\n- MongoDB Community Edition\n\n## Resource Usage\n\n### Memory Requirements for Indexing Vectors\n\nMongoDB Vector Search holds the entire index in memory, so you need to ensure there's enough memory for the MongoDB Vector Search index and JVM (Java virtual machine) if your dataset includes full precision vectors. Each index is a combination of the vectors being indexed and additional metadata. The index size is primarily determined by the size of the vectors that you are indexing, with metadata space typically being relatively nominal.\n\nWhen not using quantization, MongoDB Vector Search stores the full fidelity vectors in memory. If you enable automatic quantization, MongoDB Vector Search stores the quantized vectors, which require significantly less resources, in memory and the full fidelity vectors on disk. You can view the difference between disk and memory requirements for vector indexes by viewing the Size and Required Memory columns in the Atlas UI MongoDB Search page.\n\nConsider the following requirements for a **single vector**:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nEmbedding Model\n\n\nVector Dimension\n\n\nSpace Requirement\n\n
\nVoyage AI `voyage_3_large`\n\n\n2048\n\n\n8kb (for `float`)2.14kb (for `int8`)0.334kb (for `int1`)\n\n
\nOpenAI `text-embedding-ada-002`\n\n\n1536\n\n\n6kb\n\n
\nGoogle `text-embedding-gecko`\n\n\n768\n\n\n3kb\n\n
\nCohere `embed-english-v3.0`\n\n\n1024\n\n\n4kb (for `float`)1.07kb (for `int8`)0.167kb (for `int1`)\n\n
BinData quantized vectors. To learn more, see Ingest Quantized Vectors.\n\nThe required space scales linearly with the number of vectors that you are indexing and with the vector dimensionality. You can also use the Search Index Size metric to determine the amount of space and memory you need on your Search Nodes.\n\n### Storage Requirements for Vectors\n\nIf you use BinData or quantized vectors, you significantly reduce resource requirements compared to not using `binData` or quantized vectors. You will notice:\n\n- Disk storage of vectors on `mongod` reduce by 66% when using `binData` vectors.\n\n- RAM usage of vectors on `mongot` reduce by 3.75x (scalar) or 24x (binary) due to vector compression when using either automatic vector quantization or quantized vector ingestion.\n\nWhen you use automatic quantization, Atlas stores the full-precision vectors for rescoring or exact search on disk, with minimal RAM and cache usage for rescoring.\n\nIf you enable automatic quantization in your MongoDB Vector Search index definition, you must consider disk space also when sizing your cluster. This is because MongoDB Vector Search stores full-precision vectors also on disk for ENN (Exact Nearest Neighbor) search and for rescoring if you configured automatic quantization. Therefore, ensure that there is an appropriate disk to RAM ratio on the hardware that you use. Consider configuring search nodes that can accommodate roughly a 4:1 ratio of storage to RAM for scalar quantization or a 24:1 ratio of storage to RAM for binary quantization.\n\nThis example demonstrates how to configure binary quantization for 10 million 1024-dimension embeddings from Voyage AI stored in the field named `my-embeddings`:\n\n```\n{\n \"fields\":[\n {\n \"type\": \"vector\",\n \"path\": \"my-embeddings\",\n \"numDimensions\": 1024,\n \"similarity\": \"euclidean\",\n \"quantization\": \"binary\"\n }\n ]\n}\n```\n\nUse the following formula to roughly calculate the disk space for your binary quantization-enabled index with rescoring:\n\n```shell\nOriginal index size * (25/24)\n```\n\nHere, the `24` in the denominator represents the original index size split into `24` parts for easier fraction representation. The `25` in the numerator accounts for an additional space allocation, which is approximately 1/24 of the original index size, for additional data needed to store binary vectors. Both the original index and the Hierarchical Navigable Small Worlds graph are still stored on disk. The oversize factor is 1/24 rather than 1/32 because the HNSW graph is not compressed.\n\nSuppose your original index size is 1 GB. You can calculate the binary quantized index size with rescoring as shown below:\n\n```shell\n1 GB * (25/24) = 1.042 GB\n```\n\nIn the Atlas UI, Atlas displays the entire index size, which might be large as Atlas doesn't show a break down of the data structures within an index that are stored in RAM and on disk. The MongoDB Search metrics show a much smaller index that is held in memory when you enable automatic quantization.\n\nFor vectors for which you configured automatic quantization, we recommend allocating free disk space equal to 125% of the estimated index size.\n\n## Testing and Prototyping Environments\n\nFor testing your vector search queries and prototyping your application, we recommend the following configuration."} -{"chunk_id": "69eb0c75d0423fff078dfade-1", "page_id": "69eb0c75d0423fff078dfade", "source_name": "vector-search", "product_name": "Atlas Vector Search", "url": "https://mongodb.com/docs/vector-search/deployment/deployment-options", "title": "Review Deployment Options", "text": "### Deployment Type\n\nFor testing MongoDB Vector Search queries, you can deploy a Flex cluster, a dedicated cluster, or use a local Atlas deployment.\n\n\n\n\n\n#### Cluster Tiers\n\nFree clusters are a no-cost cluster type. Flex clusters are low-cost cluster types suitable for teams that are learning MongoDB or developing small proof-of-concept applications. You can begin your project with an Atlas Flex cluster and upgrade to a production-ready Dedicated cluster tier at a future time.\n\nThese low-cost cluster types are available for testing your MongoDB Vector Search queries. However, you might experience resource contention and query latency on Flex clusters. If you begin your project with a Flex cluster, we recommend upgrading to a higher tier when your application is ready for production.\n\nDedicated clusters include `M10` and higher tiers. The `M10` and `M20` tiers are suitable for prototyping your application. You can scale to higher tiers to handle large datasets or deploy dedicated Search Nodes for workload isolation when your application is ready for production.\n\n#### Cloud Provider and Region\n\nThe cloud provider and region that you choose affects the configuration options available for the cluster tiers and the cost of running the cluster.\n\nAll the cluster tiers are available in all the supported cloud provider regions\n\n\n\n\n\nIf you prefer to test MongoDB Vector Search queries locally, you can use the Atlas CLI to deploy a single-node replica set hosted on your local computer. To get started, complete the MongoDB Vector Search Quick Start Tutorial and select the tab for local deployments.\n\nWhen your application is ready for production, migrate your local Atlas deployment to a production environment by using Live Migration. Local deployments are limited by the CPU, memory, and storage resources of your local machine.\n\n\n\n\n\n### Node Architecture\n\nMongoDB Vector SearchFor testing and prototyping environments, we recommend a node architecture in which MongoDB processes and MongoDB Search processes run on the same node. In the following diagram of this deployment model, the MongoDB Search `mongot` process runs alongside `mongod` on each node in the Atlas cluster and they share the same resources.\n\nBy default, Atlas enables the MongoDB Search `mongot` process on the same node that runs the `mongod` process when you create your first MongoDB Vector Search index.\n\nWhen you run a query, MongoDB Search uses the configured read preference to identify the node on which to run the query. The query first goes to the MongoDB process, which is `mongod` for a replica set cluster or `mongos` for a sharded cluster.\n\nFor a replica set cluster, the `mongod` process routes the query to the `mongot` on the same node. For sharded clusters, your cluster data is partitioned across `mongod` instances (shards) and each `mongot` process can only access the data on the `mongod` instance on the same node. Therefore, you can't run MongoDB Search queries that target a particular shard. `mongos` routes the query to all shards, making these *scatter gather* queries. If you use zones to distribute a sharded collection over a subset of the shards in the cluster, MongoDB Search routes the query to the zone that contains the shards for the collection that you are querying and runs your `$search` queries on just the shards where the collection is located.\n\nAfter the query is routed to a MongoDB Search `mongot` process, the `mongot` process performs the search and scoring and returns the document IDs and other search metadata for the matching results to its corresponding `mongod` process. The `mongod` process then performs a full document lookup implicitly for the matching results and returns the results to the client. If you use the `$search` concurrent option in your query, MongoDB Search enables intra-query parallelism. To learn more, see Parallelize Query Execution Across Segments.\n\nTo learn more about the `mongot` process, see Query Processing.\n\n### Size Your Cluster for Prototyping Your Application\n\nWhen Atlas runs your database and search workloads on the same node, the MongoDB storage takes a certain percentage of the node's available memory (RAM), leaving the remaining for the MongoDB Vector Search index and the `mongot` process.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nTier\n\n\nTotal Memory (GB)\n\n\nMemory Available for MongoDB Vector Search Index (GB)\n\n
\n`M10`\n\n\n2\n\n\n1\n\n
\n`M20`\n\n\n4\n\n\n2\n\n
\n`M30`\n\n\n8\n\n\n4\n\n
For `M10`, `M20`, and `M30` cluster tiers, 25% is reserved for MongoDB and the remaining 75% is for other operations, including your MongoDB Vector Search index. For M40+ cluster tiers, 50% is reserved for MongoDB and the remaining is for other operations, including your MongoDB Vector Search index.\n\n### Limitations\n\nYou might experience resource contention between the database `mongod` and the search `mongot` processes. This could negatively impact the performance of your index and latency of your queries. We recommend this deployment model for only testing and prototyping environments. For production-ready applications and associated search workloads, we recommend migrating to dedicated Search Nodes.\n\n## Production Environment\n\nFor your production-ready application, we recommend the following cluster configuration.\n\n### Deployment Type\n\nFor production-ready applications, you need a dedicated cluster with separate Search Nodes for Workload Isolation.\n\n### Cluster Tiers\n\nDedicated clusters include `M10` and higher tiers. The `M10` and `M20` tiers are suitable for development and for production environments. However, the higher tiers can handle large datasets and production workloads. We recommend that you also deploy dedicated Search Nodes for your search workload. This allows you to scale your search deployment independently and appropriately.\n\n### Cloud Provider and Region\n\nSearch Nodes are available in all the regions for Google Cloud but are only available in a subset of AWS (Amazon Web Services) and Azure (Microsoft Azure) regions. You *must* select a cloud provider and region where Search Nodes are available for your deployment.\n\nAll cluster tiers are available in supported cloud provider regions. The cloud provider and region that you choose affects the configuration options and search tiers available for the cluster and the cost of running the cluster."} -{"chunk_id": "69eb0c75d0423fff078dfade-2", "page_id": "69eb0c75d0423fff078dfade", "source_name": "vector-search", "product_name": "Atlas Vector Search", "url": "https://mongodb.com/docs/vector-search/deployment/deployment-options", "title": "Review Deployment Options", "text": "### Node Architecture\n\nMongoDB Vector SearchHow to Index Fields for Vector SearchRun Vector Search ANN and ENN QueriesFor production environments, we recommend a node architecture in which MongoDB processes and MongoDB Search processes run on separate nodes. To deploy separate Search Nodes, see Migrate to Dedicated Search Nodes.\n\nIn the following diagram of this deployment model, the MongoDB Search `mongot` process runs on dedicated Search Nodes, which are separate from the cluster nodes on which the `mongod` process runs.\n\nAtlas deploys Search Nodes with each cluster or with each shard on the cluster. For example, if you deploy two Search Nodes for a cluster with three shards, Atlas deploys six Search Nodes (two per shard). You can also configure the number of Search Nodes and the amount of resources provisioned for each search node.\n\nWhen you deploy separate Search Nodes, Atlas automatically assigns a `mongod` for each `mongot` for indexing. The `mongot` communicates with the `mongod` to listen for and sync index changes for the indexes that it stores. MongoDB Vector Search indexes and processes your queries similar to a deployment where both the `mongod` and `mongot` processes run on the same node. To learn more, see How to Index Fields for Vector Search and Run Vector Search ANN and ENN Queries. To learn more about deploying Search Nodes separately, see Search Nodes for Workload Isolation.\n\nWhen you migrate to Search Nodes, Atlas deploys the Search Nodes, but doesn't serve queries on the nodes until it successfully builds all the indexes on the cluster on the Search Nodes. While Atlas builds the indexes on the new nodes, it continues to serve queries using the indexes on the cluster nodes. Atlas starts serving queries from the Search Nodes only after it successfully builds the indexes on the Search Nodes and removes the indexes on the cluster nodes.\n\nScaling your cluster by adding search nodes or by changing the search tier triggers a rebuild of the full MongoDB Search index. However, if your cluster on AWS (Amazon Web Services) or Azure (Microsoft Azure) has dedicated search nodes for which you haven't enabled Encryption at Rest using Customer Key Management, Atlas provides the following optimizations:\n\n- When you scale your search nodes, Atlas uses a recent copy of your index in S3 (Simple Storage Service) or Azure Blob Storage instead of rebuilding the entire MongoDB Search index on the new node.\n\n- For existing nodes, Atlas periodically takes and uploads a new incremental list of index files. Atlas retains index files for up to fourteen (14) days.\n\nThis is not yet available for clusters with dedicated search nodes on Google Cloud.\n\nWhen you run a query, the query routes to the `mongod` based on the configured read preference. The `mongod` process routes the search query through a load balancer on the same node, which distributes the requests across all of the `mongot` processes.\n\nThe MongoDB Search `mongot` process performs the search and scoring and returns the document IDs and metadata for the matching results to `mongod`. The `mongod` then performs a full document lookup for the matching results and returns the results to the client. If you use the `$search` concurrent option in your query, MongoDB Search enables intra-query parallelism. To learn more, see Parallelize Query Execution Across Segments.\n\nIf you delete all the Search Nodes on your cluster, there will be an interruption in processing your search query results. To learn more, see Modify a Cluster. If you delete your Atlas cluster, Atlas pauses and then deletes all associated MongoDB Vector Search deployments (`mongot` processes).\n\n### Benefits\n\nThis deployment model provides the following benefits:\n\n- Efficiently utilize your resources while ensuring high availability of your resources for search workloads.\n\n- Size and scale your search deployment independently from your database deployment.\n\n- Automatically process MongoDB Vector Search queries concurrently, improving the response time especially on large datasets. To learn more, see Parallel Query Execution Across Segments.\n\n### Size Your Search Nodes for Production\n\nMongoDB Vector Search holds the entire index in memory, so you need to ensure there's enough memory for the MongoDB Vector Search index and JVM (Java virtual machine). Search nodes allow for workload isolation without data isolation, and almost 90% of their RAM allocation can be used to store the vector data and indexes in memory, with the leftover being used for the JVM.\n\nEach index is a combination of the vectors being indexed and additional metadata. The index size is primarily determined by the size of the vectors that you are indexing, with metadata space typically being relatively nominal. To learn more, see Memory Requirements for Indexing Vectors.\n\nWhen you deploy dedicated Search Nodes, you can choose from different search tiers. Each search tier has a default RAM capacity, storage capacity, and CPU. This allows you to size and scale your cluster independently from your database deployment. To scale your search deployment separately, you can make the following changes to your cluster configuration at any time:\n\n- Adjust the number of Search Nodes on your cluster.\n\n- Adjust the CPU, RAM, and storage of the node by changing search tiers.\n\nTo learn more about the cost of Search Nodes and search tiers, expand View all plan features and click MongoDB Vector Search in the the MongoDB Pricing page.\n\nWe recommend that your node has RAM that is at least 10% larger than the total size of your MongoDB Vector Search indexes. We also recommend that you ensure you have enough available CPUs. Query latency depends on the number of available CPUs, which can significantly impact the level of internal concurrency that accelerates query performance.\n\nSuppose you have 1M 768 dimensions vectors of roughly 3GB in size. Both the S30 (Low-CPU) and S20 (High-CPU) search tiers have enough RAM to support the index. Instead of deploying on the S30 (Low-CPU) search tier, we recommend deploying on the S20 (High-CPU) search tier because the S20 (High-CPU) search tier has more available CPUs to run queries concurrently.\n\n### Enable Encryption at Rest\n\nMongoDB Vector SearchBy default, MongoDB and search processes run on the same nodes. With this architecture, customer-managed encryption applies to your database data, but it does not apply to search indexes.\n\nWhen you enable dedicated Search Nodes, search processes run on separate nodes. This allows you to enable Search Node Data Encryption, so you can encrypt both database data and search indexes with the same customer-managed keys for comprehensive encryption coverage.\n\nDatabase nodes and Search Nodes use different encryption methods with the same customer-managed keys. Database nodes use the WiredTiger Encrypted Storage Engine, while Search Nodes use encryption at the disk level.\n\nTo learn more, see Enable Customer Key Management for Search Nodes."} -{"chunk_id": "69eb0c75d0423fff078dfade-3", "page_id": "69eb0c75d0423fff078dfade", "source_name": "vector-search", "product_name": "Atlas Vector Search", "url": "https://mongodb.com/docs/vector-search/deployment/deployment-options", "title": "Review Deployment Options", "text": "### Migrate to Dedicated Search Nodes\n\nDedicated Search Nodes allow you to both size and scale your search deployment separately from your cluster. It also eliminates any resource contention that you might experience on a cluster that runs both the database and search processes on the same node.\n\nTo migrate to dedicated Search Nodes, make the following changes to your deployment:\n\n1. If your deployment is currently using a Free cluster or a Flex cluster, upgrade your cluster to a higher tier. Dedicated Search Nodes are supported only for `M10` and higher cluster tiers. To learn more about migrating to a different cluster tier, see Modify the Cluster Tier.\n\n2. Dedicated Search Nodes are available on a subset of the AWS (Amazon Web Services) and Azure (Microsoft Azure) regions and in all supported Google Cloud regions. Make sure to deploy your cluster in regions where Search Nodes are also available. If your existing cluster is in regions where Search Nodes are not available, migrate your cluster to regions where Search Nodes are available. To learn more, see Cloud Provider Regions.\n\n3. Enable Search Nodes for workload isolation and configure Search Nodes. To learn more, see Add Search Nodes.\n\n## MongoDB Community Edition\n\nIf you run MongoDB Vector Search on MongoDB Community Edition or another self-managed deployment, Atlas does not manage `mongot` for you. Instead, you install, configure, and operate `mongot` yourself. The following sections summarize the available architecture patterns and sizing options. For complete deployment and sizing guidance, see MongoDB Search and MongoDB Vector Search on Self-Managed Deployments and Introduction to mongot Deployment Sizing.\n\n### Architecture Patterns\n\nAs with MongoDB Vector Search on Atlas, self-managed deployments use one of the same two architecture patterns: co-located or dedicated. The only exception is that on self-managed deployments, you provision and manage the hosts yourself.\n\n### Sizing\n\nUnlike Atlas, self-managed deployments have no predefined cluster or search tiers. You provision your own hardware or cloud instances. To choose a starting configuration and refine it based on your workload, see Introduction to mongot Deployment Sizing."} -{"chunk_id": "6a514deed727379c91ba2ea9-0", "page_id": "6a514deed727379c91ba2ea9", "source_name": "vector-search", "product_name": "Atlas Vector Search", "url": "https://mongodb.com/docs/vector-search/query/native-reranking/managing", "title": "Manage Settings for $rerank Stage", "text": "# Manage Settings for $rerank Stage\n\nYou can perform the following tasks in the Atlas UI:\n\n- Enable or disable Native Reranking for all projects in your organization or per project.\n\n- Monitor Token Usage.\n\n- View rate limits.\n\n- View metrics.\n\n## Permissions Required\n\nTo enable or disable Native Reranking, you must have `Project Owner` access to the project. If you have `Organization Owner` access, you must add yourself as a `Project Owner` to the project for enabling or disabling Native Reranking.\n\nTo view rate limits and usage metrics, you must have `Project Read Only` or `Project Search Index Editor` access or above to the project.\n\n## Enable or Disable Native Reranking for a Project\n\nBefore you can use the `$rerank` stage, you must enable Native Reranking for your project.\n\n### Enable or Disable Native Reranking\n\nTo enable or disable reranking, complete the following steps:\n\n#### In Atlas, go to the Project Settings page.\n\n- If it's not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.\n\n- If it's not already displayed, select your desired project from the Projects menu in the navigation bar.\n\n- In the sidebar, click the icon next to Project Overview.\n\nThe Project Settings page displays.\n\n#### Enable or disable reranking.\n\n**To enable** reranking, do the following:\n\n- In the Project Settings tab, set the Native Reranking: $rerank in the Aggregation Pipeline toggle to On.\n\n- In the Confirm Rerank Model Usage window, select the checkbox to confirm that you understand the costs associated with using the `$rerank` stage and click Confirm.\n\n**To disable** reranking, complete the following steps:\n\n- In the Project Settings tab, set the Native Reranking: $rerank in the Aggregation Pipeline toggle to Off.\n\n- In the Disable Native Reranking confirmation window, type `Disable` and click Disable.\n\n Disabling reranking might cause running queries that use the `$rerank` stage to fail.\n\n### Restrict Native Reranking Using a Resource Policy\n\nYou can configure a resource policy at the organization level to block `$rerank` entirely or with exceptions. To do this, add a `forbid` rule written in Cedar that targets the `$rerank` action. If you configure this policy, new projects can't enable `$rerank`. However, the policy does not disable projects that already have `$rerank` enabled. You must disable `$rerank` individually for each project that already has it enabled. To disable `$rerank` for a project, see Enable or Disable Native Reranking.\n\nYou can disable `$rerank` with exceptions by using the `unless` clause in the `forbid` rule.\n\n```text\nforbid (principal, action == ResourcePolicy::Action::\"$rerank\", resource) unless { };\n```\n\nTo learn more about setting the resource policy, see Atlas Resource Policies Overview.\n\n## Monitor Token Usage\n\nMonitor your token usage on the Usage page in the Atlas UI. To view usage:\n\n### In Atlas, go to the Search & Vector Search page for your cluster.\n\nYou can go the MongoDB Search page from the Search & Vector Search option, or the Data Explorer.\n\n- If it's not already displayed, select the organization that contains your project from the Organizations menu in the navigation bar.\n\n- If it's not already displayed, select your project from the Projects menu in the navigation bar.\n\n- In the sidebar, click Search & Vector Search under the Database heading.\n\n- If your project has multiple clusters, select the cluster you want to use from the Select cluster dropdown, then click Go to Atlas Search.\n\n The Search & Vector Search page displays.\n\n- If it's not already displayed, select the organization that contains your project from the Organizations menu in the navigation bar.\n\n- If it's not already displayed, select your project from the Projects menu in the navigation bar.\n\n- In the sidebar, click Data Explorer under the Database heading.\n\n- Expand the database and select the collection.\n\n- Click the Indexes tab for the collection.\n\n- Click the Search and Vector Search link in the banner.\n\n The Search & Vector Search page displays.\n\n### Click Usage under Native Reranking in the navigation bar.\n\nThe Usage page provides several views to monitor and analyze your token usage. To learn more, see Token Usage.\n\n## Manage Rate Limits\n\nThe Rate Limits page in the Atlas UI provides the rate limits for your project and guidance on how to increase them.\n\n### Usage Tiers and Rate Limits\n\nAtlas enforces rate limits on the number of requests that you can make within a specific time frame, measured in tokens per minute (TPM) or requests per minute (RPM). Rate limits follow a tiered system, with higher tiers offering increased limits.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nModel\n\n\nRequests Per Minute (RPM)\n\n\nTokens Per Minute (TPM)\n\n
\n`rerank-3`\n\n\n4,000\n\n\n4,000,000\n\n
\n`rerank-3-lite`\n\n\n4,000\n\n\n8,000,000\n\n
\n`rerank-2.5`\n\n\n4,000\n\n\n4,000,000\n\n
\n`rerank-2.5-lite`\n\n\n4,000\n\n\n8,000,000\n\n
\n`rerank-2`\n\n\n4,000\n\n\n4,000,000\n\n
\n`rerank-2-lite`\n\n\n4,000\n\n\n8,000,000\n\n
\n\n### View Rate Limits\n\n#### In Atlas, go to the Search & Vector Search page for your cluster.\n\nYou can go the MongoDB Search page from the Search & Vector Search option, or the Data Explorer.\n\n- If it's not already displayed, select the organization that contains your project from the Organizations menu in the navigation bar.\n\n- If it's not already displayed, select your project from the Projects menu in the navigation bar.\n\n- In the sidebar, click Search & Vector Search under the Database heading.\n\n- If your project has multiple clusters, select the cluster you want to use from the Select cluster dropdown, then click Go to Atlas Search.\n\n The Search & Vector Search page displays.\n\n- If it's not already displayed, select the organization that contains your project from the Organizations menu in the navigation bar.\n\n- If it's not already displayed, select your project from the Projects menu in the navigation bar.\n\n- In the sidebar, click Data Explorer under the Database heading.\n\n- Expand the database and select the collection.\n\n- Click the Indexes tab for the collection.\n\n- Click the Search and Vector Search link in the banner.\n\n The Search & Vector Search page displays.\n\n#### Click Rate Limits under Native Reranking in the navigation bar.\n\n### Increase Rate Limits\n\nMongoDB automatically increases rate limits as your usage increases. If you still need a higher rate limit, contact MongoDB Support."} -{"chunk_id": "6a514deed727379c91ba2ea9-1", "page_id": "6a514deed727379c91ba2ea9", "source_name": "vector-search", "product_name": "Atlas Vector Search", "url": "https://mongodb.com/docs/vector-search/query/native-reranking/managing", "title": "Manage Settings for $rerank Stage", "text": "## Monitor Metrics for Native Reranking\n\nYou can monitor `$rerank` usage through the following metrics in the Atlas UI:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nMetric\n\n\nDescription\n\n
\n$rerank Query Status Rate\n\n\nThe percentage of `$rerank` queries that complete successfully. Use this metric to identify failures in `$rerank` queries, such as rate limit errors or connectivity issues with Voyage AI.\n\n
\n$rerank Token Usage Rate\n\n\nThe total number of tokens that `$rerank` queries consume. Use this metric to monitor token consumption and correlate usage with billing.\n\n
To view metrics for `$rerank` usage:\n\n### Navigate to the Metrics tab for your cluster.\n\n- Select the organization that contains your project from the Organizations menu in the navigation bar.\n\n- Select your project from the Projects menu in the navigation bar.\n\n- In the sidebar, click Clusters under the Database heading.\n\n- Click the name of the cluster to open the Cluster sidebar.\n\n- Click Metrics in the Cluster sidebar.\n\n### Select the Native Reranking Metrics to view.\n\nYou can view the $rerank Query Status Rate and $rerank Token Usage Rate metrics by clicking the appropriate metric."} -{"chunk_id": "69fc3180a8c6c8a96605288c-0", "page_id": "69fc3180a8c6c8a96605288c", "source_name": "vector-search", "product_name": "Atlas Vector Search", "url": "https://mongodb.com/docs/vector-search/crud-embeddings/automated-embedding", "title": "Automated Embedding Overview", "text": "# Automated Embedding Overview\n\n\n\n\n\nYou can configure MongoDB Vector Search to automatically generate and manage vector embeddings for the text data in your Atlas cluster. When you enable Automated Embedding, MongoDB Vector Search automatically generates embeddings using the specified Voyage AI embedding model at index-time for the specified text field in your collection and at query-time for the text string in your query.\n\nAutomated Embedding simplifies the process of building semantic search. You don't need to generate, store, or manage vector embeddings yourself. Atlas handles embedding generation, updates, and querying natively.\n\nWhen you use Automated Embedding, MongoDB Vector Search stores generated vector embeddings on your cluster.\n\nWhen you use Automated Embedding on dedicated clusters (`M10+`), you must enable storage auto-scaling. If your cluster runs out of disk space, MongoDB Vector Search pauses embedding generation and the index transitions to Stale state. Once the disk space is freed up, MongoDB Vector Search resumes embedding generation.\n\n\n\n\n\nYou can deploy MongoDB Vector Search and enable intelligent, AI-powered semantic search on your text data through Automated Embedding in MongoDB Vector Search indexes. MongoDB's Automated Embedding capabilities transform the traditionally complex process of vector search implementation into a single-step solution. Instead of managing separate embedding infrastructure, model selection, and integration code, you can now implement semantic search through simple field configuration.\n\nWhen you configure MongoDB Vector Search indexes, it automatically generates vector embeddings for text data in your collection, using your selection of a state-of-the-art Voyage AI embedding model, keeps the embeddings in sync as your data changes, and also supports use of natural language text queries. These vector embeddings capture meaningful relationships in your data and allow for searching based on intent rather than keywords.\n\nAutomated Embeddings is available as a Preview feature. The feature and the corresponding documentation might change at any time during the Preview period. Do not use this feature in your production environment. We do not use any customer data from this feature to train our models at this time. To learn more, see Preview Features.\n\n\n\n\n\n## Enable and Use Automated Embedding\n\n\n\n\n\nTo enable Automated Embedding, you create a MongoDB Vector Search index using the `autoEmbed` type. The `autoEmbed` type specifies the field for which you want to enable Automated Embedding and the embedding model that you want to use. You can also include one or more fields to pre-filter your data using the `filter` type.\n\n```json\n{\n \"fields\": [\n {\n \"type\": \"autoEmbed\",\n \"modality\": \"text\",\n \"path\": \"\",\n \"model\": \"\"\n },\n {\n \"type\": \"filter\",\n \"path\": \"\"\n },\n ...\n ]\n}\n```\n\nTo learn more about the index syntax and fields, see How to Index Fields for Vector Search.\n\nMongoDB Vector Search automatically generates embeddings for existing and new documents that you insert or update.\n\nOnce you've created the index, you can run your queries. MongoDB Vector Search automatically generates embeddings for your query text using the same embedding model that you specified in the index. You can optionally specify a different embedding model using the `model` option in the `$vectorSearch` pipeline stage, but the specified embedding model must be compatible with the embedding model used at index-time.\n\n```json\n[\n {\n \"$vectorSearch\": {\n \"index\": \"\",\n \"path\": \"\",\n \"query\": \"\",\n \"model\": \"\"\n }\n },\n {\n \"$project\": {\n \"_id\": 0,\n \"\": 1,\n \"score\": { \"$meta\": \"vectorSearchScore\" }\n }\n }\n]\n```\n\nTo learn more, see Run Vector Search ANN and ENN Queries.\n\n\n\n\n\nThe feature is available for MongoDB Search and MongoDB Vector Search deployments using Docker, tarball, or a package manager and for deployments using the MongoDB Controllers for Kubernetes Operator with MongoDB 8.2 or later Community Edition. Automated Embedding functionality is not yet available for MongoDB Enterprise Edition.\n\nWith a simple configuration change, you can enable semantic search, RAG, and memory for AI Agents, without writing embedding code, managing model infrastructure, or handling vector pipelines. That is, when deploying the MongoDB Community Edition with the MongoDB Search and Vector Search process, `mongot`, you can provide the Voyage AI API keys to use for generating embeddings, ideally one for indexing operations and another for query operations from different projects.\n\nAfter deployment:\n\n- From your collection, choose the text field for which you want to enable the semantic search.\n\n- From the list of available embedding models, choose an embedding model.\n\n- In your MongoDB Vector Search index definition, configure Automated Embedding using the `autoEmbed` type.\n\nTo learn more about configuring MongoDB Vector Search index for Automated Embedding, see How to Index Fields for Vector Search.\n\nMongoDB Vector Search automatically generates embeddings for existing and new documents that you insert or update by using the API (Application Programming Interface) keys that you specified while initializing MongoDB Community Edition.\n\nFor querying, use the `query.text` option in the `$vectorSearch` pipeline stage. MongoDB Vector Search generates embeddings for the text query using the same embedding model in the index definition. You can specify a different embedding model using the `model` option in the `$vectorSearch` pipeline stage, but the specified embedding model must be compatible with the embedding model used at index-time. MongoDB Vector Search uses the query API key that you provided during MongoDB Community initialization to generate the embeddings at query-time. To learn more, see Run Vector Search ANN and ENN Queries.\n\nYou incur charges for generating embeddings using the API (Application Programming Interface) keys. To learn more, see Manage Billing.\n\nTo automate embeddings and run a sample query, see MongoDB Vector Search Quick Start Tutorial.\n\n### Voyage AI API (Application Programming Interface) Keys\n\nWhile you can use a single API (Application Programming Interface) key for generating embeddings at index-time and at query-time, we recommend that you use separate API (Application Programming Interface) keys to avoid query operations from negatively impacting indexing operations.\n\nYou can generate API (Application Programming Interface) keys in the following ways:\n\n- (**Recommended**) Using your Atlas account, which allows you to manage your Voyage AI embedding model API (Application Programming Interface) key from the Atlas UI.\n\n To learn more about generating and managing API (Application Programming Interface) keys including configuring the rate limits (which is a combination of TPM (Tokens Per Minute) and RPM (Requests Per Minute)) and monitoring API key usage, see Model API Keys.\n\n- Voyage AI.\n\n To learn more about managing the API (Application Programming Interface) keys created from Voyage AI, see API Key.\n\nAfter creating the keys, you must specify the keys you want to use for automated embedding when configuring `mongot` during deployment with MongoDB Community Edition. MongoDB Vector Search uses the Voyage AI API (Application Programming Interface) key that you provided during deployment of `mongot` to automatically generate embeddings for your data at index- and for your query text at query-time.\n\n\n\n"} -{"chunk_id": "69fc3180a8c6c8a96605288c-1", "page_id": "69fc3180a8c6c8a96605288c", "source_name": "vector-search", "product_name": "Atlas Vector Search", "url": "https://mongodb.com/docs/vector-search/crud-embeddings/automated-embedding", "title": "Automated Embedding Overview", "text": "## Embeddings Storage\n\nAutomated embedding indexes generate vector embeddings asynchronously and persist to your MongoDB cluster on a separate reserve database. Each Automated Embedding index has exactly one corresponding generated embeddings collection. The generated embeddings collection is stored in a dedicated internal database on the same cluster.\n\nTo learn more, see Generated Embeddings Collection.\n\n## Available Models\n\nMongoDB Vector Search integrates with Voyage AI's state-of-the-art embedding models, each optimized for specific use-case:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nEmbedding Model\n\n\nDescription\n\n\nPrice Per 1M Tokens\n\n
\n`voyage-4-lite`\n\n\nOptimized for high-volume, cost-sensitive applications.\n\n\n$0.02\n\n
\n`voyage-4`\n\n\n(**Recommended**) Balanced performance for general text search.\n\n\n$0.06\n\n
\n`voyage-4-large`\n\n\nMaximum accuracy for complex semantic relationships.\n\n\n$0.12\n\n
\n`voyage-code-4`\n\n\n(**Recommended for code**) Specialized for code search and technical documentation.\n\n\n$0.12\n\n
\n`voyage-code-3`\n\n\nLegacy model specialized for code search and technical documentation. Use `voyage-code-4` instead.\n\n\n$0.18\n\n
`voyage-code-4` requires an Atlas deployment. On self-managed deployments, use `voyage-code-3` for code search and technical documentation.\n\nTo learn more, see Models for Automated Embedding.\n\n## Key Concepts\n\nEmbedding models are algorithms that convert data into vector embeddings that capture your data's semantic, or underlying, meaning. These vectors enable vector search.\n\nTo learn more about the embedding models for Automated Embedding, see Available Models.\n\nA vector embedding is an array of numbers, with each dimension representing a different feature or attribute of your data. Vectors can be used to represent any type of data, from text, images, and video to unstructured data. You create vector embeddings by passing your data through an embedding model, and you can store these embeddings in a database that supports vector embeddings like MongoDB.\n\nTo learn more about the embeddings storage for Automated Embedding, see Generated Embeddings Collection.\n\nIn the context of embedding models and LLMs, tokens are the fundamental units of text, such as words, subwords, or characters that the model processes to create embeddings or generate text. Tokens are how you are billed for usage of embedding models and LLMs.\n\nTo learn more about tokens for Automated Embedding, see Manage Billing for Automated Embedding.\n\nRate limits are restrictions imposed by API providers on the number of requests a user can make within a specific time frame, often measured in tokens per minute (TPM) or requests per minute (RPM). These limits ensure fair usage, prevent abuse, and maintain the stability and performance of the service for all users.\n\nTo learn more about rate limits for Automated Embedding, see Rate Limits.\n\nQuantization reduces the precision of vector embeddings to decrease memory and storage usage, with trade-offs in search accuracy. For Automated Embedding, MongoDB Vector Search supports the following quantization types:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nQuantization Type\n\n\nDescription\n\n
\n`float`\n\n\nStores the vector embeddings as 32-bit float values.\n\n
\n`scalar`\n\n\nReduces each vector dimension from 32-bit float to 8-bit integer.\n\n
\n`binary`\n\n\nReduces each vector dimension to a single bit and rescores the top results.\n\n
\n`binaryNoRescore`\n\n\nReduces each vector dimension to a single bit without rescoring.\n\n
To learn more about the quantization for Automated Embedding, see About Quantization.\n\nThe number of dimensions specifies the length of the embedding vector for each document (how many numbers are in the array). Higher dimensions capture more semantic detail and generally improve retrieval accuracy, but increase storage and compute costs (index size, RAM usage, and sometimes latency).\n\nTo learn more, see `numCandidates` Selection.\n\nThe similarity function is used to measure the similarity between two vectors or the closeness of a query vector to the vectors in the index. MongoDB Vector Search supports the following similarity functions:\n\n- `cosine` - measures similarity based on the angle between vectors. We recommend this similarity function for unnormalized vectors like `scalar` quantization.\n\n- `dotProduct` - measures similarity like `cosine`, but takes into account the magnitude of the vector. We recommend this similarity function for normalized vectors like float (full fidelity) quantization.\n\n- `euclidean` - measures the distance between ends of vectors. We recommend this similarity function for `binary` or `binaryNoRescore` quantization, where vectors are compressed and distance in Hamming or Euclidean space is the right signal.\n\nTo learn more about the similarity functions for Automated Embedding, see About the Similarity Functions."} -{"chunk_id": "69fc3180a8c6c8a966052890-0", "page_id": "69fc3180a8c6c8a966052890", "source_name": "vector-search", "product_name": "Atlas Vector Search", "url": "https://mongodb.com/docs/vector-search/crud-embeddings/automated-embedding/billing", "title": "Manage Billing for Automated Embedding", "text": "# Manage Billing for Automated Embedding\n\n## Overview\n\nYou can manage payments and billing for Automated Embedding through the billing and payments interface in the Atlas UI. Atlas sends billing charges to the Atlas account linked to your cluster. Your billing profile for Atlas is the same as the billing profile for your Automated Embedding. To view or edit your billing profile, see Atlas Billing.\n\nAutomated Embedding uses a token-based pricing model where you are charged based on the number of tokens processed by the embedding models. To learn more about:\n\n- **Model pricing and costs**: See Models for Automated Embedding for detailed pricing per model.\n\n- **Usage tiers and rate limits**: See Rate Limits for information about free tokens, usage tiers, and rate limit tiers.\n\n- **Supported models**: See Models for Automated Embedding for the list of available Voyage AI embedding models.\n\n\n\n\n\nYou configure billing settings at the organization level, which apply to all projects within that organization. You can examine costs and billing for your model per project in the Atlas UI.\n\n\n\n\n\nIf you use the API (Application Programming Interface) key that you created using your Atlas account, you can monitor API (Application Programming Interface) key usage from the Atlas UI. To learn more, see Billing.\n\nIf you generated the API (Application Programming Interface) key directly from Voyage AI, see Pricing to learn more about the charge for requests to the embedding service endpoint.\n\n\n\n\n\n### Token-Based Pricing\n\n\n\n\n\nMongoDB uses a pay-as-you-go pricing model and charges for usage based on consumption. Usage is based on the number of tokens embedded during:\n\n- Index creation (initial sync)\n\n- Document inserts and updates (steady-state)\n\n- Queries performed\n\nPricing varies by model. For models that process text, charges apply per token in your text field and queries. To see the cost per 1,000 tokens for each supported embedding model, see Models for Automated Embedding.\n\n\n\n\n\nEmbedding model pricing is usage-based, with charges billed to the account linked to the API (Application Programming Interface) key used for access. Usage is based on the number of tokens embedded during:\n\n- Index creation (initial sync)\n\n- Document inserts and updates (steady-state)\n\n- Queries performed\n\nPricing varies by model. Pricing is based on the number of tokens in your text field and queries. To see the cost per 1,000 tokens for each supported embedding model, see Models for Automated Embedding.\n\n\n\n\n\n### Free Tokens\n\n\n\n\n\nFor each model, Atlas includes a one-time allocation of 200 million free tokens at the organization level. The organization shares free tokens across all Atlas projects and clusters within the organization. Free tokens do not refresh. To learn more about free tokens and usage tiers, see Rate Limits.\n\n\n\n\n\nFor each model, MongoDB Vector Search includes a one-time allocation of 200 million free tokens. The free tokens are shared across all clusters in the deployment. Free tokens do not refresh. To learn more about free tokens and usage tiers, see Rate Limits.\n\n\n\n\n\n### Model Pricing\n\nThe cost for each model is as follows:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nEmbedding Model\n\n\nCost per 1K Tokens\n\n\nCost per 1M Tokens\n\n
\n`voyage-4-large`\n\n\n$0.00012\n\n\n$0.12\n\n
\n`voyage-4`\n\n\n$0.00006\n\n\n$0.06\n\n
\n`voyage-4-lite`\n\n\n$0.00002\n\n\n$0.02\n\n
\n`voyage-code-4`\n\n\n$0.00012\n\n\n$0.12\n\n
\n`voyage-code-3`\n\n\n$0.00018\n\n\n$0.18\n\n
\n\n## Manage Billing\n\n\n\n\n\n**Required Access**\n\n- To view billing information, you must have `Organization Billing Viewer` access or higher.\n\n- To configure billing settings, such as the payment method and billing profile, you must have `Organization Owner` or `Organization Billing Admin` access.\n\n\n\n\n\n\n\n\n\n### Procedure\n\nTo access billing:\n\n#### Log in to Atlas.\n\n#### In Atlas, go to the Billing page for your organization.\n\n- If it's not already displayed, select your desired organization from the Organizations menu in the navigation bar.\n\n- In the sidebar, click Overview under the Billing header.\n\nThe Billing page displays.\n\nThe Billing > Overview page includes the following:\n\n- The Pending Invoice, which includes Net Month-to-Date Amount, showing the total amount due for your usage so far this month. It also shows the Month-to-Date Usage, including whether usage went up or down compared to this time last month, the usage for This Time Last Month, the Billing Period, and the Invoice Date. Click View Pending Invoice to view details.\n\n- The Last Invoice, which shows the Amount Due, Total Usage, Billing Period, and Invoice Date. Click View Invoice to view details.\n\n- The Usage chart, which displays your organization's Automated Embedding usage over the past one year in the By Service tab. You can hover over the point in the chart to see the usage for that month.\n\n To understand how your usage translates to costs, use the Cost Explorer in the Atlas UI and filter by Automated Embedding. MongoDB derives costs from metering data and updates them every 24 hours.\n\n### Payment Method\n\nTo pay for Automated Embedding, use your configured payment method. MongoDB accepts the following payment methods through the Atlas console:\n\n- Credit card\n\n- PayPal\n\nTo set your payment method for Automated Embedding in Atlas, see Atlas Payment Methods.\n\nThrough MongoDB Sales, you can pay using:\n\n- A currency other than USD\n\n- A method other than a credit card or PayPal\n\nTo confirm your credit card information, Atlas charges $1.00 when you first connect a credit card to your account. After Atlas confirms your information, it refunds the $1.00 charge. If you encounter any issues with connecting a credit card to your account, contact your card provider or banking institution. Verify whether they declined the initial charge, which would prevent Atlas from confirming your information.\n\n## Manage Invoices\n\nFor each of your invoices, including your current invoice, you can:\n\n- View the payment amount due, the total cost of your usage for the billing period, and your billing information.\n\n- Export the invoice details to PDF or CSV.\n\n- Explore invoice cost visualization charts that show total usage costs by service, such as Automated Embedding.\n\n- Review usage summaries by project and by service, such as Automated Embedding.\n\n- Examine payment and usage details that explain usage and paid and pending charges for Automated Embedding.\n\nYour invoice shows usage broken down by embedding model (such as `voyage-4`, `voyage-4-lite`, `voyage-4-large`, `voyage-code-4`, and `voyage-code-3`), including the number of tokens processed and the cost per model. To learn more about supported models and their pricing, see Models for Automated Embedding.\n\nTo learn more about invoice features, see Invoices."} -{"chunk_id": "69fc3180a8c6c8a966052890-1", "page_id": "69fc3180a8c6c8a966052890", "source_name": "vector-search", "product_name": "Atlas Vector Search", "url": "https://mongodb.com/docs/vector-search/crud-embeddings/automated-embedding/billing", "title": "Manage Billing for Automated Embedding", "text": "### View Invoices\n\nTo view the most recent and pending charges for Automated Embedding in an organization:\n\n#### Log in to Atlas.\n\n#### Go to the Billing page for your organization.\n\n- If it's not already displayed, select your desired organization from the Organizations menu in the navigation bar.\n\n- In the sidebar, click Invoices under the Billing header.\n\n The Invoices page displays. On the Invoices page in Atlas, you can view your billing invoices for Automated Embedding.\n\n The Invoice page displays the following columns:\n\n - Payment Status: Shows `PENDING` or `SUCCESSFUL`.\n\n - Invoice Date: Shows the date when Atlas generates the invoice.\n\n - Invoice Period: Shows the billing period for the invoice. For example, you might see a usage summary for the billing period of `12/01/2025-01/01/2026`.\n\n - Total Cost: Shows your total monthly charges in your selected currency. The total monthly charges include the billed amount and any applicable taxes, but don't include any payments you made.\n\n For example, the Total Cost column might show `$29.98 (month-to-date)`. This indicates that your total charges for the month so far are $29.98, including taxes, but doesn't reflect any payments you might have made.\n\n - Download: Provides an icon for downloading the invoice. You can download your Usage Summary in PDF or CSV format. The Usage Summary shows a detailed breakdown of daily usage activity for Automated Embedding.\n\nYou can also access billing information directly from the Search & Vector Search page by clicking the View Invoice button.\n\n## Review the Costs\n\nYou can use the Cost Explorer to understand your Automated Embedding costs. The Billing Cost Explorer helps you understand your organization's billing data on a month-to-month basis. You can view monthly billing data in chart and table form. To view the specific costs for Automated Embedding, see the invoice for the month.\n\nCosts are based on the number of tokens processed by each embedding model. For detailed pricing information per model, see Models for Automated Embedding.\n\n### Procedure\n\n#### Log in to Atlas.\n\n#### Go to the Billing page for your organization.\n\n- If it's not already displayed, select your desired organization from the Organizations menu in the navigation bar.\n\n- In the sidebar, click Cost Explorer under the Billing header.\n\n The Cost Explorer page displays. The cost explorer provides a visual representation of your billing data, including Automated Embedding costs.\n\n To learn more, see Billing Cost Explorer.\n\n#### Filter by Automated Embedding.\n\nTo filter by Automated Embedding, select Automated Embedding from the Service dropdown menu."} -{"chunk_id": "69eb0c75d0423fff078dfadb-0", "page_id": "69eb0c75d0423fff078dfadb", "source_name": "vector-search", "product_name": "Atlas Vector Search", "url": "https://mongodb.com/docs/vector-search/benchmark/performance-recommendations", "title": "Additional Performance Recommendations", "text": "# Additional Performance Recommendations\n\nThis page provides additional recommendations for improving the performance of your MongoDB Vector Search queries.\n\n## Ensure Sufficient Memory\n\nHierarchical Navigable Small Worlds works efficiently when vector data is held in memory. You must ensure that the data nodes have sufficient RAM to hold the vector data and indexes. We recommend deploying separate Search Nodes for workload isolation without data isolation, which enables more efficient usage of memory for vector search use cases.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nEmbedding Model\n\n\nVector Dimension\n\n\nSpace Requirement\n\n
\nVoyage AI `voyage_3_large`\n\n\n2048\n\n\n8kb (for `float`)2.14kb (for `int8`)0.334kb (for `int1`)\n\n
\nOpenAI `text-embedding-ada-002`\n\n\n1536\n\n\n6kb\n\n
\nGoogle `text-embedding-gecko`\n\n\n768\n\n\n3kb\n\n
\nCohere `embed-english-v3.0`\n\n\n1024\n\n\n4kb (for `float`)1.07kb (for `int8`)0.167kb (for `int1`)\n\n
BinData quantized vectors. To learn more, see Ingest Quantized Vectors.\n\nThe amount of CPU, memory, and disk resources that MongoDB Vector Search consumes depends on several factors, including your index size and the query criteria. It's important to monitor your environment to understand your vector search health and performance and to confirm adequate infrastructure capacity and identify any anomalies.\n\nUse the following metrics to observe and improve the performance of your MongoDB Vector Search indexes and queries:\n\n### Search System Memory\n\nMonitor the total amount of RAM used by your MongoDB Vector Search indexes. Adequate RAM is critical for MongoDB Vector Search query performance because queries going to disk are much less performant. Ensure that the entire index is able to fit in memory.\n\nEnsure that available System Memory is always greater than used System Memory. If the index is not frequently queried, not all of the index might be in memory. Therefore, leverage the System Memory metric in conjunction with the Index Size metric to optimize provisioning.\n\nIf the vector index size is over 3 GB, we recommend vector quantization, which stores only 4% of the index in memory rather than the full index.\n\n### Search Index Size\n\nMonitor the total size of all indexes on disk in bytes. This is necessary to ensure that you have accurately sized your RAM requirements.\n\nVerify the search Index Size on disk metric to see what the full index size would be if 100% of the vector is stored in memory, and ensure that it is less than the system memory available.\n\n### Search Page Faults\n\nMonitor the average rate of page faults on a process per second over a selected sample period. The Page Faults metric indicates how frequently the search query is going to disk, which indicates that the full index is not fitting into memory.\n\nThis metric must remain as close to zero as possible. If you consistently see page faults, consider scaling the cluster tier up to provision adequate RAM.\n\n### Warm Up the Filesystem Cache\n\nWhen you perform vector search without using dedicated Search Nodes, your queries initially perform random seeks on disk as you traverse the Hierarchical Navigable Small Worlds graph and the vector values are read into memory. When using Search Nodes, this cache warming typically only occurs in the event of an index rebuild, usually during scheduled maintenance windows.\n\n## Monitor for CPU Bottlenecks\n\nVector embeddings consume computational resources during indexing. ENN (Exact Nearest Neighbor) queries on large datasets consume CPU resources. As a result, indexing and querying at the same time may cause resource bottlenecks. To prevent CPU bottlenecks, avoid indexing vectors when queries are running. When performing an initial sync, ensure that your Search Node CPU usage returns close to 0%, indicating segments have been merged and flushed to disk, before issuing test queries.\n\nMonitor the Search Normalized Process CPU metric during indexing operations, as heavy indexing will show elevated CPU usage. This metric shows the CPU usage as a percentage normalized against the number of available CPU cores, which enables you to assess the resource saturation relative to your cluster's capacity. After vector embeddings have been indexed, wait for the CPU usage to return close to 0% as segment merging and flushing complete."} -{"chunk_id": "6a514deed727379c91ba2e95-0", "page_id": "6a514deed727379c91ba2e95", "source_name": "vector-search", "product_name": "Atlas Vector Search", "url": "https://mongodb.com/docs/vector-search/benchmark/benchmark-tests", "title": "Benchmark for MongoDB Vector Search", "text": "# Benchmark for MongoDB Vector Search\n\nThis section contains the following pages, which provide information about our MongoDB Vector Search performance benchmark and how you can use it to test, evaluate, and improve your own vector search performance:\n\n- Benchmark Overview\n\n- Benchmark Results\n\n- Additional Recommendations\n\nTo view the full chart, see the Claude artifact.\n\n## How to Use This Benchmark\n\nThe primary goal for these pages is to significantly reduce friction for your first vector test at scale (>10M vectors) when evaluating performance for MongoDB Vector Search.\n\nThese pages provide a set of initial configurations (embedding model dimensionality, quantization regime, `numCandidates` selection, filtering criteria, Search Node configuration) that you can use to run tests confidently. You might need to modify your configuration based on the dataset and query patterns relevant to your use case, as this is only meant to be a starting point.\n\n## Reading Recommendations\n\nWhen reading these pages, we recommend that you focus on the primary concern that is most relevant to your use case. We provide guidance for the following primary concerns: **Recall**, **Cost**, and **Latency/Throughput**.\n\nUse the guidance that is most appropriate for your use case:\n\n\n\n\n\nRead these sections in the following order:\n\n1. The following sections in the Benchmark Overview:\n\n - Quantization\n\n - Dimensionality\n\n - Search Node Configuration\n\n2. The following sections in the Benchmark Results:\n\n - Summary of Results\n\n - Multidimensional Benchmark\n\n - Larger Benchmark\n\n - Recall and Latency Analysis\n\n - Filtering\n\n3. Additional Performance Recommendations\n\n\n\n\n\nRead these sections in the following order:\n\n1. The following sections in the Benchmark Overview:\n\n - Quantization\n\n - Dimensionality\n\n - Search Node Configuration\n\n2. The following sections in the Benchmark Results:\n\n - Summary of Results\n\n - Multidimensional Benchmark\n\n - Larger Benchmark\n\n - Recall and Latency Analysis\n\n - Concurrency\n\n3. Additional Performance Recommendations\n\n\n\n\n\nRead these sections in the following order:\n\n1. Complete Benchmark Overview\n\n2. Complete Benchmark Results\n\n3. Additional Performance Recommendations\n\n\n\n\n\n## Changelog\n\n\n\n\n\n\n\n\n\n\n
\nDate\n\n\nDescription\n\n
\n2025-07-21\n\n\nRelease of benchmark guide and results demonstrating how MongoDB Vector Search scales on a 5.5M Multidimensional and 15.3M 2048d Amazon Dataset with Voyage AI's `voyage-3-large` embeddings under various conditions.\n\n
"} -{"chunk_id": "69eb0c75d0423fff078dfadc-0", "page_id": "69eb0c75d0423fff078dfadc", "source_name": "vector-search", "product_name": "Atlas Vector Search", "url": "https://mongodb.com/docs/vector-search/deployment/compatibility-limitations", "title": "MongoDB Vector Search Compatibility & Limitations", "text": "# MongoDB Vector Search Compatibility & Limitations\n\nThis page describes the compatibility and limitations of MongoDB Vector Search features on Atlas. For details on MongoDB Vector Search compatibility with self-managed deployments, see the Deployment Options documentation.\n\n## Feature Compatibility\n\n### MongoDB Version Compatibility\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nMongoDB Vector Search Feature\n\n\nMongoDB Version for Feature\n\n
\nCreate indexes on Views\n\n\n8.0+\n\n
\nQuery Views directly with `$vectorSearch`\n\n\n8.1+\n\n
\nViews with sharded sub-pipelines via `$lookup`/`$unionWith`\n\n\n8.2+\n\n
\n`$rankFusion` on Views\n\n\n8.2+\n\n
\nIngest Pre-Quantized BinData Vectors\n\n\n7.0.2+\n\n
\nNative Reranking\n\n\n8.3+\n\n
\n\n## Supported Clients\n\nTo learn about supported clients, see Supported Clients.\n\n## Index Limitations\n\nA high index count generates significant load on the base cluster and might disrupt your workload. The number of indexes your cluster can support depends on your cluster tier and workload. Smaller cluster tiers like `M10` can experience performance degradation or out-of-memory errors as index count increases. Start with a small number of indexes and monitor your cluster's resource usage as you scale.\n\nYou cannot create more than:\n\n- 3 indexes (regardless of the type, `search` or `vector`) on Free clusters.\n\n- 10 indexes on Flex clusters.\n\nTo learn more about index limitations, see:\n\n- Prerequisites\n\n- How to Index Fields for Vector Search\n\n### Field Type Limitations\n\nMongoDB Vector Search indexes support vector embeddings that are less than or equal to 8192 dimensions in length. To learn more about indexing field types, see:\n\n- How to Index Fields for Vector Search\n\n- About Quantization\n\n### Other Limitations\n\nIf you're using a clustered collection and have the `notablescan` parameter set to `true`, your MongoDB Vector Search indexes may not finish building. To resolve this issue, you must set the `notablescan` parameter to `false` or check your log for index status transitions.\n\nBinary quantization is currently not supported for nested vector indexes. Use `scalar` quantization instead or don't specify any quantization type.\n\n## Query Limitations\n\n### Option Compatibility and Limitations\n\nTo learn about query option compatibility and limitations, see:\n\n- Run Vector Search ANN and ENN Queries\n\n- MongoDB Vector Search Filtering\n\n- $vectorSearch Options"} -{"chunk_id": "69eb0c75d0423fff078dfae4-0", "page_id": "69eb0c75d0423fff078dfae4", "source_name": "vector-search", "product_name": "Atlas Vector Search", "url": "https://mongodb.com/docs/vector-search/about/ai-agents", "title": "Build AI Agents with MongoDB", "text": "# Build AI Agents with MongoDB\n\nMongoDB provides several features for building AI agents. As both a vector and document database, MongoDB supports various search methods for agentic RAG, as well as storing agent interactions in the same database for short and long-term agent memory.\n\n## What is an AI agent?\n\nIn the context of generative AI, an AI agent typically refers to a system that can complete a task autonomously or semi-autonomously by combining AI models such as LLM (Large Language Model)s with a set of pre-defined tools.\n\nAI agents can use tools to gather context, interact with external systems, and perform actions. They can define their own execution flow (planning) and remember previous interactions to inform their responses (memory). Therefore, AI agents are best suited for complex tasks that require reasoning, planning, and decision-making.\n\n### Architecture\n\nAn AI agent typically includes a combination of the following components:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n**Perception**\n\n\nYour input for the agent. Text inputs are the most common perception mechanism for AI agents, but inputs can also be audio, images, or multimodal data.\n\n
\n**Planning**\n\n\nHow the agent determines what to do next. This component typically includes LLMs and prompts, using feedback loops and various prompt engineering techniques such as chain-of-thought and reAct, to help the LLM reason through complex tasks.\n\nAI agents can consist of a single LLM as the decision maker, LLM with multiple prompts, multiple LLMs working together, or any combination of these approaches.\n\n
\n**Tools**\n\n\nHow the agent gathers context for a task. Tools allow agents to interact with external systems and perform actions such as vector search, web search, or calling APIs from other services.\n\n
\n**Memory**\n\n\nA system for storing agent interactions, so the agent can learn from past experiences to inform its responses. Memory can be *short-term* (for the current session) or *long-term* (persisted across sessions).\n\n
AI agents vary in design pattern, function, and complexity. To learn about other agent architectures, including multi-agent systems, see Agentic Design Patterns.\n\n## Build AI Agents with MongoDB\n\nMongoDB supports the following components for building AI agents:\n\n- Tools: Leverage MongoDB search features as tools for your agent to retrieve relevant information and implement agentic RAG.\n\n- Memory: Store agent interactions in MongoDB collections for both short and long-term memory.\n\n### Agent Tools\n\nIn the context of AI agents, a tool is anything that can be programmatically defined and invoked by the agent. Tools extend the agent's capabilities beyond generating text, allowing it to interact with external systems, retrieve information, and take actions. Tools are typically defined with a specific interface that includes:\n\n- A name and description that help the agent understand when to use the tool.\n\n- Required parameters and their expected formats.\n\n- A function that performs the actual operation when invoked.\n\nThe agent uses its reasoning capabilities to determine which tool to use, when to use it, and what parameters to provide, based on the user's input and the task at hand.\n\nIn addition to standard MongoDB queries, MongoDB provides several search capabilities that you can implement as tools for your agent.\n\n- **MongoDB Vector Search**: Perform vector search to retrieve relevant context based on semantic meaning and similarity. To learn more, see MongoDB Vector Search Overview.\n\n- **MongoDB Search**: Perform full-text search to retrieve relevant context based on keyword matching and relevance scoring. To learn more, see MongoDB Search Overview.\n\n- **Hybrid Search**: Combine MongoDB Vector Search with MongoDB Search to leverage the strengths of both approaches. To learn more, see How to Perform Hybrid Search.\n\nYou can define tools manually or by using frameworks such as LangChain and LangGraph, which provide built-in abstractions for tool creation and calling.\n\n#### Tool definition\n\nTools are defined as functions that the agent can call to perform specific tasks. For example, the following syntax illustrates how you might define a tool that runs a vector search query:\n\n```python\ndef vector_search_tool(query: str) -> str:\n pipeline = [\n {\n \"$vectorSearch\": {\n # Vector search query pipeline...\n }\n }\n ]\n results = collection.aggregate(pipeline)\n\n array_of_results = []\n for doc in results:\n array_of_results.append(doc)\n return array_of_results\n```\n\n```javascript\nasync function vectorSearchTool(query) {\n const pipeline = [\n {\n $vectorSearch: {\n // Vector search query pipeline...\n }\n }\n ];\n\n const results = await collection.aggregate(pipeline).toArray();\n return results;\n}\n```\n\n#### Tool call\n\nTool calls are what the agent uses to execute the tools. You can define how to process tool calls in your agent, or use a framework to handle this for you. These are typically defined as JSON objects that include the tool name and other arguments to pass to the tool, so the agent can call the tool with the appropriate parameters. For example, the following syntax illustrates how an agent might call the vector search tool:\n\n```none\n{\n \"tool\": \"vector_search_tool\",\n \"args\": { \"query\": \"What is MongoDB?\" },\n \"id\": \"call_H5TttXb423JfoulF1qVfPN3m\"\n}\n```\n\n#### Agentic RAG\n\nBy using MongoDB as a vector database, you can create retrieval tools that implement agentic RAG, which is an advanced form of RAG that allows you to dynamically orchestrate the retrieval and generation process through an AI agent.\n\nThis approach enables more complex workflows and user interactions. For example, you can configure your AI agent to determine the optimal retrieval tool based on the task, such as using MongoDB Vector Search for semantic search and MongoDB Search for full-text search. You can also define different retrieval tools for different collections to further customize the agent's retrieval capabilities."} -{"chunk_id": "69eb0c75d0423fff078dfae4-1", "page_id": "69eb0c75d0423fff078dfae4", "source_name": "vector-search", "product_name": "Atlas Vector Search", "url": "https://mongodb.com/docs/vector-search/about/ai-agents", "title": "Build AI Agents with MongoDB", "text": "### Agent Memory\n\nMemory for agents involves storing information about previous interactions, so that the agent can learn from past experiences and provide more relevant and personalized responses. This is particularly important for tasks that require context, such as conversational agents, where the agent needs to remember previous turns in the conversation to provide coherent and contextually relevant responses. There are two primary types of agent memory:\n\n- **Short-term Memory**: Stores information for the current session, like recent conversation turns and active task context.\n\n- **Long-term Memory**: Persists information across sessions, which can include past conversations and personalized preferences over time.\n\nSince MongoDB is also a document database, you can implement memory for agents by storing its interactions in a MongoDB collection. The agent can then query or update this collection as needed. There are several ways to implement agent memory with MongoDB:\n\n- For short-term memory, you might include a `session_id` field to identify a specific session when storing interactions, and then query for interactions with the same ID to pass to the agent as context.\n\n- For long-term memory, you might process several interactions with an LLM to extract relevant information such as user preferences or important context, and then store this information in a separate collection that the agent can query when needed.\n\n- To build robust memory management systems that enable more efficient and complex retrieval of conversation histories, leverage MongoDB Search or MongoDB Vector Search to store, index, and query important interactions across sessions.\n\n\n\n\n\nA document in a collection that stores short-term memory might resemble the following:\n\n```none\n{\n \"session_id\": \"123\",\n \"user_id\": \"jane_doe\",\n \"interactions\":\n [\n {\n \"role\": \"user\",\n \"content\": \"What is MongoDB?\",\n \"timestamp\": \"2025-01-01T12:00:00Z\"\n },\n {\n \"role\": \"assistant\",\n \"content\": \"MongoDB is the world's leading modern database.\",\n \"timestamp\": \"2025-01-01T12:00:05Z\"\n }\n ]\n}\n```\n\n\n\n\n\nA document in a collection that stores long-term memory might resemble the following:\n\n```none\n{\n \"user_id\": \"jane_doe\",\n \"last_updated\": \"2025-05-22T09:15:00Z\",\n \"preferences\": {\n \"conversation_tone\": \"casual\",\n \"custom_instructions\": [\n \"I prefer concise answers.\"\n ],\n },\n \"facts\": [\n {\n \"interests\": [\"AI\", \"MongoDB\"],\n }\n ]\n}\n```\n\n\n\n\n\nThe following frameworks also provide direct abstractions for agent memory with MongoDB:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nFramework\n\n\nFeatures\n\n
\nLangChain\n\n\n- `MongoDBChatMessageHistory`: chat message history component\n\n- `MongoDBAtlasSemanticCache`: semantic cache component\n\nTo learn more, see the tutorial.\n\n
\nLangGraph\n\n\n- `MongoDBSaver`: short-term memory checkpointer that can be used for persistence\n\n- `MongoDBStore`: long-term document store for storing memories in MongoDB (available in Python integration only)\n\nTo learn more, see LangGraph and LangGraph.js.\n\n
\n\n## Get Started\n\nThe following tutorial demonstrates how to build an AI agent using MongoDB for agentic RAG and memory, without an agent framework.\n\nWork with a runnable version of this tutorial as a Python notebook.\n\n### Prerequisites\n\nTo complete this tutorial, you must have the following:\n\n- One of the following MongoDB cluster types:\n\n - An Atlas cluster running MongoDB version 6.0.11, 7.0.2, or later. Ensure that your IP address (Internet Protocol address) is included in your Atlas project's access list.\n\n - A local Atlas deployment created using Python and Docker. Install `atlas-local-lib-py` (`pip install atlas-local-lib-py`) to programmatically create and manage local deployments. To learn more, see the atlas-local-lib-py repository.\n\n - A MongoDB Community or Enterprise cluster with Search and Vector Search installed.\n\n- A Voyage AI API key.\n\n- An OpenAI API key.\n\nThis tutorial uses models from Voyage AI and OpenAI, but you can modify the code to use your models of choice."} -{"chunk_id": "69eb0c75d0423fff078dfae4-2", "page_id": "69eb0c75d0423fff078dfae4", "source_name": "vector-search", "product_name": "Atlas Vector Search", "url": "https://mongodb.com/docs/vector-search/about/ai-agents", "title": "Build AI Agents with MongoDB", "text": "### Procedure\n\nThis AI agent can be used to answer questions about a custom data source and perform calculations. It can also remember previous interactions to inform its responses. It uses the following components:\n\n- **Perception**: Text inputs.\n\n- **Planning**: An LLM and various prompts to reason through the task.\n\n- **Tools**: A vector search tool and calculator tool.\n\n- **Memory**: Stores the interactions in a MongoDB collection.\n\n#### Set up the environment.\n\n- Initialize the project and install dependencies.\n\n Create a new project directory, then install the required dependencies:\n\n ```none\n mkdir mongodb-ai-agent\n cd mongodb-ai-agent\n pip install --quiet --upgrade pymongo voyageai openai langchain langchain-mongodb\n langchain-community langchain-text-splitters python-dotenv\n ```\n\n Your project will use the following structure:\n\n ```text\n mongodb-ai-agent\n \u251c\u2500\u2500 .env\n \u251c\u2500\u2500 config.py\n \u251c\u2500\u2500 ingest_data.py\n \u251c\u2500\u2500 tools.py\n \u251c\u2500\u2500 memory.py\n \u251c\u2500\u2500 planning.py\n \u251c\u2500\u2500 main.py\n ```\n\n- Configure the environment.\n\n Create an environment file named `.env` in your project. This file will contain your API keys for the agent, the MongoDB connection string, and MongoDB database and collection names.\n\n Replace the placeholder values with your MongoDB connection string and your Voyage AI and OpenAI API keys.\n\n ```none\n MONGODB_URI=\"\"\n VOYAGE_API_KEY=\"\"\n OPENAI_API_KEY= \"\"\n ```\n\n Replace `` with the connection string for your Atlas cluster or local Atlas deployment.\n\n \n\n \n\n Your connection string should use the following format:\n\n ```\n mongodb+srv://:@..mongodb.net\n ```\n\n IMPORTANT: Ensure that your connection string includes your database user's credentials. To learn more about finding your connection string, see Connect to a Cluster via Client Libraries.\n\n \n\n \n\n Your connection string should use the following format:\n\n ```\n mongodb://localhost:/?directConnection=true\n ```\n\n To learn more, see Connection Strings.\n\n \n\n \n\n#### Configure the agent.\n\nCreate a file named `config.py` in your project. This file will read in your environment variables and connect the application to services like the MongoDB database and OpenAI.\n\n```python\nfrom pymongo import MongoClient\nfrom openai import OpenAI\nimport voyageai\nfrom dotenv import load_dotenv\nimport os\n\n# Load environment variables from .env file\nload_dotenv()\n\n# Environment variables (private)\nMONGODB_URI = os.getenv(\"MONGODB_URI\")\nVOYAGE_API_KEY = os.getenv(\"VOYAGE_API_KEY\")\nOPENAI_API_KEY = os.getenv(\"OPENAI_API_KEY\")\n\n# MongoDB cluster configuration\nmongo_client = MongoClient(MONGODB_URI)\nagent_db = mongo_client[\"ai_agent_db\"]\nvector_collection = agent_db[\"embeddings\"]\nmemory_collection = agent_db[\"chat_history\"]\n\n# Model configuration\nvoyage_client = voyageai.Client(api_key=VOYAGE_API_KEY)\nopenai_client = OpenAI(api_key=OPENAI_API_KEY)\nVOYAGE_MODEL = \"voyage-4-large\"\nOPENAI_MODEL = \"gpt-4o\"\n\n```\n\n#### Use MongoDB as a vector database.\n\nCreate a file named `ingest_data.py` in your project. This script ingests a sample PDF that contains a recent MongoDB earnings report into a collection in MongoDB by using the `voyage-4-large` embedding model. This code also includes a function to create a vector search index on your data if it doesn't already exist.\n\nTo learn more, see Ingestion.\n\n```python\nfrom config import vector_collection, voyage_client, VOYAGE_MODEL\nfrom pymongo.operations import SearchIndexModel\nfrom langchain_community.document_loaders import PyPDFLoader\nfrom langchain_text_splitters import RecursiveCharacterTextSplitter\nimport time\n\n# Define a function to generate embeddings\ndef get_embedding(data, input_type=\"document\"):\n embeddings = voyage_client.embed(\n data, model=VOYAGE_MODEL, input_type=input_type\n ).embeddings\n return embeddings[0]\n\n# --- Ingest embeddings into MongoDB ---\ndef ingest_data():\n # Chunk PDF data\n loader = PyPDFLoader(\"https://investors.mongodb.com/node/13176/pdf\")\n data = loader.load()\n text_splitter = RecursiveCharacterTextSplitter(chunk_size=400, chunk_overlap=20)\n documents = text_splitter.split_documents(data)\n print(f\"Successfully split PDF into {len(documents)} chunks.\")\n\n # Ingest chunked documents into collection\n print(\"Generating embeddings and ingesting documents...\")\n docs_to_insert = []\n for i, doc in enumerate(documents):\n embedding = get_embedding(doc.page_content)\n if embedding:\n docs_to_insert.append({\"text\": doc.page_content, \"embedding\": embedding})\n\n if docs_to_insert:\n result = vector_collection.insert_many(docs_to_insert)\n print(f\"Inserted {len(result.inserted_ids)} documents into the collection.\")\n else:\n print(\"No documents were inserted. Check embedding generation process.\")\n\n # --- Create the vector search index ---\n index_name = \"vector_index\"\n\n search_index_model = SearchIndexModel(\n definition={\n \"fields\": [\n {\n \"type\": \"vector\",\n \"numDimensions\": 1024,\n \"path\": \"embedding\",\n \"similarity\": \"cosine\",\n }\n ]\n },\n name=index_name,\n type=\"vectorSearch\",\n )\n try:\n vector_collection.create_search_index(model=search_index_model)\n print(f\"Search index '{index_name}' creation initiated.\")\n except Exception as e:\n print(f\"Error creating search index: {e}\")\n return\n\n # Wait for initial sync to complete\n print(\"Polling to check if the index is ready. This may take up to a minute.\")\n predicate = lambda index: index.get(\"queryable\") is True\n\n max_retries = 24 # ~2 minutes at 5s intervals\n for _ in range(max_retries):\n indices = list(vector_collection.list_search_indexes(index_name))\n if len(indices) and predicate(indices[0]):\n break\n time.sleep(5)\n else:\n raise TimeoutError(f\"Index '{index_name}' did not become queryable in time.\")\n print(index_name + \" is ready for querying.\")\n\n```\n\n#### Define tools for the agent.\n\nCreate a file named `tools.py` in your project. This file defines the tools that the agent can use to answer questions. In this example, you define the following tools:\n\n- `vector_search_tool`: Runs a vector search query to retrieve relevant documents from your collection.\n\n- `calculator_tool`: Uses the `eval()` function for basic math operations.\n\n```python\nfrom config import vector_collection\nfrom ingest_data import get_embedding\n\n# Define a vector search tool\ndef vector_search_tool(user_input: str) -> list:\n query_embedding = get_embedding(user_input, input_type=\"query\")\n pipeline = [\n {\n \"$vectorSearch\": {\n \"index\": \"vector_index\",\n \"queryVector\": query_embedding,\n \"path\": \"embedding\",\n \"exact\": True,\n \"limit\": 5,\n }\n },\n {\"$project\": {\"_id\": 0, \"text\": 1}},\n ]\n results = vector_collection.aggregate(pipeline)\n\n array_of_results = []\n for doc in results:\n array_of_results.append(doc)\n return array_of_results\n\n# Define a simple calculator tool\ndef calculator_tool(user_input: str) -> str:\n try:\n result = eval(user_input)\n return str(result)\n except Exception as e:\n return f\"Error: {str(e)}\"\n\n```\n\n#### Add memory to the agent.\n\nCreate a file named `memory.py` in your project. This file defines the system that the agent uses to store its interactions. In this example, you implement short-term memory by defining the following functions:\n\n- `store_chat_message`: to store information about an interaction in a MongoDB collection."} -{"chunk_id": "69eb0c75d0423fff078dfae4-3", "page_id": "69eb0c75d0423fff078dfae4", "source_name": "vector-search", "product_name": "Atlas Vector Search", "url": "https://mongodb.com/docs/vector-search/about/ai-agents", "title": "Build AI Agents with MongoDB", "text": "- `retrieve_session_history`: to get all interactions for a specific session by using the `session_id` field.\n\n```python\nfrom config import memory_collection\nfrom datetime import datetime\nfrom typing import List\n\ndef store_chat_message(session_id: str, role: str, content: str) -> None:\n message = {\n \"session_id\": session_id, # Unique identifier for the chat session\n \"role\": role, # Role of the sender (user or system)\n \"content\": content, # Content of the message\n \"timestamp\": datetime.now(), # Timestamp of when the message was sent\n }\n memory_collection.insert_one(message)\n\ndef retrieve_session_history(session_id: str) -> List:\n # Query the collection for messages with a specific \"session_id\" in ascending order\n cursor = memory_collection.find({\"session_id\": session_id}).sort(\"timestamp\", 1)\n\n # Iterate through the cursor and return a JSON object with the message role and content\n if cursor:\n messages = [{\"role\": msg[\"role\"], \"content\": msg[\"content\"]} for msg in cursor]\n else:\n messages = []\n return messages\n\n```\n\n#### Define the agent's planning.\n\nCreate a file named `planning.py` in your project. This file will include various prompts and LLM calls to determine the agent's execution flow. In this example, you define the following functions:\n\n- `tool_selector`: Determines how the LLM selects the appropriate tool for a task.\n\n- `generate_response`: Orchestrates the agent's execution flow by using tools, calling the LLM, and processing the results.\n\n- `get_llm_response`: Helper function for LLM response generation.\n\n```python\nfrom config import openai_client, OPENAI_MODEL\nfrom tools import vector_search_tool, calculator_tool\nfrom memory import (\n store_chat_message,\n retrieve_session_history,\n)\n\n# Define a tool selector function that decides which tool to use based on user input and message history\ndef tool_selector(user_input, session_history=None):\n messages = [\n {\n \"role\": \"system\",\n \"content\": (\n \"Select the appropriate tool from the options below. Consider the full context of the conversation before deciding.\\n\\n\"\n \"Tools available:\\n\"\n \"- vector_search_tool: Retrieve specific context about recent MongoDB earnings and announcements\\n\"\n \"- calculator_tool: For mathematical operations\\n\"\n \"- none: For general questions without additional context\\n\"\n \"Process for making your decision:\\n\"\n \"1. Analyze if the current question relates to or follows up on a previous vector search query\\n\"\n \"2. For follow-up questions, incorporate context from previous exchanges to create a comprehensive search query\\n\"\n \"3. Only use calculator_tool for explicit mathematical operations\\n\"\n \"4. Default to none only when certain the other tools won't help\\n\\n\"\n \"When continuing a conversation:\\n\"\n \"- Identify the specific topic being discussed\\n\"\n \"- Include relevant details from previous exchanges\\n\"\n \"- Formulate a query that stands alone but preserves conversation context\\n\\n\"\n 'Return a JSON object only: {\"tool\": \"selected_tool\", \"input\": \"your_query\"}'\n ),\n }\n ]\n if session_history:\n messages.extend(session_history)\n messages.append({\"role\": \"user\", \"content\": user_input})\n\n response = (\n openai_client.chat.completions.create(model=OPENAI_MODEL, messages=messages)\n .choices[0]\n .message.content\n )\n try:\n tool_call = eval(response)\n return tool_call.get(\"tool\"), tool_call.get(\"input\")\n except:\n return \"none\", user_input\n\n# Define the agent workflow\ndef generate_response(session_id: str, user_input: str) -> str:\n\n # Store the user input in the chat history collection\n store_chat_message(session_id, \"user\", user_input)\n\n # Initialize a list of inputs to pass to the LLM\n llm_input = []\n\n # Retrieve the session history for the current session and add it to the LLM input\n session_history = retrieve_session_history(session_id)\n llm_input.extend(session_history)\n\n # Append the user message in the correct format\n user_message = {\"role\": \"user\", \"content\": user_input}\n llm_input.append(user_message)\n\n # Call the tool_selector function to determine which tool to use\n tool, tool_input = tool_selector(user_input, session_history)\n print(\"Tool selected: \", tool)\n\n # Process based on selected tool\n if tool == \"vector_search_tool\":\n context = vector_search_tool(tool_input)\n # Construct the system prompt using the retrieved context and append it to the LLM input\n system_message_content = (\n f\"Answer the user's question based on the retrieved context and conversation history.\\n\"\n f\"1. First, understand what specific information the user is requesting\\n\"\n f\"2. Then, locate the most relevant details in the context provided\\n\"\n f\"3. Finally, provide a clear, accurate response that directly addresses the question\\n\\n\"\n f\"If the current question builds on previous exchanges, maintain continuity in your answer.\\n\"\n f\"Only state facts clearly supported by the provided context. If information is not available, say 'I DON'T KNOW'.\\n\\n\"\n f\"Context:\\n{context}\"\n )\n response = get_llm_response(llm_input, system_message_content)\n elif tool == \"calculator_tool\":\n # Perform the calculation using the calculator tool\n response = calculator_tool(tool_input)\n else:\n system_message_content = \"You are a helpful assistant. Respond to the user's prompt as best as you can based on the conversation history.\"\n response = get_llm_response(llm_input, system_message_content)\n\n # Store the system response in the chat history collection\n store_chat_message(session_id, \"system\", response)\n return response\n\n# Helper function to get the LLM response\ndef get_llm_response(messages, system_message_content):\n # Add the system message to the messages list\n system_message = {\n \"role\": \"system\",\n \"content\": system_message_content,\n }\n\n # If the system message should go at the end (for context-based queries)\n if any(msg.get(\"role\") == \"system\" for msg in messages):\n messages.append(system_message)\n else:\n # For general queries, put system message at beginning\n messages = [system_message] + messages\n\n # Get response from LLM\n response = (\n openai_client.chat.completions.create(model=OPENAI_MODEL, messages=messages)\n .choices[0]\n .message.content\n )\n\n return response\n\n```\n\n#### Test the agent.\n\nFinally, create a file named `main.py` in your project. This file runs the agent and allows you to interact with it.\n\n```python\nfrom config import mongo_client\nfrom ingest_data import ingest_data\nfrom planning import generate_response\n\nif __name__ == \"__main__\":\n try:\n run_ingest = input(\"Ingest sample data? (y/n): \")\n if run_ingest.lower() == \"y\":\n ingest_data()\n\n session_id = input(\"Enter a session ID: \")\n\n while True:\n user_query = input(\"\\nEnter your query (or type 'quit' to exit): \")\n if user_query.lower() == \"quit\":\n break\n\n if not user_query.strip():\n print(\"Query cannot be empty. Please try again.\")\n continue\n\n answer = generate_response(session_id, user_query)\n print(\"\\nAnswer:\")\n print(answer)\n finally:\n mongo_client.close()\n\n```\n\nSave your project, then run the following command. When you run the agent:\n\n- If you haven't already, instruct the agent to ingest the sample data.\n\n- Enter a session ID to start a new session or continue an existing session."} -{"chunk_id": "69eb0c75d0423fff078dfae4-4", "page_id": "69eb0c75d0423fff078dfae4", "source_name": "vector-search", "product_name": "Atlas Vector Search", "url": "https://mongodb.com/docs/vector-search/about/ai-agents", "title": "Build AI Agents with MongoDB", "text": "- Ask questions. The agent generates a response based on your tools, the previous interactions, and the prompts defined in the planning phase.\n\nRefer to the example output for a sample interaction:\n\n```none\npython main.py\n```\n\n```none\nIngest sample data? (y/n): y\nSuccessfully split PDF into 104 chunks.\nGenerating embeddings and ingesting documents...\nInserted 104 documents into the collection.\nSearch index 'vector_index' creation initiated.\nPolling to check if the index is ready. This may take up to a minute.\nvector_index is ready for querying.\nEnter a session ID: 123\n\nEnter your query (or type 'quit' to exit): What was MongoDB's latest acquisition?\nTool selected: vector_search_tool\n\nAnswer:\nMongoDB's latest acquisition was Voyage AI.\n\nEnter your query (or type 'quit' to exit): What do they do?\nTool selected: vector_search_tool\n\nAnswer:\nVoyage AI is a company that specializes in state-of-the-art embedding and reranking models designed to power next-generation AI applications. These technologies help organizations build more advanced and trustworthy AI capabilities.\n\nEnter your query (or type 'quit' to exit): What is 123+456?\nTool selected: calculator_tool\n\nAnswer:\n579\n```\n\nIf you're using Atlas, you can verify your embeddings and interactions by navigating to the `ai_agent_db.embeddings` namespace in the Atlas UI.\n\n#### Continue building.\n\nNow that you have a basic AI agent, you can continue developing it by:\n\n- Improving the performance of your vector search tools and fine tuning your RAG pipelines.\n\n- Adding more tools to the agent, such as hybrid or full-text search tools.\n\n- Refining the planning phase by using more advanced prompts and LLM calls.\n\n- Implementing long-term memory and more advanced memory systems by using MongoDB Search and MongoDB Vector Search to store and retrieve important interactions across sessions.\n\n#### Set up the environment.\n\n- Initialize the project and install dependencies.\n\n Create a new project directory, then install the required dependencies:\n\n ```none\n mkdir mongodb-ai-agent\n cd mongodb-ai-agent\n npm init -y\n npm install --quiet dotenv mongodb voyageai openai langchain @langchain/community @langchain/core mathjs pdf-parse@1\n ```\n\n Your project will use the following structure:\n\n ```text\n mongodb-ai-agent\n \u251c\u2500\u2500 .env\n \u251c\u2500\u2500 config.js\n \u251c\u2500\u2500 ingest-data.js\n \u251c\u2500\u2500 tools.js\n \u251c\u2500\u2500 memory.js\n \u251c\u2500\u2500 planning.js\n \u2514\u2500\u2500 index.js\n ```\n\n- Configure the environment.\n\n Create an environment file named `.env` in your project. This file will contain your API keys for the agent, the MongoDB connection string, and MongoDB database and collection names.\n\n Replace the placeholder values with your MongoDB connection string and your Voyage AI and OpenAI API keys.\n\n ```none\n MONGODB_URI=\"\"\n VOYAGE_API_KEY=\"\"\n OPENAI_API_KEY= \"\"\n ```\n\n Replace `` with the connection string for your Atlas cluster or local Atlas deployment.\n\n \n\n \n\n Your connection string should use the following format:\n\n ```\n mongodb+srv://:@..mongodb.net\n ```\n\n IMPORTANT: Ensure that your connection string includes your database user's credentials. To learn more about finding your connection string, see Connect to a Cluster via Client Libraries.\n\n \n\n \n\n Your connection string should use the following format:\n\n ```\n mongodb://localhost:/?directConnection=true\n ```\n\n To learn more, see Connection Strings.\n\n \n\n \n\n#### Configure the agent.\n\nCreate a file named `config.js` in your project. This file will read in your environment variables and connect the application to services like the MongoDB database and OpenAI.\n\n```javascript\nimport dotenv from 'dotenv';\nimport { MongoClient } from 'mongodb';\nimport OpenAI from 'openai';\n\n// Load environment variables from .env file\ndotenv.config();\n\n// MongoDB cluster configuration\nexport const MONGODB_URI = process.env.MONGODB_URI;\nexport const mongoClient = new MongoClient(MONGODB_URI);\nexport const agentDb = mongoClient.db('ai_agent_db');\nexport const vectorCollection = agentDb.collection('embeddings');\nexport const memoryCollection = agentDb.collection('chat_history');\n\n// Model Configuration\nexport const OPENAI_MODEL = 'gpt-4o';\nexport const VOYAGE_MODEL = 'voyage-4-large';\nexport const VOYAGE_API_KEY = process.env.VOYAGE_API_KEY;\n\n// Initialize OpenAI Client\nexport const openAIClient = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });\n\n```\n\n#### Use MongoDB as a vector database.\n\nCreate a file named `ingest-data.js` in your project. This script ingests a sample PDF that contains a recent MongoDB earnings report into a collection in MongoDB by using the `voyage-4-large` embedding model. This code also includes a function to create a vector search index on your data if it doesn't already exist.\n\nTo learn more, see Ingestion.\n\n```javascript\nimport { PDFLoader } from '@langchain/community/document_loaders/fs/pdf';\nimport { RecursiveCharacterTextSplitter } from 'langchain/text_splitter';\nimport { vectorCollection } from './config.js';\nimport { VOYAGE_API_KEY, VOYAGE_MODEL } from './config.js';\nimport { VoyageAIClient } from 'voyageai';\nimport * as fs from 'fs';\n\nconst EMBEDDING_DIMENSIONS = 1024;\n\n// Use Voyage AI Client SDK to get embeddings\nexport async function getEmbedding(data, input_type) {\n if (!VOYAGE_API_KEY) {\n throw new Error('VOYAGE_API_KEY is not set in environment variables.');\n }\n\n try {\n const client = new VoyageAIClient({ apiKey: VOYAGE_API_KEY });\n const response = await client.embed({\n input: [data],\n model: VOYAGE_MODEL,\n input_type: input_type, // \"document\" or \"query\"\n });\n\n if (response.data && response.data.length > 0) {\n return response.data[0].embedding;\n }\n throw new Error('No embedding data found from Voyage AI response.');\n } catch (error) {\n console.error('Error generating Voyage AI embedding:', error);\n return null;\n }\n}\n\n// Ingest data from a PDF, generate embeddings, and store in MongoDB\nexport async function ingestData() {\n try {\n // download PDF\n const rawData = await fetch('https://investors.mongodb.com/node/13176/pdf');\n const pdfBuffer = await rawData.arrayBuffer();\n fs.writeFileSync('investor-report.pdf', Buffer.from(pdfBuffer));\n\n // load and split PDF\n const loader = new PDFLoader('investor-report.pdf');\n const data = await loader.load();\n const textSplitter = new RecursiveCharacterTextSplitter({\n chunkSize: 400,\n chunkOverlap: 20,\n });\n const docs = await textSplitter.splitDocuments(data);\n console.log(`Chunked PDF into ${docs.length} documents.`);\n\n // generate embeddings and insert\n const insertDocuments = await Promise.all(\n docs.map(async (doc) => ({\n document: doc,\n embedding: await getEmbedding(doc.pageContent, 'document'),\n }))\n );\n\n const result = await vectorCollection.insertMany(insertDocuments, {\n ordered: false,\n });\n console.log('Inserted documents:', result.insertedCount);\n } catch (err) {\n console.error('Ingestion error:', err);\n }\n}\n\n// Create a vector search index\nexport async function createVectorIndex() {\n try {\n // check if the index already exists\n const existingIndexes = await vectorCollection\n .listSearchIndexes()\n .toArray();\n if (existingIndexes.some((index) => index.name === 'vector_index')) {\n console.log('Vector index already exists. Skipping creation.');\n return;\n }\n\n // define your Vector Search index\n const index = {\n name: 'vector_index',\n type: 'vectorSearch',\n definition: {\n fields: [\n {\n type: 'vector',\n path: 'embedding',\n numDimensions: EMBEDDING_DIMENSIONS,\n similarity: 'cosine',\n },\n ],\n },\n };"} -{"chunk_id": "69eb0c75d0423fff078dfae4-5", "page_id": "69eb0c75d0423fff078dfae4", "source_name": "vector-search", "product_name": "Atlas Vector Search", "url": "https://mongodb.com/docs/vector-search/about/ai-agents", "title": "Build AI Agents with MongoDB", "text": " // run the helper method to ensure the index is created\n const result = await vectorCollection.createSearchIndex(index);\n console.log(`New index named ${result} is building.`);\n\n // wait for the index to be ready to query\n console.log(\n 'Polling to check if the index is ready. This may take up to a minute.'\n );\n const maxRetries = 24; // ~2 minutes at 5s intervals\n let isQueryable = false;\n for (let attempt = 0; attempt < maxRetries; attempt++) {\n const indexes = await vectorCollection.listSearchIndexes().toArray();\n const target = indexes.find((index) => index.name === result);\n if (target && target.queryable) {\n console.log(`${result} is ready for querying.`);\n isQueryable = true;\n break;\n }\n await new Promise((resolve) => setTimeout(resolve, 5000));\n }\n if (!isQueryable) {\n throw new Error(`Index '${result}' did not become queryable in time.`);\n }\n } catch (err) {\n console.error('Error creating vector index:', err);\n throw err;\n }\n}\n\n```\n\n#### Define tools for the agent.\n\nCreate a file named `tools.js` in your project. This file defines the tools that the agent can use to answer questions. In this example, you define the following tools:\n\n- `vectorSearchTool`: Runs a vector search query to retrieve relevant documents from your collection.\n\n- `calculatorTool`: Uses the `mathjs` library for basic math operations.\n\n```javascript\nimport { getEmbedding } from './ingest-data.js';\nimport { vectorCollection } from './config.js';\nimport { evaluate } from 'mathjs';\n\n// Vector search tool\nexport async function vectorSearchTool(userInput) {\n const queryEmbedding = await getEmbedding(userInput, 'query');\n\n const pipeline = [\n {\n $vectorSearch: {\n index: 'vector_index',\n queryVector: queryEmbedding,\n path: 'embedding',\n exact: true,\n limit: 5,\n },\n },\n {\n $project: {\n _id: 0,\n 'document.pageContent': 1,\n },\n },\n ];\n\n const cursor = vectorCollection.aggregate(pipeline);\n const results = await cursor.toArray();\n return results;\n}\n\n// Simple calculator tool\nexport function calculatorTool(userInput) {\n try {\n const result = evaluate(userInput);\n return String(result);\n } catch (e) {\n return `Error: ${e.message}`;\n }\n}\n\n```\n\n#### Add memory to the agent.\n\nCreate a file named `memory.js` in your project. This file defines the system that the agent uses to store its interactions. In this example, you implement short-term memory by defining the following functions:\n\n- `storeChatMessage`: to store information about an interaction in a MongoDB collection.\n\n- `retrieveSessionHistory`: to get all interactions for a specific session by using the `session_id` field.\n\n```javascript\nimport { memoryCollection } from './config.js';\n\n/**\n * Store a chat message in the memory collection.\n * @param {string} sessionId - unique identifier for the chat session\n * @param {string} role - role of the sender (user or system)\n * @param {string} content - content of the message\n */\nexport async function storeChatMessage(sessionId, role, content) {\n const message = {\n session_id: sessionId,\n role,\n content,\n timestamp: new Date(), // use JS date for timestamp\n };\n await memoryCollection.insertOne(message);\n}\n\n/**\n * Retrieve the chat history for a session.\n * @param {string} sessionId - unique identifier for the chat session\n * @returns {Promise>}\n */\nexport async function retrieveSessionHistory(sessionId) {\n const cursor = memoryCollection\n .find({ session_id: sessionId })\n .sort({ timestamp: 1 });\n\n const messages = [];\n await cursor.forEach((msg) => {\n messages.push({ role: msg.role, content: msg.content });\n });\n return messages;\n}\n\n```\n\n#### Define the agent's planning.\n\nCreate a file named `planning.js` in your project. This file will include various prompts and LLM calls to determine the agent's execution flow. In this example, you define the following functions:\n\n- `openAIChatCompletion`: Helper function to call the OpenAI API for generating responses.\n\n- `toolSelector`: Determines how the LLM selects the appropriate tool for a task.\n\n- `generateAnswer`: Orchestrates the agent's execution flow by using tools, calling the LLM, and processing the results.\n\n- `getLLMResponse`: Helper function for LLM response generation.\n\n```javascript\nimport { vectorSearchTool, calculatorTool } from './tools.js';\nimport { storeChatMessage, retrieveSessionHistory } from './memory.js';\nimport { openAIClient, OPENAI_MODEL } from './config.js';\n\n// OpenAI chat completion helper\nexport async function openAIChatCompletion(messages) {\n try {\n const completion = await openAIClient.chat.completions.create({\n model: OPENAI_MODEL,\n messages,\n max_tokens: 1024,\n });\n\n return completion.choices[0].message.content;\n } catch (error) {\n console.error('Error in openAIChatCompletion:', error);\n throw error;\n }\n}\n\n// Tool selector function to determine which tool to use based on user input and session history\nexport async function toolSelector(userInput, sessionHistory = []) {\n const systemPrompt = `\nSelect the appropriate tool from the options below. Consider the full context of the conversation before deciding.\n\nTools available:\n- vector_search_tool: Retrieve specific context about recent MongoDB earnings and announcements\n- calculator_tool: For mathematical operations\n- none: For general questions without additional context\n\nProcess for making your decision:\n1. Analyze if the current question relates to or follows up on a previous vector search query\n2. For follow-up questions, incorporate context from previous exchanges to create a comprehensive search query\n3. Only use calculator_tool for explicit mathematical operations\n4. Default to none only when certain the other tools won't help\n\nWhen continuing a conversation:\n- Identify the specific topic being discussed\n- Include relevant details from previous exchanges\n- Formulate a query that stands alone but preserves conversation context\n\nReturn a JSON object only: {\"tool\": \"selected_tool\", \"input\": \"your_query\"}\n `.trim();\n\n const messages = [\n { role: 'system', content: systemPrompt },\n ...sessionHistory,\n { role: 'user', content: userInput },\n ];\n\n try {\n const response = await openAIChatCompletion(messages);\n let toolCall;\n try {\n toolCall = JSON.parse(response);\n } catch {\n try {\n toolCall = eval(`(${response})`);\n } catch {\n return { tool: 'none', input: userInput };\n }\n }\n return {\n tool: toolCall.tool || 'none',\n input: toolCall.input || userInput,\n };\n } catch (err) {\n console.error('Error in toolSelector:', err);\n return { tool: 'none', input: userInput };\n }\n}\n\n// Function to get LLM response based on messages and system message content\nasync function getLlmResponse(messages, systemMessageContent) {\n const systemMessage = { role: 'system', content: systemMessageContent };\n let fullMessages;\n if (messages.some((msg) => msg.role === 'system')) {\n fullMessages = [...messages, systemMessage];\n } else {\n fullMessages = [systemMessage, ...messages];\n }\n const response = await openAIChatCompletion(fullMessages);\n return response;\n}\n\n// Function to generate response based on user input\nexport async function generateResponse(sessionId, userInput) {\n await storeChatMessage(sessionId, 'user', userInput);\n\n const sessionHistory = await retrieveSessionHistory(sessionId);\n const llmInput = [...sessionHistory, { role: 'user', content: userInput }];\n\n const { tool, input: toolInput } = await toolSelector(\n userInput,\n sessionHistory\n );\n console.log('Tool selected:', tool);"} -{"chunk_id": "69eb0c75d0423fff078dfae4-6", "page_id": "69eb0c75d0423fff078dfae4", "source_name": "vector-search", "product_name": "Atlas Vector Search", "url": "https://mongodb.com/docs/vector-search/about/ai-agents", "title": "Build AI Agents with MongoDB", "text": " let response;\n if (tool === 'vector_search_tool') {\n const contextResults = await vectorSearchTool(toolInput);\n const context = contextResults\n .map((doc) => doc.document?.pageContent || JSON.stringify(doc))\n .join('\\n---\\n');\n const systemMessageContent = `\nAnswer the user's question based on the retrieved context and conversation history.\n1. First, understand what specific information the user is requesting\n2. Then, locate the most relevant details in the context provided\n3. Finally, provide a clear, accurate response that directly addresses the question\n\nIf the current question builds on previous exchanges, maintain continuity in your answer.\nOnly state facts clearly supported by the provided context. If information is not available, say 'I DON'T KNOW'.\n\nContext:\n${context}\n `.trim();\n response = await getLlmResponse(llmInput, systemMessageContent);\n } else if (tool === 'calculator_tool') {\n response = calculatorTool(toolInput);\n } else {\n const systemMessageContent =\n \"You are a helpful assistant. Respond to the user's prompt as best as you can based on the conversation history.\";\n response = await getLlmResponse(llmInput, systemMessageContent);\n }\n\n await storeChatMessage(sessionId, 'system', response);\n return response;\n}\n\n```\n\n#### Test the agent.\n\nFinally, create a file named `index.js` in your project. This file runs the agent and allows you to interact with it.\n\n```javascript\nimport readline from 'readline';\nimport { mongoClient } from './config.js';\nimport { ingestData, createVectorIndex } from './ingest-data.js';\nimport { generateResponse } from './planning.js';\n\n// Prompt for user input\nasync function prompt(question) {\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n return new Promise((resolve) =>\n rl.question(question, (answer) => {\n rl.close();\n resolve(answer);\n })\n );\n}\n\nasync function main() {\n try {\n await mongoClient.connect();\n\n const runIngest = await prompt('Ingest sample data? (y/n): ');\n if (runIngest.trim().toLowerCase() === 'y') {\n await ingestData();\n console.log('\\nAttempting to create/verify Vector Search Index...');\n await createVectorIndex();\n } else {\n await createVectorIndex(); // ensure index exists even if not ingesting data\n }\n\n const sessionId = await prompt('Enter a session ID: ');\n\n while (true) {\n const userQuery = await prompt(\n \"\\nEnter your query (or type 'quit' to exit): \"\n );\n if (userQuery.trim().toLowerCase() === 'quit') break;\n\n if (!userQuery.trim()) {\n console.log('Query cannot be empty. Please try again.');\n continue;\n }\n\n const answer = await generateResponse(sessionId, userQuery);\n console.log('\\nAnswer:');\n console.log(answer);\n }\n } finally {\n await mongoClient.close();\n }\n}\n\nmain();\n\n```\n\nSave your project, then run the following command. When you run the agent:\n\n- If you haven't already, instruct the agent to ingest the sample data.\n\n- Enter a session ID to start a new session or continue an existing session.\n\n- Ask questions. The agent generates a response based on your tools, the previous interactions, and the prompts defined in the planning phase.\n\nRefer to the example output for a sample interaction:\n\n```none\nnode index.js\n```\n\n```none\nIngest sample data? (y/n): y\nChunked PDF into 100 documents.\nInserted documents: 100\n\nAttempting to create/verify Vector Search Index...\nNew index named vector_index is building.\nPolling to check if the index is ready. This may take up to a minute.\nvector_index is ready for querying.\nEnter a session ID: 123\n\nEnter your query (or type 'quit' to exit): What was MongoDB's latest acquisition?\nTool selected: vector_search_tool\n\nAnswer:\nMongoDB recently acquired Voyage AI, a pioneer in embedding and reranking models that power next-generation AI applications.\n\nEnter your query (or type 'quit' to exit): What do they do?\nTool selected: vector_search_tool\n\nAnswer: Voyage AI is a company that specializes in\nstate-of-the-art embedding and reranking models designed to\npower next-generation AI applications. These technologies help\norganizations build more advanced and trustworthy AI\ncapabilities.\n\nEnter your query (or type 'quit' to exit): What is 123+456?\nTool selected: calculator_tool\n\nAnswer:\n579\n```\n\nIf you're using Atlas, you can verify your embeddings and interactions by navigating to the `ai_agent_db.embeddings` namespace in the Atlas UI.\n\n#### Continue building.\n\nNow that you have a basic AI agent, you can continue developing it by:\n\n- Improving the performance of your vector search tools and fine tuning your RAG pipelines.\n\n- Adding more tools to the agent, such as hybrid or full-text search tools.\n\n- Refining the planning phase by using more advanced prompts and LLM calls.\n\n- Implementing long-term memory and more advanced memory systems by using MongoDB Search and MongoDB Vector Search to store and retrieve important interactions across sessions.\n\n## Tutorials\n\nFor more tutorials on building AI agents with MongoDB, refer to the following table:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nFrameworks\n\n\n- Build an AI Agent with LangGraph and MongoDB Atlas\n\n- Build an AI Agent with LangGraph.js and MongoDB Atlas\n\n- Natural Language to MQL Agent with LangChain and LangGraph\n\n- Build an Agentic RAG Application with CrewAI and MongoDB\n\n- Integrate MongoDB with Mastra\n\n- Other AI framework integrations\n\n
\nEnterprise platforms\n\n\n- Get Started with the Amazon Bedrock Knowledge Base Integration\n\n- Build AI Agents with Vertex AI Agent Engine and Atlas\n\n- Azure AI Foundry\n\n
\nTools\n\n\n- Build an AI Agent with MongoDB and n8n\n\n
\nAdditional resources\n\n\n- Docs Notebooks Repository\n\n- GenAI Showcase Repository\n\n
"} -{"chunk_id": "68a95c2d5e79d242619df8bf-0", "page_id": "68a95c2d5e79d242619df8bf", "source_name": "visual-studio-extension", "product_name": "C# Analyzer", "url": "https://mongodb.com/docs/mongodb-analyzer/current/install", "title": "Install the MongoDB C# Analyzer", "text": "# Install the MongoDB C# Analyzer\n\n## Overview\n\nLearn how to install the C# Analyzer in your .NET application.\n\n## Installation\n\nTo install the C# Analyzer, run the following command from the root directory of your .NET project:\n\n```shell\ndotnet add package MongoDB.Analyzer -v 2.0.0\n```\n\nTo view the NuGet page for the C# Analyzer, see MongoDB.Analyzer on NuGet Gallery.\n\nTo learn more about installing NuGet packages from the command line, see NuGet CLI Reference from Microsoft.\n\nTo learn more about installing NuGet packages from Visual Studio, see Install and manage packages in Visual Studio using the NuGet Package Manager from Microsoft."} -{"chunk_id": "68a95c2d5e79d242619df88e-0", "page_id": "68a95c2d5e79d242619df88e", "source_name": "visual-studio-extension", "product_name": "C# Analyzer", "url": "https://mongodb.com/docs/mongodb-analyzer/current/code-type/linq", "title": "Analyze LINQ Expressions", "text": "# Analyze LINQ Expressions\n\n## Overview\n\n**LINQ** is a query syntax included in the C# language. The .NET/C# driver can translate a subset of LINQ expressions into MongoDB aggregation pipelines.\n\nTo learn more about LINQ, see the following resources:\n\n- LINQ in the .NET/C# driver documentation\n\n- LINQ in the Microsoft C# guide\n\nTo learn more about aggregation pipelines, see Aggregation in the MongoDB manual.\n\nAlthough the MongoDB Query API translations generated by the C# Analyzer have the same query shape as your runtime .NET/C# driver queries, there may be slight differences due to the following factors:\n\n- Your Serialization Settings\n\n- Your LINQ Settings\n\nThe difference between the translations the C# Analyzer generates and your queries at runtime should not impact your ability to analyze and debug your code.\n\nTo learn more about serialization and LINQ settings, see the FAQ page.\n\nUse the C# Analyzer to learn the following about your LINQ expressions:\n\n- How your LINQ expressions translate into the MongoDB Query API\n\n- If any of your LINQ expressions are not supported\n\n## Translate into the MongoDB Query API\n\nClick the following tabs to see an example of a LINQ expression and its corresponding MongoDB Query API translation:\n\n\n\n\n\n```csharp\nvar books = queryableCollection\n .Where(b =>\n b.Genre == genre &&\n b.Price >= minPrice &&\n b.Title.Contains(titleSearchTerm))\n .OrderBy(b => b.Price)\n .ToList();\n```\n\n\n\n\n\n```json\n[{ \"$match\" : {\n \"Genre\" : genre,\n \"Price\" : { \"$gte\" : minPrice },\n \"Title\" : /titleSearchTerm/s }\n },\n { \"$sort\" : { \"Price\" : 1 } }]\n```\n\n\n\n\n\nThe MongoDB Query API translations generated by the C# Analyzer contain variable names from your .NET/C# driver code. The .NET/C# driver replaces these variable names with their corresponding values when your application communicates with MongoDB.\n\n## Analyze LINQ in Visual Studio\n\nTo analyze your LINQ expressions in Visual Studio, perform the following actions:\n\n1. Install the C# Analyzer as described in the Install guide.\n\n2. Write a LINQ expression with the .NET/C# driver.\n\n3. Move your mouse over the ... annotation beneath the first method of your LINQ expression to display an information message that contains the MongoDB Query API translation.\n\n### Simple LINQ Expressions\n\nThe C# Analyzer analyzes LINQ expressions in the following syntax types:\n\n- Method syntax\n\n- Query syntax\n\nClick on the following corresponding tab to see a LINQ expression written in method syntax with or without an information message displayed:\n\n\n\n\n\n\n\n\n\n\n\n\n\nClick on the following corresponding tab to see a LINQ expression written in query syntax with or without an information message displayed:\n\n\n\n\n\n\n\n\n\n\n\n\n\n### Unsupported LINQ Expressions\n\nIf your LINQ expression is not supported, the C# Analyzer outputs a `MALinq2001` warning.\n\nThe following code snippet contains the unsupported `GetHashCode` LINQ expression:\n\n```csharp\nvar result = queryableColl.Where(b => b.GetHashCode() == 167);\n```\n\nThe C# Analyzer shows an annotation on the unsupported expression and generates the following warning message:\n\n```text\nExpression not supported: b.GetHashCode().\n```\n\nThe following screenshot shows the annotated code and the warning displayed when you hover over the annotation:\n\nIf you are using Visual Studio for Windows, you can view the output from the C# Analyzer in the Error List window.\n\nTo learn more, see Error List Window from Microsoft.\n\nTo view more examples of unsupported LINQ expressions, see the MongoDB C# Analyzer Github repository.\n\n### Analyze LINQ3\n\nTo analyze a LINQ3 expression, you must configure the C# Analyzer to use the LINQ3 provider. To learn how to configure your LINQ provider, see the configuration guide.\n\nIf your .NET/C# driver version supports LINQ3 but you configure your C# Analyzer to use the default LINQ provider (LINQ2), the C# Analyzer informs you if your LINQ expression is supported by LINQ3 but not LINQ2.\n\nClick the tabs to see a LINQ expression supported by LINQ3 but not LINQ2 and the corresponding warning output by the C# Analyzer:\n\n\n\n\n\n```csharp\nvar result = queryableColl.Where(b => b.Title.Substring(0) == \"Pane\");\n```\n\n\n\n\n\n```text\nSupported in LINQ3 only: db.coll.Aggregate([{ \"$match\" : { \"$expr\" : { \"$eq\" : [{ \"$substrCP\" : [\"$Title\", 0, { \"$subtract\" : [{ \"$strLenCP\" : \"$Title\" }, 0] }] }, \"Pane\"] } } }])\n```\n\n\n\n\n\nTo view examples of expressions the .NET/C# driver only supports with the LINQ3 provider, see the MongoDB C# Analyzer Github repository."} -{"chunk_id": "68a95c2d5e79d242619df8ae-0", "page_id": "68a95c2d5e79d242619df8ae", "source_name": "visual-studio-extension", "product_name": "C# Analyzer", "url": "https://mongodb.com/docs/mongodb-analyzer/current/rules", "title": "Rules and Message Content", "text": "# Rules and Message Content\n\n## Overview\n\nIn this guide, you can learn about the MongoDB C# Analyzer rules and attached messages. A rule evaluates different parts of your code and returns a message if a specific condition is met.\n\nFor example, the Analyzer might apply a rule if it detects a LINQ expression, which causes your IDE to display a message that contains the equivalent Query API expression. Each rule has a severity level of `Info` or `Warning` that impacts where the message might be recorded.\n\n## Rule Descriptions\n\nThe following sections describe each C# Analyzer rule, including the rule category, severity level, and description of the corresponding message. Each section also includes an example message.\n\n### MABuilders1001\n\nThe `MABuilders1001` rule evaluates your code for builders expressions and triggers a message that contains the equivalent Query API expression.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n**Category**\n\n\n`MongoDB.Analyzer.Builders`\n\n
\n**Severity**\n\n\n`Info`\n\n
\n**Notes**\n\n\nNone\n\n
The following code triggers the `MABuilders1001` rule to display a message that shows the equivalent Query API expression:\n\n```csharp\nvar filter = Builders.Filter.Eq(b => b.Genre, \"Theory\") &\n Builders.Filter.Gte(b => b.Price, 10);\n```\n\nThe following image displays the `MABuilders1001` rule and information message:\n\nTo learn more about builders expressions, see the Analyze Builders Expressions guide.\n\n### MABuilders2001\n\nThe `MABuilders2001` rule detects unsupported builders expressions and displays a translation error of the unsupported expression.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n**Category**\n\n\n`MongoDB.Analyzer.Builders`\n\n
\n**Severity**\n\n\n`Warning`\n\n
\n**Notes**\n\n\nTo view examples of unsupported builders expressions, see the source code testing files.\n\n
The following code triggers the `MABuilders2001` rule to display a message that shows the unsupported builders expression:\n\n```csharp\nvar filter = Builders.Filter.Eq(b => b.Price + 2, 1);\n```\n\nThe following image displays the `MABuilders2001` rule and information message:\n\nTo learn more about builders expressions, see the Analyze Builders Expressions guide.\n\n### MALinq1001\n\nThe `MALinq1001` rule evaluates your code for LINQ expressions and triggers a message that contains the equivalent Query API expression.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n**Category**\n\n\n`MongoDB.Analyzer.LINQ`\n\n
\n**Severity**\n\n\n`Info`\n\n
\n**Notes**\n\n\nThis rule might apply differently depending on the value of your `DefaultLinqVersion` configuration setting. To learn more, see the Analyzer Configuration Options.\n\n
The following code triggers the `MALinq1001` rule to display a message that shows the equivalent Query API expression:\n\n```csharp\nvar results = queryableColl\n .Where(b => b.Genre == \"Theory\")\n .OrderBy(b => b.Price);\n```\n\nThe following image displays the `MALinq1001` rule and information message:\n\nTo learn more about LINQ expressions, see the Analyze LINQ Expressions guide.\n\n### MALinq2001\n\nThe `MALinq2001` rule detects unsupported LINQ expressions and displays a translation error of the unsupported expression.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n**Category**\n\n\n`MongoDB.Analyzer.LINQ`\n\n
\n**Severity**\n\n\n`Warning`\n\n
\n**Notes**\n\n\nThis rule might apply differently depending on the value ofyour `DefaultLinqVersion` configuration setting. To learn more,see the Analyzer Configuration Options.To view examples of unsupported LINQ expressions, see thesource code testing files.\n\n
The following code triggers the `MALinq2001` rule to display a message that shows the unsupported LINQ expression:\n\n```csharp\nvar results = queryableColl.Where(b => b.GetHashCode() == 1);\n```\n\nThe following image displays the `MALinq2001` rule and information message:\n\nTo learn more about LINQ expressions, see the Analyze LINQ Expressions guide.\n\n### MAPoco1001\n\nThe `MAPoco1001` rule evaluates your code for POCO declarations and triggers a message that contains the JSON representation of a sample instance. This rule evaluates some BSON serialization annotations such as `BsonIgnore` and `BsonElement`.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n**Category**\n\n\n`MongoDB.Analyzer.Poco`\n\n
\n**Severity**\n\n\n`Info`\n\n
\n**Notes**\n\n\nThis rule might apply differently depending on the value of your `PocoAnalysisVerbosity` configuration setting. To learn more, see the Analyzer Configuration Options.\n\n
The following code triggers the `MAPoco1001` rule to display a message that shows the JSON representation of a sample POCO:\n\n```csharp\npublic class Person\n{\n [BsonId]\n public int Id { get; set; }\n public string FirstName { get; set; }\n public string LastName { get; set; }\n public int Age { get; set; }\n [BsonIgnore]\n public double Income { get; set; }\n}\n```\n\nThe following image displays the `MAPoco1001` rule and information message:\n\nTo learn more about POCO analysis, see the Analyze POCOs guide.\n\nTo learn more about POCO annotations, see the POCOs guide in the .NET/C# driver documentation.\n\n### MAPoco2001\n\nThe `MAPoco2001` rule evaluates your code for unsupported serialization settings specified on a POCO declaration.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n**Category**\n\n\n`MongoDB.Analyzer.Poco`\n\n
\n**Severity**\n\n\n`Warning`\n\n
\n**Notes**\n\n\nThis rule might apply differently depending on the value ofyour `PocoAnalysisVerbosity` configuration setting. To learn more,see the Analyzer Configuration Options.To view examples of unsupported POCO declarations, see thesource code testing files.\n\n
The following code triggers the `MAPoco2001` rule to display a message that explains that the code includes an invalid serialization setting on the `Date` field:\n\n```csharp\npublic class Appointment\n{\n [BsonDateTimeOptions(DateOnly = true, Kind = DateTimeKind.Local)]\n public decimal Date { get; set; }\n public string Doctor { get; set; }\n}\n```\n\nThe following image displays the `MAPoco2001` rule and information message:\n\nTo learn more about POCO analysis, see the Analyze POCOs guide.\n\nTo learn more about POCO annotations, see the POCOs guide in the .NET/C# driver documentation."} -{"chunk_id": "68a95c2d5e79d242619df8b3-0", "page_id": "68a95c2d5e79d242619df8b3", "source_name": "visual-studio-extension", "product_name": "C# Analyzer", "url": "https://mongodb.com/docs/mongodb-analyzer/current/whats-new", "title": "What's New", "text": "# What's New\n\nLearn what's new in:\n\n- Version 2.0\n\n- Version 1.5\n\n- Version 1.4\n\n## What's New in 2.0\n\nThe 2.0 MongoDB C# Analyzer release includes the following features, improvements, and fixes:\n\n- Supports only .NET/C# driver v3.0 and higher.\n\n- Drops support for the `MALinq2002` rule because .NET/C# driver v3.0 removes the `LINQ2` provider.\n\n- Drops support for `IMongoQueryable`. As a result, the C# Analyzer attempts to analyze each `IQueryable` object, except for system collections and arrays. This version adds the `LinqAnalysisVerbosity` option to control the verbosity of `IQueryable` analysis.\n\n## What's New in 1.5\n\nThe 1.5 MongoDB C# Analyzer release includes the following features, improvements, and fixes:\n\n- New analysis rules introduced for Entity Framework Core, which enable displaying MongoDB Query API translations for MongoDB Entity Framework Core Provider expressions at compile time\n\n- Support for strong named 2.28 driver\n\n- Supports fully qualified names for data models\n\n## What's New in 1.4\n\nThe 1.4 MongoDB C# Analyzer release includes the following features, improvements, and fixes:\n\n- Support for builders defined within variables. For example, the C# Analyzer analyzes the second line in the following code:\n\n ```csharp\n var movieFilterBuilder = Builders.Filter;\n var filterReviews = movieFilterBuilder.Size(p => p.Reviews, 5);\n ```"} -{"chunk_id": "68a95c2d5e79d242619df8a0-0", "page_id": "68a95c2d5e79d242619df8a0", "source_name": "visual-studio-extension", "product_name": "C# Analyzer", "url": "https://mongodb.com/docs/mongodb-analyzer/current/configuration", "title": "Configure the MongoDB C# Analyzer", "text": "# Configure the MongoDB C# Analyzer\n\n## Overview\n\nLearn how to configure the C# Analyzer in your .NET project and what configuration options are available.\n\n## Configuration\n\nTo configure the C# Analyzer, perform the following actions:\n\n1. Install the C# Analyzer as described in the installation guide.\n\n2. Create a file specifying your configuration for the C# Analyzer named `mongodb.analyzer.json`.\n\n You must name your configuration file `mongodb.analyzer.json`.\n\n3. Add your configuration to your `mongodb.analyzer.json` file.\n\n The following sample configuration disables variable tracking:\n\n ```json\n { \"EnableVariableTracking\": \"false\" }\n ```\n\n4. Add the following to the `.csproj` file for your .NET application within the `Project` tag:\n\n ```xml\n \n \" />\n \n ```\n\nIf you do not specify a configuration file, the C# Analyzer uses the default value for all configuration options.\n\nTo learn more about .NET project files, see Understanding the Project File from Microsoft.\n\nTo learn more about the `AdditionalFiles` tag, see Using Additional Files in the Roslyn documentation.\n\n## Options\n\nThe following is a description of all configuration options supported by the C# Analyzer:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nDescription\n\n
\n**EnableVariableTracking**\n\n\n**Type:** boolean**Description:** Specifies if the C# Analyzer tracks and composes builder expression variables.To learn more about builder expressions, see the Analyze Your Code page.\n\n**Accepted Values**: `true` or `false`**Default**: `true`\n\n
\n**LogFileName**\n\n\n**Type:** string**Description:** Specifies the path to which the C# Analyzer writes its internal logs.To output logs, you must specify both a logfile and the `OutputInternalLogsToFile` option.\n\nUse the following sample configuration to make the C# Analyzer output information to a logfile:\n\n```json\n\"OutputInternalLogsToFile\": true,\n\"LogFileName\": \"\"\n```\n\n**Accepted Values**: A valid file path**Default**: `\"\"`\n\n
\n**LinqAnalysisVerbosity**\n\n\n**Type:** string**Description:** Specifies which LINQ expressions the C# Analyzer analyzes. You can set this option to one of the following values:- `\"All\"`: Analyze all LINQ expressions, except system collections and arrays\n\n- `\"Medium\"`: Analyze all LINQ expressions, except for system collections and arrays, in files that include `MongoDB.Driver` and its nested namespaces only\n\n- `\"None\"`: Do not analyze LINQ expressions\n\nThe `LinqAnalysisVerbosity` configuration option is available only in C# Analyzer v2.0 and later.\n\n**Accepted Values**: `\"All\"`, `\"Medium\"`, or `\"None\"`**Default**: `\"Medium\"`\n\n
\n**OutputDriverVersion**\n\n\n**Type:** boolean**Description:** Specifies if the C# Analyzer includes your .NET/C# driver version in diagnostic messages.**Accepted Values**: `true` or `false`**Default**: `false`\n\n
\n**OutputInternalExceptions**\n\n\n**Type:** boolean**Description:** Specifies if the C# Analyzer includes internal exceptions in diagnostic messages.**Accepted Values**: `true` or `false`**Default**: `false`\n\n
\n**OutputInternalLogsToFile**\n\n\n**Type:** boolean**Description:** Specifies if the C# Analyzer writes its internal logs to a file.To output logs, you must specify both a logfile and the `OutputInternalLogsToFile` option.\n\nUse the following sample configuration to make the C# Analyzer output information to a logfile:\n\n```json\n\"OutputInternalLogsToFile\": true,\n\"LogFileName\": \"\"\n```\n\n**Accepted Values**: `true` or `false`**Default**: `false`\n\n
\n**PocoAnalysisVerbosity**\n\n\n**Type:** string**Description:** Specifies which POCOs the C# Analyzer previews as JSON. You can set this option to one of the following values:- `\"All\"`: Preview all POCOs\n\n- `\"Medium\"`: Preview only POCOs that are part of a LINQ or builders expression or have BSON attributes\n\n- `\"None\"`: Do not preview POCOs\n\n**Accepted Values**: `\"All\"`, `\"Medium\"`, or `\"None\"`**Default**: `\"Medium\"`\n\n
\n**SendTelemetry**\n\n\n**Type:** boolean**Description:** Specifies if the C# Analyzer collects and sends anonymized information to MongoDB Inc. to improve products.To learn more about telemetry in the C# Analyzer, see the Telemetry section of this guide.\n\n**Accepted Values**: `true` or `false`**Default**: `true`\n\n
To learn more about the configuration options the C# Analyzer supports, see the MongoDB C# Analyzer source code.\n\n### Telemetry\n\nWhen the C# Analyzer analyzes your source code, the tool by default collects and sends anonymized information to MongoDB Inc. to improve products.\n\nTo disable this feature, specify the following option in your configuration file:\n\n```json\n\"SendTelemetry\": false\n```\n\nTo view a complete list of all information collected by the C# Analyzer when you have enabled telemetry, see the FAQ page.\n\nTo learn more about how MongoDB Inc. uses collected data, see the Privacy Policy."} -{"chunk_id": "68a95c2d5e79d242619df8d0-0", "page_id": "68a95c2d5e79d242619df8d0", "source_name": "visual-studio-extension", "product_name": "C# Analyzer", "url": "https://mongodb.com/docs/mongodb-analyzer/current/code-type/builders", "title": "Analyze Builders Expressions", "text": "# Analyze Builders Expressions\n\n## Overview\n\nA **builder** is a class provided by the .NET/C# driver to help you construct common operations like queries and updates.\n\nTo learn more about builders, see Operations with Builders in the .NET/C# driver documentation.\n\n## Translate into the MongoDB Query API\n\nUse the C# Analyzer to translate your builder expressions into the MongoDB Query API. Click the following tabs to see an example of a builder expression and its corresponding MongoDB Query API translation:\n\n\n\n\n\n```csharp\nvar filter = Builders.Filter.Eq(b => b.Genre, genre) &\n Builders.Filter.Gte(b => b.Price, minPrice) &\n Builders.Filter.Regex(b => b.Title, titleSearchTerm);\n```\n\n\n\n\n\n```json\n{\n \"$and\": [ { \"Genre\": genre },\n { \"Price\": { \"$gte\": minPrice } },\n { \"Title\": /titleSearchTerm/ } ]\n}\n```\n\n\n\n\n\nThe MongoDB Query API translations generated by the C# Analyzer contain variable names from your .NET/C# driver code. The .NET/C# driver replaces these variable names with their corresponding values when your application communicates with MongoDB.\n\n## Analyze Builders in Visual Studio\n\nTo analyze your builder expressions in Visual Studio, perform the following actions:\n\n1. Install the C# Analyzer as described in the Install guide.\n\n2. Write a builder expression with the .NET/C# driver\n\n3. Move your mouse over the ... annotation beneath the first method of your builder expression to display an information message that contains the MongoDB Query API translation.\n\n### Simple Builder Expressions\n\nClick on the following corresponding tab to see a builder expression with or without an information message displayed:\n\n\n\n\n\n\n\n\n\n\n\n\n\n### Track Builder Variables\n\nThe C# Analyzer supports builder variable tracking and composition. You can combine multiple builder expressions with logical operators and view the MongoDB Query API translation in the information message.\n\nClick on the following corresponding tab to see a composed builder variable with or without an information message displayed:\n\n\n\n\n\n\n\n\n\n\n\n\n\n### Fluent API\n\nThe C# Analyzer supports the Fluent API using builder classes in the .NET/C# driver. You can create a sequence of chained builder methods and view the MongoDB Query API translation in the information message.\n\nClick on the following corresponding tab to see an operation using chained builder methods with or without an information message displayed:\n\n\n\n\n\n\n\n\n\n\n\n\n\nIf you are using Visual Studio for Windows, you can view the output from the C# Analyzer in the Error List window.\n\nTo learn more, see Error List Window from Microsoft.\n\n### Unsupported Builder Expressions\n\nIf your builder expression is not supported, the C# Analyzer outputs a `MABuilders2001` warning.\n\nThe following code snippet contains a builder expression that accesses the unsupported `Length` property:\n\n```csharp\nvar filter = Builders.Filter.Gt(m => m.Reviews.Length, 2);\n```\n\nThe C# Analyzer shows an annotation on the unsupported expression and generates the following warning message:\n\n```text\nExpression not supported: ArrayLength(m.Reviews).\n```\n\nThe following screenshot shows the annotated code and the warning displayed when you hover over the annotation:\n\nIf you are using Visual Studio for Windows, you can view the output from the C# Analyzer in the Error List window.\n\nTo learn more, see Error List Window from Microsoft.\n\nTo view more examples of unsupported builder expressions, see the MongoDB C# Analyzer Github repository."} -{"chunk_id": "68a95c2d5e79d242619df88b-0", "page_id": "68a95c2d5e79d242619df88b", "source_name": "visual-studio-extension", "product_name": "C# Analyzer", "url": "https://mongodb.com/docs/mongodb-analyzer/current/analyze-code", "title": "Analyze Your Code", "text": "# Analyze Your Code\n\n## Overview\n\nLearn how to use the C# Analyzer to analyze your MongoDB .NET/C# Driver code. The C# Analyzer can analyze expressions created with the following patterns:\n\n- Builders Class\n\n- Language Integrated Query (LINQ)\n\n- Plain Old CLR/Class Objects (POCOs)\n\n## Use the MongoDB C# Analyzer From the Command Line\n\nTo run the C# Analyzer from the command line and save your results to a SARIF format file, perform the following actions:\n\n- Install the C# Analyzer as described in the Install guide.\n\n- Execute the following command:\n\n```shell\ndotnet build -property:ErrorLog=\n```\n\nTo learn more about `dotnet build`, see .NET Fundamentals from Microsoft.\n\nTo learn more about the `ErrorLog` setting, see Error and Warning Options from Microsoft."} -{"chunk_id": "68a95c2d5e79d242619df8a6-0", "page_id": "68a95c2d5e79d242619df8a6", "source_name": "visual-studio-extension", "product_name": "C# Analyzer", "url": "https://mongodb.com/docs/mongodb-analyzer/current/issues-and-help", "title": "Issues & Help", "text": "# Issues & Help\n\nThe MongoDB developer community is highly engaged and encompasses users with a range of Visual Studio Code experience.\n\nYou can find support for general questions by using the MongoDB Stack Overflow tag or the MongoDB Reddit community.\n\nRefer to our support channels documentation for more information.\n\n## Bugs / Feature Requests\n\nIf you think you've found a bug or want to request a new feature in the C# Analyzer, please open a case in MongoDB's issue management tool, JIRA, by performing the following steps:\n\n1. Visit the MongoDB JIRA issue tracker and click the signup link. Create an account, and then log in to JIRA.\n\n2. Navigate to the VS JIRA project.\n\n3. Click Create to create a ticket. Please provide as much information as possible about the issue or request in the ticket.\n\nBug reports in the VS JIRA project are publicly viewable.\n\nIf you\u2019ve identified a security vulnerability in any official MongoDB product, please report it according to the instructions found in the Create a Vulnerability Report page.\n\n## Pull Requests\n\nWe're happy to accept contributions to help improve the analyzer. We will review user contributions to ensure they meet the standards of the codebase. Please include documentation and tests in your pull request.\n\nTo get started, check out the source and work on a branch:\n\n```bash\ngit clone https://github.com/mongodb/mongo-csharp-analyzer.git\ncd mongo-csharp-analyzer\ngit checkout -b myNewFeature\n```"} -{"chunk_id": "68a95c2d5e79d242619df8a3-0", "page_id": "68a95c2d5e79d242619df8a3", "source_name": "visual-studio-extension", "product_name": "C# Analyzer", "url": "https://mongodb.com/docs/mongodb-analyzer/current", "title": "MongoDB C# Analyzer", "text": "# MongoDB C# Analyzer\n\n## Overview\n\nThe C# Analyzer is a tool that helps you understand the following aspects of your MongoDB .NET/C# Driver code:\n\n- How your code translates into the MongoDB Query API\n\n- If your code includes unsupported LINQ or builder expressions\n\n- How your POCO instances serialize to JSON format\n\nThe C# Analyzer is a Roslyn Analyzer. To learn more about Roslyn Analyzers, see Overview of Source Code Analysis from Microsoft.\n\n### Supported Analysis\n\nThe C# Analyzer can analyze the following groups of .NET/C# driver expressions and classes:\n\n- Builders\n\n- LINQ\n\n- POCOs\n\n## Guides\n\nView the following guides to learn how to install and configure the C# Analyzer and how to use its features:\n\n- Installation\n\n- Analyze Your Code\n\n- Rules and Message Content\n\n- Configuration\n\nTo view known issues with the C# Analyzer's current functionality, see the Known Issues page.\n\nTo view answers to frequently asked questions, see the FAQ page.\n\nTo view the differences between versions of the extension, see the What's New page.\n\nFor further support, see the Issues and Help page."} -{"chunk_id": "68a95c2d5e79d242619df895-0", "page_id": "68a95c2d5e79d242619df895", "source_name": "visual-studio-extension", "product_name": "C# Analyzer", "url": "https://mongodb.com/docs/mongodb-analyzer/current/faq", "title": "Frequently Asked Questions", "text": "# Frequently Asked Questions\n\n## Does the C# Analyzer support JetBrains Rider?\n\nNo, the C# Analyzer does not officially support JetBrains Rider.\n\nWe have internally tested the C# Analyzer on JetBrains Rider and have seen some success though. We welcome you to test the C# Analyzer on your JetBrains Rider deployment, and if you encounter any problems feel free to file an issue on JIRA or submit a pull request on the MongoDB C# Analyzer Github repository.\n\n## Is the C# Analyzer a Roslyn Analyzer?\n\nYes, the C# Analyzer is a Roslyn Analyzer.\n\nTo learn more about Roslyn Analyzers, see Overview of Source Code Analysis from Microsoft.\n\n## Does the C# Analyzer Use Custom Serialization Settings?\n\nNo, the C# Analyzer does not use the custom serialization settings you specify for your MongoDB .NET/C# Driver.\n\nTo learn more about custom serialization settings, see Serialization in the .NET/C# driver documentation.\n\n## Does the C# Analyzer use custom LINQ settings?\n\nNo, the C# Analyzer does not use custom LINQ settings.\n\nTo learn more about custom LINQ settings, see How to add custom methods for LINQ queries from Microsoft.\n\n## What information does the C# Analyzer collect through telemetry?\n\nWhen you have telemetry enabled the C# Analyzer collects and sends anonymized information to MongoDB Inc. The following subsections list all information the C# Analyzer collects.\n\nTo learn how to disable telemetry, see the Configuration guide.\n\n### Your Code\n\nThe following is the information the C# Analyzer collects about your code:\n\n- The number of user-defined data types in your mapping\n\n- The number of unsupported LINQ and builder expressions the C# Analyzer found in your code\n\n- The number of LINQ and builder expressions the C# Analyzer found in your code\n\n- The number of MQL expressions the C# Analyzer found in your code\n\n- How long it took for the C# Analyzer to analyze your code\n\n- The number of exceptions the C# Analyzer encountered analyzing your code\n\n- The length of the syntax tree the C# Analyzer processed\n\n### Your Environment\n\nThe following is the information the C# Analyzer collects about your environment:\n\n- Your operating system\n\n- The version of the C# Analyzer you use\n\n- The internal .NET version your IDE or build utility uses to run the C# Analyzer\n\n- The version of the C# language you use\n\n- The version of the MongoDB .NET/C# Driver you use in your project\n\n- The target platform you use to compile your C# code (AnyCPU/x64/x32)\n\n- The output assembly kind generated by your .NET application\n\n- A unique identifier the C# Analyzer constructs from a hash of the following components of your Net User:\n\n - `UserName`\n\n - `/domain`\n\n### Your MongoDB C# Analyzer Configuration\n\nThe following is the information the C# Analyzer collects about your C# Analyzer configuration:\n\n- If you have logs enabled for the C# Analyzer\n\n- The LINQ provider version your C# Analyzer uses"} -{"chunk_id": "6a5878fec2014ca239cc44d3-0", "page_id": "6a5878fec2014ca239cc44d3", "source_name": "voyageai", "product_name": "Voyage AI", "url": "https://mongodb.com/docs/voyageai/management/azure-foundry", "title": "Deploy Voyage AI by MongoDB Models Using Azure AI Foundry", "text": "# Deploy Voyage AI by MongoDB Models Using Azure AI Foundry\n\nYou can use Azure AI Foundry to discover and deploy Voyage AI by MongoDB models in your Azure environment. Azure AI Foundry provides an Azure-native path for model discovery, deployment, billing, and access management.\n\nUsing Voyage AI through Azure AI Foundry provides the following benefits:\n\n1. **Data flow and access control.** Azure AI Foundry supports private networking and Azure-native access controls so you can align model access with your Azure network and security requirements. For private setups, validate the specific deployment mode and networking configuration that your Foundry project uses in the Azure portal.\n\n2. **Reliability and compliance backed by Azure.** Billing, identity, and infrastructure controls are managed through Azure.\n\n3. **Procurement and billing through Azure.** You can use your Azure subscription, billing relationship, and applicable credits instead of establishing a separate commercial relationship for model hosting.\n\n## Available Models\n\nTo see the Voyage AI by MongoDB models currently available in Azure AI Foundry, open the Voyage AI publisher page in Azure AI Foundry.\n\nModel availability can change over time. To learn more about Voyage AI model capabilities and recommended use cases, see Voyage AI Embedding and Reranking Models Overview.\n\n## Pricing\n\nAzure AI Foundry pricing depends on the deployment type that Azure uses for the selected Voyage AI model and the region in which you deploy it.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nPricing component\n\n\nWhat to expect\n\n
\nAzure subscription billing\n\n\nCharges are billed through your Azure subscription.\n\n
\nModel cost\n\n\nThe Azure AI Foundry deployment UI shows the pricing details for the selected model or deployment option before you deploy.\n\n
\nInfrastructure cost\n\n\nDedicated or managed compute deployments can include hourly infrastructure charges that vary by accelerator SKU and region.\n\n
\nRegion sensitivity\n\n\nTotal cost can vary by Azure region and deployment configuration.\n\n
Azure AI Foundry offers two deployment billing models:\n\n- **Standard Foundry deployments** are typically billed by token usage or provisioned throughput, depending on the deployment type.\n\n- **Managed compute deployments** are billed hourly per accelerator SKU.\n\nThe Azure portal or Azure AI Foundry deployment flow is the source of truth for the exact price shown at deployment time. For more information, see Microsoft documentation for deployment options in Azure AI Foundry and the Azure pricing calculator.\n\n## Prerequisites\n\nBefore you deploy a Voyage AI model through Azure AI Foundry, ensure that you have the following:\n\n- An active Azure subscription.\n\n- Permissions to create or use Azure AI Foundry resources in the target subscription.\n\n- Access to an Azure AI Foundry project, or permission to create one.\n\n- Sufficient quota in the target region for the deployment type that Azure AI Foundry requires for the selected Voyage AI model.\n\n- An Azure AI hub resource in the same region where you plan to deploy the Voyage AI model through Azure AI Foundry. For setup guidance, see Microsoft documentation for creating hubs and projects.\n\n- If your organization requires private networking, an existing virtual network and the Azure permissions needed to create and approve any required private endpoint connections.\n\n## Quota\n\nThis section includes guidance on how to verify and request quota before deployment.\n\nThe quota model in Azure AI Foundry depends on the deployment type:\n\n- Some deployment paths use Azure AI Foundry quotas rather than Azure virtual machine quotas.\n\n- Other deployment paths might surface infrastructure-oriented sizing and region availability choices in the deployment flow.\n\nBecause Azure AI Foundry can route different model families through different deployment modes, verify quota from the Azure portal and the Azure AI Foundry deployment UI before you begin.\n\n### Check Quota\n\n#### Sign in to the portal.\n\nSign in to the Azure portal.\n\n#### Open your subscription.\n\nOpen the subscription that you plan to use.\n\n#### Review quota settings.\n\nReview quota-related settings for the services and regions involved in your Foundry deployment.\n\n#### Start the deployment flow.\n\nIn Azure AI Foundry, begin the deployment flow for the Voyage AI model that you want to use, and review any quota or capacity requirements shown in the UI.\n\n#### Confirm capacity.\n\nConfirm that the target region has sufficient capacity for the selected deployment option.\n\nFor Azure AI Foundry quota guidance, see Microsoft documentation on deployment options.\n\n### Request Quota Increase\n\nIf you don't have sufficient quota or capacity:\n\n- Use the Azure portal to request the relevant quota increase for the required service or region.\n\n- If the deployment flow indicates Azure AI Foundry-specific quota requirements, follow the quota workflow linked from the Azure UI.\n\n- Retry the deployment after the increase is approved.\n\nBecause Azure AI Foundry deployment types evolve, use the Azure portal and deployment workflow as the source of truth for the exact quota process.\n\n## Prepare Networking\n\nIf your organization does not require private networking, you can use the default Azure AI Foundry networking options that the deployment supports.\n\nIf your organization requires private connectivity, prepare your networking before deployment:\n\n- Identify the virtual network and subnet that your Azure AI Foundry project or client applications will use.\n\n- Confirm that you have permission to create private endpoints and approve private endpoint connections if your organization uses them.\n\n- Confirm DNS resolution and routing requirements for private access.\n\n- Validate any outbound access policies that your applications, validation hosts, or agent tools require.\n\nFor Azure AI Foundry private networking guidance, see Microsoft documentation on network isolation for Azure AI Foundry.\n\n## Deploy a Voyage AI Model in Azure AI Foundry\n\nIn this section, you deploy a Voyage AI by MongoDB model from Azure AI Foundry.\n\nBecause Voyage AI is provided in Azure AI Foundry as a third-party managed compute offering, Azure uses a deployment wizard that provisions GPU-backed infrastructure and deploys the selected Voyage AI model on top of it.\n\n### Navigate to the portal.\n\nOpen the Azure AI Foundry portal.\n\n### Turn off New Foundry.\n\nToggle New Foundry to the left (off position).\n\n### Open the model catalogue.\n\nIn the left sidebar, select Model Catalogue.\n\n### See all models.\n\nClick See All Models.\n\n### Find the Voyage models.\n\nSearch for the Voyage series of models.\n\n### Select a model.\n\nSelect the model card for your desired model.\n\n### Use the model.\n\nClick Use this model.\n\n### Select a project.\n\nSelect the project in which you want to use the model.\n\n### Create the deployment.\n\nClick Create.\n\n### Deploy the model.\n\nFollow the instructions in the Deployment Wizard, then click Deploy.\n\nThe Azure AI Foundry portal selects the appropriate deployment path for the chosen model. Depending on the model and Azure's current integration for that listing, this can affect the fields you see during deployment and the way you connect to the deployed model."} -{"chunk_id": "6a5878fec2014ca239cc44d3-1", "page_id": "6a5878fec2014ca239cc44d3", "source_name": "voyageai", "product_name": "Voyage AI", "url": "https://mongodb.com/docs/voyageai/management/azure-foundry", "title": "Deploy Voyage AI by MongoDB Models Using Azure AI Foundry", "text": "### Deployment Settings\n\nReview the following settings carefully during deployment:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nSetting\n\n\nGuidance\n\n
\nSubscription\n\n\nUse the Azure subscription that should receive billing for the deployment.\n\n
\nProject\n\n\nUse the Azure AI Foundry project that should own the model deployment.\n\n
\nRegion\n\n\nChoose a supported region with sufficient capacity and the networking profile your organization requires.\n\n
\nDeployment type\n\n\nUse the deployment type offered by Azure for the selected Voyage AI model.\n\n
\nAuthentication\n\n\nUse the project keys that Azure AI Foundry provides for the deployment.\n\n
\nNetworking\n\n\nIf required, apply private networking or private endpoint settings supported by your Foundry resource and project.\n\n
\n\n### Confirm Completion\n\nAfter the deployment succeeds:\n\n- Open the deployed model or deployment details page in Azure AI Foundry.\n\n- Capture the endpoint information, deployment name, authentication method, and any region or networking details you need for clients.\n\n- Record whether the deployment uses the unified Azure AI Foundry project endpoint or another Azure-managed connection pattern exposed by the portal.\n\n## Connection Details\n\nAzure AI Foundry connection details depend on the deployment mode that Azure uses for the selected model. Use the deployment details page in Azure AI Foundry as the source of truth.\n\nAfter deployment, capture the following values from Azure AI Foundry:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nValue\n\n\nWhy you need it\n\n
\nProject endpoint or model endpoint\n\n\nYour client uses this base URL to send inference requests.\n\n
\nDeployment name\n\n\nSome SDKs and API routes require a deployment identifier.\n\n
\nAuthentication method\n\n\nYou need the keys or tokens that Azure AI Foundry provides for the deployment.\n\n
\nRegion\n\n\nUseful for governance, troubleshooting, and latency expectations.\n\n
\nNetworking constraints\n\n\nIndicates whether clients must connect from approved networks or through private access.\n\n
Azure AI Foundry commonly exposes one of the following connection patterns:\n\n- **Unified Foundry project endpoint.** Some Azure AI Foundry deployments are invoked through the project's unified endpoint, with the deployment name supplied in the request path or payload.\n\n- **Private or network-isolated access.** If your Foundry project is configured for private access, clients must run from approved networks and resolve Azure private endpoints correctly.\n\n### Authentication\n\nUse the authentication method shown in Azure AI Foundry for the deployed model. Voyage AI model deployments currently support key-based authentication only:\n\n- Azure AI Foundry project keys or other key-based credentials that the deployment exposes.\n\n## Verify Connectivity\n\nAfter deployment, verify that your application can connect to the deployed model.\n\n### Open the deployment page.\n\nOpen the deployment details page in Azure AI Foundry.\n\n### Copy the connection details.\n\nCopy the endpoint and authentication information.\n\n### Send a test request.\n\nSend a small test request using the Azure-provided sample code, SDK example, or API playground shown for the deployment, and confirm that the response succeeds and that the returned model metadata matches the deployment you created.\n\nIf your deployment uses private networking, also do the following:\n\n- Run the test from a client inside the approved network boundary.\n\n- Validate DNS resolution to the expected private endpoint, if applicable.\n\n- Confirm that firewall, subnet, and private endpoint settings allow the request.\n\nFor private networking validation, see Microsoft documentation on network isolation for Azure AI Foundry.\n\n### Example Validation Workflow\n\nUse the following workflow to validate the deployment end to end:\n\n#### Deploy the model.\n\nDeploy the model in Azure AI Foundry.\n\n#### Note the connection details.\n\nOpen the deployment page and note the endpoint, deployment name, and authentication requirements.\n\n#### Run an embeddings request.\n\nRun a single embeddings request with a small sample string.\n\n#### Confirm the response.\n\nConfirm that the request returns embeddings successfully.\n\n#### Record the connection pattern.\n\nRecord the exact connection pattern that Azure exposed so your production application can follow the same path.\n\n### Troubleshooting\n\nIf you can't connect to the deployment:\n\n- Confirm that the model deployment completed successfully.\n\n- Confirm that you are using the correct endpoint and deployment name.\n\n- Confirm that your authentication method matches the one shown in Azure AI Foundry.\n\n- If private networking is enabled, confirm DNS, private endpoint approval, subnet routing, and firewall configuration.\n\n- If the deployment failed before completion, review Azure quota, region availability, and any capacity limits shown in the deployment flow.\n\n## Delete a Voyage AI Deployment\n\nTo avoid ongoing charges, delete model deployments that you no longer need.\n\n### Open your project.\n\nOpen your Azure AI Foundry project.\n\n### Find the deployment.\n\nFind the deployed Voyage AI model.\n\n### Delete the deployment.\n\nDelete the deployment from the Azure UI and confirm deletion.\n\nIf your setup includes private endpoints or other supporting network resources that were created only for this deployment, review whether they should also be removed."} -{"chunk_id": "6997fd706fd39a1e7ec5ab6c-0", "page_id": "6997fd706fd39a1e7ec5ab6c", "source_name": "voyageai", "product_name": "Voyage AI", "url": "https://mongodb.com/docs/voyageai/management/rate-limits", "title": "Manage Rate Limits", "text": "# Manage Rate Limits\n\nRate limits are restrictions on the frequency and number of tokens you can request from Voyage AI within a specified period of time. To learn more about rate limits, see Best Practices.\n\nAtlas enforces rate limits based on the model API key usage (requests per minute (RPM) and tokens per minute (TPM)). If you exceed the number of requests or tokens in the most recent minute, the API (Application Programming Interface) denies any subsequent additional request and returns a `429` (Rate Limit Exceeded) HTTP status code.\n\n## Manage Rate Limits\n\nThe following sections describe how to manage rate limits in the Atlas UI.\n\n### Required Permissions\n\nTo set and reset rate limits at the project level, you must have `Project Owner` access or higher to Atlas.\n\nTo view rate limits:\n\n- At the organization and project levels, you must have `Organization Read Only` or higher access to Atlas.\n\n- At only the project level, you must have `Project Read Only` or higher access to Atlas.\n\n### Set Rate Limits\n\nYou can set different limits for each project at the project level. Project level rate limits can't exceed the rate limits for the organization. Rate limits set at the project level apply to all model API keys for the project.\n\n#### Log in to Atlas.\n\n#### Go to the AI Model APIs page in the Atlas UI.\n\n- If it's not already displayed, select your desired organization from the Organizations menu in the navigation bar.\n\n- If it's not already displayed, select your desired project from the Projects menu in the navigation bar.\n\n- At the project level, click AI Model APIs under the Services header in the navigation bar.\n\n#### Set the rate limits for the project.\n\n- From the navigation bar, select Rate Limits.\n\n- In the Actions column corresponding to the embeddings model for which you want to modify rate limits, click .\n\n- Modify the TPM (Tokens Per Minute) and RPM (Requests Per Minute) values.\n\n Project-level rate limits for each model can be any value less than or equal to the organization's rate limit.\n\n At usage tier 1, rate limits for the `voyage-4` embedding model for a project can be set to `2000` RPM and `8,000,000` TPM, or lower.\n\n- Click to apply the rate limit.\n\n### View Rate Limits\n\nYou can view the rate limits at the organization and project levels.\n\n\n\n\n\nRate Limits#### Log in to Atlas.\n\n#### Go to the AI Model APIs page in the Atlas UI.\n\n- If it's not already displayed, select your desired organization from the Organizations menu in the navigation bar.\n\n- At the organization level, click Rate Limits under the Services header in the navigation bar.\n\nThe page displays the following information:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nName\n\n\nDescription\n\n
\nModel\n\n\nList of Voyage AI embedding models.\n\n
\nTokens Per Minute (TPM)\n\n\nNumber of tokens that you can request within a minute from the Embedding and Reranking API endpoints.\n\n
\nRequests Per Min (RPM)\n\n\nNumber of API requests that you can send within a minute to the Embedding and Reranking API endpoints.\n\n
\n\n
\n\n\n\n#### Log in to Atlas.\n\n#### Go to the AI Model APIs page in the Atlas UI.\n\n- If it's not already displayed, select your desired organization from the Organizations menu in the navigation bar.\n\n- If it's not already displayed, select your desired project from the Projects menu in the navigation bar.\n\n- At the project level, click AI Model APIs under the Services header in the navigation bar.\n\n#### Select Rate Limits from the left navigation.\n\nThe page displays the following information about the rate limits:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nColumn Name\n\n\nColumn Description\n\n
\nModel\n\n\nList of Voyage AI embedding models.\n\n
\nTokens Per Minute (TPM)\n\n\nNumber of tokens that you can request within a minute from the Voyage AI Embedding and Reranking API endpoints.\n\n
\nRequests Per Min (RPM)\n\n\nNumber of requests you can send within a minute to the Voyage AI Embedding and Reranking API endpoints.\n\n
\nActions\n\n\nActions you can take. You can:\n\n- Reduce the number of tokens and requests per minute for the project.\n\n- Undo custom number of tokens and requests per minute while setting it.\n\n
If you set custom limits, the page also displays Reset all limits button to revert all the custom rate limits on the page to the default for the organization.\n\n
\n\n
\n\n### Reset All Rate Limits\n\nYou can reset all the custom limits that you set for a project at any time. When you reset the limits, the rate limits for the project revert to the default rate limits for the organization.\n\n#### Log in to Atlas.\n\n#### Go to the AI Model APIs page in the Atlas UI.\n\n- If it's not already displayed, select your desired organization from the Organizations menu in the navigation bar.\n\n- If it's not already displayed, select your desired project from the Projects menu in the navigation bar.\n\n- At the project level, click AI Model APIs under the Services header in the navigation bar.\n\n#### Reset the custom rate limits.\n\n- From the navigation bar, select Rate Limits.\n\n- On the page, click Reset all limits in the top right corner.\n\n## Usage Tiers\n\nRate limits follow a tiered system, with higher tiers offering increased limits. Qualification for a tier is based on billed usage (excluding free tokens). Atlas offers 200 million free tokens for each model. The multimodal models also include 150,000,000,000 free pixels. Once you qualify for a tier, you are never downgraded. As your usage and spending increase, Atlas automatically promotes you to the next usage tier, raising rate limits across all models.\n\nTo learn more, see Rate Limits and Usage Tiers.\n\n## Default Rate Limits\n\nThis section describes the default rate limits for each usage tier that are applied at the organization level. It also describes the rate limits that you can configure for each project."} -{"chunk_id": "6997fd706fd39a1e7ec5ab6c-1", "page_id": "6997fd706fd39a1e7ec5ab6c", "source_name": "voyageai", "product_name": "Voyage AI", "url": "https://mongodb.com/docs/voyageai/management/rate-limits", "title": "Manage Rate Limits", "text": "### Organization Rate Limits\n\nThe following tables show the default rate limits (TPM (Tokens Per Minute) and RPM (Requests Per Minute)) based on usage tier for each Voyage AI embedding model.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nModel\n\n\nTokens Per Min (TPM)\n\n\nRequests Per Min (RPM)\n\n
\n`voyage-4-lite`, `voyage-3.5-lite`\n\n\n16,000,000\n\n\n2,000\n\n
\n`voyage-4`, `voyage-3.5`, `voyage-code-4`\n\n\n8,000,000\n\n\n2,000\n\n
\n`voyage-4-large`, `voyage-context-4`\n\n\n3,000,000\n\n\n2,000\n\n
\n`voyage-3-large`, `voyage-context-3`, `voyage-code-3`, `voyage-code-2`, `voyage-law-2`, `voyage-finance-2`\n\n\n3,000,000\n\n\n2,000\n\n
\n`voyage-multimodal-3.5`, `voyage-multimodal-3`\n\n\n2,000,000\n\n\n2,000\n\n
\n`rerank-3-lite`, `rerank-2.5-lite`, `rerank-2-lite`\n\n\n4,000,000\n\n\n2,000\n\n
\n`rerank-3`, `rerank-2.5`, `rerank-2`\n\n\n2,000,000\n\n\n2,000\n\n
\n\n
\n\n\n\nThe rate limits for Usage Tier 2 are twice those of Usage Tier 1.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nModel\n\n\nTokens Per Min (TPM)\n\n\nRequests Per Min (RPM)\n\n
\n`voyage-4-lite`, `voyage-3.5-lite`\n\n\n32,000,000\n\n\n4,000\n\n
\n`voyage-4`, `voyage-3.5`, `voyage-code-4`\n\n\n16,000,000\n\n\n4,000\n\n
\n`voyage-4-large`, `voyage-context-4`\n\n\n6,000,000\n\n\n4,000\n\n
\n`voyage-3-large`, `voyage-context-3`, `voyage-code-3`, `voyage-code-2`, `voyage-law-2`, `voyage-finance-2`\n\n\n6,000,000\n\n\n4,000\n\n
\n`voyage-multimodal-3.5`, `voyage-multimodal-3`\n\n\n4,000,000\n\n\n4,000\n\n
\n`rerank-3-lite`, `rerank-2.5-lite`, `rerank-2-lite`\n\n\n8,000,000\n\n\n4,000\n\n
\n`rerank-3`, `rerank-2.5`, `rerank-2`\n\n\n4,000,000\n\n\n4,000\n\n
\n\n
\n\n\n\nThe rate limits for Usage Tier 3 are three times those of Usage Tier 1.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nModel\n\n\nTokens Per Min (TPM)\n\n\nRequests Per Min (RPM)\n\n
\n`voyage-4-lite`, `voyage-3.5-lite`\n\n\n48,000,000\n\n\n6,000\n\n
\n`voyage-4`, `voyage-3.5`, `voyage-code-4`\n\n\n24,000,000\n\n\n6,000\n\n
\n`voyage-4-large`, `voyage-context-4`\n\n\n9,000,000\n\n\n6,000\n\n
\n`voyage-3-large`, `voyage-context-3`, `voyage-code-3`, `voyage-code-2`, `voyage-law-2`, `voyage-finance-2`\n\n\n9,000,000\n\n\n6,000\n\n
\n`voyage-multimodal-3.5`, `voyage-multimodal-3`\n\n\n6,000,000\n\n\n6,000\n\n
\n`rerank-3-lite`, `rerank-2.5-lite`, `rerank-2-lite`\n\n\n12,000,000\n\n\n6,000\n\n
\n`rerank-3`, `rerank-2.5`, `rerank-2`\n\n\n6,000,000\n\n\n6,000\n\n
\n\n
\n\n
"} -{"chunk_id": "6997fd706fd39a1e7ec5ab6c-2", "page_id": "6997fd706fd39a1e7ec5ab6c", "source_name": "voyageai", "product_name": "Voyage AI", "url": "https://mongodb.com/docs/voyageai/management/rate-limits", "title": "Manage Rate Limits", "text": "### Project Rate Limits\n\nBy default, projects inherit the rate limits based on the rate limits for the organization. However, you can set different limits for each project at the project level. Project level rate limits can't exceed the rate limits for the organization. Rate limits set at the project level apply to all model API keys for the project. However, if the organization rate limit is reached first, projects might be rate-limited to a lower rate. This can occur when the sum of all project rate limits exceeds the organization limit.\n\nConsider an organization rate limit *O* with three projects with rate limits *P1*, *P2*, and *P3*. The table below illustrates three scenarios where the sum of the project rate limits is less than, equal to, or greater than the organization rate limit. For each scenario, the table indicates whether the organization limit can be reached and whether one project's usage can impact another.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n\n\nScenario 1P1 + P2 + P3 < O\n\n\nScenario 2P1 + P2 + P3 = O\n\n\nScenario 3P1 + P2 + P3 > O\n\n
\nScenario Description\n\n\nSum of all project rate limits is *less than* the organization limit.\n\n\nSum of all project rate limits is *equal to* the organization limit.\n\n\nSum of all project rate limits is *greater than* the organization limit.\n\n
\nCan the organization limit be reached?\n\n\n*No*, even if all projects reach their rate limits, the organization rate limit will not be exceeded.\n\n\n*Yes*, if all projects reach their rate limits, the organization limit will also be reached.\n\n\n*Yes*, as the sum of all project rate limits exceeds the organization limit, the organization limit can be reached before individual projects hit their own limits.\n\n
\nCan one project's usage impact another?\n\n\n*No*.\n\n\n*No*.\n\n\n*Yes*. If projects collectively consume enough usage to reach the organization limit before any or all projects reach their individual limits, projects can be rate-limited to a lower rate than their individual limits.\n\n
\n\n### Geography Rate Limits\n\nScoped endpoints have their own rate limits, separate from the rate limits that apply to the unscoped endpoint. Atlas sets these limits per scope, meaning per combination of cloud provider and Geography. Rate limits for scoped endpoints are the same as those for unscoped endpoints; however, you must request an increase for tier 2 and tier 3 limits for scoped endpoints. Conversely, Atlas automatically applies upgrades for unscoped endpoints.\n\nScoped endpoints also require a paid usage tier. To learn more, see Usage Tiers.\n\nTo learn about Geographies and their endpoints, see Geographies for Voyage AI Inference.\n\n## Best Practices\n\nRate limits ensure a balanced and efficient usage of the API (Application Programming Interface)'s resources, preventing excessive traffic that could impact the overall performance and accessibility of the service. Specifically, rate limits serve the following vital purposes:\n\n- *Rate limits promote equitable access to the API for all users*. If one individual or organization generates an excessive volume of requests, it could potentially impede the API (Application Programming Interface)'s performance for others. Through rate limiting, we ensure that a larger number of users can use the API (Application Programming Interface) without encountering performance issues.\n\n- *Rate limits enable Voyage AI to effectively manage the workload on its infrastructure*. Sudden and substantial spikes in API (Application Programming Interface) requests could strain server resources and lead to performance degradation. By establishing rate limits, Voyage AI can effectively maintain a consistent and reliable experience for all users.\n\n- *They act as a safeguard against potential abuse or misuse of the API*. For instance, malicious actors might attempt to inundate the API (Application Programming Interface) with excessive requests to overload it or disrupt its services. By instituting rate limits, Voyage AI can thwart such nefarious activities.\n\nTo avoid and manage rate limit errors, we recommend the following best practices.\n\n### Use Large Batches\n\nIf you have many documents to embed, you can increase the number of documents you embed per request and increase your overall throughput by sending larger batches. A \"batch\" is the collection of documents you are embedding in one request, and the \"batch size\" is the number of documents in the batch, meaning the length of the list of documents.\n\nSuppose you want to vectorize 512 documents. If you used a batch size of 1, then this would require 512 requests and you could hit your RPM (Requests Per Minute) limit. However, if you used a batch size of 128, then this would require only 4 requests and you would not hit your RPM (Requests Per Minute) limit. You can control the batch size by changing the number of documents you provide in the request, and using larger batch sizes will reduce your overall RPM (Requests Per Minute) for a given number of documents.\n\nYou must consider the API (Application Programming Interface) maximum batch size and tokens when selecting your batch size. You cannot exceed the API (Application Programming Interface) max batch size. If you have longer documents, the token limit per request might constrain you to a smaller batch size.\n\n### Set a Wait Period\n\nMake requests less frequently. You can do this by pacing your requests, and the most straightforward approach is inserting a wait period between each request.\n\n### Perform Exponential Backoff\n\nBackoff once you've hit your rate limit (that is, receive a `429` error). You could wait for an exponentially increased time after receiving a rate limit error before trying again. Wait until the request is successful or until a maximum number of retries is reached.\n\nIf your initial wait time was one second and you got three consecutive rate limit errors before success, you would wait one, two, and four seconds after each rate limit error, respectively, before resending the request."} -{"chunk_id": "6997fd706fd39a1e7ec5ab59-0", "page_id": "6997fd706fd39a1e7ec5ab59", "source_name": "voyageai", "product_name": "Voyage AI", "url": "https://mongodb.com/docs/voyageai/management/monitor-usage", "title": "Monitor Usage", "text": "# Monitor Usage\n\nYou can monitor the usage of your model API keys in the Atlas UI by tracking API requests, token consumption, and costs. Usage monitoring is available at both the organization and project levels.\n\n## View Usage\n\nYou can view your API key usage at the organization or project level.\n\n\n\n\n\nAt the organization level, you can view comprehensive usage metrics across all projects, including free and paid usage, and access billing information.\n\nYou must have `Organization Read Only` or higher access to Atlas.\n\n### Log in to Atlas.\n\n### Go to the Usage page in the Atlas UI.\n\n- If it's not already displayed, select your desired organization from the Organizations menu in the navigation bar.\n\n- At the organization level, click Usage under the AI Model APIs header in the navigation bar.\n\n### Review usage metrics.\n\nThe Usage page displays usage metrics for all model API keys in your organization. The page provides the following tabs:\n\n- Usage Activity: Shows detailed usage metrics and charts for your organization.\n\n- Free Usage: Shows free quota consumption by model.\n\nTo learn more, see Usage Page Features.\n\n\n\n\n\nAt the project level, you can view usage metrics for model API keys within a specific project. This view provides a focused look at usage for a single project.\n\nYou must have `Project Read Only` or higher access to Atlas.\n\n### Log in to Atlas.\n\n### Go to the AI Model APIs page in the Atlas UI.\n\n- If it's not already displayed, select your desired organization from the Organizations menu in the navigation bar.\n\n- If it's not already displayed, select your desired project from the Projects menu in the navigation bar.\n\n- At the project level, click AI Model APIs under the Services header in the navigation bar.\n\n### Click Usage in the navigation bar.\n\n### Review usage metrics.\n\nThe Usage page displays usage metrics for all model API keys in the selected project. This is a simplified version of the organization-level Usage Activity tab, scoped to a single project.\n\nTo learn more, see Usage Page Features.\n\n\n\n\n\n## Usage Page Features\n\nThe Usage page provides several views that you can use to monitor and analyze your Voyage AI usage. The available features vary depending on whether you are viewing usage at the organization or project level.\n\n### Total Usage\n\nIn the Total Usage chart, you can view the total tokens used across your organization or project over time. You can filter usage data by using the following options:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nFilter\n\n\nDescription\n\n\nOrganization Level\n\n\nProject Level\n\n
\nUsage Period\n\n\nSelect the time period for which to view usage data.\n\n\n\u2713\n\n\n\u2713\n\n
\nProjects\n\n\nFilter by specific projects in your organization.\n\n\n\u2713\n\n\n\n
\nModels\n\n\nFilter by specific Voyage AI models.\n\n\n\u2713\n\n\n\u2713\n\n
You can also toggle between Tokens and Pixels to view usage measured in tokens processed or pixels processed (applies to multimodal models).\n\n### Additional Views\n\nThe Usage page also provides the following views to help you monitor and analyze your Voyage AI usage:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nFeature\n\n\nDescription\n\n\nOrganization Level\n\n\nProject Level\n\n
\nFree Usage tab\n\n\nClick the Free Usage tab to view remaining free quota by model.\n\n\n\u2713\n\n\n\n
\nTop Keys by API Requests\n\n\nShows which model API keys are generating the most API requests.\n\n\n\u2713\n\n\n\u2713\n\n
\nTop Projects by API Requests\n\n\nDisplays which projects are making the most API requests.\n\n\n\u2713\n\n\n\n
\n\n### Usage by Geography\n\nAtlas tags every request with the Geography that served it. You can filter your usage data by Geography and segment it by Geography to see how much of your usage each Geography accounts for.\n\nTo learn about Geographies and their endpoints, see Geographies for Voyage AI Inference.\n\n### Export and Billing\n\nYou can also use the Usage page to export usage data and access billing information:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nFeature\n\n\nDescription\n\n\nOrganization Level\n\n\nProject Level\n\n
\nDownload CSV button\n\n\nDownload usage data in CSV format.\n\n\n\u2713\n\n\n\u2713\n\n
\nView Invoice button\n\n\nOpen the organization's billing invoice.\n\n\n\u2713\n\n\n\n
"} -{"chunk_id": "6997fd706fd39a1e7ec5ab6f-0", "page_id": "6997fd706fd39a1e7ec5ab6f", "source_name": "voyageai", "product_name": "Voyage AI", "url": "https://mongodb.com/docs/voyageai/management/gcp-marketplace", "title": "Deploy Voyage AI Models Using Model Garden on Gemini Enterprise Agent Platform", "text": "# Deploy Voyage AI Models Using Model Garden on Gemini Enterprise Agent Platform\n\nYou can explore and deploy Voyage AI by MongoDB models from Model Garden on Gemini Enterprise Agent Platform, formally GCP Vertex AI.\n\nModel Garden manages licenses for Voyage AI by MongoDB models and provides deployment options using either on-demand hardware or your existing Compute Engine reservations.\n\nVoyage AI by MongoDB models are self-deployed partner models, meaning you pay for both the model usage and the Gemini Enterprise Agent Platform infrastructure consumed. Gemini Enterprise Agent Platform handles deployment and provides endpoint management features.\n\n## Available Models\n\nTo see which models you can deploy, search for \"Voyage\" in the Model Garden on Gemini Enterprise Agent Platform.\n\nTo learn more about Voyage AI models, see Voyage AI Embedding and Reranking Models Overview.\n\n## Pricing\n\nPricing for Voyage AI by MongoDB models in Model Garden on Gemini Enterprise Agent Platform includes:\n\n- **Model Usage fee**: A cost for using the Voyage AI model container, billed at an hourly rate. The usage fee depends on the specific model and the hardware configuration you choose for deployment. For detailed pricing information, see the pricing section on the model's listing page in the Google Cloud Marketplace.\n\n- **Google Cloud underlying instance in your region**: The cost of the underlying Google Cloud GPU instance, such as NVIDIA L4, A100, or H100) that is specific to a region, is billed monthly and priced per vCPU. To learn more, see Google Cloud Compute Engine pricing.\n\nAll billing charges appear as the use of Gemini Enterprise Agent Platform on your Google Cloud bill.\n\nTo view pricing for a specific Voyage AI model:\n\n### Go to Model Garden.\n\n### Search for the model.\n\nSearch for the model in the Model Garden search box.\n\n### Click the model.\n\nClick the model you want to view to open its details page.\n\n### Navigate to the pricing section.\n\nIn the Overview tab, scroll to the Pricing section.\n\n### View detailed pricing.\n\nClick the link that leads to the model's Google Cloud Marketplace listing. The Pricing tab in the listing entry displays detailed pricing information.\n\n## Quotas\n\nWhen you deploy Voyage AI models, you consume Gemini Enterprise Agent Platform resources that are subject to quotas. You can view and manage your quotas in the Quotas section of the Google Cloud Console's IAM page. For more information, see View the quotas for your project. In the same page, you can right-click any current quota, click Edit quota, and submit a request to increase your quota if needed.\n\n## Prerequisites\n\nTo get started using the Voyage AI by MongoDB models through Gemini Enterprise Agent Platform, you must:\n\n- Set up a Google Cloud project and a development environment. For instructions, see Set up your project and development environment.\n\n- Enable the Gemini Enterprise Agent Platform API. For instructions, see Setup.\n\n## Hardware Configuration\n\nEach model in the Model Garden lists its recommended hardware configuration. Consult Model Garden on Gemini Enterprise Agent Platform for each Voyage model's recommended hardware specifications.\n\nFor example, for the voyage-4 model, use the following recommended instances that Model Garden on Gemini Enterprise Agent Platform suggests for deployment. These recommendations may change and we recommend that you consult the official Model Garden on Gemini Enterprise Agent Platform page for a particular Voyage AI model to see its recommended hardware.\n\n- **A2 instances**, such as `a2-highgpu-1g` or `a2-ultragpu-1g`, with A100 GPUs are the default choice.\n\n- **A3 instances**, such as `a3-highgpu-1g`, with H100 GPUs are recommended for higher performance needs.\n\n## Supported Regions\n\nThe Model Garden lists supported regions for each Voyage AI model. If you need support in another region for any of the models, contact MongoDB support.\n\n## Best Practices and Limitations\n\n- **Endpoint Type**: All Voyage AI models require a dedicated public endpoint type. For more information, see Choose an endpoint type.\n\n- **Understand input_type: Query vs. Document**: The `input_type` parameter optimizes embeddings for retrieval tasks. Use `\"query\"` for search queries and `\"document\"` for content being searched. This optimization improves retrieval accuracy. To learn more about the `input_type` parameter, see the Embedding and Reranking API Overview.\n\n- **Use Different Output Dimensions**: Voyage 4 models support multiple output dimensions: 256, 512, 1024 (default), and 2048. Smaller dimensions reduce storage and computation costs, while larger dimensions may provide better accuracy. Choose the dimension that best balances your accuracy requirements with resource constraints.\n\n## Locate the Voyage AI Models\n\nTo find Voyage AI by MongoDB models in the Model Garden:\n\n### Go to Model Garden.\n\nGo to the Model Garden console.\n\n### Search for Voyage models.\n\nIn the Search Models field, enter \"Voyage\" to display the list of Voyage AI by MongoDB models.\n\nThe Google Cloud Marketplace has two search boxes: one for the entire Marketplace and one within Model Garden on Gemini Enterprise Agent Platform. To locate Voyage AI by MongoDB models, use the search box on Model Garden on Gemini Enterprise Agent Platform.\n\nAlternatively, you can navigate to Voyage AI models through Model Garden > Model Collections > Partner Models, and then select any of the Voyage AI models listed there.\n\nYou can also scroll down to Task-specific solutions to find Voyage AI models that you can use as-is or customize to your needs.\n\n## Deploy a Voyage AI Model in Gemini Enterprise Agent Platform\n\nTo make predictions using a Voyage AI by MongoDB model, you must deploy it to a private dedicated endpoint for online inferences. Deployment associates physical resources with a model for low-latency and high-throughput online predictions. You can deploy multiple models to one endpoint, or the same model to multiple endpoints.\n\nWhen you deploy a model, consider the following options:\n\n- Endpoint location\n\n- Model container\n\n- Compute resources required to run the model\n\nOnce you deploy a model, you can't change these settings. If you need to modify any deployment configuration, you must undeploy the model and redeploy it with the new settings.\n\nVoyage AI models require a dedicated public endpoint. For more information, see Create a public endpoint in the Gemini Enterprise Agent Platform documentation.\n\nTo deploy a model in Gemini Enterprise Agent Platform using the console:\n\n### Locate the model.\n\nGo the Model Garden console and search for \"Voyage\" in the Search Models field to display the list of Voyage AI by MongoDB models.\n\n### Click the model you want to deploy to open its details page.\n\n### Enable the model and accept the agreement.\n\nClick Enable. The MongoDB Marketplace End User Agreement opens. Review and accept the agreement to enable the model and get the necessary commercial use licenses.\n\n### Review deployment options.\n\nAfter you accept the agreement, the model page displays the following options:\n\n- Deploy a model: Saves the model to the Model Registry and deploys it to an endpoint in Google Cloud. Continue with the following steps to deploy using the console.\n\n- Create an Open Notebook for Voyage Embedding Models Family: Lets you fine-tune and customize your model in a collaborative environment, and mix and match models for optimal cost and performance. See Vertex AI Notebook Samples for Voyage AI.\n\n- View Code: Displays code samples for deploying and using the model. To deploy programmatically using code, see Deploy Using Code.\n\n### Review model details.\n\nReview the model's regions, hardware requirements, considerations, use cases, and pricing information.\n\n### Click Deploy model.\n\nClick the Deploy model button to start the deployment process."} -{"chunk_id": "6997fd706fd39a1e7ec5ab6f-1", "page_id": "6997fd706fd39a1e7ec5ab6f", "source_name": "voyageai", "product_name": "Voyage AI", "url": "https://mongodb.com/docs/voyageai/management/gcp-marketplace", "title": "Deploy Voyage AI Models Using Model Garden on Gemini Enterprise Agent Platform", "text": "### Fill out the deployment form.\n\nA form opens that allows you to review and edit the deployment options. Gemini Enterprise Agent Platform provides default settings that are optimized for the model, but you can customize them as needed. For example, you can select the machine type, GPU type, and number of replicas. The following example shows default settings for the voyage-4 model, but these may change, so review the settings carefully before deploying.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nField\n\n\nDescription\n\n
\nResource ID\n\n\nSelect from the dropdown menu (preselected).\n\n
\nModel Name\n\n\nSelect from the dropdown menu (preselected).\n\n
\nRegion\n\n\nSelect your desired region, such as `us-central1`.\n\n
\nEndpoint name\n\n\nProvide a name for your endpoint, such as `mongodb_voyage-4_latest-mg-one-click-deploy`.\n\n
\nServing spec\n\n\nSelect the machine type, such as `g2-standard-4`.\n\n
\nAccelerator type\n\n\nSelect the GPU type, such as `NVIDIA_L4`.\n\n
\nAccelerator count\n\n\nSpecify the number of GPUs, such as `1`.\n\n
\nReplica count\n\n\nSpecify the minimum and maximum number of replicas, such as `1 - 1`.\n\n
\nReservation type\n\n\nSelect reservation type, such as `No reservation`.\n\n
\nVM provisioning model\n\n\nSelect provisioning model, such as `Standard`.\n\n
\nEndpoint access\n\n\nSelect Public (Dedicated endpoint).\n\n
\n\n### Review settings.\n\nGemini Enterprise Agent Platform optimizes the settings that appear, which are applied by default. To customize your settings, click Edit settings. For example, you can select a more powerful machine type or GPU.\n\n### Check quotas.\n\nThe configuration screen shows you the quotas you have available. Use the link to Quotas for managing quotas if needed.\n\n### Deploy the model.\n\nClick Deploy to start the deployment process.\n\n### Wait for completion.\n\nYou will receive a notification when deployment completes. After deployment completes, you can click Gemini Enterprise Agent Platform, Deploy, Endpoints list to find your deployment.\n\n## Deploy Using Code\n\nIf you selected View Code from the model details page, you can deploy a model programmatically using the Vertex AI SDK. This approach provides full control over deployment configuration through code.\n\nFor more information about the Google Cloud Vertex AI SDK, see the Vertex AI SDK for Python documentation.\n\nThe code examples in this section are for the voyage-4 model and are subject to change. For the most current code examples, consult the View Code tab on the model's page in the Model Garden. For other Voyage AI models, the code is similar, but check that model's page in the Model Garden for model-specific details.\n\nTo deploy a model using code:\n\n### Initialize the model.\n\nFirst, initialize the model from Model Garden and view deployment options:\n\n```python\nfrom vertexai import model_garden\n\nMODEL_NAME = \"mongodb/voyage-4@latest\"\nmodel = model_garden.OpenModel(MODEL_NAME)\n\ndeploy_options = model.list_deploy_options(concise=True)\nprint(deploy_options)\n```\n\n### Deploy to an endpoint.\n\nChoose whether to deploy a new model or use an existing endpoint:\n\n```python\n# Choose whether to deploy a new model or use an existing endpoint:\ndeployment_option = \"deploy_new\" # [\"deploy_new\", \"use_existing\"]\n\n# If using existing endpoint, provide the endpoint ID:\nENDPOINT_ID = \"\" # {type:\"string\"}\n\nif deployment_option == \"deploy_new\":\n print(\"Deploying new model...\")\n endpoint = model.deploy(\n machine_type=\"a3-highgpu-1g\",\n accelerator_type=\"NVIDIA_H100_80GB\",\n accelerator_count=1,\n accept_eula=True,\n use_dedicated_endpoint=True,\n )\n print(f\"Endpoint deployed: {endpoint.display_name}\")\n print(f\"Endpoint resource name: {endpoint.resource_name}\")\nelse:\n if not ENDPOINT_ID:\n raise ValueError(\"Please provide an ENDPOINT_ID when using existing endpoint\")\n\n from google.cloud import aiplatform\n\n print(f\"Connecting to existing endpoint: {ENDPOINT_ID}\")\n endpoint = aiplatform.Endpoint(\n endpoint_name=f\"projects/{PROJECT_ID}/locations/{LOCATION}/endpoints/{ENDPOINT_ID}\"\n )\n print(f\"Using endpoint: {endpoint.display_name}\")\n print(f\"Endpoint resource name: {endpoint.resource_name}\")\n```\n\nSet `use_dedicated_endpoint` to `True` as Voyage AI models require a dedicated public endpoint.\n\nGemini Enterprise Agent Platform deploys the model to a managed endpoint that you can access to make online inferences or batch inferences through the Google Cloud console or the Gemini Enterprise Agent Platform API.\n\nFor more information, see Deploy a model to an endpoint in the Gemini Enterprise Agent Platform documentation.\n\n### Make predictions.\n\nAfter deployment, you can make predictions using the Gemini Enterprise Agent Platform endpoint.\n\nFor all endpoint parameters and prediction options, see the Embedding and Reranking API Overview.\n\n```python\nimport json\n\n# Multiple texts to embed\ntexts = [\n \"Machine learning enables computers to learn from data.\",\n \"Natural language processing helps computers understand human language.\",\n \"Computer vision allows machines to interpret visual information.\",\n \"Deep learning uses neural networks with multiple layers.\"\n]\n\n# Prepare the batch request and make invoke call\nbody = {\n \"input\": texts,\n \"output_dimension\": 1024,\n \"input_type\": \"document\"\n}\n\nresponse = endpoint.invoke(\n request_path=\"/embeddings\",\n body=json.dumps(body).encode(\"utf-8\"),\n headers={\"Content-Type\": \"application/json\"}\n)\n\n# Extract embeddings\nresult = response.json()\nembeddings = [item[\"embedding\"] for item in result[\"data\"]]\n\nprint(f\"Number of texts embedded: {len(embeddings)}\")\nprint(f\"Embedding dimension: {len(embeddings[0])}\")\nprint(f\"\\nFirst embedding (first 5 values): {embeddings[0][:5]}\")\nprint(f\"Second embedding (first 5 values): {embeddings[1][:5]}\")\n```\n\n## Undeploy a Model and Delete the Endpoint\n\nTo remove a deployed model and its endpoint:\n\n1. Undeploy the model from the endpoint.\n\n2. Optionally delete the endpoint itself.\n\nFor detailed instructions, see Undeploy a model and delete the endpoint in the Gemini Enterprise Agent Platform documentation.\n\nYou can delete the endpoint only after all models have been undeployed from it. Undeploying models and deleting the endpoint stops all inference services and billing for that endpoint."} -{"chunk_id": "6997fd706fd39a1e7ec5ab7b-0", "page_id": "6997fd706fd39a1e7ec5ab7b", "source_name": "voyageai", "product_name": "Voyage AI", "url": "https://mongodb.com/docs/voyageai/api-reference/overview", "title": "Embedding and Reranking API Overview", "text": "# Embedding and Reranking API Overview\n\nThe Embedding and Reranking API provides programmatic access to the latest Voyage AI embedding and reranking models through a RESTful interface. This page provides an overview of the API and its features.\n\nFor detailed information and parameters, see the API specification.\n\nYou can create an Atlas Resource Policy to restrict access to the Embedding and Reranking API for all or some projects in your organization. To learn more, see Atlas Resource Policies\n\n## API Key Management\n\nYou use MongoDB Atlas to manage API keys for the Embedding and Reranking API. This includes creating and managing your model API keys across your organization and projects, monitoring usage, and configuring rate limits.\n\nTo learn more, see Manage Voyage AI Model API Keys.\n\nIt is named *model API key* to distinguish it from other API keys in Atlas. You use this key the same way as API keys from other model providers.\n\n## Authentication\n\nAll requests to the Embedding and Reranking API must include an `Authorization` header with your model API key using the Bearer token format.\n\n```http\nAuthorization: Bearer VOYAGE_API_KEY\n```\n\nWhen you use a client SDK, you set the API key when constructing a client, and the SDK sends the header on your behalf with every request. When you integrate directly with the API, you must send this header yourself.\n\n## Endpoints\n\nThe scope of your model API key determines the endpoint that you send requests to. A key scoped to a Geography works only against that Geography's endpoint, and an unscoped key works against the unscoped endpoint.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nEndpoint\n\n\nGeography\n\n
\n`ai.mongodb.com`\n\n\nUnscoped. Atlas can serve the request from any Geography.\n\n
\n`eu.ai.mongodb.com`\n\n\nEurope\n\n
\n`us.ai.mongodb.com`\n\n\nUnited States\n\n
Scoped endpoints follow the pattern `.ai.mongodb.com`, where `` is the `geography` value of the model API key that you send with the request.\n\nIf you send a scoped key to an endpoint that doesn't match its scope, the request fails. Atlas doesn't reroute the request to the endpoint that matches the key.\n\nScoped endpoints differ from the unscoped endpoint in the following ways:\n\n- Atlas charges a 10% uplift on the tokens that you send to a scoped endpoint.\n\n- Scoped endpoints require a paid usage tier and start at usage tier 1. To use a higher usage tier with a scoped endpoint, contact your account team. To learn more about usage tiers, see Usage Tiers.\n\n- Scoped endpoints have their own rate limits, which are lower than those of the unscoped endpoint. To learn more, see Geography Rate Limits.\n\n- Scoped endpoints don't serve every model. To check which endpoints serve a given model, see the Supported Endpoints column of the model tables in Model Deprecations, Lifecycle States, and Support.\n\nTo learn what a Geography is and when to use one, see Geographies for Voyage AI Inference.\n\n## JSON\n\nAll entities are represented in JSON. The following rules and conventions apply:\n\nWhen you send JSON to the server with a POST request, specify the `Content-Type: application/json` header. Client SDKs handle this automatically.\n\nIf you attempt to create a request with invalid JSON, incorrect data types, or constraint violations (such as exceeding token limits or batch sizes), the server responds with a `400` status code and an error message describing the issue.\n\nFields that contain numeric values are named to disambiguate the unit being used. For example, token counts are specified in fields like `total_tokens` and `output_dimension` to clarify the measurement unit."} -{"chunk_id": "6997fd706fd39a1e7ec5ab7b-1", "page_id": "6997fd706fd39a1e7ec5ab7b", "source_name": "voyageai", "product_name": "Voyage AI", "url": "https://mongodb.com/docs/voyageai/api-reference/overview", "title": "Embedding and Reranking API Overview", "text": "## Rate Limits and Usage Tiers\n\nThe Embedding and Reranking API implements rate limiting to ensure fair usage and optimal performance. Rate limits are applied per API key and measured in two dimensions. Your rate limits increase as you advance through usage tiers.\n\n- **TPM (Tokens Per Minute)**: Maximum number of tokens processed per minute\n\n- **RPM (Requests Per Minute)**: Maximum number of API requests per minute\n\nIf you exceed the rate limit, the API returns a `429` (Rate Limit Exceeded) HTTP status code.\n\n\n\n\n\nFree trial rate limits without a payment method are 3 RPM and 10K TPM. To qualify for higher rate limits, add a payment method to your account.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nModel\n\n\nTokens Per Min (TPM)\n\n\nRequests Per Min (RPM)\n\n
\n`voyage-4-lite`, `voyage-3.5-lite`\n\n\n16,000,000\n\n\n2,000\n\n
\n`voyage-4`, `voyage-3.5`, `voyage-code-4`\n\n\n8,000,000\n\n\n2,000\n\n
\n`voyage-4-large`, `voyage-context-4`\n\n\n3,000,000\n\n\n2,000\n\n
\n`voyage-3-large`, `voyage-context-3`, `voyage-code-3`, `voyage-code-2`, `voyage-law-2`, `voyage-finance-2`\n\n\n3,000,000\n\n\n2,000\n\n
\n`voyage-multimodal-3.5`, `voyage-multimodal-3`\n\n\n2,000,000\n\n\n2,000\n\n
\n`rerank-3-lite`, `rerank-2.5-lite`, `rerank-2-lite`\n\n\n4,000,000\n\n\n2,000\n\n
\n`rerank-3`, `rerank-2.5`, `rerank-2`\n\n\n2,000,000\n\n\n2,000\n\n
\n\n
\n\n\n\nThe rate limits for Usage Tier 2 are twice those of Usage Tier 1.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nModel\n\n\nTokens Per Min (TPM)\n\n\nRequests Per Min (RPM)\n\n
\n`voyage-4-lite`, `voyage-3.5-lite`\n\n\n32,000,000\n\n\n4,000\n\n
\n`voyage-4`, `voyage-3.5`, `voyage-code-4`\n\n\n16,000,000\n\n\n4,000\n\n
\n`voyage-4-large`, `voyage-context-4`\n\n\n6,000,000\n\n\n4,000\n\n
\n`voyage-3-large`, `voyage-context-3`, `voyage-code-3`, `voyage-code-2`, `voyage-law-2`, `voyage-finance-2`\n\n\n6,000,000\n\n\n4,000\n\n
\n`voyage-multimodal-3.5`, `voyage-multimodal-3`\n\n\n4,000,000\n\n\n4,000\n\n
\n`rerank-3-lite`, `rerank-2.5-lite`, `rerank-2-lite`\n\n\n8,000,000\n\n\n4,000\n\n
\n`rerank-3`, `rerank-2.5`, `rerank-2`\n\n\n4,000,000\n\n\n4,000\n\n
\n\n
\n\n\n\nThe rate limits for Usage Tier 3 are three times those of Usage Tier 1.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nModel\n\n\nTokens Per Min (TPM)\n\n\nRequests Per Min (RPM)\n\n
\n`voyage-4-lite`, `voyage-3.5-lite`\n\n\n48,000,000\n\n\n6,000\n\n
\n`voyage-4`, `voyage-3.5`, `voyage-code-4`\n\n\n24,000,000\n\n\n6,000\n\n
\n`voyage-4-large`, `voyage-context-4`\n\n\n9,000,000\n\n\n6,000\n\n
\n`voyage-3-large`, `voyage-context-3`, `voyage-code-3`, `voyage-code-2`, `voyage-law-2`, `voyage-finance-2`\n\n\n9,000,000\n\n\n6,000\n\n
\n`voyage-multimodal-3.5`, `voyage-multimodal-3`\n\n\n6,000,000\n\n\n6,000\n\n
\n`rerank-3-lite`, `rerank-2.5-lite`, `rerank-2-lite`\n\n\n12,000,000\n\n\n6,000\n\n
\n`rerank-3`, `rerank-2.5`, `rerank-2`\n\n\n6,000,000\n\n\n6,000\n\n
\n\n
\n\n
\n\nTo learn more about usage tiers, see Usage Tiers.\n\nTo set custom rate limits for your organization, use the Atlas UI. To learn more, see Manage Rate Limits.\n\n## Making Requests\n\nThe following example demonstrates how you can use `cURL` to make a request to the embedding service. You can also use an HTTP client in any programming language to access the API.\n\nFor additional usage examples, see the following resources:\n\n- Accessing Voyage AI Models for HTTP request and client SDK examples\n\n- Model pages for model-specific usage.\n\n- API specification for full details on all API endpoints.\n\n```bash\ncurl \\\n --request POST 'https://ai.mongodb.com/v1/embeddings' \\\n --header \"Authorization: Bearer $VOYAGE_API_KEY\" \\\n --header \"Content-Type: application/json\" \\\n --data '{\n \"input\": [\n \"MongoDB is redefining what a database is in the AI era.\",\n \"Voyage AI embedding and reranking models are state-of-the-art.\"\n ],\n \"model\": \"voyage-4-large\"\n }'\n```\n\n## Errors\n\nTo learn more about errors returned by the API, see the API specification.\n\n## Best Practices\n\nConsider the following best practices when you use the API:\n\n### Specifying Input Type\n\nFor semantic search and retrieval tasks, set the `input_type` to `query` or `document` to optimize how Voyage AI models create the vectors. Do not omit this parameter.\n\nThe parameter adds the following prompts to your input before generating embeddings:\n\n- `query`: \"Represent the query for retrieving supporting documents: \"\n\n- `document`: \"Represent the document for retrieval: \"\n\n`input_type=\"query\"` transforms \"When is Apple's conference call scheduled?\" into \"Represent the query for retrieving supporting documents: When is Apple's conference call scheduled?\"\n\n### Troubleshooting\n\nIf you're using the Python client, you must use version 0.3.7 or later. To check the version of your Python client installation, run the following command in your terminal:\n\n```shell\npython -c \"import voyageai; print(voyageai.__version__)\"\n```"} -{"chunk_id": "6997fd706fd39a1e7ec5ab66-0", "page_id": "6997fd706fd39a1e7ec5ab66", "source_name": "voyageai", "product_name": "Voyage AI", "url": "https://mongodb.com/docs/voyageai/tutorials/migrate-to-atlas", "title": "Migrate Your Applications to use the Atlas Embedding and Reranking API", "text": "# Migrate Your Applications to use the Atlas Embedding and Reranking API\n\nIf you are an existing Voyage AI user, complete the following steps to migrate your application to use the Atlas Embedding and Reranking API.\n\n## Procedure\n\n### Sign up for a free Atlas account or log in.\n\nIf you're new to Atlas, it creates an organization and project for you.\n\nTo learn more, see Create an Atlas Account.\n\n### Create a model API key for your project.\n\n- In your Atlas project, select AI Model APIs from the navigation bar.\n\n- Click Create model API key.\n\n- Give the API key a name and then click Create.\n\n- To confirm your API key is valid, you can make a test request to the Embedding and Reranking API:\n\n ```bash\n curl \\\n --request POST 'https://ai.mongodb.com/v1/embeddings' \\\n --header \"Authorization: Bearer $VOYAGE_API_KEY\" \\\n --header \"Content-Type: application/json\" \\\n --data '{\n \"input\": \"Sample text\",\n \"model\": \"voyage-4-lite\",\n \"input_type\": \"document\"\n }'\n ```\n\nTo learn more about creating and managing API keys, see Manage Voyage AI Model API Keys.\n\n### Replace your existing Voyage API key with the model API key.\n\nFor example, if you set your API key as an environment variable, update the value:\n\n```bash\nVOYAGE_API_KEY=\"\"\n```\n\nIf you pass the API key directly in your code, update the value where you initialize the client or make API requests.\n\nIf you set your API key as an environment variable, you can run the following command to verify the variable is set:\n\n```bash\necho $VOYAGE_API_KEY\n```\n\n### Replace explicit API endpoints with the Embedding and Reranking API endpoints.\n\nIf your application explicitly specifies API endpoints, update it to use the equivalent Embedding and Reranking API API endpoints:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nOld Endpoint\n\n\nNew Endpoint\n\n
\n`https://api.voyageai.com/v1/embeddings`\n\n\n`https://ai.mongodb.com/v1/embeddings`\n\n
\n`https://api.voyageai.com/v1/rerank`\n\n\n`https://ai.mongodb.com/v1/rerank`\n\n
\n`https://api.voyageai.com/v1/multimodalembeddings`\n\n\n`https://ai.mongodb.com/v1/multimodalembeddings`\n\n
\n`https://api.voyageai.com/v1/contextualizedembeddings`\n\n\n`https://ai.mongodb.com/v1/contextualizedembeddings`\n\n
If you use the `voyageai` Python client (version 0.3.7 or later), the client automatically routes requests to the correct endpoint based on the API key format. No endpoint changes are required if you use the client without explicitly setting the `base_url` parameter.\n\nTo learn more, see Python Client.\n\n### Verify that your application works with the new API key.\n\nTest your application to ensure it correctly generates embeddings and performs reranking operations using the Embedding and Reranking API.\n\n### Delete your old Voyage AI API key.\n\nAfter you confirm that your application works with the model API key, delete your old API key from the Voyage AI platform to prevent unauthorized access."} -{"chunk_id": "6997fd706fd39a1e7ec5ab5a-0", "page_id": "6997fd706fd39a1e7ec5ab5a", "source_name": "voyageai", "product_name": "Voyage AI", "url": "https://mongodb.com/docs/voyageai/management/organization-project-access", "title": "Organization and Project Access", "text": "# Organization and Project Access\n\nAn organization is the top-level entity. Billing, teams, and resource policies are managed at the organization level. Rate limits and API keys are also managed at this level but can be further constrained within projects, which are logical grouping of database deployments or clusters, and associated resources. An organization can contain multiple projects.\n\n## Roles and Permissions\n\nYou can manage users and teams for projects at the organization level. You can also assign roles that grant privileges to users at the organization and project levels, including role for creating and deleting model API keys for the project.\n\nFor the complete list of roles and privileges in Atlas that you can grants users at the organization and project levels, see Atlas User Roles.\n\n## Organization-Level Access\n\nThe following table describes the permissions for organization-level roles, which apply at the organization level and all projects in the organization:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nAction\n\n\n`Organization Owner`\n\n\n`Organization Read Only`\n\n
\nView model API keys\n\n\n\u2713\n\n\n\u2713\n\n
\nCreate, edit, or delete model API keys\n\n\n\u2713\n\n\n\n
\nView rate limits\n\n\n\u2713\n\n\n\u2713\n\n
\nConfigure rate limits\n\n\n\u2713\n\n\n\n
\nView API (Application Programming Interface) usage\n\n\n\u2713\n\n\n\u2713\n\n
\nView billing information and controls, including budget limits\n\n\n\u2713\n\n\n\u2713\n\n
\nManage billing information and controls, including budget limits\n\n\n\u2713\n\n\n\n
\n\n## Project-Level Access\n\nThe following table describes the permissions for project-level roles, which apply at the project level only:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nAction\n\n\n`Project Owner`\n\n\n`Project Model Owner`\n\n\n`Project Read Only`\n\n
\nView model API keys\n\n\n\u2713\n\n\n\u2713\n\n\n\u2713\n\n
\nCreate, edit, or delete model API keys\n\n\n\u2713\n\n\n\u2713\n\n\n\n
\nView rate limits\n\n\n\u2713\n\n\n\n\n\u2713\n\n
\nConfigure rate limits\n\n\n\u2713\n\n\n\n\n\n
\nView API (Application Programming Interface) usage\n\n\n\u2713\n\n\n\n\n\u2713\n\n
"} -{"chunk_id": "6997fd706fd39a1e7ec5ab70-0", "page_id": "6997fd706fd39a1e7ec5ab70", "source_name": "voyageai", "product_name": "Voyage AI", "url": "https://mongodb.com/docs/voyageai/models/multimodal-embeddings", "title": "Multimodal Embeddings", "text": "# Multimodal Embeddings\n\nMultimodal embedding models transform unstructured data from multiple modalities into a shared vector space. Voyage multimodal embedding models support text, images, and video, such as figures, photos, slide decks, document screenshots, and video clips. This removes the need for text extraction or ETL pipelines.\n\nUnlike multimodal models like CLIP, which process text, images, and video separately, Voyage multimodal embedding models vectorize inputs containing interleaved text, images, and video. CLIP's architecture prevents it from being usable in mixed-modality searches, as text, image, and video vectors often align with irrelevant items of the same modality. Voyage multimodal embedding models reduce this bias by processing all inputs through a single backbone.\n\n## Available Models\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nModel\n\n\nContext Length\n\n\nDimensions\n\n\nDescription\n\n
\n`voyage-multimodal-3.5`\n\n\n32,000 tokens\n\n\n1024 (default), 256, 512, 2048\n\n\nRich multimodal embedding model that can vectorize interleaved text and visual data, such as screenshots of PDFs, slides, tables, figures, videos, and more.\n\nTo learn more, see the blog post.\n\n
\n\n\n\n\n\n\n\n\n\n\n\n\n
\nModel\n\n\nContext Length\n\n\nDimensions\n\n\nDescription\n\n
\n`voyage-multimodal-3`\n\n\n32,000 tokens\n\n\n1024\n\n\nProcesses text and images into unified embeddings. Supports images from 50,000 to 2 million pixels.\n\nTo learn more, see the blog post.\n\n
\n\n## Tutorial\n\nFor a tutorial on using multimodal embeddings, see Semantic Search with Voyage AI Embeddings.\n\n## Usage\n\nYou can access Voyage multimodal embeddings in Python through the `voyageai` package. Install the `voyageai` package, set up the API key, and use the `voyageai.Client.multimodal_embed()` function to vectorize your inputs.\n\n```python\nvoyageai.Client.multimodal_embed(\n inputs: List[dict] or List[List[Union[str, PIL.Image.Image]]],\n model: str,\n input_type: Optional[str] = None,\n truncation: Optional[bool] = True\n)\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nParameter\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\n`inputs`\n\n\nArray of Objects or Array of Arrays (`List[dict]` or `List[List[Union[str, PIL.Image.Image]]]`)\n\n\nYes\n\n\nList of multimodal inputs to vectorize.\n\nEach input is a sequence of text, images, and video, which can be represented in one of the following ways:\n\n- A dictionary that contains a single key `\"content\"`, whose value represents a sequence of text, images, and video. The dictionary schema is identical to that of an input in the `inputs` parameter of the REST API.\n\n- A list containing text strings and/or PIL image objects (`List[Union[str, PIL.Image.Image]]`), where each image is an instance of the Pillow Image class. For example: `[\"This is a banana.\", PIL.Image.open(\"banana.jpg\")]`.\n\nThe following constraints apply to the `inputs` list:\n\n- The list must not contain more than 1,000 inputs.\n\n- Each image must not contain more than 16 million pixels or be larger than 20 MB in size.\n\n- With every 560 pixels of an image being counted as a token, each input in the list must not exceed 32,000 tokens, and the total number of tokens across all inputs must not exceed 320,000.\n\n
\n`model`\n\n\nString\n\n\nYes\n\n\nName of the model. Accepted values are `voyage-multimodal-3.5` (recommended) and `voyage-multimodal-3`.\n\n
\n`input_type`\n\n\nString\n\n\nNo\n\n\nType of the input text. Defaults to `None`. Valid values: `None`, `query`, `document`.\n\nFor semantic search and retrieval tasks, always specify `input_type` as either `query` or `document` for optimal results.\n\nWhen `input_type` is `None`, the embedding model directly converts the inputs into numerical vectors. If you use a \"query\" to search for relevant information among a collection of data (referred to as \"documents\"), we recommend specifying whether your inputs are intended as queries or documents by setting `input_type` to `query` or `document`, Voyage AI automatically prepends the following prompts to your inputs before vectorizing them, creating vectors more tailored for search and retrieval tasks:\n\n- For `query`, the prompt is \"Represent the query for retrieving supporting documents: \".\n\n- For `document`, the prompt is \"Represent the document for retrieval: \".\n\nWhile embeddings generated with and without the `input_type` argument are technically compatible for comparison, specifying `input_type` significantly improves retrieval accuracy.\n\n
\n`truncation`\n\n\nBoolean\n\n\nNo\n\n\nFlag that specifies whether to truncate the input to fit within the context length. Defaults to `True`.\n\n- If `True`, the system truncates an over-length input to fit within the context length before the embedding model vectorizes it.\n\n- If `False`, the system raises an error if any input exceeds the context length.\n\nIf the truncation happens in the middle of an image, the entire image is discarded.\n\n
\n\nThis method returns a `MultimodalEmbeddingsObject`, which contains the following attributes:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nAttribute\n\n\nType\n\n\nDescription\n\n
\n`embeddings`\n\n\nNested Array of Floats (`List[List[float]]`)\n\n\nList of embeddings for the corresponding list of inputs, where each embedding is a vector represented as a list of floats.\n\n
\n`text_tokens`\n\n\nInteger\n\n\nTotal number of text tokens in the list of inputs.\n\n
\n`image_pixels`\n\n\nInteger\n\n\nTotal number of image pixels in the list of inputs.\n\n
\n`total_tokens`\n\n\nInteger\n\n\nCombined total of text, image, and video tokens. Every 560 pixels counts as a token.\n\n
\n\n### Example\n\n```python\nimport voyageai\nimport PIL\n\nvo = voyageai.Client()\n# This will automatically use the environment variable VOYAGE_API_KEY.\n# Alternatively, you can use vo = voyageai.Client(api_key=\"\")\n\n# Example input containing a text string and PIL image object\ninputs = [\n [\"This is a banana.\", PIL.Image.open('banana.jpg')]\n]\n\n# Vectorize inputs\nresult = vo.multimodal_embed(inputs, model=\"voyage-multimodal-3.5\")\nprint(result.embeddings)\n```\n\nIn order to run this example, you must have an image file named `banana.jpg` in the same directory.\n\nYou can access Voyage multimodal embeddings in JavaScript or TypeScript by sending HTTP requests using the Fetch API or other HTTP clients."} -{"chunk_id": "6997fd706fd39a1e7ec5ab70-1", "page_id": "6997fd706fd39a1e7ec5ab70", "source_name": "voyageai", "product_name": "Voyage AI", "url": "https://mongodb.com/docs/voyageai/models/multimodal-embeddings", "title": "Multimodal Embeddings", "text": "### Example\n\n```javascript\nconst fs = require('fs');\nconst apiKey = process.env.VOYAGE_API_KEY;\nconst url = \"https://ai.mongodb.com/v1/multimodalembeddings\";\n\nconst headers = {\n \"Authorization\": `Bearer ${apiKey}`,\n \"Content-Type\": \"application/json\"\n};\n\n// Read and encode image to base64\nconst imageBuffer = fs.readFileSync('banana.jpg');\nconst base64Image = imageBuffer.toString('base64');\n\nconst data = {\n inputs: [\n {\n content: [\n { type: \"text\", text: \"This is a banana.\" },\n { type: \"image_base64\", image_base64: base64Image }\n ]\n }\n ],\n model: \"voyage-multimodal-3.5\"\n};\n\nconst response = await fetch(url, {\n method: \"POST\",\n headers: headers,\n body: JSON.stringify(data)\n});\n\nconst result = await response.json();\n```\n\nIn order to run this example, you must have an image file named `banana.jpg` in the same directory.\n\nYou can access Voyage multimodal embeddings in Java by sending HTTP requests using the built-in `HttpClient` or other HTTP libraries.\n\n### Example\n\n```java\nimport java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.nio.file.Files;\nimport java.nio.file.Paths;\nimport java.util.Base64;\n\nString apiKey = System.getenv(\"VOYAGE_API_KEY\");\nString url = \"https://ai.mongodb.com/v1/multimodalembeddings\";\n\n// Read and encode image to base64\nbyte[] imageBytes = Files.readAllBytes(Paths.get(\"banana.jpg\"));\nString base64Image = Base64.getEncoder().encodeToString(imageBytes);\n\nString jsonBody = String.format(\"\"\"\n {\n \"inputs\": [\n {\n \"content\": [\n {\"type\": \"text\", \"text\": \"This is a banana.\"},\n {\"type\": \"image_base64\", \"image_base64\": \"%s\"}\n ]\n }\n ],\n \"model\": \"voyage-multimodal-3.5\"\n }\n \"\"\", base64Image);\n\nHttpClient client = HttpClient.newHttpClient();\nHttpRequest request = HttpRequest.newBuilder()\n .uri(URI.create(url))\n .header(\"Authorization\", \"Bearer \" + apiKey)\n .header(\"Content-Type\", \"application/json\")\n .POST(HttpRequest.BodyPublishers.ofString(jsonBody))\n .build();\n\nHttpResponse response = client.send(request,\n HttpResponse.BodyHandlers.ofString());\nSystem.out.println(response.body());\n```\n\nIn order to run this example, you must have an image file named `banana.jpg` in the same directory.\n\nYou can access Voyage multimodal embeddings in Go by sending HTTP requests using the standard `net/http` package.\n\n### Example\n\n```go\npackage main\n\nimport (\n \"bytes\"\n \"encoding/base64\"\n \"encoding/json\"\n \"fmt\"\n \"io\"\n \"net/http\"\n \"os\"\n)\n\nfunc main() {\n apiKey := os.Getenv(\"VOYAGE_API_KEY\")\n url := \"https://ai.mongodb.com/v1/multimodalembeddings\"\n\n // Read and encode image to base64\n imageData, _ := os.ReadFile(\"banana.jpg\")\n base64Image := base64.StdEncoding.EncodeToString(imageData)\n\n requestBody := map[string]interface{}{\n \"inputs\": []map[string]interface{}{\n {\n \"content\": []map[string]string{\n {\"type\": \"text\", \"text\": \"This is a banana.\"},\n {\"type\": \"image_base64\", \"image_base64\": base64Image},\n },\n },\n },\n \"model\": \"voyage-multimodal-3.5\",\n }\n\n jsonData, _ := json.Marshal(requestBody)\n\n req, _ := http.NewRequest(\"POST\", url, bytes.NewBuffer(jsonData))\n req.Header.Set(\"Authorization\", \"Bearer \"+apiKey)\n req.Header.Set(\"Content-Type\", \"application/json\")\n\n client := &http.Client{}\n resp, _ := client.Do(req)\n defer resp.Body.Close()\n\n body, _ := io.ReadAll(resp.Body)\n fmt.Println(string(body))\n}\n```\n\nIn order to run this example, you must have an image file named `banana.jpg` in the same directory.\n\nYou can access Voyage multimodal embeddings with cURL by sending a POST request to the endpoint `https://ai.mongodb.com/v1/multimodalembeddings`.\n\nIn the REST API, each input is represented as a dictionary with a `\"content\"` key, whose value is a list of content items. Each content item is a dictionary with a `\"type\"` field (either `\"text\"` or `\"image_base64\"`) and the corresponding content:\n\n- For text: `{\"type\": \"text\", \"text\": \"your text here\"}`\n\n- For images: `{\"type\": \"image_base64\", \"image_base64\": \"base64_encoded_image_data\"}`\n\n### Example\n\n\n\n\n\n```bash\ncurl \\\n --request POST 'https://ai.mongodb.com/v1/multimodalembeddings' \\\n --header \"Authorization: Bearer $VOYAGE_API_KEY\" \\\n --header \"Content-Type: application/json\" \\\n --data '{\n \"inputs\": [\n {\n \"content\": [\n {\"type\": \"text\", \"text\": \"This is a banana.\"},\n {\"type\": \"image_base64\", \"image_base64\": \"\"}\n ]\n }\n ],\n \"model\": \"voyage-multimodal-3.5\",\n \"input_type\": \"document\"\n }'\n```\n\n\n\n\n\n```bash\ncurl \\\n --request POST 'https://ai.mongodb.com/v1/multimodalembeddings' \\\n --header \"Authorization: Bearer $VOYAGE_API_KEY\" \\\n --header \"Content-Type: application/json\" \\\n --data '{\n \"inputs\": [\n {\n \"content\": [\n {\"type\": \"text\", \"text\": \"First document with text and image.\"},\n {\"type\": \"image_base64\", \"image_base64\": \"\"}\n ]\n },\n {\n \"content\": [\n {\"type\": \"text\", \"text\": \"Second document.\"},\n {\"type\": \"image_base64\", \"image_base64\": \"\"}\n ]\n }\n ],\n \"model\": \"voyage-multimodal-3.5\"\n }'\n```\n\n\n\n"} -{"chunk_id": "6997fd706fd39a1e7ec5ab7c-0", "page_id": "6997fd706fd39a1e7ec5ab7c", "source_name": "voyageai", "product_name": "Voyage AI", "url": "https://mongodb.com/docs/voyageai/tutorials/semantic-search", "title": "Semantic Search with Voyage AI Embeddings", "text": "# Semantic Search with Voyage AI Embeddings\n\nThis guide describes how to perform semantic search with Voyage AI models. This page includes examples for basic and advanced semantic search use cases, including search with reranking, multilingual, multimodal, contextualized chunk, and large corpus retrieval.\n\n## Perform Semantic Search\n\nThis section provides code examples for various semantic search use cases with different Voyage AI models. For each example, you perform the same basic steps:\n\n1. **Embed the documents**: Convert your data into vector embeddings that capture their meaning. This data can be text, images, document chunks, or a large corpus of text.\n\n2. **Embed the query**: Transform your search query into the same vector representation as your documents.\n\n3. **Find similar documents**: Compare the query vector against your document vectors to identify the most semantically similar results.\n\nWork with a runnable version of this tutorial as a Python notebook.\n\n### Set up your environment.\n\nBefore you begin, create a project directory, install libraries, and set your model API key.\n\n- Run the following commands in your terminal to create a new directory for this tutorial and install the required libraries:\n\n ```bash\n mkdir voyage-semantic-search\n cd voyage-semantic-search\n pip install --upgrade voyageai numpy datasets\n ```\n\n- If you haven't already, follow the steps to create a model API key, then run the following command in your terminal to export it as an environment variable:\n\n ```bash\n export VOYAGE_API_KEY=\"your-model-api-key\"\n ```"} -{"chunk_id": "6997fd706fd39a1e7ec5ab7c-1", "page_id": "6997fd706fd39a1e7ec5ab7c", "source_name": "voyageai", "product_name": "Voyage AI", "url": "https://mongodb.com/docs/voyageai/tutorials/semantic-search", "title": "Semantic Search with Voyage AI Embeddings", "text": "### Run semantic search queries.\n\nExpand each section to get code examples for each type of semantic search.\n\n- Create a file named `semantic_search_basic.py` in your project and paste the following code into it:\n\n```python\nimport voyageai\nimport numpy as np\n\n# Initialize Voyage AI client\nvo = voyageai.Client()\n\n# Sample documents\ndocuments = [\n \"The Mediterranean diet emphasizes fish, olive oil, and vegetables, believed to reduce chronic diseases.\",\n \"Photosynthesis in plants converts light energy into glucose and produces essential oxygen.\",\n \"20th-century innovations, from radios to smartphones, centered on electronic advancements.\",\n \"Rivers provide water, irrigation, and habitat for aquatic species, vital for ecosystems.\",\n \"Apple's conference call to discuss fourth fiscal quarter results and business updates is scheduled for Thursday, November 2, 2023 at 2:00 p.m. PT / 5:00 p.m. ET.\",\n \"Shakespeare's works, like 'Hamlet' and 'A Midsummer Night's Dream,' endure in literature.\"\n]\n\n# Search query\nquery = \"When is Apple's conference call scheduled?\"\n\n# Generate embeddings for documents\ndoc_embeddings = vo.embed(\n texts=documents,\n model=\"voyage-4-large\",\n input_type=\"document\"\n).embeddings\n\n# Generate embedding for query\nquery_embedding = vo.embed(\n texts=[query],\n model=\"voyage-4-large\",\n input_type=\"query\"\n).embeddings[0]\n\n# Calculate similarity scores using dot product\nsimilarities = np.dot(doc_embeddings, query_embedding)\n\n# Sort documents by similarity (highest to lowest)\nranked_indices = np.argsort(-similarities)\n\n# Display results\nprint(f\"Query: '{query}'\\n\")\nfor rank, idx in enumerate(ranked_indices, 1):\n print(f\"{rank}. {documents[idx]}\")\n print(f\" Similarity: {similarities[idx]:.4f}\\n\")\n\n```\n\n- Run the following command in your terminal:\n\n```bash\npython semantic_search_basic.py\n```\n\n```none\nQuery: 'When is Apple's conference call scheduled?'\n\n1. Apple's conference call to discuss fourth fiscal quarter results and business updates is scheduled for Thursday, November 2, 2023 at 2:00 p.m. PT / 5:00 p.m. ET.\n Similarity: 0.6107\n\n2. 20th-century innovations, from radios to smartphones, centered on electronic advancements.\n Similarity: 0.0212\n\n3. Photosynthesis in plants converts light energy into glucose and produces essential oxygen.\n Similarity: -0.0185\n\n4. The Mediterranean diet emphasizes fish, olive oil, and vegetables, believed to reduce chronic diseases.\n Similarity: -0.0257\n\n5. Rivers provide water, irrigation, and habitat for aquatic species, vital for ecosystems.\n Similarity: -0.0323\n\n6. Shakespeare's works, like 'Hamlet' and 'A Midsummer Night's Dream,' endure in literature.\n Similarity: -0.0442\n\n```\n\n- Create a file named `semantic_search_reranker.py` in your project and paste the following code into it:\n\n```python\nimport voyageai\nimport numpy as np\n\n# Initialize Voyage AI client\nvo = voyageai.Client()\n\n# Sample documents\ndocuments = [\n \"The Mediterranean diet emphasizes fish, olive oil, and vegetables, believed to reduce chronic diseases.\",\n \"Photosynthesis in plants converts light energy into glucose and produces essential oxygen.\",\n \"20th-century innovations, from radios to smartphones, centered on electronic advancements.\",\n \"Rivers provide water, irrigation, and habitat for aquatic species, vital for ecosystems.\",\n \"Apple's conference call to discuss fourth fiscal quarter results and business updates is scheduled for Thursday, November 2, 2023 at 2:00 p.m. PT / 5:00 p.m. ET.\",\n \"Shakespeare's works, like 'Hamlet' and 'A Midsummer Night's Dream,' endure in literature.\"\n]\n\n# Search query\nquery = \"When is Apple's conference call scheduled?\"\n\n# Generate embeddings for documents\ndoc_embeddings = vo.embed(\n texts=documents,\n model=\"voyage-4-large\",\n input_type=\"document\"\n).embeddings\n\n# Generate embedding for query\nquery_embedding = vo.embed(\n texts=[query],\n model=\"voyage-4-large\",\n input_type=\"query\"\n).embeddings[0]\n\n# Calculate similarity scores using dot product\nsimilarities = np.dot(doc_embeddings, query_embedding)\n\n# Sort by similarity (highest to lowest)\nranked_indices = np.argsort(-similarities)\n\n# Display results before reranking\nprint(f\"Query: '{query}'\\n\")\nprint(\"Before reranker (embedding similarity only):\")\nfor rank, idx in enumerate(ranked_indices[:3], 1):\n print(f\"{rank}. {documents[idx]}\")\n print(f\" Similarity Score: {similarities[idx]:.4f}\\n\")\n\n# Rerank documents for improved accuracy\nrerank_results = vo.rerank(\n query=query,\n documents=documents,\n model=\"rerank-2.5\"\n)\n\n# Display results after reranking\nprint(\"\\nAfter reranker:\")\nfor rank, result in enumerate(rerank_results.results[:3], 1):\n print(f\"{rank}. {documents[result.index]}\")\n print(f\" Relevance Score: {result.relevance_score:.4f}\\n\")\n\n```\n\n- Run the following command in your terminal:\n\n```bash\npython semantic_search_reranker.py\n```\n\n```none\nQuery: 'When is Apple's conference call scheduled?'\n\nBefore reranker (embedding similarity only):\n1. Apple's conference call to discuss fourth fiscal quarter results and business updates is scheduled for Thursday, November 2, 2023 at 2:00 p.m. PT / 5:00 p.m. ET.\n Similarity Score: 0.6107\n\n2. 20th-century innovations, from radios to smartphones, centered on electronic advancements.\n Similarity Score: 0.0212\n\n3. Photosynthesis in plants converts light energy into glucose and produces essential oxygen.\n Similarity Score: -0.0185\n\nAfter reranker:\n1. Apple's conference call to discuss fourth fiscal quarter results and business updates is scheduled for Thursday, November 2, 2023 at 2:00 p.m. PT / 5:00 p.m. ET.\n Relevance Score: 0.9414\n\n2. 20th-century innovations, from radios to smartphones, centered on electronic advancements.\n Relevance Score: 0.2852\n\n3. The Mediterranean diet emphasizes fish, olive oil, and vegetables, believed to reduce chronic diseases.\n Relevance Score: 0.2637\n\n```\n\n- Create a file named `semantic_search_multilingual.py` in your project and paste the following code into it:\n\n```python\nimport voyageai\nimport numpy as np\n\n# Initialize Voyage AI client\nvo = voyageai.Client()\n\n# English documents about technology companies\nenglish_docs = [\n \"Apple announced record-breaking revenue in its latest quarterly earnings report.\",\n \"The Mediterranean diet emphasizes fish, olive oil, and vegetables.\",\n \"Microsoft is investing heavily in artificial intelligence and cloud computing.\",\n \"Shakespeare's plays continue to influence modern literature and theater.\"\n]\n\n# Spanish documents about technology companies\nspanish_docs = [\n \"Apple anunci\u00f3 ingresos r\u00e9cord en su \u00faltimo informe trimestral de ganancias.\",\n \"La dieta mediterr\u00e1nea enfatiza el pescado, el aceite de oliva y las verduras.\",\n \"Microsoft est\u00e1 invirtiendo fuertemente en inteligencia artificial y computaci\u00f3n en la nube.\",\n \"Las obras de Shakespeare contin\u00faan influenciando la literatura y el teatro modernos.\"\n]\n\n# Chinese documents about technology companies\nchinese_docs = [\n \"\u82f9\u679c\u516c\u53f8\u5728\u6700\u65b0\u5b63\u5ea6\u8d22\u62a5\u4e2d\u5ba3\u5e03\u521b\u7eaa\u5f55\u7684\u6536\u5165\u3002\",\n \"\u5730\u4e2d\u6d77\u996e\u98df\u5f3a\u8c03\u9c7c\u7c7b\u3001\u6a44\u6984\u6cb9\u548c\u852c\u83dc\u3002\",\n \"\u5fae\u8f6f\u6b63\u5728\u5927\u529b\u6295\u8d44\u4eba\u5de5\u667a\u80fd\u548c\u4e91\u8ba1\u7b97\u3002\",\n \"\u838e\u58eb\u6bd4\u4e9a\u7684\u4f5c\u54c1\u7ee7\u7eed\u5f71\u54cd\u73b0\u4ee3\u6587\u5b66\u548c\u620f\u5267\u3002\"\n]\n\n# Perform semantic search in English\nenglish_query = \"tech company earnings\"\n\n# Generate embeddings for English documents\nenglish_embeddings = vo.embed(\n texts=english_docs,\n model=\"voyage-4-large\",\n input_type=\"document\"\n).embeddings\n\n# Generate embedding for English query\nenglish_query_embedding = vo.embed(\n texts=[english_query],\n model=\"voyage-4-large\",\n input_type=\"query\"\n).embeddings[0]\n\n# Calculate similarity scores using dot product\nenglish_similarities = np.dot(english_embeddings, english_query_embedding)\n\n# Sort by similarity (highest to lowest)\nenglish_ranked = np.argsort(-english_similarities)\n\nprint(f\"English Query: '{english_query}'\\n\")\nfor rank, idx in enumerate(english_ranked[:2], 1):\n print(f\"{rank}. {english_docs[idx]}\")\n print(f\" Similarity: {english_similarities[idx]:.4f}\\n\")"} -{"chunk_id": "6997fd706fd39a1e7ec5ab7c-2", "page_id": "6997fd706fd39a1e7ec5ab7c", "source_name": "voyageai", "product_name": "Voyage AI", "url": "https://mongodb.com/docs/voyageai/tutorials/semantic-search", "title": "Semantic Search with Voyage AI Embeddings", "text": "# Perform semantic search in Spanish\nspanish_query = \"ganancias de empresas tecnol\u00f3gicas\"\n\n# Generate embeddings for Spanish documents\nspanish_embeddings = vo.embed(\n texts=spanish_docs,\n model=\"voyage-4-large\",\n input_type=\"document\"\n).embeddings\n\n# Generate embedding for Spanish query\nspanish_query_embedding = vo.embed(\n texts=[spanish_query],\n model=\"voyage-4-large\",\n input_type=\"query\"\n).embeddings[0]\n\n# Calculate similarity scores using dot product\nspanish_similarities = np.dot(spanish_embeddings, spanish_query_embedding)\n\n# Sort by similarity (highest to lowest)\nspanish_ranked = np.argsort(-spanish_similarities)\n\nprint(f\"Spanish Query: '{spanish_query}'\\n\")\nfor rank, idx in enumerate(spanish_ranked[:2], 1):\n print(f\"{rank}. {spanish_docs[idx]}\")\n print(f\" Similarity: {spanish_similarities[idx]:.4f}\\n\")\n\n# Perform semantic search in Chinese\nchinese_query = \"\u79d1\u6280\u516c\u53f8\u6536\u76ca\"\n\n# Generate embeddings for Chinese documents\nchinese_embeddings = vo.embed(\n texts=chinese_docs,\n model=\"voyage-4-large\",\n input_type=\"document\"\n).embeddings\n\n# Generate embedding for Chinese query\nchinese_query_embedding = vo.embed(\n texts=[chinese_query],\n model=\"voyage-4-large\",\n input_type=\"query\"\n).embeddings[0]\n\n# Calculate similarity scores using dot product\nchinese_similarities = np.dot(chinese_embeddings, chinese_query_embedding)\n\n# Sort by similarity (highest to lowest)\nchinese_ranked = np.argsort(-chinese_similarities)\n\nprint(f\"Chinese Query: '{chinese_query}'\\n\")\nfor rank, idx in enumerate(chinese_ranked[:2], 1):\n print(f\"{rank}. {chinese_docs[idx]}\")\n print(f\" Similarity: {chinese_similarities[idx]:.4f}\\n\")\n\n```\n\n- Run the following command in your terminal:\n\n```bash\npython semantic_search_multilingual.py\n```\n\n```none\nEnglish Query: 'tech company earnings'\n\n1. Apple announced record-breaking revenue in its latest quarterly earnings report.\n Similarity: 0.4126\n\n2. Microsoft is investing heavily in artificial intelligence and cloud computing.\n Similarity: 0.2168\n\nSpanish Query: 'ganancias de empresas tecnol\u00f3gicas'\n\n1. Apple anunci\u00f3 ingresos r\u00e9cord en su \u00faltimo informe trimestral de ganancias.\n Similarity: 0.4779\n\n2. Microsoft est\u00e1 invirtiendo fuertemente en inteligencia artificial y computaci\u00f3n en la nube.\n Similarity: 0.3301\n\nChinese Query: '\u79d1\u6280\u516c\u53f8\u6536\u76ca'\n\n1. \u82f9\u679c\u516c\u53f8\u5728\u6700\u65b0\u5b63\u5ea6\u8d22\u62a5\u4e2d\u5ba3\u5e03\u521b\u7eaa\u5f55\u7684\u6536\u5165\u3002\n Similarity: 0.4185\n\n2. \u5fae\u8f6f\u6b63\u5728\u5927\u529b\u6295\u8d44\u4eba\u5de5\u667a\u80fd\u548c\u4e91\u8ba1\u7b97\u3002\n Similarity: 0.2901\n\n```\n\n- Search for sample images and save them in your project directory. The following code example assumes you have images of a cat, dog, and banana.\n\n- Create a file named `semantic_search_multimodal.py` in your project and paste the following code into it:\n\n```python\nimport voyageai\nimport numpy as np\nfrom PIL import Image\n\n# Initialize Voyage AI client\nvo = voyageai.Client()\n\n# Prepare interleaved text + image inputs\ninterleaved_inputs = [\n [\"An orange cat\", Image.open('cat.jpg')],\n [\"A golden retriever\", Image.open('dog.jpg')],\n [\"A banana\", Image.open('banana.jpg')],\n]\n\n# Prepare image-only inputs\nimage_only_inputs = [\n [Image.open('cat.jpg')],\n [Image.open('dog.jpg')],\n [Image.open('banana.jpg')],\n]\n\n# Labels for display\nlabels = [\"cat.jpg\", \"dog.jpg\", \"banana.jpg\"]\n\n# Search query\nquery = \"a cute pet\"\n\n# Generate embeddings for interleaved text + image inputs\ninterleaved_embeddings = vo.multimodal_embed(\n inputs=interleaved_inputs,\n model=\"voyage-multimodal-3.5\"\n).embeddings\n\n# Generate embedding for query\nquery_embedding = vo.multimodal_embed(\n inputs=[[query]],\n model=\"voyage-multimodal-3.5\"\n).embeddings[0]\n\n# Calculate similarity scores using dot product\ninterleaved_similarities = np.dot(interleaved_embeddings, query_embedding)\n\n# Sort by similarity (highest to lowest)\ninterleaved_ranked = np.argsort(-interleaved_similarities)\n\nprint(f\"Query: '{query}'\\n\")\nprint(\"Search with interleaved text + image:\")\nfor rank, idx in enumerate(interleaved_ranked, 1):\n print(f\"{rank}. {interleaved_inputs[idx][0]}\")\n print(f\" Similarity: {interleaved_similarities[idx]:.4f}\\n\")\n\n# Generate embeddings for image-only inputs\nimage_only_embeddings = vo.multimodal_embed(\n inputs=image_only_inputs,\n model=\"voyage-multimodal-3.5\"\n).embeddings\n\n# Calculate similarity scores using dot product\nimage_only_similarities = np.dot(image_only_embeddings, query_embedding)\n\n# Sort by similarity (highest to lowest)\nimage_only_ranked = np.argsort(-image_only_similarities)\n\nprint(\"\\nSearch with image-only:\")\nfor rank, idx in enumerate(image_only_ranked, 1):\n print(f\"{rank}. {labels[idx]}\")\n print(f\" Similarity: {image_only_similarities[idx]:.4f}\\n\")\n\n```\n\n- Run the following command in your terminal:\n\n```bash\npython semantic_search_multimodal.py\n```\n\n```none\nQuery: 'a cute pet'\n\nSearch with interleaved text + image:\n1. An orange cat\n Similarity: 0.2685\n\n2. A golden retriever\n Similarity: 0.2325\n\n3. A banana\n Similarity: 0.1564\nSearch with image-only:\n1. dog.jpg\n Similarity: 0.2485\n\n2. cat.jpg\n Similarity: 0.2438\n\n3. banana.jpg\n Similarity: 0.1210\n```\n\n- Create a file named `semantic_search_contextualized.py` in your project and paste the following code into it:\n\n```python\nimport voyageai\nimport numpy as np\n\n# Initialize Voyage AI client\nvo = voyageai.Client()\n\n# Sample documents (each document is a list of chunks that share context)\ndocuments = [\n [\n \"This is the SEC filing on Greenery Corp.'s Q2 2024 performance.\",\n \"The company's revenue increased by 7% compared to the previous quarter.\"\n ],\n [\n \"This is the SEC filing on Leafy Inc.'s Q2 2024 performance.\",\n \"The company's revenue increased by 15% compared to the previous quarter.\"\n ],\n [\n \"This is the SEC filing on Elephant Ltd.'s Q2 2024 performance.\",\n \"The company's revenue decreased by 2% compared to the previous quarter.\"\n ]\n]\n\n# Search query\nquery = \"What was the revenue growth for Leafy Inc. in Q2 2024?\"\n\n# Generate contextualized embeddings (preserves relationships between chunks)\ncontextualized_result = vo.contextualized_embed(\n inputs=documents,\n model=\"voyage-context-3\",\n input_type=\"document\"\n)\n\n# Flatten the embeddings and chunks for semantic search\ncontextualized_embeddings = []\nall_chunks = []\nchunk_to_doc = [] # Maps chunk index to document index\n\nfor doc_idx, result in enumerate(contextualized_result.results):\n for emb, chunk in zip(result.embeddings, documents[doc_idx]):\n contextualized_embeddings.append(emb)\n all_chunks.append(chunk)\n chunk_to_doc.append(doc_idx)\n\n# Generate contextualized query embedding\nquery_embedding_ctx = vo.contextualized_embed(\n inputs=[[query]],\n model=\"voyage-context-3\",\n input_type=\"query\"\n).results[0].embeddings[0]\n\n# Calculate similarity scores using dot product\nsimilarities_ctx = np.dot(contextualized_embeddings, query_embedding_ctx)\n\n# Sort by similarity (highest to lowest)\nranked_indices_ctx = np.argsort(-similarities_ctx)\n\n# Display top 3 results\nprint(f\"Query: '{query}'\\n\")\nfor rank, idx in enumerate(ranked_indices_ctx[:3], 1):\n doc_idx = chunk_to_doc[idx]\n print(f\"{rank}. {all_chunks[idx]}\")\n print(f\" (From document: {documents[doc_idx][0]})\")\n print(f\" Similarity: {similarities_ctx[idx]:.4f}\\n\")\n\n```\n\n- Run the following command in your terminal:\n\n```bash\npython semantic_search_contextualized.py\n```\n\n```none\nQuery: 'What was the revenue growth for Leafy Inc. in Q2 2024?'\n\n1. The company's revenue increased by 15% compared to the previous quarter.\n (From document: This is the SEC filing on Leafy Inc.'s Q2 2024 performance.)\n Similarity: 0.7110\n\n2. This is the SEC filing on Leafy Inc.'s Q2 2024 performance.\n (From document: This is the SEC filing on Leafy Inc.'s Q2 2024 performance.)\n Similarity: 0.6616\n\n3. The company's revenue increased by 7% compared to the previous quarter.\n (From document: This is the SEC filing on Greenery Corp.'s Q2 2024 performance.)\n Similarity: 0.5530\n\n```"} -{"chunk_id": "6997fd706fd39a1e7ec5ab7c-3", "page_id": "6997fd706fd39a1e7ec5ab7c", "source_name": "voyageai", "product_name": "Voyage AI", "url": "https://mongodb.com/docs/voyageai/tutorials/semantic-search", "title": "Semantic Search with Voyage AI Embeddings", "text": "- Create a file named `semantic_search_large_corpus.py` in your project and paste the following code into it:\n\n```python\nimport voyageai\nimport numpy as np\nfrom datasets import load_dataset\nfrom collections import defaultdict\n\n# Initialize Voyage AI client\nvo = voyageai.Client()\n\n# Load legal benchmark dataset\ncorpus_ds = load_dataset(\"mteb/legalbench_consumer_contracts_qa\", \"corpus\")[\"corpus\"]\nqueries_ds = load_dataset(\"mteb/legalbench_consumer_contracts_qa\", \"queries\")[\"queries\"]\nqrels_ds = load_dataset(\"mteb/legalbench_consumer_contracts_qa\")[\"test\"]\n\n# Extract corpus and query data\ncorpus_ids = [row[\"_id\"] for row in corpus_ds]\ncorpus_texts = [row[\"text\"] for row in corpus_ds]\nquery_ids = [row[\"_id\"] for row in queries_ds]\nquery_texts = [row[\"text\"] for row in queries_ds]\n\n# Build relevance mapping (defaultdict creates sets for missing keys)\nqrels = defaultdict(set)\nfor row in qrels_ds:\n if row[\"score\"] > 0:\n qrels[row[\"query-id\"]].add(row[\"corpus-id\"])\n\n# Generate embeddings for the entire corpus\nprint(f\"Generating embeddings for {len(corpus_texts)} documents...\")\ncorpus_embeddings = vo.embed(\n texts=corpus_texts,\n model=\"voyage-4-large\",\n input_type=\"document\"\n).embeddings\n\n# Select a sample query\nquery_idx = 1\nquery = query_texts[query_idx]\nquery_id = query_ids[query_idx]\n\n# Generate embedding for the query\nquery_embedding = vo.embed(\n texts=[query],\n model=\"voyage-4-large\",\n input_type=\"query\"\n).embeddings[0]\n\n# Calculate similarity scores using dot product\nsimilarities = np.dot(corpus_embeddings, query_embedding)\n\n# Sort by similarity (highest to lowest)\nranked_indices = np.argsort(-similarities)\n\n# Display top 5 results\nprint(f\"Query: {query}\\n\")\nprint(\"Top 5 Results:\")\nfor rank, idx in enumerate(ranked_indices[:5], 1):\n doc_id = corpus_ids[idx]\n is_relevant = \"\u2713\" if doc_id in qrels[query_id] else \"\u2717\"\n print(f\"{rank}. [{is_relevant}] Document ID: {doc_id}\")\n print(f\" Similarity: {similarities[idx]:.4f}\")\n print(f\" Text: {corpus_texts[idx][:100]}...\\n\")\n\n# Show the ground truth most relevant document\nmost_relevant_id = list(qrels[query_id])[0]\nmost_relevant_idx = corpus_ids.index(most_relevant_id)\nprint(f\"Ground truth most relevant document:\")\nprint(f\"Document ID: {most_relevant_id}\")\nprint(f\"Rank in results: {np.where(ranked_indices == most_relevant_idx)[0][0] + 1}\")\nprint(f\"Similarity: {similarities[most_relevant_idx]:.4f}\")\n\n```\n\n- Run the following command in your terminal:\n\n```bash\npython semantic_search_large_corpus.py\n```\n\n```none\nGenerating embeddings for 154 documents...\nQuery: Will Google come to a users assistance in the event of an alleged violation of such users IP rights?\n\nTop 5 Results:\n1. [\u2713] Document ID: 9NIQ0Wobtq\n Similarity: 0.4978\n Text: Your content\nSome of our services give you the opportunity to make your content publicly available ...\n\n2. [\u2717] Document ID: gAk7Gdp0CX\n Similarity: 0.4136\n Text: Taking action in case of problems\nBefore taking action as described below, well provide you with adv...\n\n3. [\u2717] Document ID: 8IRh1E2JDB\n Similarity: 0.3957\n Text: OUR PROPERTY\nThe Service is protected by copyright, trademark, and other US and foreign laws. These ...\n\n4. [\u2717] Document ID: S87XwXaHCP\n Similarity: 0.3947\n Text: Privacy and Data Protection\nOur Privacy Center explains how we treat your personal data. By using th...\n\n5. [\u2717] Document ID: 5eZffTYIKI\n Similarity: 0.3891\n Text: The permission that we give you to use our services continues as long as you meet your responsibilit...\n\nGround truth most relevant document:\nDocument ID: 9NIQ0Wobtq\nRank in results: 1\nSimilarity: 0.4978\n\n```\n\n### About The Examples\n\nThe following table summarizes the examples on this page:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nExample\n\n\nModel Used\n\n\nUnderstanding Results\n\n
\nBasic Semantic Search\n\n\n`voyage-4-large`\n\n\nThe Apple conference call document ranks first, significantly higher than unrelated documents, demonstrating accurate semantic matching.\n\n
\nSemantic Search with Reranker\n\n\n`voyage-4-large` and `rerank-2.5`\n\n\nReranking improves search accuracy by analyzing the full query-document relationship. While embedding similarity alone ranks the correct document first with a moderate score, the reranker significantly boosts its relevance score which better separates it from irrelevant results.\n\n
\nMultilingual Semantic Search\n\n\n`voyage-4-large`\n\n\nVoyage models perform semantic search effectively across different languages. The example demonstrates three separate searches in English, Spanish, and Chinese, each correctly identifying the most relevant documents about tech company earnings within their respective languages.\n\n
\nMultimodal Semantic Search\n\n\n`voyage-multimodal-3.5`\n\n\nThe model supports interleaved text, image, and video. It also supports image-only and video-only search. In both cases, pet images (cat and dog) rank significantly higher than the unrelated banana image, demonstrating accurate visual content retrieval. Interleaved inputs with descriptive text produce slightly higher similarity scores than image-only inputs.\n\n
\nContextualized Chunk Embeddings\n\n\n`voyage-context-3`\n\n\nThe 15% revenue growth chunk ranks first because it's linked to the Leafy Inc. document. The similar 7% growth chunk from Greenery Corp. scores lower, showing how the model accurately considers document context to distinguish between otherwise similar chunks.\n\n
\nSemantic Search with Large Corpus\n\n\n`voyage-4-large`\n\n\nThe ground truth document about user content ranks first among 154 documents, demonstrating effective retrieval at scale despite semantic complexity.\n\n
The examples use the Python Client, `voyageai.Client()`, which automatically reads your API key from the `VOYAGE_API_KEY` environment variable. The API returns a response object. Use the `.embeddings` attribute to access the actual embedding vectors:\n\n```python\nresult = vo.embed(texts=[\"example\"], model=\"voyage-4-large\", input_type=\"document\")\nembeddings = result.embeddings # List of embedding vectors\n```\n\nThe examples calculate similarity scores between query and document embeddings using Numpy's dot product function: `np.dot()`. Since Voyage AI embeddings are normalized to length 1, the dot product is mathematically equivalent to cosine similarity.\n\nTo rank results by similarity, the examples use Numpy's `argsort()` function to display the top N results. The negative sign sorts in descending order, so the highest similarity scores appear first.\n\nThe `input_type` parameter is set to `query` or `document` to optimize how Voyage AI models create the vectors. Do not omit this parameter. To learn more, see Specifying Input Type.\n\nTo learn more, see Accessing Voyage AI Models or explore the full API specification."} -{"chunk_id": "6997fd706fd39a1e7ec5ab7c-4", "page_id": "6997fd706fd39a1e7ec5ab7c", "source_name": "voyageai", "product_name": "Voyage AI", "url": "https://mongodb.com/docs/voyageai/tutorials/semantic-search", "title": "Semantic Search with Voyage AI Embeddings", "text": "## What is Semantic Search?\n\nSemantic search is a search method that returns results based on your data's semantic, or underlying, meaning. Unlike traditional full-text search which finds text matches, semantic search finds vectors that are close to your search query in multi-dimensional space. The closer the vectors are to your query, the more similar they are in meaning.\n\nTraditional text search returns only exact matches, limiting results when users search with different terms than those in your data. For example, if your data contains documents about computer mice and animal mice, searching for \"mouse\" when you intend to find information about computer mice results in incorrect matches.\n\nSemantic search, however, captures the underlying relationship between words or phrases even when there is no lexical overlap. Searching for \"mouse\" when indicating that you are looking for computer products results in more relevant results. This is because semantic search compares the semantic meaning of the search query against your data to return only the most relevant results, regardless of the exact search terms.\n\nSimilarity functions measure how close two vectors are to each other, and therefore how similar they are. Common functions include dot product, cosine similarity, and Euclidean distance. Voyage AI embeddings are normalized to length 1, which means that:\n\n- Cosine similarity is equivalent to dot product similarity, while the latter can be computed more quickly.\n\n- Cosine similarity and Euclidean distance result in identical rankings.\n\n## Semantic Search in Production\n\nWhile storing your vectors in memory and implementing your own search pipelines is suitable for prototyping and experimentation, use a vector database and enterprise search solution for production applications so you can perform efficient retrieval from a larger corpus.\n\nMongoDB has native support for vector storage and retrieval, making it a convenient choice for storing and searching vector embeddings alongside your other data. To complete a tutorial on performing semantic search with MongoDB Vector Search, see MongoDB Vector Search Quick Start Tutorial.\n\n## Next Steps\n\nCombine semantic search with an LLM to implement a RAG application."} -{"chunk_id": "6997fd706fd39a1e7ec5ab62-0", "page_id": "6997fd706fd39a1e7ec5ab62", "source_name": "voyageai", "product_name": "Voyage AI", "url": "https://mongodb.com/docs/voyageai/models/rerankers", "title": "Rerankers", "text": "# Rerankers\n\nA reranker receives a query and many documents, and returns a ranked list of relevancy between the query and documents. The documents are often the preliminary results from an embedding-based retrieval system, and the reranker refines the ranks of these candidate documents and provides more accurate relevancy scores.\n\nUnlike embedding models that encode queries and documents separately, rerankers are cross-encoders that jointly process a pair of query and document, enabling more accurate relevancy prediction. Apply a reranker on the top candidates retrieved with embedding-based search or with lexical search algorithms such as BM25 and TF-IDF.\n\n## Available Models\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nModel\n\n\nContext Length\n\n\nDescription\n\n
\n`rerank-3`\n\n\n32,000\n\n\nHighest accuracy. Recommended for most applications.\n\nTo learn more, see the blog post.\n\n
\n`rerank-3-lite`\n\n\n32,000\n\n\nFast and cost-effective model optimized for latency-sensitive applications.\n\nTo learn more, see the blog post.\n\n
Our latest models perform better than the legacy models in all aspects, such as quality, context length, latency, and throughput.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nModel\n\n\nContext Length\n\n\nDescription\n\n
\n`rerank-2.5`\n\n\n32,000\n\n\nOur generalist reranker optimized for quality with instruction-following and multilingual support.\n\nTo learn more, see the blog post.\n\n
\n`rerank-2.5-lite`\n\n\n32,000\n\n\nFast and cost-effective model optimized for latency-sensitive applications.\n\nTo learn more, see the blog post.\n\n
\n`rerank-2`\n\n\n16,000 tokens\n\n\nOur generalist second-generation reranker optimized for quality with multilingual support.\n\nTo learn more, see the blog post.\n\n
\n`rerank-2-lite`\n\n\n8,000 tokens\n\n\nOur generalist second-generation reranker optimized for both latency and quality with multilingual support.\n\nTo learn more, see the blog post.\n\n
\n\n## Tutorials\n\nFor tutorials on using rerankers, see the following resources:\n\n- Quick Start\n\n- Semantic Search with Voyage AI Embeddings\n\n## Usage\n\nYou can access Voyage rerankers in Python through the `voyageai` package. Install the `voyageai` package and set up the API key.\n\nVoyage reranker receives as input a query and a list of candidate documents, for example, the documents retrieved by a nearest neighbor search with embeddings. It reranks the candidate documents according to their semantic relevances to the search query, and returns the list of relevance scores. To access the reranker, create a `voyageai.Client` object and use its `rerank()` method.\n\n```python\nvoyageai.Client.rerank(\n query: str,\n documents: List[str],\n model: str,\n top_k: Optional[int] = None,\n truncation: bool = True\n)\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nParameter\n\n\nType\n\n\nRequired\n\n\nDescription\n\n
\n`query`\n\n\nString\n\n\nYes\n\n\nQuery string. The query can contain a maximum of 8,000 tokens for `rerank-3`, `rerank-3-lite`, `rerank-2.5`, and `rerank-2.5-lite`. For these models, you can append or prepend optional instructions to the query to better guide the relevance.\n\n
\n`documents`\n\n\nArray of Strings (`List[str]`)\n\n\nYes\n\n\nDocuments to rerank as a list of strings. The number of documents cannot exceed 1,000. The sum of the number of tokens in the query and the number of tokens in any single document cannot exceed:\n\n- 32,000 for `rerank-3`, `rerank-3-lite`, `rerank-2.5`, and `rerank-2.5-lite`\n\nThe total number of tokens is defined using the following formula:\n\n```shell\nnumber of query tokens \u00d7 number of documents + sum of the\nnumber of tokens in all documents\n```\n\nThe total number of tokens cannot exceed the following limits:\n\n- 600K for `rerank-3`, `rerank-3-lite`, `rerank-2.5`, and `rerank-2.5-lite`\n\n
\n`model`\n\n\nString\n\n\nYes\n\n\nName of the model. Valid values: `rerank-3`, `rerank-3-lite`, `rerank-2.5`, `rerank-2.5-lite`, `rerank-2`, `rerank-2-lite`.\n\n
\n`top_k`\n\n\nInteger\n\n\nNo\n\n\nNumber of most relevant documents to return. Defaults to `None`. When you omit this parameter, Voyage AI returns the reranking results of all documents.\n\n
\n`truncation`\n\n\nBoolean\n\n\nNo\n\n\nFlag that specifies whether to truncate the input to satisfy the \"context length limit\" on the query and the documents. Defaults to `True`.\n\nIf `True`, Voyage AI truncates the query and documents to fit within the context length limit, before processing using the reranker model.\n\nIf `False`, Voyage AI returns an error when the query exceeds 8,000 tokens for `rerank-3`, `rerank-3-lite`, `rerank-2.5`, and `rerank-2.5-lite`.\n\n
\n\nThis method returns a `RerankingObject`, which contains the following attributes:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\nAttribute\n\n\nType\n\n\nDescription\n\n
\n`results`\n\n\nArray of Objects (`List[RerankingResult]`)\n\n\nList of `RerankingResult`, sorted by the descending order of relevance scores. When you specify this argument, the length of the list equals `top_k` and when you omit this argument, the length of the list is the number of the input documents. Each element in the list is a `RerankingResult` object, which contains the following attributes:\n\n- `index` (int) - The index of the document in the input list.\n\n- `document` (str) - The document as a string.\n\n- `relevance_score` (float) - The relevance score of the document with respect to the query.\n\n
\n`total_tokens`\n\n\nInteger\n\n\nTotal number of tokens in the input texts, calculated using the following formula:\n\n```shell\nnumber of query tokens \u00d7 number of documents + sum of the\nnumber of tokens in all documents\n```\n\n
"} -{"chunk_id": "6997fd706fd39a1e7ec5ab62-1", "page_id": "6997fd706fd39a1e7ec5ab62", "source_name": "voyageai", "product_name": "Voyage AI", "url": "https://mongodb.com/docs/voyageai/models/rerankers", "title": "Rerankers", "text": "### Example\n\n```python\nimport voyageai\n\nvo = voyageai.Client()\n# This will automatically use the environment variable VOYAGE_API_KEY.\n# Alternatively, you can use vo = voyageai.Client(api_key=\"\")\n\nquery = \"When is Apple's conference call scheduled?\"\ndocuments = [\n \"The Mediterranean diet emphasizes fish, olive oil, and vegetables, believed to reduce chronic diseases.\",\n \"Photosynthesis in plants converts light energy into glucose and produces essential oxygen.\",\n \"20th-century innovations, from radios to smartphones, centered on electronic advancements.\",\n \"Rivers provide water, irrigation, and habitat for aquatic species, vital for ecosystems.\",\n \"Apple's conference call to discuss fourth fiscal quarter results and business updates is scheduled for Thursday, November 2, 2023 at 2:00 p.m. PT / 5:00 p.m. ET.\",\n \"Shakespeare's works, like 'Hamlet' and 'A Midsummer Night's Dream,' endure in literature.\"\n]\n\nreranking = vo.rerank(query, documents, model=\"rerank-3\", top_k=3)\nfor r in reranking.results:\n print(f\"Document: {r.document}\")\n print(f\"Relevance Score: {r.relevance_score}\")\n print()\n```\n\nYou can access Voyage rerankers in JavaScript or TypeScript through HTTP requests using the Fetch API or other HTTP clients.\n\n### Example\n\n```javascript\nconst apiKey = process.env.VOYAGE_API_KEY;\nconst url = \"https://ai.mongodb.com/v1/rerank\";\n\nconst headers = {\n \"Authorization\": `Bearer ${apiKey}`,\n \"Content-Type\": \"application/json\"\n};\n\nconst data = {\n query: \"When is Apple's conference call scheduled?\",\n documents: [\n \"The Mediterranean diet emphasizes fish, olive oil, and vegetables, believed to reduce chronic diseases.\",\n \"Photosynthesis in plants converts light energy into glucose and produces essential oxygen.\",\n \"20th-century innovations, from radios to smartphones, centered on electronic advancements.\",\n \"Rivers provide water, irrigation, and habitat for aquatic species, vital for ecosystems.\",\n \"Apple's conference call to discuss fourth fiscal quarter results and business updates is scheduled for Thursday, November 2, 2023 at 2:00 p.m. PT / 5:00 p.m. ET.\",\n \"Shakespeare's works, like 'Hamlet' and 'A Midsummer Night's Dream,' endure in literature.\"\n ],\n model: \"rerank-3\",\n top_k: 3\n};\n\nconst response = await fetch(url, {\n method: \"POST\",\n headers: headers,\n body: JSON.stringify(data)\n});\n\nconst result = await response.json();\n```\n\nYou can access Voyage rerankers in Java by sending HTTP requests using the built-in `HttpClient` or other HTTP libraries.\n\n### Example\n\n```java\nimport java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\n\nString apiKey = System.getenv(\"VOYAGE_API_KEY\");\nString url = \"https://ai.mongodb.com/v1/rerank\";\n\nString jsonBody = \"\"\"\n {\n \"query\": \"When is Apple's conference call scheduled?\",\n \"documents\": [\n \"The Mediterranean diet emphasizes fish, olive oil, and vegetables, believed to reduce chronic diseases.\",\n \"Photosynthesis in plants converts light energy into glucose and produces essential oxygen.\",\n \"20th-century innovations, from radios to smartphones, centered on electronic advancements.\",\n \"Rivers provide water, irrigation, and habitat for aquatic species, vital for ecosystems.\",\n \"Apple's conference call to discuss fourth fiscal quarter results and business updates is scheduled for Thursday, November 2, 2023 at 2:00 p.m. PT / 5:00 p.m. ET.\",\n \"Shakespeare's works, like 'Hamlet' and 'A Midsummer Night's Dream,' endure in literature.\"\n ],\n \"model\": \"rerank-3\",\n \"top_k\": 3\n }\n \"\"\";\n\nHttpClient client = HttpClient.newHttpClient();\nHttpRequest request = HttpRequest.newBuilder()\n .uri(URI.create(url))\n .header(\"Authorization\", \"Bearer \" + apiKey)\n .header(\"Content-Type\", \"application/json\")\n .POST(HttpRequest.BodyPublishers.ofString(jsonBody))\n .build();\n\nHttpResponse response = client.send(request,\n HttpResponse.BodyHandlers.ofString());\nSystem.out.println(response.body());\n```\n\nYou can access Voyage rerankers in Go by sending HTTP requests using the standard `net/http` package.\n\n### Example\n\n```go\npackage main\n\nimport (\n \"bytes\"\n \"encoding/json\"\n \"fmt\"\n \"io\"\n \"net/http\"\n \"os\"\n)\n\nfunc main() {\n apiKey := os.Getenv(\"VOYAGE_API_KEY\")\n url := \"https://ai.mongodb.com/v1/rerank\"\n\n query := \"When is Apple's conference call scheduled?\"\n documents := []string{\n \"The Mediterranean diet emphasizes fish, olive oil, and vegetables, believed to reduce chronic diseases.\",\n \"Photosynthesis in plants converts light energy into glucose and produces essential oxygen.\",\n \"20th-century innovations, from radios to smartphones, centered on electronic advancements.\",\n \"Rivers provide water, irrigation, and habitat for aquatic species, vital for ecosystems.\",\n \"Apple's conference call to discuss fourth fiscal quarter results and business updates is scheduled for Thursday, November 2, 2023 at 2:00 p.m. PT / 5:00 p.m. ET.\",\n \"Shakespeare's works, like 'Hamlet' and 'A Midsummer Night's Dream,' endure in literature.\",\n }\n\n requestBody := map[string]interface{}{\n \"query\": query,\n \"documents\": documents,\n \"model\": \"rerank-3\",\n \"top_k\": 3,\n }\n\n jsonData, _ := json.Marshal(requestBody)\n\n req, _ := http.NewRequest(\"POST\", url, bytes.NewBuffer(jsonData))\n req.Header.Set(\"Authorization\", \"Bearer \"+apiKey)\n req.Header.Set(\"Content-Type\", \"application/json\")\n\n client := &http.Client{}\n resp, _ := client.Do(req)\n defer resp.Body.Close()\n\n body, _ := io.ReadAll(resp.Body)\n fmt.Println(string(body))\n}\n```\n\nYou can access Voyage reranker with cURL by sending a POST request to the endpoint `https://ai.mongodb.com/v1/rerank`.\n\n### Example\n\n```bash\ncurl \\\n --request POST 'https://ai.mongodb.com/v1/rerank' \\\n --header \"Authorization: Bearer $VOYAGE_API_KEY\" \\\n --header \"Content-Type: application/json\" \\\n --data '{\n \"query\": \"Sample query\",\n \"documents\": [\n \"Sample document 1\",\n \"Sample document 2\"\n ],\n \"model\": \"rerank-3\"\n }'\n```"} +version https://git-lfs.github.com/spec/v1 +oid sha256:7985d43559f567db1cc0175d0e7b8a4cf86b2c7fc69e9c1541847ffab63875f9 +size 22292835