Esta página fornece orientações sobre como gerar queries do MongoDB para seus dados a partir da linguagem natural usando um grandes modelos de linguagem (LLM).
Por exemplo, considere a seguinte query de linguagem natural para query gerada no mongosh
para o banco de dados Atlas sample_mflix:
Dada a seguinte query de linguagem natural:
| Isso gera o seguinte código
|
Métodos disponíveis
Além de usar LLMs prontos para uso, você pode usar as seguintes ferramentas criadas pelo MongoDB para gerar queries do MongoDB a partir da linguagem natural:
Selecionar um modelo
Modelos que funcionam bem em tarefas gerais normalmente também funcionam bem na geração de queries do MongoDB . Ao selecionar um LLM para gerar queries MongoDB , consulte benchmarks populares como MMLU-Pro e Chartbot Array LO para avaliar o desempenho entre modelos.
Solicitação eficaz
Esta seção descreve estratégias eficazes para solicitar que um LLM gere queries para o MongoDB .
Observação
As estratégias de instrução a seguir são baseadas em parâmetros criados pelo MongoDB. Para saber mais, consulte nossa referência pública de linguagem natural para códigomongosh
sobre Abraçando a Face.
Prompt de base
Seu prompt de base, também chamado de prompt do sistema, deve fornecer uma visão geral clara de sua tarefa, incluindo:
O tipo de query a gerar.
Informações sobre a estrutura de saída esperada, como a linguagem do driver ou a ferramenta que executa a query.
O seguinte exemplo de prompt base demonstra como gerar uma operação de leitura MongoDB ou agregação para mongosh
:
You are an expert data analyst experienced at using MongoDB. Your job is to take information about a MongoDB database plus a natural language query and generate a MongoDB shell (mongosh) query to execute to retrieve the information needed to answer the natural language query. Format the mongosh query in the following structure: `db.<collection name>.find({/* query */})` or `db.<collection name>.aggregate({/* query */})`
Orientação geral
Para melhorar a qualidade da query, adicione a seguinte orientação ao seu prompt base para fornecer ao modelo dicas comuns para gerar queries MongoDB eficazes:
Some general query-authoring tips: 1. Ensure proper use of MongoDB operators ($eq, $gt, $lt, etc.) and data types (ObjectId, ISODate) 2. For complex queries, use aggregation pipeline with proper stages ($match, $group, $lookup, etc.) 3. Consider performance by utilizing available indexes, avoiding $where and full collection scans, and using covered queries where possible 4. Include sorting (.sort()) and limiting (.limit()), when appropriate, for result set management 5. Handle null values and existence checks explicitly with $exists and $type operators to differentiate between missing fields, null values, and empty arrays 6. Do not include `null` in results objects in aggregation, e.g. do not include _id: null 7. For date operations, NEVER use an empty new date object (e.g. `new Date()`). ALWAYS specify the date, such as `new Date("2024-10-24")`. 8. For Decimal128 operations, prefer range queries over exact equality 9. When querying arrays, use appropriate operators like $elemMatch for complex matching, $all to match multiple elements, or $size for array length checks
Corrente de ideias
Você pode solicitar que o modelo "pense em voz alta" antes de gerar a resposta para melhorar a qualidade da resposta. Essa técnica, chamada de cadeia de ideias, melhora o desempenho, mas aumenta o tempo e os custos de geração.
Para encorajar o modelo a pensar passo a passo antes de gerar a query, adicione o seguinte texto ao seu prompt base:
Think step by step about the code in the answer before providing it. In your thoughts, consider: 1. Which collections are relevant to the query. 2. Which query operation to use (find vs aggregate) and what specific operators ($match, $group, $project, etc.) are needed. 3. What fields are relevant to the query. 4. Which indexes you can use to improve performance. 5. What specific transformations or projections are required. 6. What data types are involved and how to handle them appropriately (ObjectId, Decimal128, Date, etc.). 7. What edge cases to consider (empty results, null values, missing fields). 8. How to handle any array fields that require special operators ($elemMatch, $all, $size). 9. Any other relevant considerations.
Incluir documentos de amostra
Para melhorar significativamente a qualidade da query, inclua alguns documentos de amostra representativos da sua coleção. Dois a três documentos representativos normalmente fornecem ao modelo contexto suficiente sobre a estrutura de dados.
Ao fornecer documentos de amostra, siga estas diretrizes:
Use o BSON.EJSON.serialize() função para converter documentos BSON em strings EJSON para o prompt.
Truncar campos longos ou objetos profundamente aninhados.
Exclua valores de string longos.
Para arrays grandes, como incorporações de vetor, inclua apenas alguns elementos.
Por exemplo, para o banco de dados sample_mflix
e a collection movies
, você pode incluir os seguintes documentos em seu prompt:
[ { _id: { $oid: "573a13bbf29313caabd526d0", }, plot: "Van Erp shows us what the Dutch do in their spare time and takes a look at the industry behind all t...", genres: ["Documentary"], runtime: 90, title: "Pretpark Nederland", num_mflix_comments: 0, poster: "https://m.media-amazon.com/images/M/MV5BMTUwNjU0ODg3N15BMl5BanBnXkFtZTcwMzg3NjYxNA@@._V1_SY1000_SX67...", countries: ["Netherlands"], fullplot: "Van Erp displays the mechanics behind the Dutch tourism industry. Key figures behind events and dest...", languages: ["Dutch", "Mandarin"], released: { $date: "2006-10-18T00:00:00.000Z", }, directors: ["Michiel van Erp"], writers: ["Renè van 't Erve (scenario)", "Michiel van Erp (scenario)"], awards: { wins: 0, nominations: 1, text: "1 nomination.", }, lastupdated: "2015-02-26T00:48:24.883Z", year: 2006, imdb: { rating: 7.3, votes: 237, id: 882800, }, type: "movie", tomatoes: { viewer: { rating: 2.2, numReviews: 19, }, dvd: { $date: "2010-06-22T00:00:00.000Z", }, lastUpdated: { $date: "2014-11-24T14:15:50.000Z", }, }, hash: { low: -1866172407, high: -2147460187, unsigned: false, }, }, { _id: { $oid: "573a13caf29313caabd7c4e0", }, fullplot: "A drama centered on a rising country-music songwriter (Hedlund) who sparks with a fallen star (Paltr...", imdb: { rating: 6.3, votes: 14066, id: 1555064, }, year: 2010, plot: "A rising country-music songwriter works with a fallen star to work their way fame, causing romantic ...", genres: ["Drama", "Music"], rated: "PG-13", metacritic: 45, title: "Country Strong", lastupdated: "2015-09-03T00:39:54.710Z", languages: ["English"], writers: ["Shana Feste"], type: "movie", tomatoes: { website: "http://www.countrystrong-movie.com/?hs308=CST6186", viewer: { rating: 3.3, numReviews: 32825, meter: 53, }, dvd: { $date: "2011-04-12T00:00:00.000Z", }, critic: { rating: 4.5, numReviews: 130, meter: 22, }, boxOffice: "$20.2M", consensus: "The cast gives it their all, and Paltrow handles her songs with aplomb, but Country Strong's cliched...", rotten: 101, production: "Screen Gems", lastUpdated: { $date: "2015-08-17T18:04:40.000Z", }, fresh: 29, }, poster: "https://m.media-amazon.com/images/M/MV5BMTUxMjQ0NjE3OV5BMl5BanBnXkFtZTcwODIxNDEwNA@@._V1_SY1000_SX67...", num_mflix_comments: 0, released: { $date: "2011-01-07T00:00:00.000Z", }, awards: { wins: 2, nominations: 6, text: "Nominated for 1 Oscar. Another 1 win & 6 nominations.", }, countries: ["USA"], cast: [ "Gwyneth Paltrow", "Tim McGraw", "Garrett Hedlund", "...and 1 more items", ], }, ];
Melhores práticas
Aplique as seguintes práticas recomendadas de solicitação para casos de uso específicos ao gerar queries do MongoDB a partir de linguagem natural.
Incluir informações de índice
Inclua índices de collection em seu prompt para encorajar o LLM a gerar queries de mais desempenho. Os drivers e mongosh
do MongoDB fornecem métodos para obter informações do índice. Por exemplo, o driver Node.js fornece o método listIndexes() para obter índices para seu prompt.
Queries baseadas em tempo
A maioria das ferramentas LLM inclui a data em seu prompt do sistema. No entanto, se você estiver usando um LLM pronto para uso, o modelo não saberá a data ou hora atual. Portanto, ao trabalhar com modelos básicos ou construir sua própria linguagem natural para ferramentas MongoDB , inclua a data mais recente em seu prompt. Use o método para sua linguagem de programação para obter a data atual como uma string, como new Date().toString()
do JavaScript ou str(datetime.now())
do Python.
Esquemas de banco de dados anotados
Inclua esquemas anotados de collections de banco de dados relevantes em seu prompt. Embora nenhum método de representação funcione melhor para todos os LLMs, algumas abordagens são mais eficazes do que outras.
Recomendamos representar coleções usando tipos nativos da linguagem de programação que descrevem a forma de dados, como tipos Typescript, modelos Python Pydantial ou estruturas Go. Se você usar o MongoDB desses idiomas, é provável que você já tenha o formato de dados definido. Para orientar o LLM e reduzir a ambiguidade, adicione comentários ao seu prompt para descrever cada campo.
O exemplo a seguir mostra um tipo Typescript para a coleção sample_mflix.movies
:
interface Movie { /** * Unique identifier for the movie document. */ _id: ObjectId; /** * Brief description of the movie's plot. */ plot: string; /** * List of genres associated with the movie. */ genres: string[]; /** * Duration of the movie in minutes. */ runtime: number; /** * Title of the movie. */ title: string; /** * Number of comments on the movie in the mflix system. */ num_mflix_comments: number; /** * URL to the movie's poster image. */ poster: string; /** * List of countries where the movie was produced. */ countries: string[]; /** * Detailed description of the movie's plot. */ fullplot: string; /** * Languages spoken in the movie. */ languages: string[]; /** * Release date of the movie. */ released: Date; /** * List of directors of the movie. */ directors: string[]; /** * List of writers of the movie. */ writers: string[]; /** * Awards received by the movie. */ awards: { /** * Number of awards won by the movie. */ wins: number; /** * Number of award nominations received by the movie. */ nominations: number; /** * Textual description of the awards. */ text: string; }; /** * Last updated timestamp for the movie document. */ lastupdated: string; /** * Year the movie was released. */ year: number; /** * IMDb information for the movie. */ imdb: { /** * IMDb rating of the movie. */ rating: number; /** * Number of votes the movie received on IMDb. */ votes: number; /** * IMDb identifier for the movie. */ id: number; }; /** * Type of the movie (e.g., movie, series). */ type: string; /** * Rotten Tomatoes information for the movie. */ tomatoes: { /** * Viewer ratings on Rotten Tomatoes. */ viewer?: { /** * Viewer rating score. */ rating: number; /** * Number of reviews by viewers. */ numReviews: number; /** * Viewer meter score. */ meter: number; }; /** * DVD release date. */ dvd?: Date; /** * Last updated timestamp for Rotten Tomatoes data. */ lastUpdated?: Date; /** * Official website for the movie. */ website?: string; /** * Critic ratings on Rotten Tomatoes. */ critic?: { /** * Critic rating score. */ rating: number; /** * Number of reviews by critics. */ numReviews: number; /** * Critic meter score. */ meter: number; }; /** * Box office earnings. */ boxOffice?: string; /** * Consensus statement from Rotten Tomatoes. */ consensus?: string; /** * Number of rotten reviews. */ rotten?: number; /** * Production company. */ production?: string; /** * Number of fresh reviews. */ fresh?: number; }; /** * Hash value for the movie document. */ hash: Long; /** * MPAA rating of the movie. */ rated?: string; /** * Metacritic score of the movie. */ metacritic?: number; /** * List of main cast members in the movie. */ cast: string[]; }
Prompt Template
O exemplo a seguir demonstra um prompt completo usando as estratégias descritas nesta página para gerar códigomongosh
a partir de linguagem natural.
Exemplo de prompt do Base
Use o seguinte exemplo de prompt do sistema como modelo para suas tarefas de geração de query do MongoDB . A amostra de prompt inclui os seguintes componentes:
Visão geral da tarefa e formato de saída esperado
You are an expert data analyst experienced at using MongoDB. Your job is to take information about a MongoDB database plus a natural language query and generate a MongoDB shell (mongosh) query to execute to retrieve the information needed to answer the natural language query. Format the mongosh query in the following structure: `db.<collection name>.find({/* query */})` or `db.<collection name>.aggregate({/* query */})` Some general query-authoring tips: 1. Ensure proper use of MongoDB operators ($eq, $gt, $lt, etc.) and data types (ObjectId, ISODate). 2. For complex queries, use aggregation pipeline with proper stages ($match, $group, $lookup, etc.). 3. Consider performance by utilizing available indexes, avoiding $where and full collection scans, and using covered queries where possible. 4. Include sorting (.sort()) and limiting (.limit()) when appropriate for result set management. 5. Handle null values and existence checks explicitly with $exists and $type operators to differentiate between missing fields, null values, and empty arrays. 6. Do not include `null` in results objects in aggregation, e.g. do not include _id: null. 7. For date operations, NEVER use an empty new date object (e.g. `new Date()`). ALWAYS specify the date, such as `new Date("2024-10-24")`. Use the provided 'Latest Date' field to inform dates in queries. 8. For Decimal128 operations, prefer range queries over exact equality. 9. When querying arrays, use appropriate operators like $elemMatch for complex matching, $all to match multiple elements, or $size for array length checks.
Observação
Você também pode adicionar o prompt de cadeia de ideias para encorajar a reflexão passo a passo antes da geração de código.
Modelo de mensagem do usuário
Em seguida, use o seguinte modelo de mensagem do usuário para fornecer ao modelo o contexto necessário sobre seu banco de dados e a query desejada:
Generate MongoDB Shell (mongosh) queries for the following database and natural language query: ## Database Information Name: {{Database name}} Description: {{database description}} Latest Date: {{latest date}} (use this to inform dates in queries) ### Collections #### Collection `{{collection name. Do for each collection you want to query over}}` Description: {{collection description}} Schema: ``` {{interpreted or annotated schema here}} ``` Example documents: ``` {{truncated example documents here}} ``` Indexes: ``` {{collection index descriptions here}} ``` Natural language query: {{Natural language query here}}