From 4c68963b91203be7b6b5a68cbe5b0217ad665d00 Mon Sep 17 00:00:00 2001 From: ajosh0504 Date: Thu, 12 Dec 2024 13:15:59 -0800 Subject: [PATCH] Testing that everything works with the official package --- .../langchain_parent_document_retrieval.ipynb | 223 ++++++++---------- 1 file changed, 100 insertions(+), 123 deletions(-) diff --git a/notebooks/techniques/langchain_parent_document_retrieval.ipynb b/notebooks/techniques/langchain_parent_document_retrieval.ipynb index c9a10c3..701f085 100644 --- a/notebooks/techniques/langchain_parent_document_retrieval.ipynb +++ b/notebooks/techniques/langchain_parent_document_retrieval.ipynb @@ -63,7 +63,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 2, "metadata": {}, "outputs": [], "source": [ @@ -90,10 +90,10 @@ "data": { "text/plain": [ "{'ok': 1.0,\n", - " '$clusterTime': {'clusterTime': Timestamp(1733161666, 1),\n", - " 'signature': {'hash': b'\\x83\\xff\\xe1*\\xc9\\xea\\xfa\\xd3\\xbd\\xd0\\x03\\xdbrI\\x98\\xcf\\xae\\xac\\xc2\\x10',\n", + " '$clusterTime': {'clusterTime': Timestamp(1734037711, 1),\n", + " 'signature': {'hash': b'v\\xa2\\xc7\\xf6\\xc4\\xc5z\\x97%Q_\\xc1\\xa5\\xaf}\\x05(\\x92\\x80\\xc2',\n", " 'keyId': 7390069253761662978}},\n", - " 'operationTime': Timestamp(1733161666, 1)}" + " 'operationTime': Timestamp(1734037711, 1)}" ] }, "execution_count": 4, @@ -127,9 +127,18 @@ }, { "cell_type": "code", - "execution_count": 30, + "execution_count": 6, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "/Users/apoorva.joshi/Documents/GenAI-Showcase/.venv/lib/python3.12/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n", + " from .autonotebook import tqdm as notebook_tqdm\n" + ] + } + ], "source": [ "from datasets import load_dataset\n", "import pandas as pd" @@ -137,7 +146,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 7, "metadata": {}, "outputs": [], "source": [ @@ -148,7 +157,7 @@ }, { "cell_type": "code", - "execution_count": 38, + "execution_count": 8, "metadata": {}, "outputs": [ { @@ -292,7 +301,7 @@ "4 Resolve Alerts " ] }, - "execution_count": 38, + "execution_count": 8, "metadata": {}, "output_type": "execute_result" } @@ -310,7 +319,7 @@ }, { "cell_type": "code", - "execution_count": 39, + "execution_count": 9, "metadata": {}, "outputs": [], "source": [ @@ -319,7 +328,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 10, "metadata": {}, "outputs": [], "source": [ @@ -335,7 +344,7 @@ }, { "cell_type": "code", - "execution_count": 41, + "execution_count": 11, "metadata": {}, "outputs": [ { @@ -344,7 +353,7 @@ "Document(metadata={'contentType': None, 'pageDescription': None, 'productName': 'MongoDB Atlas', 'tags': ['atlas', 'docs'], 'version': None, 'updated': {'$date': '2024-05-20T17:30:49.148Z'}, 'url': 'https://mongodb.com/docs/atlas/access-tracking/', 'title': 'View Database Access History'}, page_content='# View Database Access History\\n\\n- This feature is not available for `M0` free clusters, `M2`, and `M5` clusters. To learn more, see Atlas M0 (Free Cluster), M2, and M5 Limits.\\n\\n- This feature is not supported on Serverless instances at this time. To learn more, see Serverless Instance Limitations.\\n\\n## Overview\\n\\nAtlas parses the MongoDB database logs to collect a list of authentication requests made against your clusters through the following methods:\\n\\n- `mongosh`\\n\\n- Compass\\n\\n- Drivers\\n\\nAuthentication requests made with API Keys through the Atlas Administration API are not logged.\\n\\nAtlas logs the following information for each authentication request within the last 7 days:\\n\\n\\n\\n\\n\\n\\n\\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
\\nTimestamp\\n\\n\\nThe date and time of the authentication request.\\n\\n
\\nUsername\\n\\n\\nThe username associated with the database user who made the authentication request.\\n\\nFor LDAP usernames, the UI displays the resolved LDAP name. Hover over the name to see the full LDAP username.\\n\\n
\\nIP Address\\n\\n\\nThe IP address of the machine that sent the authentication request.\\n\\n
\\nHost\\n\\n\\nThe target server that processed the authentication request.\\n\\n
\\nAuthentication Source\\n\\n\\nThe database that the authentication request was made against. `admin` is the authentication source for SCRAM-SHA users and `$external` for LDAP users.\\n\\n
\\nAuthentication Result\\n\\n\\nThe success or failure of the authentication request. A reason code is displayed for the failed authentication requests.\\n\\n
Authentication requests are pre-sorted by descending timestamp with 25 entries per page.\\n\\n### Logging Limitations\\n\\nIf a cluster experiences an activity spike and generates an extremely large quantity of log messages, Atlas may stop collecting and storing new logs for a period of time.\\n\\nLog analysis rate limits apply only to the Performance Advisor UI, the Query Insights UI, the Access Tracking UI, and the Atlas Search Query Analytics UI. Downloadable log files are always complete.\\n\\nIf authentication requests occur during a period when logs are not collected, they will not appear in the database access history.\\n\\n## Required Access\\n\\nTo view database access history, you must have `Project Owner` or `Organization Owner` access to Atlas.\\n\\n## Procedure\\n\\n\\n\\n\\n\\nTo return the access logs for a cluster using the Atlas CLI, run the following command:\\n\\n```sh\\n\\natlas accessLogs list [options]\\n\\n```\\n\\nTo learn more about the command syntax and parameters, see the Atlas CLI documentation for atlas accessLogs list.\\n\\n- Install the Atlas CLI\\n\\n- Connect to the Atlas CLI\\n\\n\\n\\n\\n\\nTo view the database access history using the API, see Access Tracking.\\n\\n\\n\\n\\n\\nUse the following procedure to view your database access history using the Atlas UI:\\n\\n### Navigate to the Clusters 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 the Clusters page is not already displayed, click Database in the sidebar.\\n\\n### View the cluster\\'s database access history.\\n\\n- On the cluster card, click .\\n\\n- Select View Database Access History.\\n\\nor\\n\\n- Click the cluster name.\\n\\n- Click .\\n\\n- Select View Database Access History.\\n\\n\\n\\n\\n\\n')" ] }, - "execution_count": 41, + "execution_count": 11, "metadata": {}, "output_type": "execute_result" } @@ -355,7 +364,7 @@ }, { "cell_type": "code", - "execution_count": 42, + "execution_count": 12, "metadata": {}, "outputs": [ { @@ -364,7 +373,7 @@ "1000" ] }, - "execution_count": 42, + "execution_count": 12, "metadata": {}, "output_type": "execute_result" } @@ -382,11 +391,11 @@ }, { "cell_type": "code", - "execution_count": 43, + "execution_count": 16, "metadata": {}, "outputs": [], "source": [ - "from langchain_mongodb.retrievers.parent_document import (\n", + "from langchain_mongodb.retrievers import (\n", " MongoDBAtlasParentDocumentRetriever,\n", ")\n", "from langchain_text_splitters import RecursiveCharacterTextSplitter\n", @@ -395,7 +404,7 @@ }, { "cell_type": "code", - "execution_count": 44, + "execution_count": 17, "metadata": {}, "outputs": [], "source": [ @@ -404,7 +413,7 @@ }, { "cell_type": "code", - "execution_count": 66, + "execution_count": 18, "metadata": {}, "outputs": [], "source": [ @@ -414,7 +423,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 19, "metadata": {}, "outputs": [], "source": [ @@ -444,7 +453,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 20, "metadata": {}, "outputs": [], "source": [ @@ -465,7 +474,7 @@ "metadata": {}, "outputs": [], "source": [ - "# Parent chunk retriever\n", + "# # Parent chunk retriever\n", "# parent_chunk_retriever = MongoDBAtlasParentDocumentRetriever.from_connection_string(\n", "# connection_string=MONGODB_URI,\n", "# embedding_model=embedding_model,\n", @@ -487,7 +496,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 22, "metadata": {}, "outputs": [], "source": [ @@ -497,7 +506,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 23, "metadata": {}, "outputs": [], "source": [ @@ -507,7 +516,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 24, "metadata": {}, "outputs": [], "source": [ @@ -526,7 +535,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 25, "metadata": {}, "outputs": [], "source": [ @@ -547,7 +556,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 26, "metadata": {}, "outputs": [], "source": [ @@ -574,7 +583,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 27, "metadata": {}, "outputs": [ { @@ -607,7 +616,7 @@ }, { "cell_type": "code", - "execution_count": 77, + "execution_count": 28, "metadata": {}, "outputs": [], "source": [ @@ -617,7 +626,7 @@ }, { "cell_type": "code", - "execution_count": 78, + "execution_count": 29, "metadata": {}, "outputs": [], "source": [ @@ -626,7 +635,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 30, "metadata": {}, "outputs": [], "source": [ @@ -689,7 +698,7 @@ }, { "cell_type": "code", - "execution_count": 81, + "execution_count": 31, "metadata": {}, "outputs": [], "source": [ @@ -701,7 +710,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 32, "metadata": {}, "outputs": [], "source": [ @@ -728,7 +737,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 33, "metadata": {}, "outputs": [ { @@ -738,37 +747,33 @@ "To improve slow queries in MongoDB, you can follow these steps:\n", "\n", "1. **Use the Performance Advisor**:\n", - " - The Performance Advisor monitors slow queries and suggests new indexes to improve query performance.\n", - " - Review the suggested indexes, especially those with high Impact scores and low Average Query Targeting scores, and create them if they align with your indexing strategies.\n", + " - The Performance Advisor monitors slow queries and suggests indexes to improve performance.\n", + " - Create the suggested indexes, especially those with high Impact scores and low Average Query Targeting scores.\n", "\n", "2. **Analyze Query Performance**:\n", - " - Use the **Query Profiler** to explore slow-running operations and their key performance statistics for up to the last 24 hours.\n", + " - Use the **Query Profiler** to identify slow-running operations and their key performance statistics.\n", " - Use the **Real-Time Performance Panel (RTPP)** to evaluate query execution times and the ratio of documents scanned to documents returned.\n", + " - Use **Namespace Insights** to monitor collection-level query latency.\n", "\n", - "3. **Monitor Query Latency**:\n", - " - Use **Namespace Insights** to monitor collection-level query latency and view query latency metrics and statistics.\n", + "3. **Optimize Indexes**:\n", + " - Create indexes that support your queries to reduce the time needed to search for results.\n", + " - Remove unused or inefficient indexes to improve write performance and free storage space.\n", + " - Perform rolling index builds to minimize performance impact on replica sets and sharded clusters.\n", "\n", - "4. **Fix Inefficient Queries**:\n", - " - Address `Query Targeting` alerts by adding indexes to support inefficient queries.\n", + "4. **Fix Query Targeting Issues**:\n", + " - Address `Query Targeting: Scanned Objects / Returned` or `Query Targeting: Scanned / Returned` alerts by adding indexes to support inefficient queries.\n", " - Use the `cursor.explain()` command to analyze query plans and identify inefficiencies.\n", "\n", "5. **Follow Best Practices**:\n", - " - Create queries that are supported by existing indexes.\n", - " - Avoid large array fields in documents that are costly to search and index.\n", - " - Optimize and remove unused or inefficient indexes to balance read and write performance.\n", - " - Perform rolling index builds to minimize performance impact on replica sets and sharded clusters.\n", - "\n", - "6. **Configure Slow Query Threshold**:\n", - " - Adjust the slow query threshold to identify slow queries more effectively. By default, Atlas dynamically adjusts this threshold, but you can set a fixed threshold of 100 milliseconds if needed.\n", - "\n", - "7. **Monitor Progress**:\n", - " - Use Query Targeting metrics, Namespace Insights, and the Query Profiler to visualize and track improvements in query performance.\n", + " - Avoid creating documents with large array fields that are costly to search and index.\n", + " - Optimize queries to take advantage of existing indexes.\n", + " - Use the suggested indexes from the Performance Advisor when they align with your indexing strategies.\n", "\n", - "8. **Address Common Issues**:\n", - " - Ensure queries are supported by indexes.\n", - " - Optimize queries involving `$lookup` or large array fields.\n", + "6. **Monitor and Adjust**:\n", + " - Use Query Targeting metrics and Query Profiler to monitor progress and ensure query performance improves.\n", + " - Adjust the slow query threshold if needed to better suit your workload.\n", "\n", - "By implementing these steps, you can identify and resolve slow queries, improving overall query performance in MongoDB.\n" + "By implementing these steps, you can significantly improve the performance of slow queries in MongoDB.\n" ] } ], @@ -786,7 +791,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 34, "metadata": {}, "outputs": [], "source": [ @@ -801,7 +806,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 35, "metadata": {}, "outputs": [], "source": [ @@ -824,7 +829,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 36, "metadata": {}, "outputs": [], "source": [ @@ -833,7 +838,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 37, "metadata": {}, "outputs": [], "source": [ @@ -861,7 +866,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 38, "metadata": {}, "outputs": [], "source": [ @@ -872,7 +877,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 39, "metadata": {}, "outputs": [], "source": [ @@ -894,7 +899,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 40, "metadata": {}, "outputs": [], "source": [ @@ -904,7 +909,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 41, "metadata": {}, "outputs": [], "source": [ @@ -927,83 +932,55 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 42, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ - "[HumanMessage(content='How do I improve slow queries in MongoDB?', additional_kwargs={}, response_metadata={}, id='d24196f2-dd7e-4342-9660-7f2a9933b807')]\n", "Node agent:\n", - "{'messages': [AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_8uC6x6EalTyPlaDn1xHG5bcr', 'function': {'arguments': '{\"user_query\":\"How do I improve slow queries in MongoDB?\"}', 'name': 'get_info_about_mongodb'}, 'type': 'function'}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 27, 'prompt_tokens': 165, 'total_tokens': 192, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-4o-2024-11-20', 'system_fingerprint': 'fp_a523ccd45c', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-81181db3-2a33-479b-9ee6-f773c47c1275-0', tool_calls=[{'name': 'get_info_about_mongodb', 'args': {'user_query': 'How do I improve slow queries in MongoDB?'}, 'id': 'call_8uC6x6EalTyPlaDn1xHG5bcr', 'type': 'tool_call'}], usage_metadata={'input_tokens': 165, 'output_tokens': 27, 'total_tokens': 192, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 0}})]}\n", + "{'messages': [AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_sifH0mrhbpesQie4BTnQytNk', 'function': {'arguments': '{\"user_query\":\"How do I improve slow queries in MongoDB?\"}', 'name': 'get_info_about_mongodb'}, 'type': 'function'}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 27, 'prompt_tokens': 165, 'total_tokens': 192, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-4o-2024-11-20', 'system_fingerprint': 'fp_d924043139', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-bc1db263-f4f5-40ba-a6ba-b18a3585e095-0', tool_calls=[{'name': 'get_info_about_mongodb', 'args': {'user_query': 'How do I improve slow queries in MongoDB?'}, 'id': 'call_sifH0mrhbpesQie4BTnQytNk', 'type': 'tool_call'}], usage_metadata={'input_tokens': 165, 'output_tokens': 27, 'total_tokens': 192, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 0}})]}\n", "Node tools:\n", - "{'messages': [ToolMessage(content='# Analyze Slow Queries\\n\\nAtlas provides several tools to help analyze slow queries executed on your clusters. See the following sections for descriptions of each tool. To optimize your query performance, review the best practices for query performance.\\n\\n## Performance Advisor\\n\\nThe Performance Advisor monitors queries that MongoDB considers slow and suggests new indexes to improve query performance.\\n\\nYou can use the Performance Advisor to review the following information:\\n\\n- Index Ranking\\n\\n- Drop Index Recommendations\\n\\n## Namespace Insights\\n\\nMonitor collection-level query latency with Namespace Insights. You can view query latency metrics and statistics for certain hosts and operation types. Manage pinned namespaces and choose up to five namespaces to show in the corresponding query latency charts.\\n\\n## Query Profiler\\n\\nThe Query Profiler displays slow-running operations and their key performance statistics. You can explore a sample of historical queries for up to the last 24 hours without additional cost or performance overhead. Before you enable the Query Profiler, see Considerations.\\n\\n## Real-Time Performance Panel (RTPP)\\n\\nThe Real-Time Performance Panel identifies relevant database operations, evaluates query execution times, and shows the ratio of documents scanned to documents returned during query execution. RTPP (Real-Time Performance Panel) is enabled by default.\\n\\nTo enable or disable Real-Time Performance Panel for a project, you must have the `Project Owner` role for the project.\\n\\n## Best Practices for Query Performance\\n\\nTo optimize query performance, review the following best practices:\\n\\n- Create queries that your current indexes support to reduce the time needed to search for your results.\\n\\n- Avoid creating documents with large array fields that require a lot of processing to search and index.\\n\\n- Optimize your indexes and remove unused or inefficent indexes. Too many indexes can negatively impact write performance.\\n\\n- Consider the suggested indexes from the Performance Advisor with the highest Impact scores and lowest Average Query Targeting scores.\\n\\n- Create the indexes that the Performance Advisor suggests when they align with your Indexing Strategies.\\n\\n- The Performance Advisor cannot suggest indexes for MongoDB databases configured to use the ctime timestamp format. As a workaround, set the timestamp format for such databases to either iso8601-utc or iso8601-local.\\n\\n- Perform rolling index builds to reduce the performance impact of building indexes on replica sets and sharded clusters.\\n\\n- Drop unused, redundant, and hidden indexes to improve write performance and free storage space.\\n\\n\\n\\n# Fix Query Issues\\n\\n`Query Targeting` alerts often indicate inefficient queries.\\n\\n## Alert Conditions\\n\\nYou can configure the following alert conditions in the project-level alert settings page to trigger alerts.\\n\\n`Query Targeting: Scanned Objects / Returned` alerts are triggered when the average number of documents scanned relative to the average number of documents returned server-wide across all operations during a sampling period exceeds a defined threshold. The default alert uses a 1000:1 threshold.\\n\\nIdeally, the ratio of scanned documents to returned documents should be close to 1. A high ratio negatively impacts query performance.\\n\\n`Query Targeting: Scanned / Returned` occurs if the number of index keys examined to fulfill a query relative to the actual number of returned documents meets or exceeds a user-defined threshold. This alert is not enabled by default.\\n\\nThe following mongod log entry shows statistics generated from an inefficient query:\\n\\n```json\\n COMMAND \\nplanSummary: COLLSCAN keysExamined:0\\ndocsExamined: 10000 cursorExhausted:1 numYields:234\\nnreturned:4 protocol:op_query 358ms\\n```\\n\\nThis query scanned 10,000 documents and returned only 4 for a ratio of 2500, which is highly inefficient. No index keys were examined, so MongoDB scanned all documents in the collection, known as a collection scan.\\n\\n## Common Triggers\\n\\nThe query targeting alert typically occurs when there is no index to support a query or queries or when an existing index only partially supports a query or queries.\\n\\nThe change streams cursors that the Atlas Search process (`mongot`) uses to keep Atlas Search indexes updated can contribute to the query targeting ratio and trigger query targeting alerts if the ratio is high.\\n\\n## Fix the Immediate Problem\\n\\nAdd one or more indexes to better serve the inefficient queries.\\n\\nThe Performance Advisor provides the easiest and quickest way to create an index. The Performance Advisor monitors queries that MongoDB considers slow and recommends indexes to improve performance. Atlas dynamically adjusts your slow query threshold based on the execution time of operations across your cluster.\\n\\nClick Create Index on a slow query for instructions on how to create the recommended index.\\n\\nIt is possible to receive a Query Targeting alert for an inefficient query without receiving index suggestions from the Performance Advisor if the query exceeds the slow query threshold and the ratio of scanned to returned documents is greater than the threshold specified in the alert.\\n\\nIn addition, you can use the following resources to determine which query generated the alert:\\n\\n- The Real-Time Performance Panel monitors and displays current network traffic and database operations on machines hosting MongoDB in your Atlas clusters.\\n\\n- The MongoDB logs maintain an account of activity, including queries, for each `mongod` instance in your Atlas clusters.\\n\\n- The cursor.explain() command for `mongosh` provides performance details for all queries.\\n\\n- Namespace Insights monitors collection-level query latency.\\n\\n- The Atlas Query Profiler records operations that Atlas considers slow when compared to average execution time for all operations on your cluster.\\n\\n## Implement a Long-Term Solution\\n\\nRefer to the following for more information on query performance:\\n\\n- MongoDB Indexing Strategies\\n\\n- Query Optimization\\n\\n- Analyze Query Plan\\n\\n## Monitor Your Progress\\n\\nAtlas provides the following methods to visualize query targeting:\\n\\n- Query Targeting metrics, which highlight high ratios of objects scanned to objects returned.\\n\\n- Namespace Insights, which monitors collection-level query latency.\\n\\n- The Query Profiler, which describes specific inefficient queries executed on the cluster.\\n\\n### Query Targeting Metrics\\n\\nYou can view historical metrics to help you visualize the query performance of your cluster. To view Query Targeting metrics in the Atlas UI:\\n\\n1. Click Database in the top-left corner of Atlas.\\n\\n2. Click View Monitoring on the dashboard for the cluster.\\n\\n3. On the Metrics page, click the Add Chart dropdown menu and select Query Targeting.\\n\\nThe Query Targeting chart displays the following metrics for queries executed on the server:\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n
\\nMetric\\n\\n\\nDescription\\n\\n
\\nScanned Objects / Returned\\n\\n\\nIndicates the average number of documents examined relative to the average number of returned documents.\\n\\n
\\nScanned / Returned\\n\\n\\nIndicates the number of index keys examined to fulfill a query relative to the actual number of returned documents.\\n\\n
The change streams cursors that the Atlas Search process (`mongot`) uses to keep Atlas Search indexes updated can contribute to the query targeting ratio and trigger query targeting alerts if the ratio is high.\\n\\nIf either of these metrics exceed the user-defined threshold, Atlas generates the corresponding `Query Targeting: Scanned Objects / Returned` or `Query Targeting: Scanned / Returned` alert.\\n\\nYou can also view Query Targeting ratios of operations in real-time using the Real-Time Performance Panel.\\n\\n### Namespace Insights\\n\\nNamespace Insights monitors collection-level query latency. You can view query latency metrics and statistics for certain hosts and operation types. Manage pinned namespaces and choose up to five namespaces to show in the corresponding query latency charts.\\n\\nTo access Namespace Insights:\\n\\n1. Click Database in the top-left corner of Atlas.\\n\\n2. Click View Monitoring on the dashboard for the cluster.\\n\\n3. Click the Query Insights tab.\\n\\n4. Click the Namespace Insights tab.\\n\\n### Query Profiler\\n\\nThe Query Profiler contains several metrics you can use to pinpoint specific inefficient queries. You can visualize up to the past 24 hours of query operations. The Query Profiler can show the Examined : Returned Ratio (index keys examined to documents returned) of logged queries, which might help you identify the queries that triggered a `Query Targeting: Scanned / Returned` alert. The chart shows the number of index keys examined to fulfill a query relative to the actual number of returned documents.\\n\\nThe default\\n`Query Targeting: Scanned Objects / Returned` alert ratio differs slightly. The ratio of the average number of documents scanned to the average number of documents returned during a sampling period triggers this alert.\\n\\nAtlas might not log the individual operations that contribute to the Query Targeting ratios due to automatically set thresholds. However, you can still use the Query Profiler and Query Targeting metrics to analyze and optimize query performance.\\n\\nTo access the Query Profiler:\\n\\n1. Click Database in the top-left corner of Atlas.\\n\\n2. Click View Monitoring on the dashboard for the cluster.\\n\\n3. Click the Query Insights tab.\\n\\n4. Click the Query Profiler tab.\\n\\n\\n\\n# Monitor and Improve Slow Queries\\n\\n*Only available on M10+ clusters and serverless instances*\\n\\nThe Performance Advisor monitors queries that MongoDB considers slow and suggests new indexes to improve query performance. The threshold for slow queries varies based on the average time of operations on your cluster to provide recommendations pertinent to your workload.\\n\\nRecommended indexes are accompanied by sample queries, grouped by query shape, that were run against a collection that would benefit from the suggested index. The Performance Advisor doesn\\'t negatively affect the performance of your Atlas clusters.\\n\\nYou can also monitor collection-level query latency with Namespace Insights and query performance with the Query Profiler.\\n\\nIf the slow query log contains consecutive `$match` stages in the aggregation pipeline, the two stages can coalesce into the first `$match` stage and result in a single `$match` stage. As a result, the query shape in the Performance Advisor might differ from the actual query you ran.\\n\\n## Common Reasons for Slow Queries\\n\\nIf a query is slow, common reasons include:\\n\\n- The query is unsupported by your current indexes.\\n\\n- Some documents in your collection have large array fields that are costly to search and index.\\n\\n- One query retrieves information from multiple collections with $lookup.\\n\\n## Required Access\\n\\nTo view collections with slow queries and see suggested indexes, you must have `Project Read Only` access or higher to the project.\\n\\nTo view field values in a sample query in the Performance Advisor, you must have `Project Data Access Read/Write` access or higher to the project.\\n\\nTo enable or disable the Atlas-managed slow operation threshold, you must have `Project Owner` access to the project. Users with `Organization Owner` access must add themselves to the project as a `Project Owner`.\\n\\n## Configure the Slow Query Threshold\\n\\nBy default, Atlas dynamically adjusts your slow query threshold based on the execution time of operations across your cluster. However, you can opt out of this feature and instead use a fixed slow query threshold of 100 milliseconds. You can disable the Atlas-managed slow operation threshold with the Atlas CLI, Atlas Administration API, or Atlas UI.\\n\\nAtlas clusters with Atlas Search enabled don\\'t support the Atlas-managed slow query operation threshold.\\n\\nFor `M0`, `M2`, `M5` clusters and serverless instances, Atlas disables the Atlas-managed slow query operation threshold by default and you can\\'t enable it.\\n\\n### Disable the Atlas-Managed Slow Operation Threshold\\n\\nBy default, Atlas dynamically adjusts your slow query threshold based on the execution time of operations across your cluster. If you disable the Atlas-managed slow query threshold, it no longer dynamically adjusts. MongoDB defaults the fixed slow query threshold to 100 milliseconds. We don\\'t recommend that you set the fixed slow query threshold lower than 100 milliseconds.\\n\\nTo disable the Atlas-managed slow operation threshold and use a fixed threshold of 100 milliseconds:\\n\\n\\n\\n\\n\\nTo disable the Atlas-managed slow operation threshold for your project using the Atlas CLI, run the following command:\\n\\n```sh\\n\\natlas performanceAdvisor slowOperationThreshold disable [options]\\n\\n```\\n\\nTo learn more about the command syntax and parameters, see the Atlas CLI documentation for atlas performanceAdvisor slowOperationThreshold disable.\\n\\n- Install the Atlas CLI\\n\\n- Connect to the Atlas CLI\\n\\n\\n\\n\\n\\nSee Disable Managed Slow Operation Threshold.\\n\\n\\n\\n\\n\\nIn the Project Settings for the current project, toggle Managed Slow Operations to Off.\\n\\n\\n\\n\\n\\n### Enable the Atlas-Managed Slow Operation Threshold\\n\\nAtlas enables the Atlas-managed slow operation threshold by default. To re-enable the Atlas-managed slow operation threshold that you previously disabled:\\n\\n\\n\\n\\n\\nTo enable the Atlas-managed slow operation threshold for your project using the Atlas CLI, run the following command:\\n\\n```sh\\n\\natlas performanceAdvisor slowOperationThreshold enable [options]\\n\\n```\\n\\nTo learn more about the command syntax and parameters, see the Atlas CLI documentation for atlas performanceAdvisor slowOperationThreshold enable.\\n\\n- Install the Atlas CLI\\n\\n- Connect to the Atlas CLI\\n\\n\\n\\n\\n\\nSee Enable Managed Slow Operation Threshold.\\n\\n\\n\\n\\n\\nIn the Project Settings for the current project, toggle Managed Slow Operations to On.\\n\\n\\n\\n\\n\\n## Index Considerations\\n\\nIndexes improve read performance, but a large number of indexes can negatively impact write performance since indexes must be updated during writes. If your collection already has several indexes, consider this tradeoff of read and write performance when deciding whether to create new indexes. Examine whether a query for such a collection can be modified to take advantage of existing indexes, as well as whether a query occurs often enough to justify the cost of a new index.\\n\\n## Access Performance Advisor\\n\\n\\n\\n\\n\\n### View Collections with Slow Queries\\n\\nTo return up to 20 namespaces in `.` format for collections experiencing slow queries using the Atlas CLI, run the following command:\\n\\n```sh\\n\\natlas performanceAdvisor namespaces list [options]\\n\\n```\\n\\nTo learn more about the command syntax and parameters, see the Atlas CLI documentation for atlas performanceAdvisor namespaces list.\\n\\n- Install the Atlas CLI\\n\\n- Connect to the Atlas CLI\\n\\n### View Slow Query Logs\\n\\nTo return query log line items for slow queries that the Performance Advisor and Query Profiler identify using the Atlas CLI, run the following command:\\n\\n```sh\\n\\natlas performanceAdvisor slowQueryLogs list [options]\\n\\n```\\n\\nTo learn more about the command syntax and parameters, see the Atlas CLI documentation for atlas performanceAdvisor slowQueryLogs list.\\n\\n- Install the Atlas CLI\\n\\n- Connect to the Atlas CLI\\n\\n### View Suggested Indexes\\n\\nTo return suggested indexes for collections experiencing slow queries using the Atlas CLI, run the following command:\\n\\n```sh\\n\\natlas performanceAdvisor suggestedIndexes list [options]\\n\\n```\\n\\nTo learn more about the command syntax and parameters, see the Atlas CLI documentation for atlas performanceAdvisor suggestedIndexes list.\\n\\n- Install the Atlas CLI\\n\\n- Connect to the Atlas CLI\\n\\n\\n\\n\\n\\nTo access the Performance Advisor using the Atlas UI:\\n\\n\\n\\n\\n\\n### Click Database.\\n\\n### Click the replica set where the collection resides.\\n\\nIf the replica set resides in a sharded cluster, first click the sharded cluster containing the replica set.\\n\\n### Click Performance Advisor.\\n\\n### Select a collection from the Collections dropdown.\\n\\n### Select a time period from the Time Range dropdown.\\n\\n\\n\\n\\n\\n### Click Database.\\n\\n### Click the serverless instance.\\n\\n### Click Performance Advisor.\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nThe Performance Advisor displays up to 20 query shapes across all collections in the cluster and suggested indexes for those shapes. The Performance Advisor ranks the indexes according to their Impact, which indicates High or Medium based on the total wasted bytes read. To learn more about index ranking, see Review Index Ranking.\\n\\n## Index Suggestions\\n\\nThe Performance Advisor ranks the indexes that it suggests according to their Impact, which indicates High or Medium based on the total wasted bytes read. To learn more about how the Performance Advisor ranks indexes, see Review Index Ranking.\\n\\nTo learn how to create indexes that the Performance Advisor suggests, see Create Suggested Indexes.\\n\\n### Index Metrics\\n\\nEach index that the Performance Advisor suggests contains the following metrics. These metrics apply specifically to queries which would be improved by the index:\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n
\\nMetric\\n\\n\\nDescription\\n\\n
\\nExecution Count\\n\\n\\nNumber of queries executed per hour which would be improved.\\n\\n
\\nAverage Execution Time\\n\\n\\nCurrent average execution time in milliseconds for affected queries.\\n\\n
\\nAverage Query Targeting\\n\\n\\nAverage number of documents read per document returned by affected queries. A higher query targeting score indicates a greater degree of inefficiency. For more information on query targeting, see Query Targeting.\\n\\n
\\nIn Memory Sort\\n\\n\\nCurrent number of affected queries per hour that needed to be sorted in memory.\\n\\n
\\nAverage Docs Scanned\\n\\n\\nAverage number of documents scanned.\\n\\n
\\nAverage Docs Returned\\n\\n\\nAverage number of documents returned.\\n\\n
\\nAverage Object Size\\n\\n\\nAverage object size.\\n\\n
\\n\\n### Sample Queries\\n\\nFor each suggested index, the Performance Advisor shows the most commonly executed query shapes that the index would improve. For each query shape, the Performance Advisor displays the following metrics:\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n
\\nMetric\\n\\n\\nDescription\\n\\n
\\nExecution Count\\n\\n\\nNumber of queries executed per hour which match the query shape.\\n\\n
\\nAverage Execution Time\\n\\n\\nAverage execution time in milliseconds for queries which match the query shape.\\n\\n
\\nAverage Query Targeting\\n\\n\\nAverage number of documents read for every document returned by matching queries. A higher query targeting score indicates a greater degree of inefficiency. For more information on query targeting, see Query Targeting.\\n\\n
\\nAverage Docs Scanned\\n\\n\\nAverage number of documents scanned.\\n\\n
\\nAverage Docs Returned\\n\\n\\nAverage number of documents returned.\\n\\n
The Performance Advisor also shows each executed sample query that matches the query shape, with specific metrics for that query.\\n\\n### Query Targeting\\n\\nEach index suggestion includes an Average Query Targeting score indicating how many documents were read for every document returned for the index\\'s corresponding query shapes. A score of 1 represents very efficient query shapes because every document read matched the query and was returned with the query results. All suggested indexes represent an opportunity to improve query performance.\\n\\n### Filter Index Suggestions\\n\\nBy default, the Performance Advisor suggests indexes for all clusters in the deployment. To only show suggested indexes from a specific collection, use the Collection dropdown at the top of the Performance Advisor.\\n\\nYou can also adjust the time range the Performance Advisor takes into account when suggesting indexes by using the Time Range dropdown at the top of the Performance Advisor.\\n\\n### Limitations of Index Suggestions\\n\\n#### Timestamp Format\\n\\nThe Performance Advisor can\\'t suggest indexes for MongoDB databases configured to use the `ctime` timestamp format. As a workaround, set the timestamp format for such databases to either `iso8601-utc` or `iso8601-local`. To learn more about timestamp formats, see mongod --timeStampFormat.\\n\\n#### Log Size\\n\\nThe Performance Advisor analyzes up to 200,000 of your cluster\\'s most recent log lines.\\n\\n#### Log Quantity\\n\\nIf a cluster experiences an activity spike and generates an extremely large quantity of log messages, Atlas may stop collecting and storing new logs for a period of time.\\n\\nLog analysis rate limits apply only to the Performance Advisor UI, the Query Insights UI, the Access Tracking UI, and the Atlas Search Query Analytics UI. Downloadable log files are always complete.\\n\\n#### Time-Series Collections\\n\\nThe Performance Advisor doesn\\'t provide performance suggestions for time-series collections.\\n\\n#### User Feedback\\n\\nThe Performance Advisor includes a user feedback button for Index Suggestions. Atlas hides this button for serverless instances.\\n\\n## Create Suggested Indexes\\n\\nYou can create indexes suggested by the Performance Advisor directly within the Performance Advisor itself. When you create indexes, keep the ratio of reads to writes on the target collection in mind. Indexes come with a performance cost, but are more than worth the cost for frequent queries on large data sets. To learn more about indexing strategies, see Indexing Strategies.\\n\\n### Behavior and Limitations\\n\\n- You can\\'t create indexes through the Performance Advisor if Data Explorer is disabled for your project. You can still view the Performance Advisor recommendations, but you must create those indexes from `mongosh`.\\n\\n- You can only create one index at a time through the Performance Advisor. If you want to create more simultaneously, you can do so using the Atlas UI, a driver, or the shell\\n\\n- Atlas always creates indexes for entire clusters. If you create an index while viewing the Performance Advisor for a single shard in a sharded cluster, Atlas creates that index for the entire sharded cluster.\\n\\n### Procedure\\n\\nTo create a suggested index:\\n\\n#### For the index you want to create, click Create Index.\\n\\nThe Performance Advisor opens the Create Index dialog and prepopulates the Fields based on the index you selected.\\n\\n#### *(Optional)* Specify the index options.\\n\\n```javascript\\n{ : , ... }\\n```\\n\\nThe following options document specifies the `unique` option and the `name` for the index:\\n\\n```javascript\\n{ unique: true, name: \"myUniqueIndex\" }\\n```\\n\\n#### *(Optional)* Set the Collation options.\\n\\nUse collation to specify language-specific rules for string comparison, such as rules for lettercase and accent marks. The collation document contains a `locale` field which indicates the ICU Locale code, and may contain other fields to define collation behavior.\\n\\nThe following collation option document specifies a locale value of `fr` for a French language collation:\\n\\n```json\\n{ \"locale\": \"fr\" }\\n```\\n\\nTo review the list of locales that MongoDB collation supports, see the list of languages and locales. To learn more about collation options, including which are enabled by default for each locale, see Collation in the MongoDB manual.\\n\\n#### *(Optional)* Enable building indexes in a rolling fashion.\\n\\nRolling index builds succeed only when they meet certain conditions. To ensure your index build succeeds, avoid the following design patterns that commonly trigger a restart loop:\\n\\n- Index key exceeds the index key limit\\n\\n- Index name already exists\\n\\n- Index on more than one array field\\n\\n- Index on collection that has the maximum number of text indexes\\n\\n- Text index on collection that has the maximum number of text indexes\\n\\nthe Atlas UI doesn\\'t support building indexes with a rolling build for `M0` free clusters and `M2/M5` shared clusters. You can\\'t build indexes with a rolling build for serverless instances.\\n\\nFor workloads which cannot tolerate performance decrease due to index builds, consider building indexes in a rolling fashion.\\n\\nTo maintain cluster availability:\\n\\n- Atlas removes one node from the cluster at a time starting with a secondary.\\n\\n- More than one node can go down at a time, but Atlas always keeps a majority of the nodes online.\\n\\nAtlas automatically cancels rolling index builds that don\\'t succeed on all nodes. When a rolling index build completes on some nodes, but fails on others, Atlas cancels the build and removes the index from any nodes that it was successfully built on.\\n\\nIn the event of a rolling index build cancellation, Atlas generates an activity feed event and sends a notification email to the project owner with the following information:\\n\\n- Name of the cluster on which the rolling index build failed\\n\\n- Namespace on which the rolling index build failed\\n\\n- Project that contains the cluster and namespace\\n\\n- Organization that contains the project\\n\\n- Link to the activity feed event\\n\\nTo learn more about rebuilding indexes, see Build Indexes on Replica Sets.\\n\\nUnique\\nindex options are incompatible with building indexes in a rolling fashion. If you specify `unique` in the Options pane, Atlas rejects your configuration with an error message.\\n\\n#### Click Review.\\n\\n#### In the Confirm Operation dialog, confirm your index.\\n\\nWhen an index build completes, Atlas generates an activity feed event and sends a notification email to the project owner with the following information:\\n\\n- Completion date of the index build\\n\\n- Name of the cluster on which the index build completed\\n\\n- Namespace on which the index build completed\\n\\n- Project containing the cluster and namespace\\n\\n- Organization containing the project\\n\\n- Link to the activity feed event\\n\\n', name='get_info_about_mongodb', id='e5bb7c63-71df-428b-b811-8784fec6e2cd', tool_call_id='call_8uC6x6EalTyPlaDn1xHG5bcr')]}\n", - "[HumanMessage(content='How do I improve slow queries in MongoDB?', additional_kwargs={}, response_metadata={}, id='d24196f2-dd7e-4342-9660-7f2a9933b807'), AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_8uC6x6EalTyPlaDn1xHG5bcr', 'function': {'arguments': '{\"user_query\":\"How do I improve slow queries in MongoDB?\"}', 'name': 'get_info_about_mongodb'}, 'type': 'function'}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 27, 'prompt_tokens': 165, 'total_tokens': 192, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-4o-2024-11-20', 'system_fingerprint': 'fp_a523ccd45c', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-81181db3-2a33-479b-9ee6-f773c47c1275-0', tool_calls=[{'name': 'get_info_about_mongodb', 'args': {'user_query': 'How do I improve slow queries in MongoDB?'}, 'id': 'call_8uC6x6EalTyPlaDn1xHG5bcr', 'type': 'tool_call'}], usage_metadata={'input_tokens': 165, 'output_tokens': 27, 'total_tokens': 192, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 0}}), ToolMessage(content='# Analyze Slow Queries\\n\\nAtlas provides several tools to help analyze slow queries executed on your clusters. See the following sections for descriptions of each tool. To optimize your query performance, review the best practices for query performance.\\n\\n## Performance Advisor\\n\\nThe Performance Advisor monitors queries that MongoDB considers slow and suggests new indexes to improve query performance.\\n\\nYou can use the Performance Advisor to review the following information:\\n\\n- Index Ranking\\n\\n- Drop Index Recommendations\\n\\n## Namespace Insights\\n\\nMonitor collection-level query latency with Namespace Insights. You can view query latency metrics and statistics for certain hosts and operation types. Manage pinned namespaces and choose up to five namespaces to show in the corresponding query latency charts.\\n\\n## Query Profiler\\n\\nThe Query Profiler displays slow-running operations and their key performance statistics. You can explore a sample of historical queries for up to the last 24 hours without additional cost or performance overhead. Before you enable the Query Profiler, see Considerations.\\n\\n## Real-Time Performance Panel (RTPP)\\n\\nThe Real-Time Performance Panel identifies relevant database operations, evaluates query execution times, and shows the ratio of documents scanned to documents returned during query execution. RTPP (Real-Time Performance Panel) is enabled by default.\\n\\nTo enable or disable Real-Time Performance Panel for a project, you must have the `Project Owner` role for the project.\\n\\n## Best Practices for Query Performance\\n\\nTo optimize query performance, review the following best practices:\\n\\n- Create queries that your current indexes support to reduce the time needed to search for your results.\\n\\n- Avoid creating documents with large array fields that require a lot of processing to search and index.\\n\\n- Optimize your indexes and remove unused or inefficent indexes. Too many indexes can negatively impact write performance.\\n\\n- Consider the suggested indexes from the Performance Advisor with the highest Impact scores and lowest Average Query Targeting scores.\\n\\n- Create the indexes that the Performance Advisor suggests when they align with your Indexing Strategies.\\n\\n- The Performance Advisor cannot suggest indexes for MongoDB databases configured to use the ctime timestamp format. As a workaround, set the timestamp format for such databases to either iso8601-utc or iso8601-local.\\n\\n- Perform rolling index builds to reduce the performance impact of building indexes on replica sets and sharded clusters.\\n\\n- Drop unused, redundant, and hidden indexes to improve write performance and free storage space.\\n\\n\\n\\n# Fix Query Issues\\n\\n`Query Targeting` alerts often indicate inefficient queries.\\n\\n## Alert Conditions\\n\\nYou can configure the following alert conditions in the project-level alert settings page to trigger alerts.\\n\\n`Query Targeting: Scanned Objects / Returned` alerts are triggered when the average number of documents scanned relative to the average number of documents returned server-wide across all operations during a sampling period exceeds a defined threshold. The default alert uses a 1000:1 threshold.\\n\\nIdeally, the ratio of scanned documents to returned documents should be close to 1. A high ratio negatively impacts query performance.\\n\\n`Query Targeting: Scanned / Returned` occurs if the number of index keys examined to fulfill a query relative to the actual number of returned documents meets or exceeds a user-defined threshold. This alert is not enabled by default.\\n\\nThe following mongod log entry shows statistics generated from an inefficient query:\\n\\n```json\\n COMMAND \\nplanSummary: COLLSCAN keysExamined:0\\ndocsExamined: 10000 cursorExhausted:1 numYields:234\\nnreturned:4 protocol:op_query 358ms\\n```\\n\\nThis query scanned 10,000 documents and returned only 4 for a ratio of 2500, which is highly inefficient. No index keys were examined, so MongoDB scanned all documents in the collection, known as a collection scan.\\n\\n## Common Triggers\\n\\nThe query targeting alert typically occurs when there is no index to support a query or queries or when an existing index only partially supports a query or queries.\\n\\nThe change streams cursors that the Atlas Search process (`mongot`) uses to keep Atlas Search indexes updated can contribute to the query targeting ratio and trigger query targeting alerts if the ratio is high.\\n\\n## Fix the Immediate Problem\\n\\nAdd one or more indexes to better serve the inefficient queries.\\n\\nThe Performance Advisor provides the easiest and quickest way to create an index. The Performance Advisor monitors queries that MongoDB considers slow and recommends indexes to improve performance. Atlas dynamically adjusts your slow query threshold based on the execution time of operations across your cluster.\\n\\nClick Create Index on a slow query for instructions on how to create the recommended index.\\n\\nIt is possible to receive a Query Targeting alert for an inefficient query without receiving index suggestions from the Performance Advisor if the query exceeds the slow query threshold and the ratio of scanned to returned documents is greater than the threshold specified in the alert.\\n\\nIn addition, you can use the following resources to determine which query generated the alert:\\n\\n- The Real-Time Performance Panel monitors and displays current network traffic and database operations on machines hosting MongoDB in your Atlas clusters.\\n\\n- The MongoDB logs maintain an account of activity, including queries, for each `mongod` instance in your Atlas clusters.\\n\\n- The cursor.explain() command for `mongosh` provides performance details for all queries.\\n\\n- Namespace Insights monitors collection-level query latency.\\n\\n- The Atlas Query Profiler records operations that Atlas considers slow when compared to average execution time for all operations on your cluster.\\n\\n## Implement a Long-Term Solution\\n\\nRefer to the following for more information on query performance:\\n\\n- MongoDB Indexing Strategies\\n\\n- Query Optimization\\n\\n- Analyze Query Plan\\n\\n## Monitor Your Progress\\n\\nAtlas provides the following methods to visualize query targeting:\\n\\n- Query Targeting metrics, which highlight high ratios of objects scanned to objects returned.\\n\\n- Namespace Insights, which monitors collection-level query latency.\\n\\n- The Query Profiler, which describes specific inefficient queries executed on the cluster.\\n\\n### Query Targeting Metrics\\n\\nYou can view historical metrics to help you visualize the query performance of your cluster. To view Query Targeting metrics in the Atlas UI:\\n\\n1. Click Database in the top-left corner of Atlas.\\n\\n2. Click View Monitoring on the dashboard for the cluster.\\n\\n3. On the Metrics page, click the Add Chart dropdown menu and select Query Targeting.\\n\\nThe Query Targeting chart displays the following metrics for queries executed on the server:\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n
\\nMetric\\n\\n\\nDescription\\n\\n
\\nScanned Objects / Returned\\n\\n\\nIndicates the average number of documents examined relative to the average number of returned documents.\\n\\n
\\nScanned / Returned\\n\\n\\nIndicates the number of index keys examined to fulfill a query relative to the actual number of returned documents.\\n\\n
The change streams cursors that the Atlas Search process (`mongot`) uses to keep Atlas Search indexes updated can contribute to the query targeting ratio and trigger query targeting alerts if the ratio is high.\\n\\nIf either of these metrics exceed the user-defined threshold, Atlas generates the corresponding `Query Targeting: Scanned Objects / Returned` or `Query Targeting: Scanned / Returned` alert.\\n\\nYou can also view Query Targeting ratios of operations in real-time using the Real-Time Performance Panel.\\n\\n### Namespace Insights\\n\\nNamespace Insights monitors collection-level query latency. You can view query latency metrics and statistics for certain hosts and operation types. Manage pinned namespaces and choose up to five namespaces to show in the corresponding query latency charts.\\n\\nTo access Namespace Insights:\\n\\n1. Click Database in the top-left corner of Atlas.\\n\\n2. Click View Monitoring on the dashboard for the cluster.\\n\\n3. Click the Query Insights tab.\\n\\n4. Click the Namespace Insights tab.\\n\\n### Query Profiler\\n\\nThe Query Profiler contains several metrics you can use to pinpoint specific inefficient queries. You can visualize up to the past 24 hours of query operations. The Query Profiler can show the Examined : Returned Ratio (index keys examined to documents returned) of logged queries, which might help you identify the queries that triggered a `Query Targeting: Scanned / Returned` alert. The chart shows the number of index keys examined to fulfill a query relative to the actual number of returned documents.\\n\\nThe default\\n`Query Targeting: Scanned Objects / Returned` alert ratio differs slightly. The ratio of the average number of documents scanned to the average number of documents returned during a sampling period triggers this alert.\\n\\nAtlas might not log the individual operations that contribute to the Query Targeting ratios due to automatically set thresholds. However, you can still use the Query Profiler and Query Targeting metrics to analyze and optimize query performance.\\n\\nTo access the Query Profiler:\\n\\n1. Click Database in the top-left corner of Atlas.\\n\\n2. Click View Monitoring on the dashboard for the cluster.\\n\\n3. Click the Query Insights tab.\\n\\n4. Click the Query Profiler tab.\\n\\n\\n\\n# Monitor and Improve Slow Queries\\n\\n*Only available on M10+ clusters and serverless instances*\\n\\nThe Performance Advisor monitors queries that MongoDB considers slow and suggests new indexes to improve query performance. The threshold for slow queries varies based on the average time of operations on your cluster to provide recommendations pertinent to your workload.\\n\\nRecommended indexes are accompanied by sample queries, grouped by query shape, that were run against a collection that would benefit from the suggested index. The Performance Advisor doesn\\'t negatively affect the performance of your Atlas clusters.\\n\\nYou can also monitor collection-level query latency with Namespace Insights and query performance with the Query Profiler.\\n\\nIf the slow query log contains consecutive `$match` stages in the aggregation pipeline, the two stages can coalesce into the first `$match` stage and result in a single `$match` stage. As a result, the query shape in the Performance Advisor might differ from the actual query you ran.\\n\\n## Common Reasons for Slow Queries\\n\\nIf a query is slow, common reasons include:\\n\\n- The query is unsupported by your current indexes.\\n\\n- Some documents in your collection have large array fields that are costly to search and index.\\n\\n- One query retrieves information from multiple collections with $lookup.\\n\\n## Required Access\\n\\nTo view collections with slow queries and see suggested indexes, you must have `Project Read Only` access or higher to the project.\\n\\nTo view field values in a sample query in the Performance Advisor, you must have `Project Data Access Read/Write` access or higher to the project.\\n\\nTo enable or disable the Atlas-managed slow operation threshold, you must have `Project Owner` access to the project. Users with `Organization Owner` access must add themselves to the project as a `Project Owner`.\\n\\n## Configure the Slow Query Threshold\\n\\nBy default, Atlas dynamically adjusts your slow query threshold based on the execution time of operations across your cluster. However, you can opt out of this feature and instead use a fixed slow query threshold of 100 milliseconds. You can disable the Atlas-managed slow operation threshold with the Atlas CLI, Atlas Administration API, or Atlas UI.\\n\\nAtlas clusters with Atlas Search enabled don\\'t support the Atlas-managed slow query operation threshold.\\n\\nFor `M0`, `M2`, `M5` clusters and serverless instances, Atlas disables the Atlas-managed slow query operation threshold by default and you can\\'t enable it.\\n\\n### Disable the Atlas-Managed Slow Operation Threshold\\n\\nBy default, Atlas dynamically adjusts your slow query threshold based on the execution time of operations across your cluster. If you disable the Atlas-managed slow query threshold, it no longer dynamically adjusts. MongoDB defaults the fixed slow query threshold to 100 milliseconds. We don\\'t recommend that you set the fixed slow query threshold lower than 100 milliseconds.\\n\\nTo disable the Atlas-managed slow operation threshold and use a fixed threshold of 100 milliseconds:\\n\\n\\n\\n\\n\\nTo disable the Atlas-managed slow operation threshold for your project using the Atlas CLI, run the following command:\\n\\n```sh\\n\\natlas performanceAdvisor slowOperationThreshold disable [options]\\n\\n```\\n\\nTo learn more about the command syntax and parameters, see the Atlas CLI documentation for atlas performanceAdvisor slowOperationThreshold disable.\\n\\n- Install the Atlas CLI\\n\\n- Connect to the Atlas CLI\\n\\n\\n\\n\\n\\nSee Disable Managed Slow Operation Threshold.\\n\\n\\n\\n\\n\\nIn the Project Settings for the current project, toggle Managed Slow Operations to Off.\\n\\n\\n\\n\\n\\n### Enable the Atlas-Managed Slow Operation Threshold\\n\\nAtlas enables the Atlas-managed slow operation threshold by default. To re-enable the Atlas-managed slow operation threshold that you previously disabled:\\n\\n\\n\\n\\n\\nTo enable the Atlas-managed slow operation threshold for your project using the Atlas CLI, run the following command:\\n\\n```sh\\n\\natlas performanceAdvisor slowOperationThreshold enable [options]\\n\\n```\\n\\nTo learn more about the command syntax and parameters, see the Atlas CLI documentation for atlas performanceAdvisor slowOperationThreshold enable.\\n\\n- Install the Atlas CLI\\n\\n- Connect to the Atlas CLI\\n\\n\\n\\n\\n\\nSee Enable Managed Slow Operation Threshold.\\n\\n\\n\\n\\n\\nIn the Project Settings for the current project, toggle Managed Slow Operations to On.\\n\\n\\n\\n\\n\\n## Index Considerations\\n\\nIndexes improve read performance, but a large number of indexes can negatively impact write performance since indexes must be updated during writes. If your collection already has several indexes, consider this tradeoff of read and write performance when deciding whether to create new indexes. Examine whether a query for such a collection can be modified to take advantage of existing indexes, as well as whether a query occurs often enough to justify the cost of a new index.\\n\\n## Access Performance Advisor\\n\\n\\n\\n\\n\\n### View Collections with Slow Queries\\n\\nTo return up to 20 namespaces in `.` format for collections experiencing slow queries using the Atlas CLI, run the following command:\\n\\n```sh\\n\\natlas performanceAdvisor namespaces list [options]\\n\\n```\\n\\nTo learn more about the command syntax and parameters, see the Atlas CLI documentation for atlas performanceAdvisor namespaces list.\\n\\n- Install the Atlas CLI\\n\\n- Connect to the Atlas CLI\\n\\n### View Slow Query Logs\\n\\nTo return query log line items for slow queries that the Performance Advisor and Query Profiler identify using the Atlas CLI, run the following command:\\n\\n```sh\\n\\natlas performanceAdvisor slowQueryLogs list [options]\\n\\n```\\n\\nTo learn more about the command syntax and parameters, see the Atlas CLI documentation for atlas performanceAdvisor slowQueryLogs list.\\n\\n- Install the Atlas CLI\\n\\n- Connect to the Atlas CLI\\n\\n### View Suggested Indexes\\n\\nTo return suggested indexes for collections experiencing slow queries using the Atlas CLI, run the following command:\\n\\n```sh\\n\\natlas performanceAdvisor suggestedIndexes list [options]\\n\\n```\\n\\nTo learn more about the command syntax and parameters, see the Atlas CLI documentation for atlas performanceAdvisor suggestedIndexes list.\\n\\n- Install the Atlas CLI\\n\\n- Connect to the Atlas CLI\\n\\n\\n\\n\\n\\nTo access the Performance Advisor using the Atlas UI:\\n\\n\\n\\n\\n\\n### Click Database.\\n\\n### Click the replica set where the collection resides.\\n\\nIf the replica set resides in a sharded cluster, first click the sharded cluster containing the replica set.\\n\\n### Click Performance Advisor.\\n\\n### Select a collection from the Collections dropdown.\\n\\n### Select a time period from the Time Range dropdown.\\n\\n\\n\\n\\n\\n### Click Database.\\n\\n### Click the serverless instance.\\n\\n### Click Performance Advisor.\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nThe Performance Advisor displays up to 20 query shapes across all collections in the cluster and suggested indexes for those shapes. The Performance Advisor ranks the indexes according to their Impact, which indicates High or Medium based on the total wasted bytes read. To learn more about index ranking, see Review Index Ranking.\\n\\n## Index Suggestions\\n\\nThe Performance Advisor ranks the indexes that it suggests according to their Impact, which indicates High or Medium based on the total wasted bytes read. To learn more about how the Performance Advisor ranks indexes, see Review Index Ranking.\\n\\nTo learn how to create indexes that the Performance Advisor suggests, see Create Suggested Indexes.\\n\\n### Index Metrics\\n\\nEach index that the Performance Advisor suggests contains the following metrics. These metrics apply specifically to queries which would be improved by the index:\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n
\\nMetric\\n\\n\\nDescription\\n\\n
\\nExecution Count\\n\\n\\nNumber of queries executed per hour which would be improved.\\n\\n
\\nAverage Execution Time\\n\\n\\nCurrent average execution time in milliseconds for affected queries.\\n\\n
\\nAverage Query Targeting\\n\\n\\nAverage number of documents read per document returned by affected queries. A higher query targeting score indicates a greater degree of inefficiency. For more information on query targeting, see Query Targeting.\\n\\n
\\nIn Memory Sort\\n\\n\\nCurrent number of affected queries per hour that needed to be sorted in memory.\\n\\n
\\nAverage Docs Scanned\\n\\n\\nAverage number of documents scanned.\\n\\n
\\nAverage Docs Returned\\n\\n\\nAverage number of documents returned.\\n\\n
\\nAverage Object Size\\n\\n\\nAverage object size.\\n\\n
\\n\\n### Sample Queries\\n\\nFor each suggested index, the Performance Advisor shows the most commonly executed query shapes that the index would improve. For each query shape, the Performance Advisor displays the following metrics:\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n
\\nMetric\\n\\n\\nDescription\\n\\n
\\nExecution Count\\n\\n\\nNumber of queries executed per hour which match the query shape.\\n\\n
\\nAverage Execution Time\\n\\n\\nAverage execution time in milliseconds for queries which match the query shape.\\n\\n
\\nAverage Query Targeting\\n\\n\\nAverage number of documents read for every document returned by matching queries. A higher query targeting score indicates a greater degree of inefficiency. For more information on query targeting, see Query Targeting.\\n\\n
\\nAverage Docs Scanned\\n\\n\\nAverage number of documents scanned.\\n\\n
\\nAverage Docs Returned\\n\\n\\nAverage number of documents returned.\\n\\n
The Performance Advisor also shows each executed sample query that matches the query shape, with specific metrics for that query.\\n\\n### Query Targeting\\n\\nEach index suggestion includes an Average Query Targeting score indicating how many documents were read for every document returned for the index\\'s corresponding query shapes. A score of 1 represents very efficient query shapes because every document read matched the query and was returned with the query results. All suggested indexes represent an opportunity to improve query performance.\\n\\n### Filter Index Suggestions\\n\\nBy default, the Performance Advisor suggests indexes for all clusters in the deployment. To only show suggested indexes from a specific collection, use the Collection dropdown at the top of the Performance Advisor.\\n\\nYou can also adjust the time range the Performance Advisor takes into account when suggesting indexes by using the Time Range dropdown at the top of the Performance Advisor.\\n\\n### Limitations of Index Suggestions\\n\\n#### Timestamp Format\\n\\nThe Performance Advisor can\\'t suggest indexes for MongoDB databases configured to use the `ctime` timestamp format. As a workaround, set the timestamp format for such databases to either `iso8601-utc` or `iso8601-local`. To learn more about timestamp formats, see mongod --timeStampFormat.\\n\\n#### Log Size\\n\\nThe Performance Advisor analyzes up to 200,000 of your cluster\\'s most recent log lines.\\n\\n#### Log Quantity\\n\\nIf a cluster experiences an activity spike and generates an extremely large quantity of log messages, Atlas may stop collecting and storing new logs for a period of time.\\n\\nLog analysis rate limits apply only to the Performance Advisor UI, the Query Insights UI, the Access Tracking UI, and the Atlas Search Query Analytics UI. Downloadable log files are always complete.\\n\\n#### Time-Series Collections\\n\\nThe Performance Advisor doesn\\'t provide performance suggestions for time-series collections.\\n\\n#### User Feedback\\n\\nThe Performance Advisor includes a user feedback button for Index Suggestions. Atlas hides this button for serverless instances.\\n\\n## Create Suggested Indexes\\n\\nYou can create indexes suggested by the Performance Advisor directly within the Performance Advisor itself. When you create indexes, keep the ratio of reads to writes on the target collection in mind. Indexes come with a performance cost, but are more than worth the cost for frequent queries on large data sets. To learn more about indexing strategies, see Indexing Strategies.\\n\\n### Behavior and Limitations\\n\\n- You can\\'t create indexes through the Performance Advisor if Data Explorer is disabled for your project. You can still view the Performance Advisor recommendations, but you must create those indexes from `mongosh`.\\n\\n- You can only create one index at a time through the Performance Advisor. If you want to create more simultaneously, you can do so using the Atlas UI, a driver, or the shell\\n\\n- Atlas always creates indexes for entire clusters. If you create an index while viewing the Performance Advisor for a single shard in a sharded cluster, Atlas creates that index for the entire sharded cluster.\\n\\n### Procedure\\n\\nTo create a suggested index:\\n\\n#### For the index you want to create, click Create Index.\\n\\nThe Performance Advisor opens the Create Index dialog and prepopulates the Fields based on the index you selected.\\n\\n#### *(Optional)* Specify the index options.\\n\\n```javascript\\n{ : , ... }\\n```\\n\\nThe following options document specifies the `unique` option and the `name` for the index:\\n\\n```javascript\\n{ unique: true, name: \"myUniqueIndex\" }\\n```\\n\\n#### *(Optional)* Set the Collation options.\\n\\nUse collation to specify language-specific rules for string comparison, such as rules for lettercase and accent marks. The collation document contains a `locale` field which indicates the ICU Locale code, and may contain other fields to define collation behavior.\\n\\nThe following collation option document specifies a locale value of `fr` for a French language collation:\\n\\n```json\\n{ \"locale\": \"fr\" }\\n```\\n\\nTo review the list of locales that MongoDB collation supports, see the list of languages and locales. To learn more about collation options, including which are enabled by default for each locale, see Collation in the MongoDB manual.\\n\\n#### *(Optional)* Enable building indexes in a rolling fashion.\\n\\nRolling index builds succeed only when they meet certain conditions. To ensure your index build succeeds, avoid the following design patterns that commonly trigger a restart loop:\\n\\n- Index key exceeds the index key limit\\n\\n- Index name already exists\\n\\n- Index on more than one array field\\n\\n- Index on collection that has the maximum number of text indexes\\n\\n- Text index on collection that has the maximum number of text indexes\\n\\nthe Atlas UI doesn\\'t support building indexes with a rolling build for `M0` free clusters and `M2/M5` shared clusters. You can\\'t build indexes with a rolling build for serverless instances.\\n\\nFor workloads which cannot tolerate performance decrease due to index builds, consider building indexes in a rolling fashion.\\n\\nTo maintain cluster availability:\\n\\n- Atlas removes one node from the cluster at a time starting with a secondary.\\n\\n- More than one node can go down at a time, but Atlas always keeps a majority of the nodes online.\\n\\nAtlas automatically cancels rolling index builds that don\\'t succeed on all nodes. When a rolling index build completes on some nodes, but fails on others, Atlas cancels the build and removes the index from any nodes that it was successfully built on.\\n\\nIn the event of a rolling index build cancellation, Atlas generates an activity feed event and sends a notification email to the project owner with the following information:\\n\\n- Name of the cluster on which the rolling index build failed\\n\\n- Namespace on which the rolling index build failed\\n\\n- Project that contains the cluster and namespace\\n\\n- Organization that contains the project\\n\\n- Link to the activity feed event\\n\\nTo learn more about rebuilding indexes, see Build Indexes on Replica Sets.\\n\\nUnique\\nindex options are incompatible with building indexes in a rolling fashion. If you specify `unique` in the Options pane, Atlas rejects your configuration with an error message.\\n\\n#### Click Review.\\n\\n#### In the Confirm Operation dialog, confirm your index.\\n\\nWhen an index build completes, Atlas generates an activity feed event and sends a notification email to the project owner with the following information:\\n\\n- Completion date of the index build\\n\\n- Name of the cluster on which the index build completed\\n\\n- Namespace on which the index build completed\\n\\n- Project containing the cluster and namespace\\n\\n- Organization containing the project\\n\\n- Link to the activity feed event\\n\\n', name='get_info_about_mongodb', id='e5bb7c63-71df-428b-b811-8784fec6e2cd', tool_call_id='call_8uC6x6EalTyPlaDn1xHG5bcr')]\n", + "{'messages': [ToolMessage(content='# Monitor and Improve Slow Queries\\n\\n*Only available on M10+ clusters and serverless instances*\\n\\nThe Performance Advisor monitors queries that MongoDB considers slow and suggests new indexes to improve query performance. The threshold for slow queries varies based on the average time of operations on your cluster to provide recommendations pertinent to your workload.\\n\\nRecommended indexes are accompanied by sample queries, grouped by query shape, that were run against a collection that would benefit from the suggested index. The Performance Advisor doesn\\'t negatively affect the performance of your Atlas clusters.\\n\\nYou can also monitor collection-level query latency with Namespace Insights and query performance with the Query Profiler.\\n\\nIf the slow query log contains consecutive `$match` stages in the aggregation pipeline, the two stages can coalesce into the first `$match` stage and result in a single `$match` stage. As a result, the query shape in the Performance Advisor might differ from the actual query you ran.\\n\\n## Common Reasons for Slow Queries\\n\\nIf a query is slow, common reasons include:\\n\\n- The query is unsupported by your current indexes.\\n\\n- Some documents in your collection have large array fields that are costly to search and index.\\n\\n- One query retrieves information from multiple collections with $lookup.\\n\\n## Required Access\\n\\nTo view collections with slow queries and see suggested indexes, you must have `Project Read Only` access or higher to the project.\\n\\nTo view field values in a sample query in the Performance Advisor, you must have `Project Data Access Read/Write` access or higher to the project.\\n\\nTo enable or disable the Atlas-managed slow operation threshold, you must have `Project Owner` access to the project. Users with `Organization Owner` access must add themselves to the project as a `Project Owner`.\\n\\n## Configure the Slow Query Threshold\\n\\nBy default, Atlas dynamically adjusts your slow query threshold based on the execution time of operations across your cluster. However, you can opt out of this feature and instead use a fixed slow query threshold of 100 milliseconds. You can disable the Atlas-managed slow operation threshold with the Atlas CLI, Atlas Administration API, or Atlas UI.\\n\\nAtlas clusters with Atlas Search enabled don\\'t support the Atlas-managed slow query operation threshold.\\n\\nFor `M0`, `M2`, `M5` clusters and serverless instances, Atlas disables the Atlas-managed slow query operation threshold by default and you can\\'t enable it.\\n\\n### Disable the Atlas-Managed Slow Operation Threshold\\n\\nBy default, Atlas dynamically adjusts your slow query threshold based on the execution time of operations across your cluster. If you disable the Atlas-managed slow query threshold, it no longer dynamically adjusts. MongoDB defaults the fixed slow query threshold to 100 milliseconds. We don\\'t recommend that you set the fixed slow query threshold lower than 100 milliseconds.\\n\\nTo disable the Atlas-managed slow operation threshold and use a fixed threshold of 100 milliseconds:\\n\\n\\n\\n\\n\\nTo disable the Atlas-managed slow operation threshold for your project using the Atlas CLI, run the following command:\\n\\n```sh\\n\\natlas performanceAdvisor slowOperationThreshold disable [options]\\n\\n```\\n\\nTo learn more about the command syntax and parameters, see the Atlas CLI documentation for atlas performanceAdvisor slowOperationThreshold disable.\\n\\n- Install the Atlas CLI\\n\\n- Connect to the Atlas CLI\\n\\n\\n\\n\\n\\nSee Disable Managed Slow Operation Threshold.\\n\\n\\n\\n\\n\\nIn the Project Settings for the current project, toggle Managed Slow Operations to Off.\\n\\n\\n\\n\\n\\n### Enable the Atlas-Managed Slow Operation Threshold\\n\\nAtlas enables the Atlas-managed slow operation threshold by default. To re-enable the Atlas-managed slow operation threshold that you previously disabled:\\n\\n\\n\\n\\n\\nTo enable the Atlas-managed slow operation threshold for your project using the Atlas CLI, run the following command:\\n\\n```sh\\n\\natlas performanceAdvisor slowOperationThreshold enable [options]\\n\\n```\\n\\nTo learn more about the command syntax and parameters, see the Atlas CLI documentation for atlas performanceAdvisor slowOperationThreshold enable.\\n\\n- Install the Atlas CLI\\n\\n- Connect to the Atlas CLI\\n\\n\\n\\n\\n\\nSee Enable Managed Slow Operation Threshold.\\n\\n\\n\\n\\n\\nIn the Project Settings for the current project, toggle Managed Slow Operations to On.\\n\\n\\n\\n\\n\\n## Index Considerations\\n\\nIndexes improve read performance, but a large number of indexes can negatively impact write performance since indexes must be updated during writes. If your collection already has several indexes, consider this tradeoff of read and write performance when deciding whether to create new indexes. Examine whether a query for such a collection can be modified to take advantage of existing indexes, as well as whether a query occurs often enough to justify the cost of a new index.\\n\\n## Access Performance Advisor\\n\\n\\n\\n\\n\\n### View Collections with Slow Queries\\n\\nTo return up to 20 namespaces in `.` format for collections experiencing slow queries using the Atlas CLI, run the following command:\\n\\n```sh\\n\\natlas performanceAdvisor namespaces list [options]\\n\\n```\\n\\nTo learn more about the command syntax and parameters, see the Atlas CLI documentation for atlas performanceAdvisor namespaces list.\\n\\n- Install the Atlas CLI\\n\\n- Connect to the Atlas CLI\\n\\n### View Slow Query Logs\\n\\nTo return query log line items for slow queries that the Performance Advisor and Query Profiler identify using the Atlas CLI, run the following command:\\n\\n```sh\\n\\natlas performanceAdvisor slowQueryLogs list [options]\\n\\n```\\n\\nTo learn more about the command syntax and parameters, see the Atlas CLI documentation for atlas performanceAdvisor slowQueryLogs list.\\n\\n- Install the Atlas CLI\\n\\n- Connect to the Atlas CLI\\n\\n### View Suggested Indexes\\n\\nTo return suggested indexes for collections experiencing slow queries using the Atlas CLI, run the following command:\\n\\n```sh\\n\\natlas performanceAdvisor suggestedIndexes list [options]\\n\\n```\\n\\nTo learn more about the command syntax and parameters, see the Atlas CLI documentation for atlas performanceAdvisor suggestedIndexes list.\\n\\n- Install the Atlas CLI\\n\\n- Connect to the Atlas CLI\\n\\n\\n\\n\\n\\nTo access the Performance Advisor using the Atlas UI:\\n\\n\\n\\n\\n\\n### Click Database.\\n\\n### Click the replica set where the collection resides.\\n\\nIf the replica set resides in a sharded cluster, first click the sharded cluster containing the replica set.\\n\\n### Click Performance Advisor.\\n\\n### Select a collection from the Collections dropdown.\\n\\n### Select a time period from the Time Range dropdown.\\n\\n\\n\\n\\n\\n### Click Database.\\n\\n### Click the serverless instance.\\n\\n### Click Performance Advisor.\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nThe Performance Advisor displays up to 20 query shapes across all collections in the cluster and suggested indexes for those shapes. The Performance Advisor ranks the indexes according to their Impact, which indicates High or Medium based on the total wasted bytes read. To learn more about index ranking, see Review Index Ranking.\\n\\n## Index Suggestions\\n\\nThe Performance Advisor ranks the indexes that it suggests according to their Impact, which indicates High or Medium based on the total wasted bytes read. To learn more about how the Performance Advisor ranks indexes, see Review Index Ranking.\\n\\nTo learn how to create indexes that the Performance Advisor suggests, see Create Suggested Indexes.\\n\\n### Index Metrics\\n\\nEach index that the Performance Advisor suggests contains the following metrics. These metrics apply specifically to queries which would be improved by the index:\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n
\\nMetric\\n\\n\\nDescription\\n\\n
\\nExecution Count\\n\\n\\nNumber of queries executed per hour which would be improved.\\n\\n
\\nAverage Execution Time\\n\\n\\nCurrent average execution time in milliseconds for affected queries.\\n\\n
\\nAverage Query Targeting\\n\\n\\nAverage number of documents read per document returned by affected queries. A higher query targeting score indicates a greater degree of inefficiency. For more information on query targeting, see Query Targeting.\\n\\n
\\nIn Memory Sort\\n\\n\\nCurrent number of affected queries per hour that needed to be sorted in memory.\\n\\n
\\nAverage Docs Scanned\\n\\n\\nAverage number of documents scanned.\\n\\n
\\nAverage Docs Returned\\n\\n\\nAverage number of documents returned.\\n\\n
\\nAverage Object Size\\n\\n\\nAverage object size.\\n\\n
\\n\\n### Sample Queries\\n\\nFor each suggested index, the Performance Advisor shows the most commonly executed query shapes that the index would improve. For each query shape, the Performance Advisor displays the following metrics:\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n
\\nMetric\\n\\n\\nDescription\\n\\n
\\nExecution Count\\n\\n\\nNumber of queries executed per hour which match the query shape.\\n\\n
\\nAverage Execution Time\\n\\n\\nAverage execution time in milliseconds for queries which match the query shape.\\n\\n
\\nAverage Query Targeting\\n\\n\\nAverage number of documents read for every document returned by matching queries. A higher query targeting score indicates a greater degree of inefficiency. For more information on query targeting, see Query Targeting.\\n\\n
\\nAverage Docs Scanned\\n\\n\\nAverage number of documents scanned.\\n\\n
\\nAverage Docs Returned\\n\\n\\nAverage number of documents returned.\\n\\n
The Performance Advisor also shows each executed sample query that matches the query shape, with specific metrics for that query.\\n\\n### Query Targeting\\n\\nEach index suggestion includes an Average Query Targeting score indicating how many documents were read for every document returned for the index\\'s corresponding query shapes. A score of 1 represents very efficient query shapes because every document read matched the query and was returned with the query results. All suggested indexes represent an opportunity to improve query performance.\\n\\n### Filter Index Suggestions\\n\\nBy default, the Performance Advisor suggests indexes for all clusters in the deployment. To only show suggested indexes from a specific collection, use the Collection dropdown at the top of the Performance Advisor.\\n\\nYou can also adjust the time range the Performance Advisor takes into account when suggesting indexes by using the Time Range dropdown at the top of the Performance Advisor.\\n\\n### Limitations of Index Suggestions\\n\\n#### Timestamp Format\\n\\nThe Performance Advisor can\\'t suggest indexes for MongoDB databases configured to use the `ctime` timestamp format. As a workaround, set the timestamp format for such databases to either `iso8601-utc` or `iso8601-local`. To learn more about timestamp formats, see mongod --timeStampFormat.\\n\\n#### Log Size\\n\\nThe Performance Advisor analyzes up to 200,000 of your cluster\\'s most recent log lines.\\n\\n#### Log Quantity\\n\\nIf a cluster experiences an activity spike and generates an extremely large quantity of log messages, Atlas may stop collecting and storing new logs for a period of time.\\n\\nLog analysis rate limits apply only to the Performance Advisor UI, the Query Insights UI, the Access Tracking UI, and the Atlas Search Query Analytics UI. Downloadable log files are always complete.\\n\\n#### Time-Series Collections\\n\\nThe Performance Advisor doesn\\'t provide performance suggestions for time-series collections.\\n\\n#### User Feedback\\n\\nThe Performance Advisor includes a user feedback button for Index Suggestions. Atlas hides this button for serverless instances.\\n\\n## Create Suggested Indexes\\n\\nYou can create indexes suggested by the Performance Advisor directly within the Performance Advisor itself. When you create indexes, keep the ratio of reads to writes on the target collection in mind. Indexes come with a performance cost, but are more than worth the cost for frequent queries on large data sets. To learn more about indexing strategies, see Indexing Strategies.\\n\\n### Behavior and Limitations\\n\\n- You can\\'t create indexes through the Performance Advisor if Data Explorer is disabled for your project. You can still view the Performance Advisor recommendations, but you must create those indexes from `mongosh`.\\n\\n- You can only create one index at a time through the Performance Advisor. If you want to create more simultaneously, you can do so using the Atlas UI, a driver, or the shell\\n\\n- Atlas always creates indexes for entire clusters. If you create an index while viewing the Performance Advisor for a single shard in a sharded cluster, Atlas creates that index for the entire sharded cluster.\\n\\n### Procedure\\n\\nTo create a suggested index:\\n\\n#### For the index you want to create, click Create Index.\\n\\nThe Performance Advisor opens the Create Index dialog and prepopulates the Fields based on the index you selected.\\n\\n#### *(Optional)* Specify the index options.\\n\\n```javascript\\n{ : , ... }\\n```\\n\\nThe following options document specifies the `unique` option and the `name` for the index:\\n\\n```javascript\\n{ unique: true, name: \"myUniqueIndex\" }\\n```\\n\\n#### *(Optional)* Set the Collation options.\\n\\nUse collation to specify language-specific rules for string comparison, such as rules for lettercase and accent marks. The collation document contains a `locale` field which indicates the ICU Locale code, and may contain other fields to define collation behavior.\\n\\nThe following collation option document specifies a locale value of `fr` for a French language collation:\\n\\n```json\\n{ \"locale\": \"fr\" }\\n```\\n\\nTo review the list of locales that MongoDB collation supports, see the list of languages and locales. To learn more about collation options, including which are enabled by default for each locale, see Collation in the MongoDB manual.\\n\\n#### *(Optional)* Enable building indexes in a rolling fashion.\\n\\nRolling index builds succeed only when they meet certain conditions. To ensure your index build succeeds, avoid the following design patterns that commonly trigger a restart loop:\\n\\n- Index key exceeds the index key limit\\n\\n- Index name already exists\\n\\n- Index on more than one array field\\n\\n- Index on collection that has the maximum number of text indexes\\n\\n- Text index on collection that has the maximum number of text indexes\\n\\nthe Atlas UI doesn\\'t support building indexes with a rolling build for `M0` free clusters and `M2/M5` shared clusters. You can\\'t build indexes with a rolling build for serverless instances.\\n\\nFor workloads which cannot tolerate performance decrease due to index builds, consider building indexes in a rolling fashion.\\n\\nTo maintain cluster availability:\\n\\n- Atlas removes one node from the cluster at a time starting with a secondary.\\n\\n- More than one node can go down at a time, but Atlas always keeps a majority of the nodes online.\\n\\nAtlas automatically cancels rolling index builds that don\\'t succeed on all nodes. When a rolling index build completes on some nodes, but fails on others, Atlas cancels the build and removes the index from any nodes that it was successfully built on.\\n\\nIn the event of a rolling index build cancellation, Atlas generates an activity feed event and sends a notification email to the project owner with the following information:\\n\\n- Name of the cluster on which the rolling index build failed\\n\\n- Namespace on which the rolling index build failed\\n\\n- Project that contains the cluster and namespace\\n\\n- Organization that contains the project\\n\\n- Link to the activity feed event\\n\\nTo learn more about rebuilding indexes, see Build Indexes on Replica Sets.\\n\\nUnique\\nindex options are incompatible with building indexes in a rolling fashion. If you specify `unique` in the Options pane, Atlas rejects your configuration with an error message.\\n\\n#### Click Review.\\n\\n#### In the Confirm Operation dialog, confirm your index.\\n\\nWhen an index build completes, Atlas generates an activity feed event and sends a notification email to the project owner with the following information:\\n\\n- Completion date of the index build\\n\\n- Name of the cluster on which the index build completed\\n\\n- Namespace on which the index build completed\\n\\n- Project containing the cluster and namespace\\n\\n- Organization containing the project\\n\\n- Link to the activity feed event\\n\\n\\n\\n# Fix Query Issues\\n\\n`Query Targeting` alerts often indicate inefficient queries.\\n\\n## Alert Conditions\\n\\nYou can configure the following alert conditions in the project-level alert settings page to trigger alerts.\\n\\n`Query Targeting: Scanned Objects / Returned` alerts are triggered when the average number of documents scanned relative to the average number of documents returned server-wide across all operations during a sampling period exceeds a defined threshold. The default alert uses a 1000:1 threshold.\\n\\nIdeally, the ratio of scanned documents to returned documents should be close to 1. A high ratio negatively impacts query performance.\\n\\n`Query Targeting: Scanned / Returned` occurs if the number of index keys examined to fulfill a query relative to the actual number of returned documents meets or exceeds a user-defined threshold. This alert is not enabled by default.\\n\\nThe following mongod log entry shows statistics generated from an inefficient query:\\n\\n```json\\n COMMAND \\nplanSummary: COLLSCAN keysExamined:0\\ndocsExamined: 10000 cursorExhausted:1 numYields:234\\nnreturned:4 protocol:op_query 358ms\\n```\\n\\nThis query scanned 10,000 documents and returned only 4 for a ratio of 2500, which is highly inefficient. No index keys were examined, so MongoDB scanned all documents in the collection, known as a collection scan.\\n\\n## Common Triggers\\n\\nThe query targeting alert typically occurs when there is no index to support a query or queries or when an existing index only partially supports a query or queries.\\n\\nThe change streams cursors that the Atlas Search process (`mongot`) uses to keep Atlas Search indexes updated can contribute to the query targeting ratio and trigger query targeting alerts if the ratio is high.\\n\\n## Fix the Immediate Problem\\n\\nAdd one or more indexes to better serve the inefficient queries.\\n\\nThe Performance Advisor provides the easiest and quickest way to create an index. The Performance Advisor monitors queries that MongoDB considers slow and recommends indexes to improve performance. Atlas dynamically adjusts your slow query threshold based on the execution time of operations across your cluster.\\n\\nClick Create Index on a slow query for instructions on how to create the recommended index.\\n\\nIt is possible to receive a Query Targeting alert for an inefficient query without receiving index suggestions from the Performance Advisor if the query exceeds the slow query threshold and the ratio of scanned to returned documents is greater than the threshold specified in the alert.\\n\\nIn addition, you can use the following resources to determine which query generated the alert:\\n\\n- The Real-Time Performance Panel monitors and displays current network traffic and database operations on machines hosting MongoDB in your Atlas clusters.\\n\\n- The MongoDB logs maintain an account of activity, including queries, for each `mongod` instance in your Atlas clusters.\\n\\n- The cursor.explain() command for `mongosh` provides performance details for all queries.\\n\\n- Namespace Insights monitors collection-level query latency.\\n\\n- The Atlas Query Profiler records operations that Atlas considers slow when compared to average execution time for all operations on your cluster.\\n\\n## Implement a Long-Term Solution\\n\\nRefer to the following for more information on query performance:\\n\\n- MongoDB Indexing Strategies\\n\\n- Query Optimization\\n\\n- Analyze Query Plan\\n\\n## Monitor Your Progress\\n\\nAtlas provides the following methods to visualize query targeting:\\n\\n- Query Targeting metrics, which highlight high ratios of objects scanned to objects returned.\\n\\n- Namespace Insights, which monitors collection-level query latency.\\n\\n- The Query Profiler, which describes specific inefficient queries executed on the cluster.\\n\\n### Query Targeting Metrics\\n\\nYou can view historical metrics to help you visualize the query performance of your cluster. To view Query Targeting metrics in the Atlas UI:\\n\\n1. Click Database in the top-left corner of Atlas.\\n\\n2. Click View Monitoring on the dashboard for the cluster.\\n\\n3. On the Metrics page, click the Add Chart dropdown menu and select Query Targeting.\\n\\nThe Query Targeting chart displays the following metrics for queries executed on the server:\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n
\\nMetric\\n\\n\\nDescription\\n\\n
\\nScanned Objects / Returned\\n\\n\\nIndicates the average number of documents examined relative to the average number of returned documents.\\n\\n
\\nScanned / Returned\\n\\n\\nIndicates the number of index keys examined to fulfill a query relative to the actual number of returned documents.\\n\\n
The change streams cursors that the Atlas Search process (`mongot`) uses to keep Atlas Search indexes updated can contribute to the query targeting ratio and trigger query targeting alerts if the ratio is high.\\n\\nIf either of these metrics exceed the user-defined threshold, Atlas generates the corresponding `Query Targeting: Scanned Objects / Returned` or `Query Targeting: Scanned / Returned` alert.\\n\\nYou can also view Query Targeting ratios of operations in real-time using the Real-Time Performance Panel.\\n\\n### Namespace Insights\\n\\nNamespace Insights monitors collection-level query latency. You can view query latency metrics and statistics for certain hosts and operation types. Manage pinned namespaces and choose up to five namespaces to show in the corresponding query latency charts.\\n\\nTo access Namespace Insights:\\n\\n1. Click Database in the top-left corner of Atlas.\\n\\n2. Click View Monitoring on the dashboard for the cluster.\\n\\n3. Click the Query Insights tab.\\n\\n4. Click the Namespace Insights tab.\\n\\n### Query Profiler\\n\\nThe Query Profiler contains several metrics you can use to pinpoint specific inefficient queries. You can visualize up to the past 24 hours of query operations. The Query Profiler can show the Examined : Returned Ratio (index keys examined to documents returned) of logged queries, which might help you identify the queries that triggered a `Query Targeting: Scanned / Returned` alert. The chart shows the number of index keys examined to fulfill a query relative to the actual number of returned documents.\\n\\nThe default\\n`Query Targeting: Scanned Objects / Returned` alert ratio differs slightly. The ratio of the average number of documents scanned to the average number of documents returned during a sampling period triggers this alert.\\n\\nAtlas might not log the individual operations that contribute to the Query Targeting ratios due to automatically set thresholds. However, you can still use the Query Profiler and Query Targeting metrics to analyze and optimize query performance.\\n\\nTo access the Query Profiler:\\n\\n1. Click Database in the top-left corner of Atlas.\\n\\n2. Click View Monitoring on the dashboard for the cluster.\\n\\n3. Click the Query Insights tab.\\n\\n4. Click the Query Profiler tab.\\n\\n\\n\\n# Analyze Slow Queries\\n\\nAtlas provides several tools to help analyze slow queries executed on your clusters. See the following sections for descriptions of each tool. To optimize your query performance, review the best practices for query performance.\\n\\n## Performance Advisor\\n\\nThe Performance Advisor monitors queries that MongoDB considers slow and suggests new indexes to improve query performance.\\n\\nYou can use the Performance Advisor to review the following information:\\n\\n- Index Ranking\\n\\n- Drop Index Recommendations\\n\\n## Namespace Insights\\n\\nMonitor collection-level query latency with Namespace Insights. You can view query latency metrics and statistics for certain hosts and operation types. Manage pinned namespaces and choose up to five namespaces to show in the corresponding query latency charts.\\n\\n## Query Profiler\\n\\nThe Query Profiler displays slow-running operations and their key performance statistics. You can explore a sample of historical queries for up to the last 24 hours without additional cost or performance overhead. Before you enable the Query Profiler, see Considerations.\\n\\n## Real-Time Performance Panel (RTPP)\\n\\nThe Real-Time Performance Panel identifies relevant database operations, evaluates query execution times, and shows the ratio of documents scanned to documents returned during query execution. RTPP (Real-Time Performance Panel) is enabled by default.\\n\\nTo enable or disable Real-Time Performance Panel for a project, you must have the `Project Owner` role for the project.\\n\\n## Best Practices for Query Performance\\n\\nTo optimize query performance, review the following best practices:\\n\\n- Create queries that your current indexes support to reduce the time needed to search for your results.\\n\\n- Avoid creating documents with large array fields that require a lot of processing to search and index.\\n\\n- Optimize your indexes and remove unused or inefficent indexes. Too many indexes can negatively impact write performance.\\n\\n- Consider the suggested indexes from the Performance Advisor with the highest Impact scores and lowest Average Query Targeting scores.\\n\\n- Create the indexes that the Performance Advisor suggests when they align with your Indexing Strategies.\\n\\n- The Performance Advisor cannot suggest indexes for MongoDB databases configured to use the ctime timestamp format. As a workaround, set the timestamp format for such databases to either iso8601-utc or iso8601-local.\\n\\n- Perform rolling index builds to reduce the performance impact of building indexes on replica sets and sharded clusters.\\n\\n- Drop unused, redundant, and hidden indexes to improve write performance and free storage space.\\n\\n', name='get_info_about_mongodb', id='58b5fb08-1776-49d8-a6f6-956431f77388', tool_call_id='call_sifH0mrhbpesQie4BTnQytNk')]}\n", "Node agent:\n", - "{'messages': [AIMessage(content=\"To improve slow queries in MongoDB, you can follow these steps and best practices:\\n\\n### Tools and Features to Analyze and Optimize Queries:\\n1. **Performance Advisor**:\\n - Monitors slow queries and suggests indexes to improve performance.\\n - Provides recommendations based on query shapes and their impact.\\n\\n2. **Query Profiler**:\\n - Displays slow-running operations and their performance statistics.\\n - Allows you to explore historical queries for up to 24 hours.\\n\\n3. **Real-Time Performance Panel (RTPP)**:\\n - Identifies database operations, evaluates query execution times, and shows the ratio of documents scanned to documents returned.\\n\\n4. **Namespace Insights**:\\n - Monitors collection-level query latency and provides metrics for specific hosts and operation types.\\n\\n5. **Query Targeting Metrics**:\\n - Highlights inefficiencies in queries by showing the ratio of scanned objects to returned objects.\\n\\n### Best Practices for Query Performance:\\n1. **Indexing**:\\n - Create indexes that support your queries to reduce search time.\\n - Use the Performance Advisor to identify and create suggested indexes.\\n - Remove unused or inefficient indexes to improve write performance.\\n\\n2. **Query Design**:\\n - Avoid queries that require scanning large arrays or documents.\\n - Optimize queries to take advantage of existing indexes.\\n\\n3. **Rolling Index Builds**:\\n - For replica sets and sharded clusters, perform rolling index builds to minimize performance impact.\\n\\n4. **Monitor Query Targeting**:\\n - Ensure the ratio of scanned documents to returned documents is close to 1 for efficiency.\\n - Address alerts for high ratios by adding appropriate indexes.\\n\\n5. **Analyze Query Plans**:\\n - Use the `explain()` method to understand query execution and identify bottlenecks.\\n\\n6. **Avoid Over-Indexing**:\\n - Too many indexes can negatively impact write performance. Balance the trade-off between read and write performance.\\n\\n### Common Reasons for Slow Queries:\\n- Queries are unsupported by current indexes.\\n- Documents have large array fields that are costly to search.\\n- Queries involve multiple collections with `$lookup`.\\n\\n### Steps to Fix Slow Queries:\\n1. **Immediate Fix**:\\n - Add indexes to support inefficient queries.\\n - Use the Performance Advisor to create recommended indexes.\\n\\n2. **Long-Term Solution**:\\n - Optimize query design and indexing strategies.\\n - Regularly monitor query performance using tools like the Query Profiler and Namespace Insights.\\n\\n3. **Monitor Progress**:\\n - Use Query Targeting metrics and Namespace Insights to track improvements.\\n\\nBy following these steps and leveraging MongoDB's tools, you can significantly improve the performance of slow queries.\", additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 536, 'prompt_tokens': 5355, 'total_tokens': 5891, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-4o-2024-11-20', 'system_fingerprint': 'fp_a523ccd45c', 'finish_reason': 'stop', 'logprobs': None}, id='run-73908bfe-67dc-4ce7-971e-1ca3265720cb-0', usage_metadata={'input_tokens': 5355, 'output_tokens': 536, 'total_tokens': 5891, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 0}})]}\n", + "{'messages': [AIMessage(content=\"To improve slow queries in MongoDB, you can follow these steps:\\n\\n### 1. **Analyze the Problem**\\n - Use the **Performance Advisor** to monitor slow queries and get index recommendations.\\n - Check the **Query Profiler** to identify slow-running operations and their key performance statistics.\\n - Use **Namespace Insights** to monitor collection-level query latency.\\n - Analyze the **Real-Time Performance Panel (RTPP)** for real-time query execution metrics.\\n\\n### 2. **Common Causes of Slow Queries**\\n - Queries are not supported by existing indexes.\\n - Large array fields in documents that are costly to search and index.\\n - Queries involving multiple collections using `$lookup`.\\n\\n### 3. **Fix Immediate Issues**\\n - **Add Indexes**: Create indexes to support inefficient queries. The Performance Advisor provides suggestions for indexes with high impact.\\n - **Optimize Queries**: Ensure queries are designed to utilize existing indexes effectively.\\n - **Avoid Collection Scans**: If a query scans all documents in a collection (COLLSCAN), it indicates the need for an index.\\n\\n### 4. **Long-Term Solutions**\\n - **Optimize Indexes**: Remove unused or redundant indexes to improve write performance.\\n - **Monitor Query Targeting**: Keep the ratio of documents scanned to documents returned close to 1.\\n - **Avoid Large Arrays**: Minimize the use of large array fields in documents.\\n\\n### 5. **Best Practices**\\n - Use the **Query Targeting Metrics** to identify inefficiencies.\\n - Perform **rolling index builds** to minimize performance impact on replica sets and sharded clusters.\\n - Drop unused or hidden indexes to free up storage and improve write performance.\\n\\n### 6. **Tools for Monitoring and Optimization**\\n - **Performance Advisor**: Suggests indexes and provides query insights.\\n - **Query Profiler**: Displays slow-running queries and their statistics.\\n - **Namespace Insights**: Monitors query latency at the collection level.\\n - **Real-Time Performance Panel**: Provides real-time metrics for query execution.\\n\\nBy following these steps and utilizing MongoDB's built-in tools, you can significantly improve the performance of slow queries.\", additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 451, 'prompt_tokens': 5355, 'total_tokens': 5806, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-4o-2024-11-20', 'system_fingerprint': 'fp_d924043139', 'finish_reason': 'stop', 'logprobs': None}, id='run-ad3b553a-e5e6-4c9e-9246-d6e0f7286abb-0', usage_metadata={'input_tokens': 5355, 'output_tokens': 451, 'total_tokens': 5806, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 0}})]}\n", "---FINAL ANSWER---\n", - "To improve slow queries in MongoDB, you can follow these steps and best practices:\n", - "\n", - "### Tools and Features to Analyze and Optimize Queries:\n", - "1. **Performance Advisor**:\n", - " - Monitors slow queries and suggests indexes to improve performance.\n", - " - Provides recommendations based on query shapes and their impact.\n", - "\n", - "2. **Query Profiler**:\n", - " - Displays slow-running operations and their performance statistics.\n", - " - Allows you to explore historical queries for up to 24 hours.\n", - "\n", - "3. **Real-Time Performance Panel (RTPP)**:\n", - " - Identifies database operations, evaluates query execution times, and shows the ratio of documents scanned to documents returned.\n", - "\n", - "4. **Namespace Insights**:\n", - " - Monitors collection-level query latency and provides metrics for specific hosts and operation types.\n", - "\n", - "5. **Query Targeting Metrics**:\n", - " - Highlights inefficiencies in queries by showing the ratio of scanned objects to returned objects.\n", - "\n", - "### Best Practices for Query Performance:\n", - "1. **Indexing**:\n", - " - Create indexes that support your queries to reduce search time.\n", - " - Use the Performance Advisor to identify and create suggested indexes.\n", - " - Remove unused or inefficient indexes to improve write performance.\n", - "\n", - "2. **Query Design**:\n", - " - Avoid queries that require scanning large arrays or documents.\n", - " - Optimize queries to take advantage of existing indexes.\n", - "\n", - "3. **Rolling Index Builds**:\n", - " - For replica sets and sharded clusters, perform rolling index builds to minimize performance impact.\n", - "\n", - "4. **Monitor Query Targeting**:\n", - " - Ensure the ratio of scanned documents to returned documents is close to 1 for efficiency.\n", - " - Address alerts for high ratios by adding appropriate indexes.\n", + "To improve slow queries in MongoDB, you can follow these steps:\n", "\n", - "5. **Analyze Query Plans**:\n", - " - Use the `explain()` method to understand query execution and identify bottlenecks.\n", + "### 1. **Analyze the Problem**\n", + " - Use the **Performance Advisor** to monitor slow queries and get index recommendations.\n", + " - Check the **Query Profiler** to identify slow-running operations and their key performance statistics.\n", + " - Use **Namespace Insights** to monitor collection-level query latency.\n", + " - Analyze the **Real-Time Performance Panel (RTPP)** for real-time query execution metrics.\n", "\n", - "6. **Avoid Over-Indexing**:\n", - " - Too many indexes can negatively impact write performance. Balance the trade-off between read and write performance.\n", + "### 2. **Common Causes of Slow Queries**\n", + " - Queries are not supported by existing indexes.\n", + " - Large array fields in documents that are costly to search and index.\n", + " - Queries involving multiple collections using `$lookup`.\n", "\n", - "### Common Reasons for Slow Queries:\n", - "- Queries are unsupported by current indexes.\n", - "- Documents have large array fields that are costly to search.\n", - "- Queries involve multiple collections with `$lookup`.\n", + "### 3. **Fix Immediate Issues**\n", + " - **Add Indexes**: Create indexes to support inefficient queries. The Performance Advisor provides suggestions for indexes with high impact.\n", + " - **Optimize Queries**: Ensure queries are designed to utilize existing indexes effectively.\n", + " - **Avoid Collection Scans**: If a query scans all documents in a collection (COLLSCAN), it indicates the need for an index.\n", "\n", - "### Steps to Fix Slow Queries:\n", - "1. **Immediate Fix**:\n", - " - Add indexes to support inefficient queries.\n", - " - Use the Performance Advisor to create recommended indexes.\n", + "### 4. **Long-Term Solutions**\n", + " - **Optimize Indexes**: Remove unused or redundant indexes to improve write performance.\n", + " - **Monitor Query Targeting**: Keep the ratio of documents scanned to documents returned close to 1.\n", + " - **Avoid Large Arrays**: Minimize the use of large array fields in documents.\n", "\n", - "2. **Long-Term Solution**:\n", - " - Optimize query design and indexing strategies.\n", - " - Regularly monitor query performance using tools like the Query Profiler and Namespace Insights.\n", + "### 5. **Best Practices**\n", + " - Use the **Query Targeting Metrics** to identify inefficiencies.\n", + " - Perform **rolling index builds** to minimize performance impact on replica sets and sharded clusters.\n", + " - Drop unused or hidden indexes to free up storage and improve write performance.\n", "\n", - "3. **Monitor Progress**:\n", - " - Use Query Targeting metrics and Namespace Insights to track improvements.\n", + "### 6. **Tools for Monitoring and Optimization**\n", + " - **Performance Advisor**: Suggests indexes and provides query insights.\n", + " - **Query Profiler**: Displays slow-running queries and their statistics.\n", + " - **Namespace Insights**: Monitors query latency at the collection level.\n", + " - **Real-Time Performance Panel**: Provides real-time metrics for query execution.\n", "\n", - "By following these steps and leveraging MongoDB's tools, you can significantly improve the performance of slow queries.\n" + "By following these steps and utilizing MongoDB's built-in tools, you can significantly improve the performance of slow queries.\n" ] } ],